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.

279798 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 0
  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 0
  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. #ifndef JUCE_SUPPORT_CARBON
  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. embeddedView (0),
  761. recursiveResize (false)
  762. {
  763. }
  764. virtual ~CarbonViewWrapperComponent()
  765. {
  766. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  767. }
  768. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  769. virtual void removeView (HIViewRef embeddedView) = 0;
  770. virtual void mouseDown (int, int) {}
  771. virtual void paint() {}
  772. virtual bool getEmbeddedViewSize (int& w, int& h)
  773. {
  774. if (embeddedView == 0)
  775. return false;
  776. HIRect bounds;
  777. HIViewGetBounds (embeddedView, &bounds);
  778. w = jmax (1, roundToInt (bounds.size.width));
  779. h = jmax (1, roundToInt (bounds.size.height));
  780. return true;
  781. }
  782. void createWindow()
  783. {
  784. if (wrapperWindow == 0)
  785. {
  786. Rect r;
  787. r.left = getScreenX();
  788. r.top = getScreenY();
  789. r.right = r.left + getWidth();
  790. r.bottom = r.top + getHeight();
  791. CreateNewWindow (kDocumentWindowClass,
  792. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  793. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  794. &r, &wrapperWindow);
  795. jassert (wrapperWindow != 0);
  796. if (wrapperWindow == 0)
  797. return;
  798. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  799. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  800. [ownerWindow addChildWindow: carbonWindow
  801. ordered: NSWindowAbove];
  802. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  803. EventTypeSpec windowEventTypes[] =
  804. {
  805. { kEventClassWindow, kEventWindowGetClickActivation },
  806. { kEventClassWindow, kEventWindowHandleDeactivate },
  807. { kEventClassWindow, kEventWindowBoundsChanging },
  808. { kEventClassMouse, kEventMouseDown },
  809. { kEventClassMouse, kEventMouseMoved },
  810. { kEventClassMouse, kEventMouseDragged },
  811. { kEventClassMouse, kEventMouseUp},
  812. { kEventClassWindow, kEventWindowDrawContent },
  813. { kEventClassWindow, kEventWindowShown },
  814. { kEventClassWindow, kEventWindowHidden }
  815. };
  816. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  817. InstallWindowEventHandler (wrapperWindow, upp,
  818. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  819. windowEventTypes, this, &eventHandlerRef);
  820. setOurSizeToEmbeddedViewSize();
  821. setEmbeddedWindowToOurSize();
  822. creationTime = Time::getCurrentTime();
  823. }
  824. }
  825. void deleteWindow()
  826. {
  827. removeView (embeddedView);
  828. embeddedView = 0;
  829. if (wrapperWindow != 0)
  830. {
  831. RemoveEventHandler (eventHandlerRef);
  832. DisposeWindow (wrapperWindow);
  833. wrapperWindow = 0;
  834. }
  835. }
  836. void setOurSizeToEmbeddedViewSize()
  837. {
  838. int w, h;
  839. if (getEmbeddedViewSize (w, h))
  840. {
  841. if (w != getWidth() || h != getHeight())
  842. {
  843. startTimer (50);
  844. setSize (w, h);
  845. if (getParentComponent() != 0)
  846. getParentComponent()->setSize (w, h);
  847. }
  848. else
  849. {
  850. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  851. }
  852. }
  853. else
  854. {
  855. stopTimer();
  856. }
  857. }
  858. void setEmbeddedWindowToOurSize()
  859. {
  860. if (! recursiveResize)
  861. {
  862. recursiveResize = true;
  863. if (embeddedView != 0)
  864. {
  865. HIRect r;
  866. r.origin.x = 0;
  867. r.origin.y = 0;
  868. r.size.width = (float) getWidth();
  869. r.size.height = (float) getHeight();
  870. HIViewSetFrame (embeddedView, &r);
  871. }
  872. if (wrapperWindow != 0)
  873. {
  874. Rect wr;
  875. wr.left = getScreenX();
  876. wr.top = getScreenY();
  877. wr.right = wr.left + getWidth();
  878. wr.bottom = wr.top + getHeight();
  879. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  880. ShowWindow (wrapperWindow);
  881. }
  882. recursiveResize = false;
  883. }
  884. }
  885. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  886. {
  887. setEmbeddedWindowToOurSize();
  888. }
  889. void componentPeerChanged()
  890. {
  891. deleteWindow();
  892. createWindow();
  893. }
  894. void componentVisibilityChanged (Component&)
  895. {
  896. if (isShowing())
  897. createWindow();
  898. else
  899. deleteWindow();
  900. setEmbeddedWindowToOurSize();
  901. }
  902. static void recursiveHIViewRepaint (HIViewRef view)
  903. {
  904. HIViewSetNeedsDisplay (view, true);
  905. HIViewRef child = HIViewGetFirstSubview (view);
  906. while (child != 0)
  907. {
  908. recursiveHIViewRepaint (child);
  909. child = HIViewGetNextView (child);
  910. }
  911. }
  912. void timerCallback()
  913. {
  914. setOurSizeToEmbeddedViewSize();
  915. // To avoid strange overpainting problems when the UI is first opened, we'll
  916. // repaint it a few times during the first second that it's on-screen..
  917. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  918. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  919. }
  920. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  921. 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. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  932. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  933. sizeof (ClickActivationResult), &howToHandleClick);
  934. HIViewSetNeedsDisplay (embeddedView, true);
  935. return noErr;
  936. }
  937. }
  938. return eventNotHandledErr;
  939. }
  940. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  941. EventRef event, void* userData)
  942. {
  943. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  944. }
  945. protected:
  946. WindowRef wrapperWindow;
  947. HIViewRef embeddedView;
  948. bool recursiveResize;
  949. Time creationTime;
  950. EventHandlerRef eventHandlerRef;
  951. };
  952. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  953. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  954. END_JUCE_NAMESPACE
  955. #endif
  956. #define JUCE_AMALGAMATED_TEMPLATE 1
  957. //==============================================================================
  958. #if JUCE_BUILD_CORE
  959. /*** Start of inlined file: juce_FileLogger.cpp ***/
  960. BEGIN_JUCE_NAMESPACE
  961. FileLogger::FileLogger (const File& logFile_,
  962. const String& welcomeMessage,
  963. const int maxInitialFileSizeBytes)
  964. : logFile (logFile_)
  965. {
  966. if (maxInitialFileSizeBytes >= 0)
  967. trimFileSize (maxInitialFileSizeBytes);
  968. if (! logFile_.exists())
  969. {
  970. // do this so that the parent directories get created..
  971. logFile_.create();
  972. }
  973. String welcome;
  974. welcome << "\r\n**********************************************************\r\n"
  975. << welcomeMessage
  976. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  977. << "\r\n";
  978. logMessage (welcome);
  979. }
  980. FileLogger::~FileLogger()
  981. {
  982. }
  983. void FileLogger::logMessage (const String& message)
  984. {
  985. DBG (message);
  986. const ScopedLock sl (logLock);
  987. FileOutputStream out (logFile, 256);
  988. out << message << "\r\n";
  989. }
  990. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  991. {
  992. if (maxFileSizeBytes <= 0)
  993. {
  994. logFile.deleteFile();
  995. }
  996. else
  997. {
  998. const int64 fileSize = logFile.getSize();
  999. if (fileSize > maxFileSizeBytes)
  1000. {
  1001. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1002. jassert (in != 0);
  1003. if (in != 0)
  1004. {
  1005. in->setPosition (fileSize - maxFileSizeBytes);
  1006. String content;
  1007. {
  1008. MemoryBlock contentToSave;
  1009. contentToSave.setSize (maxFileSizeBytes + 4);
  1010. contentToSave.fillWith (0);
  1011. in->read (contentToSave.getData(), maxFileSizeBytes);
  1012. in = 0;
  1013. content = contentToSave.toString();
  1014. }
  1015. int newStart = 0;
  1016. while (newStart < fileSize
  1017. && content[newStart] != '\n'
  1018. && content[newStart] != '\r')
  1019. ++newStart;
  1020. logFile.deleteFile();
  1021. logFile.appendText (content.substring (newStart), false, false);
  1022. }
  1023. }
  1024. }
  1025. }
  1026. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1027. const String& logFileName,
  1028. const String& welcomeMessage,
  1029. const int maxInitialFileSizeBytes)
  1030. {
  1031. #if JUCE_MAC
  1032. File logFile ("~/Library/Logs");
  1033. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1034. .getChildFile (logFileName);
  1035. #else
  1036. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1037. if (logFile.isDirectory())
  1038. {
  1039. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1040. .getChildFile (logFileName);
  1041. }
  1042. #endif
  1043. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1044. }
  1045. END_JUCE_NAMESPACE
  1046. /*** End of inlined file: juce_FileLogger.cpp ***/
  1047. /*** Start of inlined file: juce_Logger.cpp ***/
  1048. BEGIN_JUCE_NAMESPACE
  1049. Logger::Logger()
  1050. {
  1051. }
  1052. Logger::~Logger()
  1053. {
  1054. }
  1055. Logger* Logger::currentLogger = 0;
  1056. void Logger::setCurrentLogger (Logger* const newLogger,
  1057. const bool deleteOldLogger)
  1058. {
  1059. Logger* const oldLogger = currentLogger;
  1060. currentLogger = newLogger;
  1061. if (deleteOldLogger)
  1062. delete oldLogger;
  1063. }
  1064. void Logger::writeToLog (const String& message)
  1065. {
  1066. if (currentLogger != 0)
  1067. currentLogger->logMessage (message);
  1068. else
  1069. outputDebugString (message);
  1070. }
  1071. #if JUCE_LOG_ASSERTIONS
  1072. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1073. {
  1074. String m ("JUCE Assertion failure in ");
  1075. m << filename << ", line " << lineNum;
  1076. Logger::writeToLog (m);
  1077. }
  1078. #endif
  1079. END_JUCE_NAMESPACE
  1080. /*** End of inlined file: juce_Logger.cpp ***/
  1081. /*** Start of inlined file: juce_Random.cpp ***/
  1082. BEGIN_JUCE_NAMESPACE
  1083. Random::Random (const int64 seedValue) throw()
  1084. : seed (seedValue)
  1085. {
  1086. }
  1087. Random::~Random() throw()
  1088. {
  1089. }
  1090. void Random::setSeed (const int64 newSeed) throw()
  1091. {
  1092. seed = newSeed;
  1093. }
  1094. void Random::combineSeed (const int64 seedValue) throw()
  1095. {
  1096. seed ^= nextInt64() ^ seedValue;
  1097. }
  1098. void Random::setSeedRandomly()
  1099. {
  1100. combineSeed ((int64) (pointer_sized_int) this);
  1101. combineSeed (Time::getMillisecondCounter());
  1102. combineSeed (Time::getHighResolutionTicks());
  1103. combineSeed (Time::getHighResolutionTicksPerSecond());
  1104. combineSeed (Time::currentTimeMillis());
  1105. }
  1106. int Random::nextInt() throw()
  1107. {
  1108. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1109. return (int) (seed >> 16);
  1110. }
  1111. int Random::nextInt (const int maxValue) throw()
  1112. {
  1113. jassert (maxValue > 0);
  1114. return (nextInt() & 0x7fffffff) % maxValue;
  1115. }
  1116. int64 Random::nextInt64() throw()
  1117. {
  1118. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1119. }
  1120. bool Random::nextBool() throw()
  1121. {
  1122. return (nextInt() & 0x80000000) != 0;
  1123. }
  1124. float Random::nextFloat() throw()
  1125. {
  1126. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1127. }
  1128. double Random::nextDouble() throw()
  1129. {
  1130. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1131. }
  1132. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1133. {
  1134. BigInteger n;
  1135. do
  1136. {
  1137. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1138. }
  1139. while (n >= maximumValue);
  1140. return n;
  1141. }
  1142. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1143. {
  1144. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1145. while ((startBit & 31) != 0 && numBits > 0)
  1146. {
  1147. arrayToChange.setBit (startBit++, nextBool());
  1148. --numBits;
  1149. }
  1150. while (numBits >= 32)
  1151. {
  1152. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1153. startBit += 32;
  1154. numBits -= 32;
  1155. }
  1156. while (--numBits >= 0)
  1157. arrayToChange.setBit (startBit + numBits, nextBool());
  1158. }
  1159. Random& Random::getSystemRandom() throw()
  1160. {
  1161. static Random sysRand (1);
  1162. return sysRand;
  1163. }
  1164. END_JUCE_NAMESPACE
  1165. /*** End of inlined file: juce_Random.cpp ***/
  1166. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1167. BEGIN_JUCE_NAMESPACE
  1168. RelativeTime::RelativeTime (const double seconds_) throw()
  1169. : seconds (seconds_)
  1170. {
  1171. }
  1172. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1173. : seconds (other.seconds)
  1174. {
  1175. }
  1176. RelativeTime::~RelativeTime() throw()
  1177. {
  1178. }
  1179. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1180. {
  1181. return RelativeTime (milliseconds * 0.001);
  1182. }
  1183. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1184. {
  1185. return RelativeTime (milliseconds * 0.001);
  1186. }
  1187. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1188. {
  1189. return RelativeTime (numberOfMinutes * 60.0);
  1190. }
  1191. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1192. {
  1193. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1194. }
  1195. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1196. {
  1197. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1198. }
  1199. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1200. {
  1201. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1202. }
  1203. int64 RelativeTime::inMilliseconds() const throw()
  1204. {
  1205. return (int64) (seconds * 1000.0);
  1206. }
  1207. double RelativeTime::inMinutes() const throw()
  1208. {
  1209. return seconds / 60.0;
  1210. }
  1211. double RelativeTime::inHours() const throw()
  1212. {
  1213. return seconds / (60.0 * 60.0);
  1214. }
  1215. double RelativeTime::inDays() const throw()
  1216. {
  1217. return seconds / (60.0 * 60.0 * 24.0);
  1218. }
  1219. double RelativeTime::inWeeks() const throw()
  1220. {
  1221. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1222. }
  1223. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1224. {
  1225. if (seconds < 0.001 && seconds > -0.001)
  1226. return returnValueForZeroTime;
  1227. String result;
  1228. if (seconds < 0)
  1229. result = "-";
  1230. int fieldsShown = 0;
  1231. int n = abs ((int) inWeeks());
  1232. if (n > 0)
  1233. {
  1234. result << n << ((n == 1) ? TRANS(" week ")
  1235. : TRANS(" weeks "));
  1236. ++fieldsShown;
  1237. }
  1238. n = abs ((int) inDays()) % 7;
  1239. if (n > 0)
  1240. {
  1241. result << n << ((n == 1) ? TRANS(" day ")
  1242. : TRANS(" days "));
  1243. ++fieldsShown;
  1244. }
  1245. if (fieldsShown < 2)
  1246. {
  1247. n = abs ((int) inHours()) % 24;
  1248. if (n > 0)
  1249. {
  1250. result << n << ((n == 1) ? TRANS(" hr ")
  1251. : TRANS(" hrs "));
  1252. ++fieldsShown;
  1253. }
  1254. if (fieldsShown < 2)
  1255. {
  1256. n = abs ((int) inMinutes()) % 60;
  1257. if (n > 0)
  1258. {
  1259. result << n << ((n == 1) ? TRANS(" min ")
  1260. : TRANS(" mins "));
  1261. ++fieldsShown;
  1262. }
  1263. if (fieldsShown < 2)
  1264. {
  1265. n = abs ((int) inSeconds()) % 60;
  1266. if (n > 0)
  1267. {
  1268. result << n << ((n == 1) ? TRANS(" sec ")
  1269. : TRANS(" secs "));
  1270. ++fieldsShown;
  1271. }
  1272. if (fieldsShown < 1)
  1273. {
  1274. n = abs ((int) inMilliseconds()) % 1000;
  1275. if (n > 0)
  1276. {
  1277. result << n << TRANS(" ms");
  1278. ++fieldsShown;
  1279. }
  1280. }
  1281. }
  1282. }
  1283. }
  1284. return result.trimEnd();
  1285. }
  1286. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1287. {
  1288. seconds = other.seconds;
  1289. return *this;
  1290. }
  1291. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  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. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1298. {
  1299. return RelativeTime (seconds + timeToAdd.seconds);
  1300. }
  1301. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1302. {
  1303. return RelativeTime (seconds - timeToSubtract.seconds);
  1304. }
  1305. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1306. {
  1307. return RelativeTime (seconds + secondsToAdd);
  1308. }
  1309. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1310. {
  1311. return RelativeTime (seconds - secondsToSubtract);
  1312. }
  1313. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1314. {
  1315. seconds += timeToAdd.seconds;
  1316. return *this;
  1317. }
  1318. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1319. {
  1320. seconds -= timeToSubtract.seconds;
  1321. return *this;
  1322. }
  1323. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1324. {
  1325. seconds += secondsToAdd;
  1326. return *this;
  1327. }
  1328. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1329. {
  1330. seconds -= secondsToSubtract;
  1331. return *this;
  1332. }
  1333. END_JUCE_NAMESPACE
  1334. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1335. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1336. BEGIN_JUCE_NAMESPACE
  1337. SystemStats::CPUFlags SystemStats::cpuFlags;
  1338. const String SystemStats::getJUCEVersion()
  1339. {
  1340. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1341. + "." + String (JUCE_MINOR_VERSION)
  1342. + "." + String (JUCE_BUILDNUMBER);
  1343. }
  1344. const StringArray SystemStats::getMACAddressStrings()
  1345. {
  1346. int64 macAddresses [16];
  1347. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1348. StringArray s;
  1349. for (int i = 0; i < numAddresses; ++i)
  1350. {
  1351. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1352. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1353. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1354. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1355. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1356. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1357. }
  1358. return s;
  1359. }
  1360. #ifdef JUCE_DLL
  1361. void* juce_Malloc (const int size)
  1362. {
  1363. return malloc (size);
  1364. }
  1365. void* juce_Calloc (const int size)
  1366. {
  1367. return calloc (1, size);
  1368. }
  1369. void* juce_Realloc (void* const block, const int size)
  1370. {
  1371. return realloc (block, size);
  1372. }
  1373. void juce_Free (void* const block)
  1374. {
  1375. free (block);
  1376. }
  1377. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1378. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1379. {
  1380. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1381. }
  1382. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1383. {
  1384. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1385. }
  1386. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1387. {
  1388. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1389. }
  1390. void juce_DebugFree (void* const block)
  1391. {
  1392. _free_dbg (block, _NORMAL_BLOCK);
  1393. }
  1394. #endif
  1395. #endif
  1396. END_JUCE_NAMESPACE
  1397. /*** End of inlined file: juce_SystemStats.cpp ***/
  1398. /*** Start of inlined file: juce_Time.cpp ***/
  1399. #if JUCE_MSVC
  1400. #pragma warning (push)
  1401. #pragma warning (disable: 4514)
  1402. #endif
  1403. #ifndef JUCE_WINDOWS
  1404. #include <sys/time.h>
  1405. #else
  1406. #include <ctime>
  1407. #endif
  1408. #include <sys/timeb.h>
  1409. #if JUCE_MSVC
  1410. #pragma warning (pop)
  1411. #ifdef _INC_TIME_INL
  1412. #define USE_NEW_SECURE_TIME_FNS
  1413. #endif
  1414. #endif
  1415. BEGIN_JUCE_NAMESPACE
  1416. namespace TimeHelpers
  1417. {
  1418. static struct tm millisToLocal (const int64 millis) throw()
  1419. {
  1420. struct tm result;
  1421. const int64 seconds = millis / 1000;
  1422. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1423. {
  1424. // use extended maths for dates beyond 1970 to 2037..
  1425. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1426. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1427. const int days = (int) (jdm / literal64bit (86400));
  1428. const int a = 32044 + days;
  1429. const int b = (4 * a + 3) / 146097;
  1430. const int c = a - (b * 146097) / 4;
  1431. const int d = (4 * c + 3) / 1461;
  1432. const int e = c - (d * 1461) / 4;
  1433. const int m = (5 * e + 2) / 153;
  1434. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1435. result.tm_mon = m + 2 - 12 * (m / 10);
  1436. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1437. result.tm_wday = (days + 1) % 7;
  1438. result.tm_yday = -1;
  1439. int t = (int) (jdm % literal64bit (86400));
  1440. result.tm_hour = t / 3600;
  1441. t %= 3600;
  1442. result.tm_min = t / 60;
  1443. result.tm_sec = t % 60;
  1444. result.tm_isdst = -1;
  1445. }
  1446. else
  1447. {
  1448. time_t now = static_cast <time_t> (seconds);
  1449. #if JUCE_WINDOWS
  1450. #ifdef USE_NEW_SECURE_TIME_FNS
  1451. if (now >= 0 && now <= 0x793406fff)
  1452. localtime_s (&result, &now);
  1453. else
  1454. zeromem (&result, sizeof (result));
  1455. #else
  1456. result = *localtime (&now);
  1457. #endif
  1458. #else
  1459. // more thread-safe
  1460. localtime_r (&now, &result);
  1461. #endif
  1462. }
  1463. return result;
  1464. }
  1465. static int extendedModulo (const int64 value, const int modulo) throw()
  1466. {
  1467. return (int) (value >= 0 ? (value % modulo)
  1468. : (value - ((value / modulo) + 1) * modulo));
  1469. }
  1470. static uint32 lastMSCounterValue = 0;
  1471. }
  1472. Time::Time() throw()
  1473. : millisSinceEpoch (0)
  1474. {
  1475. }
  1476. Time::Time (const Time& other) throw()
  1477. : millisSinceEpoch (other.millisSinceEpoch)
  1478. {
  1479. }
  1480. Time::Time (const int64 ms) throw()
  1481. : millisSinceEpoch (ms)
  1482. {
  1483. }
  1484. Time::Time (const int year,
  1485. const int month,
  1486. const int day,
  1487. const int hours,
  1488. const int minutes,
  1489. const int seconds,
  1490. const int milliseconds,
  1491. const bool useLocalTime) throw()
  1492. {
  1493. jassert (year > 100); // year must be a 4-digit version
  1494. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1495. {
  1496. // use extended maths for dates beyond 1970 to 2037..
  1497. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1498. : 0;
  1499. const int a = (13 - month) / 12;
  1500. const int y = year + 4800 - a;
  1501. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1502. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1503. - 32045;
  1504. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1505. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1506. + milliseconds;
  1507. }
  1508. else
  1509. {
  1510. struct tm t;
  1511. t.tm_year = year - 1900;
  1512. t.tm_mon = month;
  1513. t.tm_mday = day;
  1514. t.tm_hour = hours;
  1515. t.tm_min = minutes;
  1516. t.tm_sec = seconds;
  1517. t.tm_isdst = -1;
  1518. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1519. if (millisSinceEpoch < 0)
  1520. millisSinceEpoch = 0;
  1521. else
  1522. millisSinceEpoch += milliseconds;
  1523. }
  1524. }
  1525. Time::~Time() throw()
  1526. {
  1527. }
  1528. Time& Time::operator= (const Time& other) throw()
  1529. {
  1530. millisSinceEpoch = other.millisSinceEpoch;
  1531. return *this;
  1532. }
  1533. int64 Time::currentTimeMillis() throw()
  1534. {
  1535. static uint32 lastCounterResult = 0xffffffff;
  1536. static int64 correction = 0;
  1537. const uint32 now = getMillisecondCounter();
  1538. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1539. if (now < lastCounterResult)
  1540. {
  1541. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1542. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1543. {
  1544. // get the time once using normal library calls, and store the difference needed to
  1545. // turn the millisecond counter into a real time.
  1546. #if JUCE_WINDOWS
  1547. struct _timeb t;
  1548. #ifdef USE_NEW_SECURE_TIME_FNS
  1549. _ftime_s (&t);
  1550. #else
  1551. _ftime (&t);
  1552. #endif
  1553. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1554. #else
  1555. struct timeval tv;
  1556. struct timezone tz;
  1557. gettimeofday (&tv, &tz);
  1558. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1559. #endif
  1560. }
  1561. }
  1562. lastCounterResult = now;
  1563. return correction + now;
  1564. }
  1565. uint32 juce_millisecondsSinceStartup() throw();
  1566. uint32 Time::getMillisecondCounter() throw()
  1567. {
  1568. const uint32 now = juce_millisecondsSinceStartup();
  1569. if (now < TimeHelpers::lastMSCounterValue)
  1570. {
  1571. // in multi-threaded apps this might be called concurrently, so
  1572. // make sure that our last counter value only increases and doesn't
  1573. // go backwards..
  1574. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1575. TimeHelpers::lastMSCounterValue = now;
  1576. }
  1577. else
  1578. {
  1579. TimeHelpers::lastMSCounterValue = now;
  1580. }
  1581. return now;
  1582. }
  1583. uint32 Time::getApproximateMillisecondCounter() throw()
  1584. {
  1585. jassert (TimeHelpers::lastMSCounterValue != 0);
  1586. return TimeHelpers::lastMSCounterValue;
  1587. }
  1588. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1589. {
  1590. for (;;)
  1591. {
  1592. const uint32 now = getMillisecondCounter();
  1593. if (now >= targetTime)
  1594. break;
  1595. const int toWait = targetTime - now;
  1596. if (toWait > 2)
  1597. {
  1598. Thread::sleep (jmin (20, toWait >> 1));
  1599. }
  1600. else
  1601. {
  1602. // xxx should consider using mutex_pause on the mac as it apparently
  1603. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1604. for (int i = 10; --i >= 0;)
  1605. Thread::yield();
  1606. }
  1607. }
  1608. }
  1609. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1610. {
  1611. return ticks / (double) getHighResolutionTicksPerSecond();
  1612. }
  1613. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1614. {
  1615. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1616. }
  1617. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1618. {
  1619. return Time (currentTimeMillis());
  1620. }
  1621. const String Time::toString (const bool includeDate,
  1622. const bool includeTime,
  1623. const bool includeSeconds,
  1624. const bool use24HourClock) const throw()
  1625. {
  1626. String result;
  1627. if (includeDate)
  1628. {
  1629. result << getDayOfMonth() << ' '
  1630. << getMonthName (true) << ' '
  1631. << getYear();
  1632. if (includeTime)
  1633. result << ' ';
  1634. }
  1635. if (includeTime)
  1636. {
  1637. const int mins = getMinutes();
  1638. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1639. << (mins < 10 ? ":0" : ":") << mins;
  1640. if (includeSeconds)
  1641. {
  1642. const int secs = getSeconds();
  1643. result << (secs < 10 ? ":0" : ":") << secs;
  1644. }
  1645. if (! use24HourClock)
  1646. result << (isAfternoon() ? "pm" : "am");
  1647. }
  1648. return result.trimEnd();
  1649. }
  1650. const String Time::formatted (const String& format) const
  1651. {
  1652. String buffer;
  1653. int bufferSize = 128;
  1654. buffer.preallocateStorage (bufferSize);
  1655. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1656. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1657. {
  1658. bufferSize += 128;
  1659. buffer.preallocateStorage (bufferSize);
  1660. }
  1661. return buffer;
  1662. }
  1663. int Time::getYear() const throw()
  1664. {
  1665. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1666. }
  1667. int Time::getMonth() const throw()
  1668. {
  1669. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1670. }
  1671. int Time::getDayOfMonth() const throw()
  1672. {
  1673. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1674. }
  1675. int Time::getDayOfWeek() const throw()
  1676. {
  1677. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1678. }
  1679. int Time::getHours() const throw()
  1680. {
  1681. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1682. }
  1683. int Time::getHoursInAmPmFormat() const throw()
  1684. {
  1685. const int hours = getHours();
  1686. if (hours == 0)
  1687. return 12;
  1688. else if (hours <= 12)
  1689. return hours;
  1690. else
  1691. return hours - 12;
  1692. }
  1693. bool Time::isAfternoon() const throw()
  1694. {
  1695. return getHours() >= 12;
  1696. }
  1697. int Time::getMinutes() const throw()
  1698. {
  1699. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1700. }
  1701. int Time::getSeconds() const throw()
  1702. {
  1703. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1704. }
  1705. int Time::getMilliseconds() const throw()
  1706. {
  1707. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1708. }
  1709. bool Time::isDaylightSavingTime() const throw()
  1710. {
  1711. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1712. }
  1713. const String Time::getTimeZone() const throw()
  1714. {
  1715. String zone[2];
  1716. #if JUCE_WINDOWS
  1717. _tzset();
  1718. #ifdef USE_NEW_SECURE_TIME_FNS
  1719. {
  1720. char name [128];
  1721. size_t length;
  1722. for (int i = 0; i < 2; ++i)
  1723. {
  1724. zeromem (name, sizeof (name));
  1725. _get_tzname (&length, name, 127, i);
  1726. zone[i] = name;
  1727. }
  1728. }
  1729. #else
  1730. const char** const zonePtr = (const char**) _tzname;
  1731. zone[0] = zonePtr[0];
  1732. zone[1] = zonePtr[1];
  1733. #endif
  1734. #else
  1735. tzset();
  1736. const char** const zonePtr = (const char**) tzname;
  1737. zone[0] = zonePtr[0];
  1738. zone[1] = zonePtr[1];
  1739. #endif
  1740. if (isDaylightSavingTime())
  1741. {
  1742. zone[0] = zone[1];
  1743. if (zone[0].length() > 3
  1744. && zone[0].containsIgnoreCase ("daylight")
  1745. && zone[0].contains ("GMT"))
  1746. zone[0] = "BST";
  1747. }
  1748. return zone[0].substring (0, 3);
  1749. }
  1750. const String Time::getMonthName (const bool threeLetterVersion) const
  1751. {
  1752. return getMonthName (getMonth(), threeLetterVersion);
  1753. }
  1754. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1755. {
  1756. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1757. }
  1758. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1759. {
  1760. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1761. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1762. monthNumber %= 12;
  1763. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1764. : longMonthNames [monthNumber]);
  1765. }
  1766. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1767. {
  1768. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1769. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1770. day %= 7;
  1771. return TRANS (threeLetterVersion ? shortDayNames [day]
  1772. : longDayNames [day]);
  1773. }
  1774. END_JUCE_NAMESPACE
  1775. /*** End of inlined file: juce_Time.cpp ***/
  1776. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1777. BEGIN_JUCE_NAMESPACE
  1778. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1779. #endif
  1780. #if JUCE_WINDOWS
  1781. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1782. #endif
  1783. #if JUCE_DEBUG
  1784. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1785. #endif
  1786. static bool juceInitialisedNonGUI = false;
  1787. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1788. {
  1789. if (! juceInitialisedNonGUI)
  1790. {
  1791. juceInitialisedNonGUI = true;
  1792. JUCE_AUTORELEASEPOOL
  1793. DBG (SystemStats::getJUCEVersion());
  1794. SystemStats::initialiseStats();
  1795. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1796. }
  1797. // Some basic tests, to keep an eye on things and make sure these types work ok
  1798. // on all platforms. Let me know if any of these assertions fail on your system!
  1799. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1800. static_jassert (sizeof (int8) == 1);
  1801. static_jassert (sizeof (uint8) == 1);
  1802. static_jassert (sizeof (int16) == 2);
  1803. static_jassert (sizeof (uint16) == 2);
  1804. static_jassert (sizeof (int32) == 4);
  1805. static_jassert (sizeof (uint32) == 4);
  1806. static_jassert (sizeof (int64) == 8);
  1807. static_jassert (sizeof (uint64) == 8);
  1808. }
  1809. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1810. {
  1811. if (juceInitialisedNonGUI)
  1812. {
  1813. juceInitialisedNonGUI = false;
  1814. JUCE_AUTORELEASEPOOL
  1815. LocalisedStrings::setCurrentMappings (0);
  1816. Thread::stopAllThreads (3000);
  1817. #if JUCE_WINDOWS
  1818. juce_shutdownWin32Sockets();
  1819. #endif
  1820. #if JUCE_DEBUG
  1821. juce_CheckForDanglingStreams();
  1822. #endif
  1823. }
  1824. }
  1825. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1826. void juce_setCurrentThreadName (const String& name);
  1827. static bool juceInitialisedGUI = false;
  1828. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1829. {
  1830. if (! juceInitialisedGUI)
  1831. {
  1832. juceInitialisedGUI = true;
  1833. JUCE_AUTORELEASEPOOL
  1834. initialiseJuce_NonGUI();
  1835. MessageManager::getInstance();
  1836. LookAndFeel::setDefaultLookAndFeel (0);
  1837. juce_setCurrentThreadName ("Juce Message Thread");
  1838. #if JUCE_DEBUG
  1839. // This section is just for catching people who mess up their project settings and
  1840. // turn RTTI off..
  1841. try
  1842. {
  1843. TextButton tb (String::empty);
  1844. Component* c = &tb;
  1845. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1846. c = dynamic_cast <Button*> (c);
  1847. }
  1848. catch (...)
  1849. {
  1850. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1851. jassertfalse;
  1852. }
  1853. #endif
  1854. }
  1855. }
  1856. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1857. {
  1858. if (juceInitialisedGUI)
  1859. {
  1860. juceInitialisedGUI = false;
  1861. JUCE_AUTORELEASEPOOL
  1862. DeletedAtShutdown::deleteAll();
  1863. LookAndFeel::clearDefaultLookAndFeel();
  1864. delete MessageManager::getInstance();
  1865. shutdownJuce_NonGUI();
  1866. }
  1867. }
  1868. #endif
  1869. #if JUCE_UNIT_TESTS
  1870. class AtomicTests : public UnitTest
  1871. {
  1872. public:
  1873. AtomicTests() : UnitTest ("Atomics") {}
  1874. void runTest()
  1875. {
  1876. beginTest ("Misc");
  1877. char a1[7];
  1878. expect (numElementsInArray(a1) == 7);
  1879. int a2[3];
  1880. expect (numElementsInArray(a2) == 3);
  1881. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1882. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1883. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1884. beginTest ("Atomic types");
  1885. AtomicTester <int>::testInteger (*this);
  1886. AtomicTester <unsigned int>::testInteger (*this);
  1887. AtomicTester <int32>::testInteger (*this);
  1888. AtomicTester <uint32>::testInteger (*this);
  1889. AtomicTester <long>::testInteger (*this);
  1890. AtomicTester <void*>::testInteger (*this);
  1891. AtomicTester <int*>::testInteger (*this);
  1892. AtomicTester <float>::testFloat (*this);
  1893. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1894. AtomicTester <int64>::testInteger (*this);
  1895. AtomicTester <uint64>::testInteger (*this);
  1896. AtomicTester <double>::testFloat (*this);
  1897. #endif
  1898. }
  1899. template <typename Type>
  1900. class AtomicTester
  1901. {
  1902. public:
  1903. AtomicTester() {}
  1904. static void testInteger (UnitTest& test)
  1905. {
  1906. Atomic<Type> a, b;
  1907. a.set ((Type) 10);
  1908. a += (Type) 15;
  1909. a.memoryBarrier();
  1910. a -= (Type) 5;
  1911. ++a; ++a; --a;
  1912. a.memoryBarrier();
  1913. testFloat (test);
  1914. }
  1915. static void testFloat (UnitTest& test)
  1916. {
  1917. Atomic<Type> a, b;
  1918. a = (Type) 21;
  1919. a.memoryBarrier();
  1920. /* These are some simple test cases to check the atomics - let me know
  1921. if any of these assertions fail on your system!
  1922. */
  1923. test.expect (a.get() == (Type) 21);
  1924. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1925. test.expect (a.get() == (Type) 21);
  1926. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1927. test.expect (a.get() == (Type) 101);
  1928. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1929. test.expect (a.get() == (Type) 101);
  1930. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1931. test.expect (a.get() == (Type) 200);
  1932. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1933. test.expect (a.get() == (Type) 300);
  1934. b = a;
  1935. test.expect (b.get() == a.get());
  1936. }
  1937. };
  1938. };
  1939. static AtomicTests atomicUnitTests;
  1940. #endif
  1941. END_JUCE_NAMESPACE
  1942. /*** End of inlined file: juce_Initialisation.cpp ***/
  1943. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1944. BEGIN_JUCE_NAMESPACE
  1945. BigInteger::BigInteger()
  1946. : numValues (4),
  1947. highestBit (-1),
  1948. negative (false)
  1949. {
  1950. values.calloc (numValues + 1);
  1951. }
  1952. BigInteger::BigInteger (const int value)
  1953. : numValues (4),
  1954. highestBit (31),
  1955. negative (value < 0)
  1956. {
  1957. values.calloc (numValues + 1);
  1958. values[0] = abs (value);
  1959. highestBit = getHighestBit();
  1960. }
  1961. BigInteger::BigInteger (int64 value)
  1962. : numValues (4),
  1963. highestBit (63),
  1964. negative (value < 0)
  1965. {
  1966. values.calloc (numValues + 1);
  1967. if (value < 0)
  1968. value = -value;
  1969. values[0] = (unsigned int) value;
  1970. values[1] = (unsigned int) (value >> 32);
  1971. highestBit = getHighestBit();
  1972. }
  1973. BigInteger::BigInteger (const unsigned int value)
  1974. : numValues (4),
  1975. highestBit (31),
  1976. negative (false)
  1977. {
  1978. values.calloc (numValues + 1);
  1979. values[0] = value;
  1980. highestBit = getHighestBit();
  1981. }
  1982. BigInteger::BigInteger (const BigInteger& other)
  1983. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1984. highestBit (other.getHighestBit()),
  1985. negative (other.negative)
  1986. {
  1987. values.malloc (numValues + 1);
  1988. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1989. }
  1990. BigInteger::~BigInteger()
  1991. {
  1992. }
  1993. void BigInteger::swapWith (BigInteger& other) throw()
  1994. {
  1995. values.swapWith (other.values);
  1996. swapVariables (numValues, other.numValues);
  1997. swapVariables (highestBit, other.highestBit);
  1998. swapVariables (negative, other.negative);
  1999. }
  2000. BigInteger& BigInteger::operator= (const BigInteger& other)
  2001. {
  2002. if (this != &other)
  2003. {
  2004. highestBit = other.getHighestBit();
  2005. numValues = jmax (4, (highestBit >> 5) + 1);
  2006. negative = other.negative;
  2007. values.malloc (numValues + 1);
  2008. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2009. }
  2010. return *this;
  2011. }
  2012. void BigInteger::ensureSize (const int numVals)
  2013. {
  2014. if (numVals + 2 >= numValues)
  2015. {
  2016. int oldSize = numValues;
  2017. numValues = ((numVals + 2) * 3) / 2;
  2018. values.realloc (numValues + 1);
  2019. while (oldSize < numValues)
  2020. values [oldSize++] = 0;
  2021. }
  2022. }
  2023. bool BigInteger::operator[] (const int bit) const throw()
  2024. {
  2025. return bit <= highestBit && bit >= 0
  2026. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2027. }
  2028. int BigInteger::toInteger() const throw()
  2029. {
  2030. const int n = (int) (values[0] & 0x7fffffff);
  2031. return negative ? -n : n;
  2032. }
  2033. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2034. {
  2035. BigInteger r;
  2036. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2037. r.ensureSize (numBits >> 5);
  2038. r.highestBit = numBits;
  2039. int i = 0;
  2040. while (numBits > 0)
  2041. {
  2042. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2043. numBits -= 32;
  2044. startBit += 32;
  2045. }
  2046. r.highestBit = r.getHighestBit();
  2047. return r;
  2048. }
  2049. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2050. {
  2051. if (numBits > 32)
  2052. {
  2053. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2054. numBits = 32;
  2055. }
  2056. numBits = jmin (numBits, highestBit + 1 - startBit);
  2057. if (numBits <= 0)
  2058. return 0;
  2059. const int pos = startBit >> 5;
  2060. const int offset = startBit & 31;
  2061. const int endSpace = 32 - numBits;
  2062. uint32 n = ((uint32) values [pos]) >> offset;
  2063. if (offset > endSpace)
  2064. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2065. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2066. }
  2067. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2068. {
  2069. if (numBits > 32)
  2070. {
  2071. jassertfalse;
  2072. numBits = 32;
  2073. }
  2074. for (int i = 0; i < numBits; ++i)
  2075. {
  2076. setBit (startBit + i, (valueToSet & 1) != 0);
  2077. valueToSet >>= 1;
  2078. }
  2079. }
  2080. void BigInteger::clear()
  2081. {
  2082. if (numValues > 16)
  2083. {
  2084. numValues = 4;
  2085. values.calloc (numValues + 1);
  2086. }
  2087. else
  2088. {
  2089. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2090. }
  2091. highestBit = -1;
  2092. negative = false;
  2093. }
  2094. void BigInteger::setBit (const int bit)
  2095. {
  2096. if (bit >= 0)
  2097. {
  2098. if (bit > highestBit)
  2099. {
  2100. ensureSize (bit >> 5);
  2101. highestBit = bit;
  2102. }
  2103. values [bit >> 5] |= (1 << (bit & 31));
  2104. }
  2105. }
  2106. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2107. {
  2108. if (shouldBeSet)
  2109. setBit (bit);
  2110. else
  2111. clearBit (bit);
  2112. }
  2113. void BigInteger::clearBit (const int bit) throw()
  2114. {
  2115. if (bit >= 0 && bit <= highestBit)
  2116. values [bit >> 5] &= ~(1 << (bit & 31));
  2117. }
  2118. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2119. {
  2120. while (--numBits >= 0)
  2121. setBit (startBit++, shouldBeSet);
  2122. }
  2123. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2124. {
  2125. if (bit >= 0)
  2126. shiftBits (1, bit);
  2127. setBit (bit, shouldBeSet);
  2128. }
  2129. bool BigInteger::isZero() const throw()
  2130. {
  2131. return getHighestBit() < 0;
  2132. }
  2133. bool BigInteger::isOne() const throw()
  2134. {
  2135. return getHighestBit() == 0 && ! negative;
  2136. }
  2137. bool BigInteger::isNegative() const throw()
  2138. {
  2139. return negative && ! isZero();
  2140. }
  2141. void BigInteger::setNegative (const bool neg) throw()
  2142. {
  2143. negative = neg;
  2144. }
  2145. void BigInteger::negate() throw()
  2146. {
  2147. negative = (! negative) && ! isZero();
  2148. }
  2149. int BigInteger::countNumberOfSetBits() const throw()
  2150. {
  2151. int total = 0;
  2152. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2153. {
  2154. unsigned int n = values[i];
  2155. if (n == 0xffffffff)
  2156. {
  2157. total += 32;
  2158. }
  2159. else
  2160. {
  2161. while (n != 0)
  2162. {
  2163. total += (n & 1);
  2164. n >>= 1;
  2165. }
  2166. }
  2167. }
  2168. return total;
  2169. }
  2170. int BigInteger::getHighestBit() const throw()
  2171. {
  2172. for (int i = highestBit + 1; --i >= 0;)
  2173. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2174. return i;
  2175. return -1;
  2176. }
  2177. int BigInteger::findNextSetBit (int i) const throw()
  2178. {
  2179. for (; i <= highestBit; ++i)
  2180. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2181. return i;
  2182. return -1;
  2183. }
  2184. int BigInteger::findNextClearBit (int i) const throw()
  2185. {
  2186. for (; i <= highestBit; ++i)
  2187. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2188. break;
  2189. return i;
  2190. }
  2191. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2192. {
  2193. if (other.isNegative())
  2194. return operator-= (-other);
  2195. if (isNegative())
  2196. {
  2197. if (compareAbsolute (other) < 0)
  2198. {
  2199. BigInteger temp (*this);
  2200. temp.negate();
  2201. *this = other;
  2202. operator-= (temp);
  2203. }
  2204. else
  2205. {
  2206. negate();
  2207. operator-= (other);
  2208. negate();
  2209. }
  2210. }
  2211. else
  2212. {
  2213. if (other.highestBit > highestBit)
  2214. highestBit = other.highestBit;
  2215. ++highestBit;
  2216. const int numInts = (highestBit >> 5) + 1;
  2217. ensureSize (numInts);
  2218. int64 remainder = 0;
  2219. for (int i = 0; i <= numInts; ++i)
  2220. {
  2221. if (i < numValues)
  2222. remainder += values[i];
  2223. if (i < other.numValues)
  2224. remainder += other.values[i];
  2225. values[i] = (unsigned int) remainder;
  2226. remainder >>= 32;
  2227. }
  2228. jassert (remainder == 0);
  2229. highestBit = getHighestBit();
  2230. }
  2231. return *this;
  2232. }
  2233. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2234. {
  2235. if (other.isNegative())
  2236. return operator+= (-other);
  2237. if (! isNegative())
  2238. {
  2239. if (compareAbsolute (other) < 0)
  2240. {
  2241. BigInteger temp (other);
  2242. swapWith (temp);
  2243. operator-= (temp);
  2244. negate();
  2245. return *this;
  2246. }
  2247. }
  2248. else
  2249. {
  2250. negate();
  2251. operator+= (other);
  2252. negate();
  2253. return *this;
  2254. }
  2255. const int numInts = (highestBit >> 5) + 1;
  2256. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2257. int64 amountToSubtract = 0;
  2258. for (int i = 0; i <= numInts; ++i)
  2259. {
  2260. if (i <= maxOtherInts)
  2261. amountToSubtract += (int64) other.values[i];
  2262. if (values[i] >= amountToSubtract)
  2263. {
  2264. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2265. amountToSubtract = 0;
  2266. }
  2267. else
  2268. {
  2269. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2270. values[i] = (unsigned int) n;
  2271. amountToSubtract = 1;
  2272. }
  2273. }
  2274. return *this;
  2275. }
  2276. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2277. {
  2278. BigInteger total;
  2279. highestBit = getHighestBit();
  2280. const bool wasNegative = isNegative();
  2281. setNegative (false);
  2282. for (int i = 0; i <= highestBit; ++i)
  2283. {
  2284. if (operator[](i))
  2285. {
  2286. BigInteger n (other);
  2287. n.setNegative (false);
  2288. n <<= i;
  2289. total += n;
  2290. }
  2291. }
  2292. total.setNegative (wasNegative ^ other.isNegative());
  2293. swapWith (total);
  2294. return *this;
  2295. }
  2296. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2297. {
  2298. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2299. const int divHB = divisor.getHighestBit();
  2300. const int ourHB = getHighestBit();
  2301. if (divHB < 0 || ourHB < 0)
  2302. {
  2303. // division by zero
  2304. remainder.clear();
  2305. clear();
  2306. }
  2307. else
  2308. {
  2309. const bool wasNegative = isNegative();
  2310. swapWith (remainder);
  2311. remainder.setNegative (false);
  2312. clear();
  2313. BigInteger temp (divisor);
  2314. temp.setNegative (false);
  2315. int leftShift = ourHB - divHB;
  2316. temp <<= leftShift;
  2317. while (leftShift >= 0)
  2318. {
  2319. if (remainder.compareAbsolute (temp) >= 0)
  2320. {
  2321. remainder -= temp;
  2322. setBit (leftShift);
  2323. }
  2324. if (--leftShift >= 0)
  2325. temp >>= 1;
  2326. }
  2327. negative = wasNegative ^ divisor.isNegative();
  2328. remainder.setNegative (wasNegative);
  2329. }
  2330. }
  2331. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2332. {
  2333. BigInteger remainder;
  2334. divideBy (other, remainder);
  2335. return *this;
  2336. }
  2337. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2338. {
  2339. // this operation doesn't take into account negative values..
  2340. jassert (isNegative() == other.isNegative());
  2341. if (other.highestBit >= 0)
  2342. {
  2343. ensureSize (other.highestBit >> 5);
  2344. int n = (other.highestBit >> 5) + 1;
  2345. while (--n >= 0)
  2346. values[n] |= other.values[n];
  2347. if (other.highestBit > highestBit)
  2348. highestBit = other.highestBit;
  2349. highestBit = getHighestBit();
  2350. }
  2351. return *this;
  2352. }
  2353. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2354. {
  2355. // this operation doesn't take into account negative values..
  2356. jassert (isNegative() == other.isNegative());
  2357. int n = numValues;
  2358. while (n > other.numValues)
  2359. values[--n] = 0;
  2360. while (--n >= 0)
  2361. values[n] &= other.values[n];
  2362. if (other.highestBit < highestBit)
  2363. highestBit = other.highestBit;
  2364. highestBit = getHighestBit();
  2365. return *this;
  2366. }
  2367. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2368. {
  2369. // this operation will only work with the absolute values
  2370. jassert (isNegative() == other.isNegative());
  2371. if (other.highestBit >= 0)
  2372. {
  2373. ensureSize (other.highestBit >> 5);
  2374. int n = (other.highestBit >> 5) + 1;
  2375. while (--n >= 0)
  2376. values[n] ^= other.values[n];
  2377. if (other.highestBit > highestBit)
  2378. highestBit = other.highestBit;
  2379. highestBit = getHighestBit();
  2380. }
  2381. return *this;
  2382. }
  2383. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2384. {
  2385. BigInteger remainder;
  2386. divideBy (divisor, remainder);
  2387. swapWith (remainder);
  2388. return *this;
  2389. }
  2390. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2391. {
  2392. shiftBits (numBitsToShift, 0);
  2393. return *this;
  2394. }
  2395. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2396. {
  2397. return operator<<= (-numBitsToShift);
  2398. }
  2399. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2400. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2401. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2402. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2403. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2404. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2405. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2406. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2407. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2408. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2409. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2410. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2411. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2412. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2413. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2414. int BigInteger::compare (const BigInteger& other) const throw()
  2415. {
  2416. if (isNegative() == other.isNegative())
  2417. {
  2418. const int absComp = compareAbsolute (other);
  2419. return isNegative() ? -absComp : absComp;
  2420. }
  2421. else
  2422. {
  2423. return isNegative() ? -1 : 1;
  2424. }
  2425. }
  2426. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2427. {
  2428. const int h1 = getHighestBit();
  2429. const int h2 = other.getHighestBit();
  2430. if (h1 > h2)
  2431. return 1;
  2432. else if (h1 < h2)
  2433. return -1;
  2434. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2435. if (values[i] != other.values[i])
  2436. return (values[i] > other.values[i]) ? 1 : -1;
  2437. return 0;
  2438. }
  2439. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2440. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2441. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2442. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2443. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2444. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2445. void BigInteger::shiftBits (int bits, const int startBit)
  2446. {
  2447. if (highestBit < 0)
  2448. return;
  2449. if (startBit > 0)
  2450. {
  2451. if (bits < 0)
  2452. {
  2453. // right shift
  2454. for (int i = startBit; i <= highestBit; ++i)
  2455. setBit (i, operator[] (i - bits));
  2456. highestBit = getHighestBit();
  2457. }
  2458. else if (bits > 0)
  2459. {
  2460. // left shift
  2461. for (int i = highestBit + 1; --i >= startBit;)
  2462. setBit (i + bits, operator[] (i));
  2463. while (--bits >= 0)
  2464. clearBit (bits + startBit);
  2465. }
  2466. }
  2467. else
  2468. {
  2469. if (bits < 0)
  2470. {
  2471. // right shift
  2472. bits = -bits;
  2473. if (bits > highestBit)
  2474. {
  2475. clear();
  2476. }
  2477. else
  2478. {
  2479. const int wordsToMove = bits >> 5;
  2480. int top = 1 + (highestBit >> 5) - wordsToMove;
  2481. highestBit -= bits;
  2482. if (wordsToMove > 0)
  2483. {
  2484. int i;
  2485. for (i = 0; i < top; ++i)
  2486. values [i] = values [i + wordsToMove];
  2487. for (i = 0; i < wordsToMove; ++i)
  2488. values [top + i] = 0;
  2489. bits &= 31;
  2490. }
  2491. if (bits != 0)
  2492. {
  2493. const int invBits = 32 - bits;
  2494. --top;
  2495. for (int i = 0; i < top; ++i)
  2496. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2497. values[top] = (values[top] >> bits);
  2498. }
  2499. highestBit = getHighestBit();
  2500. }
  2501. }
  2502. else if (bits > 0)
  2503. {
  2504. // left shift
  2505. ensureSize (((highestBit + bits) >> 5) + 1);
  2506. const int wordsToMove = bits >> 5;
  2507. int top = 1 + (highestBit >> 5);
  2508. highestBit += bits;
  2509. if (wordsToMove > 0)
  2510. {
  2511. int i;
  2512. for (i = top; --i >= 0;)
  2513. values [i + wordsToMove] = values [i];
  2514. for (i = 0; i < wordsToMove; ++i)
  2515. values [i] = 0;
  2516. bits &= 31;
  2517. }
  2518. if (bits != 0)
  2519. {
  2520. const int invBits = 32 - bits;
  2521. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2522. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2523. values [wordsToMove] = values [wordsToMove] << bits;
  2524. }
  2525. highestBit = getHighestBit();
  2526. }
  2527. }
  2528. }
  2529. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2530. {
  2531. while (! m->isZero())
  2532. {
  2533. if (n->compareAbsolute (*m) > 0)
  2534. swapVariables (m, n);
  2535. *m -= *n;
  2536. }
  2537. return *n;
  2538. }
  2539. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2540. {
  2541. BigInteger m (*this);
  2542. while (! n.isZero())
  2543. {
  2544. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2545. return simpleGCD (&m, &n);
  2546. BigInteger temp1 (m), temp2;
  2547. temp1.divideBy (n, temp2);
  2548. m = n;
  2549. n = temp2;
  2550. }
  2551. return m;
  2552. }
  2553. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2554. {
  2555. BigInteger exp (exponent);
  2556. exp %= modulus;
  2557. BigInteger value (1);
  2558. swapWith (value);
  2559. value %= modulus;
  2560. while (! exp.isZero())
  2561. {
  2562. if (exp [0])
  2563. {
  2564. operator*= (value);
  2565. operator%= (modulus);
  2566. }
  2567. value *= value;
  2568. value %= modulus;
  2569. exp >>= 1;
  2570. }
  2571. }
  2572. void BigInteger::inverseModulo (const BigInteger& modulus)
  2573. {
  2574. if (modulus.isOne() || modulus.isNegative())
  2575. {
  2576. clear();
  2577. return;
  2578. }
  2579. if (isNegative() || compareAbsolute (modulus) >= 0)
  2580. operator%= (modulus);
  2581. if (isOne())
  2582. return;
  2583. if (! (*this)[0])
  2584. {
  2585. // not invertible
  2586. clear();
  2587. return;
  2588. }
  2589. BigInteger a1 (modulus);
  2590. BigInteger a2 (*this);
  2591. BigInteger b1 (modulus);
  2592. BigInteger b2 (1);
  2593. while (! a2.isOne())
  2594. {
  2595. BigInteger temp1, temp2, multiplier (a1);
  2596. multiplier.divideBy (a2, temp1);
  2597. temp1 = a2;
  2598. temp1 *= multiplier;
  2599. temp2 = a1;
  2600. temp2 -= temp1;
  2601. a1 = a2;
  2602. a2 = temp2;
  2603. temp1 = b2;
  2604. temp1 *= multiplier;
  2605. temp2 = b1;
  2606. temp2 -= temp1;
  2607. b1 = b2;
  2608. b2 = temp2;
  2609. }
  2610. while (b2.isNegative())
  2611. b2 += modulus;
  2612. b2 %= modulus;
  2613. swapWith (b2);
  2614. }
  2615. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2616. {
  2617. return stream << value.toString (10);
  2618. }
  2619. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2620. {
  2621. String s;
  2622. BigInteger v (*this);
  2623. if (base == 2 || base == 8 || base == 16)
  2624. {
  2625. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2626. static const char* const hexDigits = "0123456789abcdef";
  2627. for (;;)
  2628. {
  2629. const int remainder = v.getBitRangeAsInt (0, bits);
  2630. v >>= bits;
  2631. if (remainder == 0 && v.isZero())
  2632. break;
  2633. s = String::charToString (hexDigits [remainder]) + s;
  2634. }
  2635. }
  2636. else if (base == 10)
  2637. {
  2638. const BigInteger ten (10);
  2639. BigInteger remainder;
  2640. for (;;)
  2641. {
  2642. v.divideBy (ten, remainder);
  2643. if (remainder.isZero() && v.isZero())
  2644. break;
  2645. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2646. }
  2647. }
  2648. else
  2649. {
  2650. jassertfalse; // can't do the specified base!
  2651. return String::empty;
  2652. }
  2653. s = s.paddedLeft ('0', minimumNumCharacters);
  2654. return isNegative() ? "-" + s : s;
  2655. }
  2656. void BigInteger::parseString (const String& text, const int base)
  2657. {
  2658. clear();
  2659. const juce_wchar* t = text;
  2660. if (base == 2 || base == 8 || base == 16)
  2661. {
  2662. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2663. for (;;)
  2664. {
  2665. const juce_wchar c = *t++;
  2666. const int digit = CharacterFunctions::getHexDigitValue (c);
  2667. if (((unsigned int) digit) < (unsigned int) base)
  2668. {
  2669. operator<<= (bits);
  2670. operator+= (digit);
  2671. }
  2672. else if (c == 0)
  2673. {
  2674. break;
  2675. }
  2676. }
  2677. }
  2678. else if (base == 10)
  2679. {
  2680. const BigInteger ten ((unsigned int) 10);
  2681. for (;;)
  2682. {
  2683. const juce_wchar c = *t++;
  2684. if (c >= '0' && c <= '9')
  2685. {
  2686. operator*= (ten);
  2687. operator+= ((int) (c - '0'));
  2688. }
  2689. else if (c == 0)
  2690. {
  2691. break;
  2692. }
  2693. }
  2694. }
  2695. setNegative (text.trimStart().startsWithChar ('-'));
  2696. }
  2697. const MemoryBlock BigInteger::toMemoryBlock() const
  2698. {
  2699. const int numBytes = (getHighestBit() + 8) >> 3;
  2700. MemoryBlock mb ((size_t) numBytes);
  2701. for (int i = 0; i < numBytes; ++i)
  2702. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2703. return mb;
  2704. }
  2705. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2706. {
  2707. clear();
  2708. for (int i = (int) data.getSize(); --i >= 0;)
  2709. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2710. }
  2711. END_JUCE_NAMESPACE
  2712. /*** End of inlined file: juce_BigInteger.cpp ***/
  2713. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2714. BEGIN_JUCE_NAMESPACE
  2715. MemoryBlock::MemoryBlock() throw()
  2716. : size (0)
  2717. {
  2718. }
  2719. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2720. {
  2721. if (initialSize > 0)
  2722. {
  2723. size = initialSize;
  2724. data.allocate (initialSize, initialiseToZero);
  2725. }
  2726. else
  2727. {
  2728. size = 0;
  2729. }
  2730. }
  2731. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2732. : size (other.size)
  2733. {
  2734. if (size > 0)
  2735. {
  2736. jassert (other.data != 0);
  2737. data.malloc (size);
  2738. memcpy (data, other.data, size);
  2739. }
  2740. }
  2741. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2742. : size (jmax ((size_t) 0, sizeInBytes))
  2743. {
  2744. jassert (sizeInBytes >= 0);
  2745. if (size > 0)
  2746. {
  2747. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2748. data.malloc (size);
  2749. if (dataToInitialiseFrom != 0)
  2750. memcpy (data, dataToInitialiseFrom, size);
  2751. }
  2752. }
  2753. MemoryBlock::~MemoryBlock() throw()
  2754. {
  2755. jassert (size >= 0); // should never happen
  2756. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2757. }
  2758. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2759. {
  2760. if (this != &other)
  2761. {
  2762. setSize (other.size, false);
  2763. memcpy (data, other.data, size);
  2764. }
  2765. return *this;
  2766. }
  2767. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2768. {
  2769. return matches (other.data, other.size);
  2770. }
  2771. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2772. {
  2773. return ! operator== (other);
  2774. }
  2775. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2776. {
  2777. return size == dataSize
  2778. && memcmp (data, dataToCompare, size) == 0;
  2779. }
  2780. // this will resize the block to this size
  2781. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2782. {
  2783. if (size != newSize)
  2784. {
  2785. if (newSize <= 0)
  2786. {
  2787. data.free();
  2788. size = 0;
  2789. }
  2790. else
  2791. {
  2792. if (data != 0)
  2793. {
  2794. data.realloc (newSize);
  2795. if (initialiseToZero && (newSize > size))
  2796. zeromem (data + size, newSize - size);
  2797. }
  2798. else
  2799. {
  2800. data.allocate (newSize, initialiseToZero);
  2801. }
  2802. size = newSize;
  2803. }
  2804. }
  2805. }
  2806. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2807. {
  2808. if (size < minimumSize)
  2809. setSize (minimumSize, initialiseToZero);
  2810. }
  2811. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2812. {
  2813. swapVariables (size, other.size);
  2814. data.swapWith (other.data);
  2815. }
  2816. void MemoryBlock::fillWith (const uint8 value) throw()
  2817. {
  2818. memset (data, (int) value, size);
  2819. }
  2820. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2821. {
  2822. if (numBytes > 0)
  2823. {
  2824. const size_t oldSize = size;
  2825. setSize (size + numBytes);
  2826. memcpy (data + oldSize, srcData, numBytes);
  2827. }
  2828. }
  2829. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2830. {
  2831. const char* d = static_cast<const char*> (src);
  2832. if (offset < 0)
  2833. {
  2834. d -= offset;
  2835. num -= offset;
  2836. offset = 0;
  2837. }
  2838. if (offset + num > size)
  2839. num = size - offset;
  2840. if (num > 0)
  2841. memcpy (data + offset, d, num);
  2842. }
  2843. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2844. {
  2845. char* d = static_cast<char*> (dst);
  2846. if (offset < 0)
  2847. {
  2848. zeromem (d, -offset);
  2849. d -= offset;
  2850. num += offset;
  2851. offset = 0;
  2852. }
  2853. if (offset + num > size)
  2854. {
  2855. const size_t newNum = size - offset;
  2856. zeromem (d + newNum, num - newNum);
  2857. num = newNum;
  2858. }
  2859. if (num > 0)
  2860. memcpy (d, data + offset, num);
  2861. }
  2862. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2863. {
  2864. if (startByte < 0)
  2865. {
  2866. numBytesToRemove += startByte;
  2867. startByte = 0;
  2868. }
  2869. if (startByte + numBytesToRemove >= size)
  2870. {
  2871. setSize (startByte);
  2872. }
  2873. else if (numBytesToRemove > 0)
  2874. {
  2875. memmove (data + startByte,
  2876. data + startByte + numBytesToRemove,
  2877. size - (startByte + numBytesToRemove));
  2878. setSize (size - numBytesToRemove);
  2879. }
  2880. }
  2881. const String MemoryBlock::toString() const
  2882. {
  2883. return String (static_cast <const char*> (getData()), size);
  2884. }
  2885. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2886. {
  2887. int res = 0;
  2888. size_t byte = bitRangeStart >> 3;
  2889. int offsetInByte = (int) bitRangeStart & 7;
  2890. size_t bitsSoFar = 0;
  2891. while (numBits > 0 && (size_t) byte < size)
  2892. {
  2893. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2894. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2895. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2896. bitsSoFar += bitsThisTime;
  2897. numBits -= bitsThisTime;
  2898. ++byte;
  2899. offsetInByte = 0;
  2900. }
  2901. return res;
  2902. }
  2903. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2904. {
  2905. size_t byte = bitRangeStart >> 3;
  2906. int offsetInByte = (int) bitRangeStart & 7;
  2907. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2908. while (numBits > 0 && (size_t) byte < size)
  2909. {
  2910. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2911. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2912. const unsigned int tempBits = bitsToSet << offsetInByte;
  2913. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2914. ++byte;
  2915. numBits -= bitsThisTime;
  2916. bitsToSet >>= bitsThisTime;
  2917. mask >>= bitsThisTime;
  2918. offsetInByte = 0;
  2919. }
  2920. }
  2921. void MemoryBlock::loadFromHexString (const String& hex)
  2922. {
  2923. ensureSize (hex.length() >> 1);
  2924. char* dest = data;
  2925. int i = 0;
  2926. for (;;)
  2927. {
  2928. int byte = 0;
  2929. for (int loop = 2; --loop >= 0;)
  2930. {
  2931. byte <<= 4;
  2932. for (;;)
  2933. {
  2934. const juce_wchar c = hex [i++];
  2935. if (c >= '0' && c <= '9')
  2936. {
  2937. byte |= c - '0';
  2938. break;
  2939. }
  2940. else if (c >= 'a' && c <= 'z')
  2941. {
  2942. byte |= c - ('a' - 10);
  2943. break;
  2944. }
  2945. else if (c >= 'A' && c <= 'Z')
  2946. {
  2947. byte |= c - ('A' - 10);
  2948. break;
  2949. }
  2950. else if (c == 0)
  2951. {
  2952. setSize (static_cast <size_t> (dest - data));
  2953. return;
  2954. }
  2955. }
  2956. }
  2957. *dest++ = (char) byte;
  2958. }
  2959. }
  2960. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2961. const String MemoryBlock::toBase64Encoding() const
  2962. {
  2963. const size_t numChars = ((size << 3) + 5) / 6;
  2964. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2965. const int initialLen = destString.length();
  2966. destString.preallocateStorage (initialLen + 2 + numChars);
  2967. juce_wchar* d = destString;
  2968. d += initialLen;
  2969. *d++ = '.';
  2970. for (size_t i = 0; i < numChars; ++i)
  2971. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2972. *d++ = 0;
  2973. return destString;
  2974. }
  2975. bool MemoryBlock::fromBase64Encoding (const String& s)
  2976. {
  2977. const int startPos = s.indexOfChar ('.') + 1;
  2978. if (startPos <= 0)
  2979. return false;
  2980. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2981. setSize (numBytesNeeded, true);
  2982. const int numChars = s.length() - startPos;
  2983. const juce_wchar* srcChars = s;
  2984. srcChars += startPos;
  2985. int pos = 0;
  2986. for (int i = 0; i < numChars; ++i)
  2987. {
  2988. const char c = (char) srcChars[i];
  2989. for (int j = 0; j < 64; ++j)
  2990. {
  2991. if (encodingTable[j] == c)
  2992. {
  2993. setBitRange (pos, 6, j);
  2994. pos += 6;
  2995. break;
  2996. }
  2997. }
  2998. }
  2999. return true;
  3000. }
  3001. END_JUCE_NAMESPACE
  3002. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3003. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3004. BEGIN_JUCE_NAMESPACE
  3005. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3006. : properties (ignoreCaseOfKeyNames),
  3007. fallbackProperties (0),
  3008. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3009. {
  3010. }
  3011. PropertySet::PropertySet (const PropertySet& other)
  3012. : properties (other.properties),
  3013. fallbackProperties (other.fallbackProperties),
  3014. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3015. {
  3016. }
  3017. PropertySet& PropertySet::operator= (const PropertySet& other)
  3018. {
  3019. properties = other.properties;
  3020. fallbackProperties = other.fallbackProperties;
  3021. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3022. propertyChanged();
  3023. return *this;
  3024. }
  3025. PropertySet::~PropertySet()
  3026. {
  3027. }
  3028. void PropertySet::clear()
  3029. {
  3030. const ScopedLock sl (lock);
  3031. if (properties.size() > 0)
  3032. {
  3033. properties.clear();
  3034. propertyChanged();
  3035. }
  3036. }
  3037. const String PropertySet::getValue (const String& keyName,
  3038. const String& defaultValue) const throw()
  3039. {
  3040. const ScopedLock sl (lock);
  3041. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3042. if (index >= 0)
  3043. return properties.getAllValues() [index];
  3044. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3045. : defaultValue;
  3046. }
  3047. int PropertySet::getIntValue (const String& keyName,
  3048. const int defaultValue) const throw()
  3049. {
  3050. const ScopedLock sl (lock);
  3051. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3052. if (index >= 0)
  3053. return properties.getAllValues() [index].getIntValue();
  3054. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3055. : defaultValue;
  3056. }
  3057. double PropertySet::getDoubleValue (const String& keyName,
  3058. const double defaultValue) const throw()
  3059. {
  3060. const ScopedLock sl (lock);
  3061. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3062. if (index >= 0)
  3063. return properties.getAllValues()[index].getDoubleValue();
  3064. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3065. : defaultValue;
  3066. }
  3067. bool PropertySet::getBoolValue (const String& keyName,
  3068. const bool defaultValue) const throw()
  3069. {
  3070. const ScopedLock sl (lock);
  3071. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3072. if (index >= 0)
  3073. return properties.getAllValues() [index].getIntValue() != 0;
  3074. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3075. : defaultValue;
  3076. }
  3077. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3078. {
  3079. XmlDocument doc (getValue (keyName));
  3080. return doc.getDocumentElement();
  3081. }
  3082. void PropertySet::setValue (const String& keyName, const var& v)
  3083. {
  3084. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3085. if (keyName.isNotEmpty())
  3086. {
  3087. const String value (v.toString());
  3088. const ScopedLock sl (lock);
  3089. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3090. if (index < 0 || properties.getAllValues() [index] != value)
  3091. {
  3092. properties.set (keyName, value);
  3093. propertyChanged();
  3094. }
  3095. }
  3096. }
  3097. void PropertySet::removeValue (const String& keyName)
  3098. {
  3099. if (keyName.isNotEmpty())
  3100. {
  3101. const ScopedLock sl (lock);
  3102. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3103. if (index >= 0)
  3104. {
  3105. properties.remove (keyName);
  3106. propertyChanged();
  3107. }
  3108. }
  3109. }
  3110. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3111. {
  3112. setValue (keyName, xml == 0 ? var::null
  3113. : var (xml->createDocument (String::empty, true)));
  3114. }
  3115. bool PropertySet::containsKey (const String& keyName) const throw()
  3116. {
  3117. const ScopedLock sl (lock);
  3118. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3119. }
  3120. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3121. {
  3122. const ScopedLock sl (lock);
  3123. fallbackProperties = fallbackProperties_;
  3124. }
  3125. XmlElement* PropertySet::createXml (const String& nodeName) const
  3126. {
  3127. const ScopedLock sl (lock);
  3128. XmlElement* const xml = new XmlElement (nodeName);
  3129. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3130. {
  3131. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3132. e->setAttribute ("name", properties.getAllKeys()[i]);
  3133. e->setAttribute ("val", properties.getAllValues()[i]);
  3134. }
  3135. return xml;
  3136. }
  3137. void PropertySet::restoreFromXml (const XmlElement& xml)
  3138. {
  3139. const ScopedLock sl (lock);
  3140. clear();
  3141. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3142. {
  3143. if (e->hasAttribute ("name")
  3144. && e->hasAttribute ("val"))
  3145. {
  3146. properties.set (e->getStringAttribute ("name"),
  3147. e->getStringAttribute ("val"));
  3148. }
  3149. }
  3150. if (properties.size() > 0)
  3151. propertyChanged();
  3152. }
  3153. void PropertySet::propertyChanged()
  3154. {
  3155. }
  3156. END_JUCE_NAMESPACE
  3157. /*** End of inlined file: juce_PropertySet.cpp ***/
  3158. /*** Start of inlined file: juce_Identifier.cpp ***/
  3159. BEGIN_JUCE_NAMESPACE
  3160. StringPool& Identifier::getPool()
  3161. {
  3162. static StringPool pool;
  3163. return pool;
  3164. }
  3165. Identifier::Identifier() throw()
  3166. : name (0)
  3167. {
  3168. }
  3169. Identifier::Identifier (const Identifier& other) throw()
  3170. : name (other.name)
  3171. {
  3172. }
  3173. Identifier& Identifier::operator= (const Identifier& other) throw()
  3174. {
  3175. name = other.name;
  3176. return *this;
  3177. }
  3178. Identifier::Identifier (const String& name_)
  3179. : name (Identifier::getPool().getPooledString (name_))
  3180. {
  3181. /* An Identifier string must be suitable for use as a script variable or XML
  3182. attribute, so it can only contain this limited set of characters.. */
  3183. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3184. }
  3185. Identifier::Identifier (const char* const name_)
  3186. : name (Identifier::getPool().getPooledString (name_))
  3187. {
  3188. /* An Identifier string must be suitable for use as a script variable or XML
  3189. attribute, so it can only contain this limited set of characters.. */
  3190. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3191. }
  3192. Identifier::~Identifier()
  3193. {
  3194. }
  3195. END_JUCE_NAMESPACE
  3196. /*** End of inlined file: juce_Identifier.cpp ***/
  3197. /*** Start of inlined file: juce_Variant.cpp ***/
  3198. BEGIN_JUCE_NAMESPACE
  3199. class var::VariantType
  3200. {
  3201. public:
  3202. VariantType() {}
  3203. virtual ~VariantType() {}
  3204. virtual int toInt (const ValueUnion&) const { return 0; }
  3205. virtual double toDouble (const ValueUnion&) const { return 0; }
  3206. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3207. virtual bool toBool (const ValueUnion&) const { return false; }
  3208. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3209. virtual bool isVoid() const throw() { return false; }
  3210. virtual bool isInt() const throw() { return false; }
  3211. virtual bool isBool() const throw() { return false; }
  3212. virtual bool isDouble() const throw() { return false; }
  3213. virtual bool isString() const throw() { return false; }
  3214. virtual bool isObject() const throw() { return false; }
  3215. virtual bool isMethod() const throw() { return false; }
  3216. virtual void cleanUp (ValueUnion&) const throw() {}
  3217. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3218. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3219. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3220. };
  3221. class var::VariantType_Void : public var::VariantType
  3222. {
  3223. public:
  3224. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3225. bool isVoid() const throw() { return true; }
  3226. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3227. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3228. };
  3229. class var::VariantType_Int : public var::VariantType
  3230. {
  3231. public:
  3232. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3233. int toInt (const ValueUnion& data) const { return data.intValue; };
  3234. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3235. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3236. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3237. bool isInt() const throw() { return true; }
  3238. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3239. {
  3240. return otherType.toInt (otherData) == data.intValue;
  3241. }
  3242. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3243. {
  3244. output.writeCompressedInt (5);
  3245. output.writeByte (1);
  3246. output.writeInt (data.intValue);
  3247. }
  3248. };
  3249. class var::VariantType_Double : public var::VariantType
  3250. {
  3251. public:
  3252. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3253. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3254. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3255. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3256. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3257. bool isDouble() const throw() { return true; }
  3258. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3259. {
  3260. return otherType.toDouble (otherData) == data.doubleValue;
  3261. }
  3262. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3263. {
  3264. output.writeCompressedInt (9);
  3265. output.writeByte (4);
  3266. output.writeDouble (data.doubleValue);
  3267. }
  3268. };
  3269. class var::VariantType_Bool : public var::VariantType
  3270. {
  3271. public:
  3272. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3273. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3274. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3275. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3276. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3277. bool isBool() const throw() { return true; }
  3278. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3279. {
  3280. return otherType.toBool (otherData) == data.boolValue;
  3281. }
  3282. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3283. {
  3284. output.writeCompressedInt (1);
  3285. output.writeByte (data.boolValue ? 2 : 3);
  3286. }
  3287. };
  3288. class var::VariantType_String : public var::VariantType
  3289. {
  3290. public:
  3291. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3292. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3293. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3294. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3295. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3296. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3297. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3298. || data.stringValue->trim().equalsIgnoreCase ("true")
  3299. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3300. bool isString() const throw() { return true; }
  3301. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3302. {
  3303. return otherType.toString (otherData) == *data.stringValue;
  3304. }
  3305. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3306. {
  3307. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3308. output.writeCompressedInt (len + 1);
  3309. output.writeByte (5);
  3310. HeapBlock<char> temp (len);
  3311. data.stringValue->copyToUTF8 (temp, len);
  3312. output.write (temp, len);
  3313. }
  3314. };
  3315. class var::VariantType_Object : public var::VariantType
  3316. {
  3317. public:
  3318. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3319. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3320. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3321. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3322. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3323. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3324. bool isObject() const throw() { return true; }
  3325. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3326. {
  3327. return otherType.toObject (otherData) == data.objectValue;
  3328. }
  3329. void writeToStream (const ValueUnion&, OutputStream& output) const
  3330. {
  3331. jassertfalse; // Can't write an object to a stream!
  3332. output.writeCompressedInt (0);
  3333. }
  3334. };
  3335. class var::VariantType_Method : public var::VariantType
  3336. {
  3337. public:
  3338. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3339. const String toString (const ValueUnion&) const { return "Method"; }
  3340. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3341. bool isMethod() const throw() { return true; }
  3342. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3343. {
  3344. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3345. }
  3346. void writeToStream (const ValueUnion&, OutputStream& output) const
  3347. {
  3348. jassertfalse; // Can't write a method to a stream!
  3349. output.writeCompressedInt (0);
  3350. }
  3351. };
  3352. var::var() throw()
  3353. : type (VariantType_Void::getInstance())
  3354. {
  3355. }
  3356. var::~var() throw()
  3357. {
  3358. type->cleanUp (value);
  3359. }
  3360. const var var::null;
  3361. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3362. {
  3363. type->createCopy (value, valueToCopy.value);
  3364. }
  3365. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3366. {
  3367. value.intValue = value_;
  3368. }
  3369. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3370. {
  3371. value.boolValue = value_;
  3372. }
  3373. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3374. {
  3375. value.doubleValue = value_;
  3376. }
  3377. var::var (const String& value_) : type (VariantType_String::getInstance())
  3378. {
  3379. value.stringValue = new String (value_);
  3380. }
  3381. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3382. {
  3383. value.stringValue = new String (value_);
  3384. }
  3385. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3386. {
  3387. value.stringValue = new String (value_);
  3388. }
  3389. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3390. {
  3391. value.objectValue = object;
  3392. if (object != 0)
  3393. object->incReferenceCount();
  3394. }
  3395. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3396. {
  3397. value.methodValue = method_;
  3398. }
  3399. bool var::isVoid() const throw() { return type->isVoid(); }
  3400. bool var::isInt() const throw() { return type->isInt(); }
  3401. bool var::isBool() const throw() { return type->isBool(); }
  3402. bool var::isDouble() const throw() { return type->isDouble(); }
  3403. bool var::isString() const throw() { return type->isString(); }
  3404. bool var::isObject() const throw() { return type->isObject(); }
  3405. bool var::isMethod() const throw() { return type->isMethod(); }
  3406. var::operator int() const { return type->toInt (value); }
  3407. var::operator bool() const { return type->toBool (value); }
  3408. var::operator float() const { return (float) type->toDouble (value); }
  3409. var::operator double() const { return type->toDouble (value); }
  3410. const String var::toString() const { return type->toString (value); }
  3411. var::operator const String() const { return type->toString (value); }
  3412. DynamicObject* var::getObject() const { return type->toObject (value); }
  3413. void var::swapWith (var& other) throw()
  3414. {
  3415. swapVariables (type, other.type);
  3416. swapVariables (value, other.value);
  3417. }
  3418. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3419. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3420. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3421. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3422. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3423. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3424. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3425. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3426. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3427. bool var::equals (const var& other) const throw()
  3428. {
  3429. return type->equals (value, other.value, *other.type);
  3430. }
  3431. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3432. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3433. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3434. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3435. void var::writeToStream (OutputStream& output) const
  3436. {
  3437. type->writeToStream (value, output);
  3438. }
  3439. const var var::readFromStream (InputStream& input)
  3440. {
  3441. const int numBytes = input.readCompressedInt();
  3442. if (numBytes > 0)
  3443. {
  3444. switch (input.readByte())
  3445. {
  3446. case 1: return var (input.readInt());
  3447. case 2: return var (true);
  3448. case 3: return var (false);
  3449. case 4: return var (input.readDouble());
  3450. case 5:
  3451. {
  3452. MemoryOutputStream mo;
  3453. mo.writeFromInputStream (input, numBytes - 1);
  3454. return var (mo.toUTF8());
  3455. }
  3456. default: input.skipNextBytes (numBytes - 1); break;
  3457. }
  3458. }
  3459. return var::null;
  3460. }
  3461. const var var::operator[] (const Identifier& propertyName) const
  3462. {
  3463. DynamicObject* const o = getObject();
  3464. return o != 0 ? o->getProperty (propertyName) : var::null;
  3465. }
  3466. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3467. {
  3468. DynamicObject* const o = getObject();
  3469. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3470. }
  3471. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3472. {
  3473. if (isMethod())
  3474. {
  3475. DynamicObject* const target = targetObject.getObject();
  3476. if (target != 0)
  3477. return (target->*(value.methodValue)) (arguments, numArguments);
  3478. }
  3479. return var::null;
  3480. }
  3481. const var var::call (const Identifier& method) const
  3482. {
  3483. return invoke (method, 0, 0);
  3484. }
  3485. const var var::call (const Identifier& method, const var& arg1) const
  3486. {
  3487. return invoke (method, &arg1, 1);
  3488. }
  3489. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3490. {
  3491. var args[] = { arg1, arg2 };
  3492. return invoke (method, args, 2);
  3493. }
  3494. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3495. {
  3496. var args[] = { arg1, arg2, arg3 };
  3497. return invoke (method, args, 3);
  3498. }
  3499. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3500. {
  3501. var args[] = { arg1, arg2, arg3, arg4 };
  3502. return invoke (method, args, 4);
  3503. }
  3504. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3505. {
  3506. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3507. return invoke (method, args, 5);
  3508. }
  3509. END_JUCE_NAMESPACE
  3510. /*** End of inlined file: juce_Variant.cpp ***/
  3511. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3512. BEGIN_JUCE_NAMESPACE
  3513. NamedValueSet::NamedValue::NamedValue() throw()
  3514. {
  3515. }
  3516. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3517. : name (name_), value (value_)
  3518. {
  3519. }
  3520. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3521. {
  3522. return name == other.name && value == other.value;
  3523. }
  3524. NamedValueSet::NamedValueSet() throw()
  3525. {
  3526. }
  3527. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3528. : values (other.values)
  3529. {
  3530. }
  3531. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3532. {
  3533. values = other.values;
  3534. return *this;
  3535. }
  3536. NamedValueSet::~NamedValueSet()
  3537. {
  3538. }
  3539. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3540. {
  3541. return values == other.values;
  3542. }
  3543. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3544. {
  3545. return ! operator== (other);
  3546. }
  3547. int NamedValueSet::size() const throw()
  3548. {
  3549. return values.size();
  3550. }
  3551. const var& NamedValueSet::operator[] (const Identifier& name) const
  3552. {
  3553. for (int i = values.size(); --i >= 0;)
  3554. {
  3555. const NamedValue& v = values.getReference(i);
  3556. if (v.name == name)
  3557. return v.value;
  3558. }
  3559. return var::null;
  3560. }
  3561. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3562. {
  3563. const var* v = getItem (name);
  3564. return v != 0 ? *v : defaultReturnValue;
  3565. }
  3566. var* NamedValueSet::getItem (const Identifier& name) const
  3567. {
  3568. for (int i = values.size(); --i >= 0;)
  3569. {
  3570. NamedValue& v = values.getReference(i);
  3571. if (v.name == name)
  3572. return &(v.value);
  3573. }
  3574. return 0;
  3575. }
  3576. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3577. {
  3578. for (int i = values.size(); --i >= 0;)
  3579. {
  3580. NamedValue& v = values.getReference(i);
  3581. if (v.name == name)
  3582. {
  3583. if (v.value == newValue)
  3584. return false;
  3585. v.value = newValue;
  3586. return true;
  3587. }
  3588. }
  3589. values.add (NamedValue (name, newValue));
  3590. return true;
  3591. }
  3592. bool NamedValueSet::contains (const Identifier& name) const
  3593. {
  3594. return getItem (name) != 0;
  3595. }
  3596. bool NamedValueSet::remove (const Identifier& name)
  3597. {
  3598. for (int i = values.size(); --i >= 0;)
  3599. {
  3600. if (values.getReference(i).name == name)
  3601. {
  3602. values.remove (i);
  3603. return true;
  3604. }
  3605. }
  3606. return false;
  3607. }
  3608. const Identifier NamedValueSet::getName (const int index) const
  3609. {
  3610. jassert (((unsigned int) index) < (unsigned int) values.size());
  3611. return values [index].name;
  3612. }
  3613. const var NamedValueSet::getValueAt (const int index) const
  3614. {
  3615. jassert (((unsigned int) index) < (unsigned int) values.size());
  3616. return values [index].value;
  3617. }
  3618. void NamedValueSet::clear()
  3619. {
  3620. values.clear();
  3621. }
  3622. END_JUCE_NAMESPACE
  3623. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3624. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3625. BEGIN_JUCE_NAMESPACE
  3626. DynamicObject::DynamicObject()
  3627. {
  3628. }
  3629. DynamicObject::~DynamicObject()
  3630. {
  3631. }
  3632. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3633. {
  3634. var* const v = properties.getItem (propertyName);
  3635. return v != 0 && ! v->isMethod();
  3636. }
  3637. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3638. {
  3639. return properties [propertyName];
  3640. }
  3641. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3642. {
  3643. properties.set (propertyName, newValue);
  3644. }
  3645. void DynamicObject::removeProperty (const Identifier& propertyName)
  3646. {
  3647. properties.remove (propertyName);
  3648. }
  3649. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3650. {
  3651. return getProperty (methodName).isMethod();
  3652. }
  3653. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3654. const var* parameters,
  3655. int numParameters)
  3656. {
  3657. return properties [methodName].invoke (var (this), parameters, numParameters);
  3658. }
  3659. void DynamicObject::setMethod (const Identifier& name,
  3660. var::MethodFunction methodFunction)
  3661. {
  3662. properties.set (name, var (methodFunction));
  3663. }
  3664. void DynamicObject::clear()
  3665. {
  3666. properties.clear();
  3667. }
  3668. END_JUCE_NAMESPACE
  3669. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3670. /*** Start of inlined file: juce_Expression.cpp ***/
  3671. BEGIN_JUCE_NAMESPACE
  3672. class Expression::Helpers
  3673. {
  3674. public:
  3675. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3676. class Constant : public Term
  3677. {
  3678. public:
  3679. Constant (const double value_, bool isResolutionTarget_)
  3680. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3681. Type getType() const throw() { return constantType; }
  3682. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3683. double evaluate (const EvaluationContext&, int) const { return value; }
  3684. int getNumInputs() const { return 0; }
  3685. Term* getInput (int) const { return 0; }
  3686. const TermPtr negated()
  3687. {
  3688. return new Constant (-value, isResolutionTarget);
  3689. }
  3690. const String toString() const
  3691. {
  3692. if (isResolutionTarget)
  3693. return "@" + String (value);
  3694. return String (value);
  3695. }
  3696. double value;
  3697. bool isResolutionTarget;
  3698. };
  3699. class Symbol : public Term
  3700. {
  3701. public:
  3702. explicit Symbol (const String& symbol_)
  3703. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3704. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3705. {}
  3706. Symbol (const String& symbol_, const String& member_)
  3707. : mainSymbol (symbol_),
  3708. member (member_)
  3709. {}
  3710. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3711. {
  3712. if (++recursionDepth > 256)
  3713. throw EvaluationError ("Recursive symbol references");
  3714. try
  3715. {
  3716. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3717. }
  3718. catch (...)
  3719. {}
  3720. return 0;
  3721. }
  3722. Type getType() const throw() { return symbolType; }
  3723. Term* clone() const { return new Symbol (mainSymbol, member); }
  3724. int getNumInputs() const { return 0; }
  3725. Term* getInput (int) const { return 0; }
  3726. const String getSymbolName() const { return toString(); }
  3727. const String toString() const
  3728. {
  3729. return member.isEmpty() ? mainSymbol
  3730. : mainSymbol + "." + member;
  3731. }
  3732. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3733. {
  3734. if (s == mainSymbol)
  3735. return true;
  3736. if (++recursionDepth > 256)
  3737. throw EvaluationError ("Recursive symbol references");
  3738. try
  3739. {
  3740. return c != 0 && c->getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3741. }
  3742. catch (EvaluationError&)
  3743. {
  3744. return false;
  3745. }
  3746. }
  3747. String mainSymbol, member;
  3748. };
  3749. class Function : public Term
  3750. {
  3751. public:
  3752. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3753. : functionName (functionName_), parameters (parameters_)
  3754. {}
  3755. Term* clone() const { return new Function (functionName, parameters); }
  3756. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3757. {
  3758. HeapBlock <double> params (parameters.size());
  3759. for (int i = 0; i < parameters.size(); ++i)
  3760. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3761. return c.evaluateFunction (functionName, params, parameters.size());
  3762. }
  3763. Type getType() const throw() { return functionType; }
  3764. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3765. int getNumInputs() const { return parameters.size(); }
  3766. Term* getInput (int i) const { return parameters [i]; }
  3767. const String getFunctionName() const { return functionName; }
  3768. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3769. {
  3770. for (int i = 0; i < parameters.size(); ++i)
  3771. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3772. return true;
  3773. return false;
  3774. }
  3775. const String toString() const
  3776. {
  3777. if (parameters.size() == 0)
  3778. return functionName + "()";
  3779. String s (functionName + " (");
  3780. for (int i = 0; i < parameters.size(); ++i)
  3781. {
  3782. s << parameters.getUnchecked(i)->toString();
  3783. if (i < parameters.size() - 1)
  3784. s << ", ";
  3785. }
  3786. s << ')';
  3787. return s;
  3788. }
  3789. const String functionName;
  3790. ReferenceCountedArray<Term> parameters;
  3791. };
  3792. class Negate : public Term
  3793. {
  3794. public:
  3795. Negate (const TermPtr& input_) : input (input_)
  3796. {
  3797. jassert (input_ != 0);
  3798. }
  3799. Type getType() const throw() { return operatorType; }
  3800. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3801. int getNumInputs() const { return 1; }
  3802. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3803. Term* clone() const { return new Negate (input->clone()); }
  3804. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3805. const String getFunctionName() const { return "-"; }
  3806. const TermPtr negated()
  3807. {
  3808. return input;
  3809. }
  3810. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3811. {
  3812. jassert (input_ == input);
  3813. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3814. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3815. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3816. }
  3817. const String toString() const
  3818. {
  3819. if (input->getOperatorPrecedence() > 0)
  3820. return "-(" + input->toString() + ")";
  3821. else
  3822. return "-" + input->toString();
  3823. }
  3824. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3825. {
  3826. return input->referencesSymbol (s, c, recursionDepth);
  3827. }
  3828. private:
  3829. const TermPtr input;
  3830. };
  3831. class BinaryTerm : public Term
  3832. {
  3833. public:
  3834. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3835. {
  3836. jassert (left_ != 0 && right_ != 0);
  3837. }
  3838. int getInputIndexFor (const Term* possibleInput) const
  3839. {
  3840. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3841. }
  3842. Type getType() const throw() { return operatorType; }
  3843. int getNumInputs() const { return 2; }
  3844. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3845. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3846. {
  3847. return left->referencesSymbol (s, c, recursionDepth)
  3848. || right->referencesSymbol (s, c, recursionDepth);
  3849. }
  3850. const String toString() const
  3851. {
  3852. String s;
  3853. const int ourPrecendence = getOperatorPrecedence();
  3854. if (left->getOperatorPrecedence() > ourPrecendence)
  3855. s << '(' << left->toString() << ')';
  3856. else
  3857. s = left->toString();
  3858. s << ' ' << getFunctionName() << ' ';
  3859. if (right->getOperatorPrecedence() >= ourPrecendence)
  3860. s << '(' << right->toString() << ')';
  3861. else
  3862. s << right->toString();
  3863. return s;
  3864. }
  3865. protected:
  3866. const TermPtr left, right;
  3867. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3868. {
  3869. jassert (input == left || input == right);
  3870. if (input != left && input != right)
  3871. return 0;
  3872. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3873. if (dest == 0)
  3874. return new Constant (overallTarget, false);
  3875. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3876. }
  3877. };
  3878. class Add : public BinaryTerm
  3879. {
  3880. public:
  3881. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3882. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3883. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3884. int getOperatorPrecedence() const { return 2; }
  3885. const String getFunctionName() const { return "+"; }
  3886. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3887. {
  3888. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3889. if (newDest == 0)
  3890. return 0;
  3891. return new Subtract (newDest, (input == left ? right : left)->clone());
  3892. }
  3893. };
  3894. class Subtract : public BinaryTerm
  3895. {
  3896. public:
  3897. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3898. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3899. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3900. int getOperatorPrecedence() const { return 2; }
  3901. const String getFunctionName() const { return "-"; }
  3902. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3903. {
  3904. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3905. if (newDest == 0)
  3906. return 0;
  3907. if (input == left)
  3908. return new Add (newDest, right->clone());
  3909. else
  3910. return new Subtract (left->clone(), newDest);
  3911. }
  3912. };
  3913. class Multiply : public BinaryTerm
  3914. {
  3915. public:
  3916. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3917. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  3918. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  3919. const String getFunctionName() const { return "*"; }
  3920. int getOperatorPrecedence() const { return 1; }
  3921. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3922. {
  3923. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3924. if (newDest == 0)
  3925. return 0;
  3926. return new Divide (newDest, (input == left ? right : left)->clone());
  3927. }
  3928. };
  3929. class Divide : public BinaryTerm
  3930. {
  3931. public:
  3932. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3933. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  3934. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  3935. const String getFunctionName() const { return "/"; }
  3936. int getOperatorPrecedence() const { return 1; }
  3937. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3938. {
  3939. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3940. if (newDest == 0)
  3941. return 0;
  3942. if (input == left)
  3943. return new Multiply (newDest, right->clone());
  3944. else
  3945. return new Divide (left->clone(), newDest);
  3946. }
  3947. };
  3948. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  3949. {
  3950. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  3951. if (inputIndex >= 0)
  3952. return topLevel;
  3953. for (int i = topLevel->getNumInputs(); --i >= 0;)
  3954. {
  3955. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  3956. if (t != 0)
  3957. return t;
  3958. }
  3959. return 0;
  3960. }
  3961. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  3962. {
  3963. Constant* c = dynamic_cast<Constant*> (term);
  3964. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  3965. return c;
  3966. if (dynamic_cast<Function*> (term) != 0)
  3967. return 0;
  3968. int i;
  3969. const int numIns = term->getNumInputs();
  3970. for (i = 0; i < numIns; ++i)
  3971. {
  3972. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  3973. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  3974. return c;
  3975. }
  3976. for (i = 0; i < numIns; ++i)
  3977. {
  3978. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  3979. if (c != 0)
  3980. return c;
  3981. }
  3982. return 0;
  3983. }
  3984. static bool containsAnySymbols (const Term* const t)
  3985. {
  3986. if (dynamic_cast <const Symbol*> (t) != 0)
  3987. return true;
  3988. for (int i = t->getNumInputs(); --i >= 0;)
  3989. if (containsAnySymbols (t->getInput (i)))
  3990. return true;
  3991. return false;
  3992. }
  3993. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  3994. {
  3995. Symbol* const sym = dynamic_cast <Symbol*> (t);
  3996. if (sym != 0 && sym->mainSymbol == oldName)
  3997. {
  3998. sym->mainSymbol = newName;
  3999. return true;
  4000. }
  4001. bool anyChanged = false;
  4002. for (int i = t->getNumInputs(); --i >= 0;)
  4003. if (renameSymbol (t->getInput (i), oldName, newName))
  4004. anyChanged = true;
  4005. return anyChanged;
  4006. }
  4007. class Parser
  4008. {
  4009. public:
  4010. Parser (const String& stringToParse, int& textIndex_)
  4011. : textString (stringToParse), textIndex (textIndex_)
  4012. {
  4013. text = textString;
  4014. }
  4015. const TermPtr readExpression()
  4016. {
  4017. TermPtr lhs (readMultiplyOrDivideExpression());
  4018. char opType;
  4019. while (lhs != 0 && readOperator ("+-", &opType))
  4020. {
  4021. TermPtr rhs (readMultiplyOrDivideExpression());
  4022. if (rhs == 0)
  4023. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4024. if (opType == '+')
  4025. lhs = new Add (lhs, rhs);
  4026. else
  4027. lhs = new Subtract (lhs, rhs);
  4028. }
  4029. return lhs;
  4030. }
  4031. private:
  4032. const String textString;
  4033. const juce_wchar* text;
  4034. int& textIndex;
  4035. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4036. {
  4037. return c >= '0' && c <= '9';
  4038. }
  4039. void skipWhitespace (int& i)
  4040. {
  4041. while (CharacterFunctions::isWhitespace (text [i]))
  4042. ++i;
  4043. }
  4044. bool readChar (const juce_wchar required)
  4045. {
  4046. if (text[textIndex] == required)
  4047. {
  4048. ++textIndex;
  4049. return true;
  4050. }
  4051. return false;
  4052. }
  4053. bool readOperator (const char* ops, char* const opType = 0)
  4054. {
  4055. skipWhitespace (textIndex);
  4056. while (*ops != 0)
  4057. {
  4058. if (readChar (*ops))
  4059. {
  4060. if (opType != 0)
  4061. *opType = *ops;
  4062. return true;
  4063. }
  4064. ++ops;
  4065. }
  4066. return false;
  4067. }
  4068. bool readIdentifier (String& identifier)
  4069. {
  4070. skipWhitespace (textIndex);
  4071. int i = textIndex;
  4072. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4073. {
  4074. ++i;
  4075. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4076. ++i;
  4077. }
  4078. if (i > textIndex)
  4079. {
  4080. identifier = String (text + textIndex, i - textIndex);
  4081. textIndex = i;
  4082. return true;
  4083. }
  4084. return false;
  4085. }
  4086. Term* readNumber()
  4087. {
  4088. skipWhitespace (textIndex);
  4089. int i = textIndex;
  4090. const bool isResolutionTarget = (text[i] == '@');
  4091. if (isResolutionTarget)
  4092. {
  4093. ++i;
  4094. skipWhitespace (i);
  4095. textIndex = i;
  4096. }
  4097. if (text[i] == '-')
  4098. {
  4099. ++i;
  4100. skipWhitespace (i);
  4101. }
  4102. int numDigits = 0;
  4103. while (isDecimalDigit (text[i]))
  4104. {
  4105. ++i;
  4106. ++numDigits;
  4107. }
  4108. const bool hasPoint = (text[i] == '.');
  4109. if (hasPoint)
  4110. {
  4111. ++i;
  4112. while (isDecimalDigit (text[i]))
  4113. {
  4114. ++i;
  4115. ++numDigits;
  4116. }
  4117. }
  4118. if (numDigits == 0)
  4119. return 0;
  4120. juce_wchar c = text[i];
  4121. const bool hasExponent = (c == 'e' || c == 'E');
  4122. if (hasExponent)
  4123. {
  4124. ++i;
  4125. c = text[i];
  4126. if (c == '+' || c == '-')
  4127. ++i;
  4128. int numExpDigits = 0;
  4129. while (isDecimalDigit (text[i]))
  4130. {
  4131. ++i;
  4132. ++numExpDigits;
  4133. }
  4134. if (numExpDigits == 0)
  4135. return 0;
  4136. }
  4137. const int start = textIndex;
  4138. textIndex = i;
  4139. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4140. }
  4141. const TermPtr readMultiplyOrDivideExpression()
  4142. {
  4143. TermPtr lhs (readUnaryExpression());
  4144. char opType;
  4145. while (lhs != 0 && readOperator ("*/", &opType))
  4146. {
  4147. TermPtr rhs (readUnaryExpression());
  4148. if (rhs == 0)
  4149. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4150. if (opType == '*')
  4151. lhs = new Multiply (lhs, rhs);
  4152. else
  4153. lhs = new Divide (lhs, rhs);
  4154. }
  4155. return lhs;
  4156. }
  4157. const TermPtr readUnaryExpression()
  4158. {
  4159. char opType;
  4160. if (readOperator ("+-", &opType))
  4161. {
  4162. TermPtr term (readUnaryExpression());
  4163. if (term == 0)
  4164. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4165. if (opType == '-')
  4166. term = term->negated();
  4167. return term;
  4168. }
  4169. return readPrimaryExpression();
  4170. }
  4171. const TermPtr readPrimaryExpression()
  4172. {
  4173. TermPtr e (readParenthesisedExpression());
  4174. if (e != 0)
  4175. return e;
  4176. e = readNumber();
  4177. if (e != 0)
  4178. return e;
  4179. String identifier;
  4180. if (readIdentifier (identifier))
  4181. {
  4182. if (readOperator ("(")) // method call...
  4183. {
  4184. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4185. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4186. TermPtr param (readExpression());
  4187. if (param == 0)
  4188. {
  4189. if (readOperator (")"))
  4190. return func.release();
  4191. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4192. }
  4193. f->parameters.add (param);
  4194. while (readOperator (","))
  4195. {
  4196. param = readExpression();
  4197. if (param == 0)
  4198. throw ParseError ("Expected expression after \",\"");
  4199. f->parameters.add (param);
  4200. }
  4201. if (readOperator (")"))
  4202. return func.release();
  4203. throw ParseError ("Expected \")\"");
  4204. }
  4205. else // just a symbol..
  4206. {
  4207. return new Symbol (identifier);
  4208. }
  4209. }
  4210. return 0;
  4211. }
  4212. const TermPtr readParenthesisedExpression()
  4213. {
  4214. if (! readOperator ("("))
  4215. return 0;
  4216. const TermPtr e (readExpression());
  4217. if (e == 0 || ! readOperator (")"))
  4218. return 0;
  4219. return e;
  4220. }
  4221. Parser (const Parser&);
  4222. Parser& operator= (const Parser&);
  4223. };
  4224. };
  4225. Expression::Expression()
  4226. : term (new Expression::Helpers::Constant (0, false))
  4227. {
  4228. }
  4229. Expression::~Expression()
  4230. {
  4231. }
  4232. Expression::Expression (Term* const term_)
  4233. : term (term_)
  4234. {
  4235. jassert (term != 0);
  4236. }
  4237. Expression::Expression (const double constant)
  4238. : term (new Expression::Helpers::Constant (constant, false))
  4239. {
  4240. }
  4241. Expression::Expression (const Expression& other)
  4242. : term (other.term)
  4243. {
  4244. }
  4245. Expression& Expression::operator= (const Expression& other)
  4246. {
  4247. term = other.term;
  4248. return *this;
  4249. }
  4250. Expression::Expression (const String& stringToParse)
  4251. {
  4252. int i = 0;
  4253. Helpers::Parser parser (stringToParse, i);
  4254. term = parser.readExpression();
  4255. if (term == 0)
  4256. term = new Helpers::Constant (0, false);
  4257. }
  4258. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4259. {
  4260. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4261. const Helpers::TermPtr term (parser.readExpression());
  4262. if (term != 0)
  4263. return Expression (term);
  4264. return Expression();
  4265. }
  4266. double Expression::evaluate() const
  4267. {
  4268. return evaluate (Expression::EvaluationContext());
  4269. }
  4270. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4271. {
  4272. return term->evaluate (context, 0);
  4273. }
  4274. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4275. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4276. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4277. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4278. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4279. const String Expression::toString() const
  4280. {
  4281. return term->toString();
  4282. }
  4283. const Expression Expression::symbol (const String& symbol)
  4284. {
  4285. return Expression (new Helpers::Symbol (symbol));
  4286. }
  4287. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4288. {
  4289. ReferenceCountedArray<Term> params;
  4290. for (int i = 0; i < parameters.size(); ++i)
  4291. params.add (parameters.getReference(i).term);
  4292. return Expression (new Helpers::Function (functionName, params));
  4293. }
  4294. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4295. const Expression::EvaluationContext& context) const
  4296. {
  4297. ScopedPointer<Term> newTerm (term->clone());
  4298. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4299. if (termToAdjust == 0)
  4300. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4301. if (termToAdjust == 0)
  4302. {
  4303. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4304. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4305. }
  4306. jassert (termToAdjust != 0);
  4307. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4308. if (parent == 0)
  4309. {
  4310. termToAdjust->value = targetValue;
  4311. }
  4312. else
  4313. {
  4314. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4315. if (reverseTerm == 0)
  4316. return Expression (targetValue);
  4317. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4318. }
  4319. return Expression (newTerm.release());
  4320. }
  4321. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4322. {
  4323. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4324. Expression newExpression (term->clone());
  4325. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4326. return newExpression;
  4327. }
  4328. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4329. {
  4330. return term->referencesSymbol (symbol, context, 0);
  4331. }
  4332. bool Expression::usesAnySymbols() const
  4333. {
  4334. return Helpers::containsAnySymbols (term);
  4335. }
  4336. Expression::Type Expression::getType() const throw()
  4337. {
  4338. return term->getType();
  4339. }
  4340. const String Expression::getSymbol() const
  4341. {
  4342. return term->getSymbolName();
  4343. }
  4344. const String Expression::getFunction() const
  4345. {
  4346. return term->getFunctionName();
  4347. }
  4348. const String Expression::getOperator() const
  4349. {
  4350. return term->getFunctionName();
  4351. }
  4352. int Expression::getNumInputs() const
  4353. {
  4354. return term->getNumInputs();
  4355. }
  4356. const Expression Expression::getInput (int index) const
  4357. {
  4358. return Expression (term->getInput (index));
  4359. }
  4360. int Expression::Term::getOperatorPrecedence() const
  4361. {
  4362. return 0;
  4363. }
  4364. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4365. {
  4366. return false;
  4367. }
  4368. int Expression::Term::getInputIndexFor (const Term*) const
  4369. {
  4370. return -1;
  4371. }
  4372. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4373. {
  4374. jassertfalse;
  4375. return 0;
  4376. }
  4377. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4378. {
  4379. return new Helpers::Negate (this);
  4380. }
  4381. const String Expression::Term::getSymbolName() const
  4382. {
  4383. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4384. return String::empty;
  4385. }
  4386. const String Expression::Term::getFunctionName() const
  4387. {
  4388. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4389. return String::empty;
  4390. }
  4391. Expression::ParseError::ParseError (const String& message)
  4392. : description (message)
  4393. {
  4394. DBG ("Expression::ParseError: " + message);
  4395. }
  4396. Expression::EvaluationError::EvaluationError (const String& message)
  4397. : description (message)
  4398. {
  4399. DBG ("Expression::EvaluationError: " + message);
  4400. }
  4401. Expression::EvaluationContext::EvaluationContext() {}
  4402. Expression::EvaluationContext::~EvaluationContext() {}
  4403. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4404. {
  4405. throw EvaluationError ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")));
  4406. }
  4407. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4408. {
  4409. if (numParams > 0)
  4410. {
  4411. if (functionName == "min")
  4412. {
  4413. double v = parameters[0];
  4414. for (int i = 1; i < numParams; ++i)
  4415. v = jmin (v, parameters[i]);
  4416. return v;
  4417. }
  4418. else if (functionName == "max")
  4419. {
  4420. double v = parameters[0];
  4421. for (int i = 1; i < numParams; ++i)
  4422. v = jmax (v, parameters[i]);
  4423. return v;
  4424. }
  4425. else if (numParams == 1)
  4426. {
  4427. if (functionName == "sin")
  4428. return sin (parameters[0]);
  4429. else if (functionName == "cos")
  4430. return cos (parameters[0]);
  4431. else if (functionName == "tan")
  4432. return tan (parameters[0]);
  4433. else if (functionName == "abs")
  4434. return std::abs (parameters[0]);
  4435. }
  4436. }
  4437. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4438. }
  4439. END_JUCE_NAMESPACE
  4440. /*** End of inlined file: juce_Expression.cpp ***/
  4441. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4442. BEGIN_JUCE_NAMESPACE
  4443. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4444. {
  4445. jassert (keyData != 0);
  4446. jassert (keyBytes > 0);
  4447. static const uint32 initialPValues [18] =
  4448. {
  4449. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4450. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4451. 0x9216d5d9, 0x8979fb1b
  4452. };
  4453. static const uint32 initialSValues [4 * 256] =
  4454. {
  4455. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4456. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4457. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4458. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4459. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4460. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4461. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4462. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4463. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4464. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4465. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4466. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4467. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4468. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4469. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4470. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4471. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4472. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4473. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4474. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4475. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4476. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4477. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4478. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4479. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4480. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4481. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4482. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4483. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4484. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4485. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4486. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4487. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4488. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4489. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4490. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4491. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4492. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4493. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4494. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4495. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4496. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4497. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4498. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4499. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4500. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4501. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4502. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4503. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4504. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4505. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4506. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4507. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4508. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4509. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4510. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4511. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4512. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4513. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4514. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4515. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4516. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4517. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4518. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4519. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4520. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4521. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4522. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4523. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4524. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4525. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4526. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4527. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4528. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4529. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4530. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4531. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4532. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4533. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4534. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4535. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4536. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4537. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4538. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4539. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4540. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4541. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4542. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4543. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4544. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4545. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4546. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4547. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4548. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4549. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4550. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4551. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4552. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4553. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4554. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4555. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4556. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4557. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4558. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4559. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4560. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4561. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4562. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4563. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4564. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4565. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4566. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4567. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4568. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4569. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4570. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4571. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4572. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4573. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4574. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4575. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4576. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4577. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4578. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4579. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4580. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4581. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4582. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4583. };
  4584. memcpy (p, initialPValues, sizeof (p));
  4585. int i, j = 0;
  4586. for (i = 4; --i >= 0;)
  4587. {
  4588. s[i].malloc (256);
  4589. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4590. }
  4591. for (i = 0; i < 18; ++i)
  4592. {
  4593. uint32 d = 0;
  4594. for (int k = 0; k < 4; ++k)
  4595. {
  4596. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4597. if (++j >= keyBytes)
  4598. j = 0;
  4599. }
  4600. p[i] = initialPValues[i] ^ d;
  4601. }
  4602. uint32 l = 0, r = 0;
  4603. for (i = 0; i < 18; i += 2)
  4604. {
  4605. encrypt (l, r);
  4606. p[i] = l;
  4607. p[i + 1] = r;
  4608. }
  4609. for (i = 0; i < 4; ++i)
  4610. {
  4611. for (j = 0; j < 256; j += 2)
  4612. {
  4613. encrypt (l, r);
  4614. s[i][j] = l;
  4615. s[i][j + 1] = r;
  4616. }
  4617. }
  4618. }
  4619. BlowFish::BlowFish (const BlowFish& other)
  4620. {
  4621. for (int i = 4; --i >= 0;)
  4622. s[i].malloc (256);
  4623. operator= (other);
  4624. }
  4625. BlowFish& BlowFish::operator= (const BlowFish& other)
  4626. {
  4627. memcpy (p, other.p, sizeof (p));
  4628. for (int i = 4; --i >= 0;)
  4629. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4630. return *this;
  4631. }
  4632. BlowFish::~BlowFish()
  4633. {
  4634. }
  4635. uint32 BlowFish::F (const uint32 x) const throw()
  4636. {
  4637. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4638. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4639. }
  4640. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4641. {
  4642. uint32 l = data1;
  4643. uint32 r = data2;
  4644. for (int i = 0; i < 16; ++i)
  4645. {
  4646. l ^= p[i];
  4647. r ^= F(l);
  4648. swapVariables (l, r);
  4649. }
  4650. data1 = r ^ p[17];
  4651. data2 = l ^ p[16];
  4652. }
  4653. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4654. {
  4655. uint32 l = data1;
  4656. uint32 r = data2;
  4657. for (int i = 17; i > 1; --i)
  4658. {
  4659. l ^= p[i];
  4660. r ^= F(l);
  4661. swapVariables (l, r);
  4662. }
  4663. data1 = r ^ p[0];
  4664. data2 = l ^ p[1];
  4665. }
  4666. END_JUCE_NAMESPACE
  4667. /*** End of inlined file: juce_BlowFish.cpp ***/
  4668. /*** Start of inlined file: juce_MD5.cpp ***/
  4669. BEGIN_JUCE_NAMESPACE
  4670. MD5::MD5()
  4671. {
  4672. zerostruct (result);
  4673. }
  4674. MD5::MD5 (const MD5& other)
  4675. {
  4676. memcpy (result, other.result, sizeof (result));
  4677. }
  4678. MD5& MD5::operator= (const MD5& other)
  4679. {
  4680. memcpy (result, other.result, sizeof (result));
  4681. return *this;
  4682. }
  4683. MD5::MD5 (const MemoryBlock& data)
  4684. {
  4685. ProcessContext context;
  4686. context.processBlock (data.getData(), data.getSize());
  4687. context.finish (result);
  4688. }
  4689. MD5::MD5 (const void* data, const size_t numBytes)
  4690. {
  4691. ProcessContext context;
  4692. context.processBlock (data, numBytes);
  4693. context.finish (result);
  4694. }
  4695. MD5::MD5 (const String& text)
  4696. {
  4697. ProcessContext context;
  4698. const int len = text.length();
  4699. const juce_wchar* const t = text;
  4700. for (int i = 0; i < len; ++i)
  4701. {
  4702. // force the string into integer-sized unicode characters, to try to make it
  4703. // get the same results on all platforms + compilers.
  4704. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4705. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4706. }
  4707. context.finish (result);
  4708. }
  4709. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4710. {
  4711. ProcessContext context;
  4712. if (numBytesToRead < 0)
  4713. numBytesToRead = std::numeric_limits<int64>::max();
  4714. while (numBytesToRead > 0)
  4715. {
  4716. uint8 tempBuffer [512];
  4717. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4718. if (bytesRead <= 0)
  4719. break;
  4720. numBytesToRead -= bytesRead;
  4721. context.processBlock (tempBuffer, bytesRead);
  4722. }
  4723. context.finish (result);
  4724. }
  4725. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4726. {
  4727. processStream (input, numBytesToRead);
  4728. }
  4729. MD5::MD5 (const File& file)
  4730. {
  4731. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4732. if (fin != 0)
  4733. processStream (*fin, -1);
  4734. else
  4735. zerostruct (result);
  4736. }
  4737. MD5::~MD5()
  4738. {
  4739. }
  4740. namespace MD5Functions
  4741. {
  4742. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4743. {
  4744. for (int i = 0; i < (numBytes >> 2); ++i)
  4745. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4746. }
  4747. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4748. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4749. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4750. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4751. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4752. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4753. {
  4754. a += F (b, c, d) + x + ac;
  4755. a = rotateLeft (a, s) + b;
  4756. }
  4757. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4758. {
  4759. a += G (b, c, d) + x + ac;
  4760. a = rotateLeft (a, s) + b;
  4761. }
  4762. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4763. {
  4764. a += H (b, c, d) + x + ac;
  4765. a = rotateLeft (a, s) + b;
  4766. }
  4767. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4768. {
  4769. a += I (b, c, d) + x + ac;
  4770. a = rotateLeft (a, s) + b;
  4771. }
  4772. }
  4773. MD5::ProcessContext::ProcessContext()
  4774. {
  4775. state[0] = 0x67452301;
  4776. state[1] = 0xefcdab89;
  4777. state[2] = 0x98badcfe;
  4778. state[3] = 0x10325476;
  4779. count[0] = 0;
  4780. count[1] = 0;
  4781. }
  4782. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4783. {
  4784. int bufferPos = ((count[0] >> 3) & 0x3F);
  4785. count[0] += (uint32) (dataSize << 3);
  4786. if (count[0] < ((uint32) dataSize << 3))
  4787. count[1]++;
  4788. count[1] += (uint32) (dataSize >> 29);
  4789. const size_t spaceLeft = 64 - bufferPos;
  4790. size_t i = 0;
  4791. if (dataSize >= spaceLeft)
  4792. {
  4793. memcpy (buffer + bufferPos, data, spaceLeft);
  4794. transform (buffer);
  4795. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4796. transform (static_cast <const char*> (data) + i);
  4797. bufferPos = 0;
  4798. }
  4799. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4800. }
  4801. void MD5::ProcessContext::finish (void* const result)
  4802. {
  4803. unsigned char encodedLength[8];
  4804. MD5Functions::encode (encodedLength, count, 8);
  4805. // Pad out to 56 mod 64.
  4806. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4807. const int paddingLength = (index < 56) ? (56 - index)
  4808. : (120 - index);
  4809. uint8 paddingBuffer [64];
  4810. zeromem (paddingBuffer, paddingLength);
  4811. paddingBuffer [0] = 0x80;
  4812. processBlock (paddingBuffer, paddingLength);
  4813. processBlock (encodedLength, 8);
  4814. MD5Functions::encode (result, state, 16);
  4815. zerostruct (buffer);
  4816. }
  4817. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4818. {
  4819. using namespace MD5Functions;
  4820. uint32 a = state[0];
  4821. uint32 b = state[1];
  4822. uint32 c = state[2];
  4823. uint32 d = state[3];
  4824. uint32 x[16];
  4825. encode (x, bufferToTransform, 64);
  4826. enum Constants
  4827. {
  4828. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4829. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4830. };
  4831. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4832. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4833. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4834. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4835. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4836. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4837. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4838. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4839. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4840. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4841. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4842. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4843. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4844. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4845. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4846. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4847. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4848. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4849. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4850. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4851. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4852. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4853. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4854. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4855. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4856. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4857. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4858. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4859. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4860. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4861. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4862. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4863. state[0] += a;
  4864. state[1] += b;
  4865. state[2] += c;
  4866. state[3] += d;
  4867. zerostruct (x);
  4868. }
  4869. const MemoryBlock MD5::getRawChecksumData() const
  4870. {
  4871. return MemoryBlock (result, sizeof (result));
  4872. }
  4873. const String MD5::toHexString() const
  4874. {
  4875. return String::toHexString (result, sizeof (result), 0);
  4876. }
  4877. bool MD5::operator== (const MD5& other) const
  4878. {
  4879. return memcmp (result, other.result, sizeof (result)) == 0;
  4880. }
  4881. bool MD5::operator!= (const MD5& other) const
  4882. {
  4883. return ! operator== (other);
  4884. }
  4885. END_JUCE_NAMESPACE
  4886. /*** End of inlined file: juce_MD5.cpp ***/
  4887. /*** Start of inlined file: juce_Primes.cpp ***/
  4888. BEGIN_JUCE_NAMESPACE
  4889. namespace PrimesHelpers
  4890. {
  4891. static void createSmallSieve (const int numBits, BigInteger& result)
  4892. {
  4893. result.setBit (numBits);
  4894. result.clearBit (numBits); // to enlarge the array
  4895. result.setBit (0);
  4896. int n = 2;
  4897. do
  4898. {
  4899. for (int i = n + n; i < numBits; i += n)
  4900. result.setBit (i);
  4901. n = result.findNextClearBit (n + 1);
  4902. }
  4903. while (n <= (numBits >> 1));
  4904. }
  4905. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4906. const BigInteger& smallSieve, const int smallSieveSize)
  4907. {
  4908. jassert (! base[0]); // must be even!
  4909. result.setBit (numBits);
  4910. result.clearBit (numBits); // to enlarge the array
  4911. int index = smallSieve.findNextClearBit (0);
  4912. do
  4913. {
  4914. const int prime = (index << 1) + 1;
  4915. BigInteger r (base), remainder;
  4916. r.divideBy (prime, remainder);
  4917. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4918. if (r.isZero())
  4919. i += prime;
  4920. if ((i & 1) == 0)
  4921. i += prime;
  4922. i = (i - 1) >> 1;
  4923. while (i < numBits)
  4924. {
  4925. result.setBit (i);
  4926. i += prime;
  4927. }
  4928. index = smallSieve.findNextClearBit (index + 1);
  4929. }
  4930. while (index < smallSieveSize);
  4931. }
  4932. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4933. const int numBits, BigInteger& result, const int certainty)
  4934. {
  4935. for (int i = 0; i < numBits; ++i)
  4936. {
  4937. if (! sieve[i])
  4938. {
  4939. result = base + (unsigned int) ((i << 1) + 1);
  4940. if (Primes::isProbablyPrime (result, certainty))
  4941. return true;
  4942. }
  4943. }
  4944. return false;
  4945. }
  4946. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4947. {
  4948. const BigInteger one (1), two (2);
  4949. const BigInteger nMinusOne (n - one);
  4950. BigInteger d (nMinusOne);
  4951. const int s = d.findNextSetBit (0);
  4952. d >>= s;
  4953. BigInteger smallPrimes;
  4954. int numBitsInSmallPrimes = 0;
  4955. for (;;)
  4956. {
  4957. numBitsInSmallPrimes += 256;
  4958. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4959. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4960. if (numPrimesFound > iterations + 1)
  4961. break;
  4962. }
  4963. int smallPrime = 2;
  4964. while (--iterations >= 0)
  4965. {
  4966. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4967. BigInteger r (smallPrime);
  4968. r.exponentModulo (d, n);
  4969. if (r != one && r != nMinusOne)
  4970. {
  4971. for (int j = 0; j < s; ++j)
  4972. {
  4973. r.exponentModulo (two, n);
  4974. if (r == nMinusOne)
  4975. break;
  4976. }
  4977. if (r != nMinusOne)
  4978. return false;
  4979. }
  4980. }
  4981. return true;
  4982. }
  4983. }
  4984. const BigInteger Primes::createProbablePrime (const int bitLength,
  4985. const int certainty,
  4986. const int* randomSeeds,
  4987. int numRandomSeeds)
  4988. {
  4989. using namespace PrimesHelpers;
  4990. int defaultSeeds [16];
  4991. if (numRandomSeeds <= 0)
  4992. {
  4993. randomSeeds = defaultSeeds;
  4994. numRandomSeeds = numElementsInArray (defaultSeeds);
  4995. Random r (0);
  4996. for (int j = 10; --j >= 0;)
  4997. {
  4998. r.setSeedRandomly();
  4999. for (int i = numRandomSeeds; --i >= 0;)
  5000. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5001. }
  5002. }
  5003. BigInteger smallSieve;
  5004. const int smallSieveSize = 15000;
  5005. createSmallSieve (smallSieveSize, smallSieve);
  5006. BigInteger p;
  5007. for (int i = numRandomSeeds; --i >= 0;)
  5008. {
  5009. BigInteger p2;
  5010. Random r (randomSeeds[i]);
  5011. r.fillBitsRandomly (p2, 0, bitLength);
  5012. p ^= p2;
  5013. }
  5014. p.setBit (bitLength - 1);
  5015. p.clearBit (0);
  5016. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5017. while (p.getHighestBit() < bitLength)
  5018. {
  5019. p += 2 * searchLen;
  5020. BigInteger sieve;
  5021. bigSieve (p, searchLen, sieve,
  5022. smallSieve, smallSieveSize);
  5023. BigInteger candidate;
  5024. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5025. return candidate;
  5026. }
  5027. jassertfalse;
  5028. return BigInteger();
  5029. }
  5030. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5031. {
  5032. using namespace PrimesHelpers;
  5033. if (! number[0])
  5034. return false;
  5035. if (number.getHighestBit() <= 10)
  5036. {
  5037. const int num = number.getBitRangeAsInt (0, 10);
  5038. for (int i = num / 2; --i > 1;)
  5039. if (num % i == 0)
  5040. return false;
  5041. return true;
  5042. }
  5043. else
  5044. {
  5045. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5046. return false;
  5047. return passesMillerRabin (number, certainty);
  5048. }
  5049. }
  5050. END_JUCE_NAMESPACE
  5051. /*** End of inlined file: juce_Primes.cpp ***/
  5052. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5053. BEGIN_JUCE_NAMESPACE
  5054. RSAKey::RSAKey()
  5055. {
  5056. }
  5057. RSAKey::RSAKey (const String& s)
  5058. {
  5059. if (s.containsChar (','))
  5060. {
  5061. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5062. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5063. }
  5064. else
  5065. {
  5066. // the string needs to be two hex numbers, comma-separated..
  5067. jassertfalse;
  5068. }
  5069. }
  5070. RSAKey::~RSAKey()
  5071. {
  5072. }
  5073. bool RSAKey::operator== (const RSAKey& other) const throw()
  5074. {
  5075. return part1 == other.part1 && part2 == other.part2;
  5076. }
  5077. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5078. {
  5079. return ! operator== (other);
  5080. }
  5081. const String RSAKey::toString() const
  5082. {
  5083. return part1.toString (16) + "," + part2.toString (16);
  5084. }
  5085. bool RSAKey::applyToValue (BigInteger& value) const
  5086. {
  5087. if (part1.isZero() || part2.isZero() || value <= 0)
  5088. {
  5089. jassertfalse; // using an uninitialised key
  5090. value.clear();
  5091. return false;
  5092. }
  5093. BigInteger result;
  5094. while (! value.isZero())
  5095. {
  5096. result *= part2;
  5097. BigInteger remainder;
  5098. value.divideBy (part2, remainder);
  5099. remainder.exponentModulo (part1, part2);
  5100. result += remainder;
  5101. }
  5102. value.swapWith (result);
  5103. return true;
  5104. }
  5105. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5106. {
  5107. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5108. // are fast to divide + multiply
  5109. for (int i = 2; i <= 65536; i *= 2)
  5110. {
  5111. const BigInteger e (1 + i);
  5112. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5113. return e;
  5114. }
  5115. BigInteger e (4);
  5116. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5117. ++e;
  5118. return e;
  5119. }
  5120. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5121. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5122. {
  5123. jassert (numBits > 16); // not much point using less than this..
  5124. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5125. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5126. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5127. const BigInteger n (p * q);
  5128. const BigInteger m (--p * --q);
  5129. const BigInteger e (findBestCommonDivisor (p, q));
  5130. BigInteger d (e);
  5131. d.inverseModulo (m);
  5132. publicKey.part1 = e;
  5133. publicKey.part2 = n;
  5134. privateKey.part1 = d;
  5135. privateKey.part2 = n;
  5136. }
  5137. END_JUCE_NAMESPACE
  5138. /*** End of inlined file: juce_RSAKey.cpp ***/
  5139. /*** Start of inlined file: juce_InputStream.cpp ***/
  5140. BEGIN_JUCE_NAMESPACE
  5141. char InputStream::readByte()
  5142. {
  5143. char temp = 0;
  5144. read (&temp, 1);
  5145. return temp;
  5146. }
  5147. bool InputStream::readBool()
  5148. {
  5149. return readByte() != 0;
  5150. }
  5151. short InputStream::readShort()
  5152. {
  5153. char temp[2];
  5154. if (read (temp, 2) == 2)
  5155. return (short) ByteOrder::littleEndianShort (temp);
  5156. return 0;
  5157. }
  5158. short InputStream::readShortBigEndian()
  5159. {
  5160. char temp[2];
  5161. if (read (temp, 2) == 2)
  5162. return (short) ByteOrder::bigEndianShort (temp);
  5163. return 0;
  5164. }
  5165. int InputStream::readInt()
  5166. {
  5167. char temp[4];
  5168. if (read (temp, 4) == 4)
  5169. return (int) ByteOrder::littleEndianInt (temp);
  5170. return 0;
  5171. }
  5172. int InputStream::readIntBigEndian()
  5173. {
  5174. char temp[4];
  5175. if (read (temp, 4) == 4)
  5176. return (int) ByteOrder::bigEndianInt (temp);
  5177. return 0;
  5178. }
  5179. int InputStream::readCompressedInt()
  5180. {
  5181. const unsigned char sizeByte = readByte();
  5182. if (sizeByte == 0)
  5183. return 0;
  5184. const int numBytes = (sizeByte & 0x7f);
  5185. if (numBytes > 4)
  5186. {
  5187. jassertfalse; // trying to read corrupt data - this method must only be used
  5188. // to read data that was written by OutputStream::writeCompressedInt()
  5189. return 0;
  5190. }
  5191. char bytes[4] = { 0, 0, 0, 0 };
  5192. if (read (bytes, numBytes) != numBytes)
  5193. return 0;
  5194. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5195. return (sizeByte >> 7) ? -num : num;
  5196. }
  5197. int64 InputStream::readInt64()
  5198. {
  5199. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5200. if (read (n.asBytes, 8) == 8)
  5201. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5202. return 0;
  5203. }
  5204. int64 InputStream::readInt64BigEndian()
  5205. {
  5206. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5207. if (read (n.asBytes, 8) == 8)
  5208. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5209. return 0;
  5210. }
  5211. float InputStream::readFloat()
  5212. {
  5213. // the union below relies on these types being the same size...
  5214. static_jassert (sizeof (int32) == sizeof (float));
  5215. union { int32 asInt; float asFloat; } n;
  5216. n.asInt = (int32) readInt();
  5217. return n.asFloat;
  5218. }
  5219. float InputStream::readFloatBigEndian()
  5220. {
  5221. union { int32 asInt; float asFloat; } n;
  5222. n.asInt = (int32) readIntBigEndian();
  5223. return n.asFloat;
  5224. }
  5225. double InputStream::readDouble()
  5226. {
  5227. union { int64 asInt; double asDouble; } n;
  5228. n.asInt = readInt64();
  5229. return n.asDouble;
  5230. }
  5231. double InputStream::readDoubleBigEndian()
  5232. {
  5233. union { int64 asInt; double asDouble; } n;
  5234. n.asInt = readInt64BigEndian();
  5235. return n.asDouble;
  5236. }
  5237. const String InputStream::readString()
  5238. {
  5239. MemoryBlock buffer (256);
  5240. char* data = static_cast<char*> (buffer.getData());
  5241. size_t i = 0;
  5242. while ((data[i] = readByte()) != 0)
  5243. {
  5244. if (++i >= buffer.getSize())
  5245. {
  5246. buffer.setSize (buffer.getSize() + 512);
  5247. data = static_cast<char*> (buffer.getData());
  5248. }
  5249. }
  5250. return String::fromUTF8 (data, (int) i);
  5251. }
  5252. const String InputStream::readNextLine()
  5253. {
  5254. MemoryBlock buffer (256);
  5255. char* data = static_cast<char*> (buffer.getData());
  5256. size_t i = 0;
  5257. while ((data[i] = readByte()) != 0)
  5258. {
  5259. if (data[i] == '\n')
  5260. break;
  5261. if (data[i] == '\r')
  5262. {
  5263. const int64 lastPos = getPosition();
  5264. if (readByte() != '\n')
  5265. setPosition (lastPos);
  5266. break;
  5267. }
  5268. if (++i >= buffer.getSize())
  5269. {
  5270. buffer.setSize (buffer.getSize() + 512);
  5271. data = static_cast<char*> (buffer.getData());
  5272. }
  5273. }
  5274. return String::fromUTF8 (data, (int) i);
  5275. }
  5276. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5277. {
  5278. MemoryOutputStream mo (block, true);
  5279. return mo.writeFromInputStream (*this, numBytes);
  5280. }
  5281. const String InputStream::readEntireStreamAsString()
  5282. {
  5283. MemoryOutputStream mo;
  5284. mo.writeFromInputStream (*this, -1);
  5285. return mo.toString();
  5286. }
  5287. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5288. {
  5289. if (numBytesToSkip > 0)
  5290. {
  5291. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5292. HeapBlock<char> temp (skipBufferSize);
  5293. while (numBytesToSkip > 0 && ! isExhausted())
  5294. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5295. }
  5296. }
  5297. END_JUCE_NAMESPACE
  5298. /*** End of inlined file: juce_InputStream.cpp ***/
  5299. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5300. BEGIN_JUCE_NAMESPACE
  5301. #if JUCE_DEBUG
  5302. static Array<void*, CriticalSection> activeStreams;
  5303. void juce_CheckForDanglingStreams()
  5304. {
  5305. /*
  5306. It's always a bad idea to leak any object, but if you're leaking output
  5307. streams, then there's a good chance that you're failing to flush a file
  5308. to disk properly, which could result in corrupted data and other similar
  5309. nastiness..
  5310. */
  5311. jassert (activeStreams.size() == 0);
  5312. };
  5313. #endif
  5314. OutputStream::OutputStream()
  5315. {
  5316. #if JUCE_DEBUG
  5317. activeStreams.add (this);
  5318. #endif
  5319. }
  5320. OutputStream::~OutputStream()
  5321. {
  5322. #if JUCE_DEBUG
  5323. activeStreams.removeValue (this);
  5324. #endif
  5325. }
  5326. void OutputStream::writeBool (const bool b)
  5327. {
  5328. writeByte (b ? (char) 1
  5329. : (char) 0);
  5330. }
  5331. void OutputStream::writeByte (char byte)
  5332. {
  5333. write (&byte, 1);
  5334. }
  5335. void OutputStream::writeShort (short value)
  5336. {
  5337. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5338. write (&v, 2);
  5339. }
  5340. void OutputStream::writeShortBigEndian (short value)
  5341. {
  5342. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5343. write (&v, 2);
  5344. }
  5345. void OutputStream::writeInt (int value)
  5346. {
  5347. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5348. write (&v, 4);
  5349. }
  5350. void OutputStream::writeIntBigEndian (int value)
  5351. {
  5352. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5353. write (&v, 4);
  5354. }
  5355. void OutputStream::writeCompressedInt (int value)
  5356. {
  5357. unsigned int un = (value < 0) ? (unsigned int) -value
  5358. : (unsigned int) value;
  5359. uint8 data[5];
  5360. int num = 0;
  5361. while (un > 0)
  5362. {
  5363. data[++num] = (uint8) un;
  5364. un >>= 8;
  5365. }
  5366. data[0] = (uint8) num;
  5367. if (value < 0)
  5368. data[0] |= 0x80;
  5369. write (data, num + 1);
  5370. }
  5371. void OutputStream::writeInt64 (int64 value)
  5372. {
  5373. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5374. write (&v, 8);
  5375. }
  5376. void OutputStream::writeInt64BigEndian (int64 value)
  5377. {
  5378. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5379. write (&v, 8);
  5380. }
  5381. void OutputStream::writeFloat (float value)
  5382. {
  5383. union { int asInt; float asFloat; } n;
  5384. n.asFloat = value;
  5385. writeInt (n.asInt);
  5386. }
  5387. void OutputStream::writeFloatBigEndian (float value)
  5388. {
  5389. union { int asInt; float asFloat; } n;
  5390. n.asFloat = value;
  5391. writeIntBigEndian (n.asInt);
  5392. }
  5393. void OutputStream::writeDouble (double value)
  5394. {
  5395. union { int64 asInt; double asDouble; } n;
  5396. n.asDouble = value;
  5397. writeInt64 (n.asInt);
  5398. }
  5399. void OutputStream::writeDoubleBigEndian (double value)
  5400. {
  5401. union { int64 asInt; double asDouble; } n;
  5402. n.asDouble = value;
  5403. writeInt64BigEndian (n.asInt);
  5404. }
  5405. void OutputStream::writeString (const String& text)
  5406. {
  5407. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5408. // if lots of large, persistent strings were to be written to streams).
  5409. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5410. HeapBlock<char> temp (numBytes);
  5411. text.copyToUTF8 (temp, numBytes);
  5412. write (temp, numBytes);
  5413. }
  5414. void OutputStream::writeText (const String& text, const bool asUnicode,
  5415. const bool writeUnicodeHeaderBytes)
  5416. {
  5417. if (asUnicode)
  5418. {
  5419. if (writeUnicodeHeaderBytes)
  5420. write ("\x0ff\x0fe", 2);
  5421. const juce_wchar* src = text;
  5422. bool lastCharWasReturn = false;
  5423. while (*src != 0)
  5424. {
  5425. if (*src == L'\n' && ! lastCharWasReturn)
  5426. writeShort ((short) L'\r');
  5427. lastCharWasReturn = (*src == L'\r');
  5428. writeShort ((short) *src++);
  5429. }
  5430. }
  5431. else
  5432. {
  5433. const char* src = text.toUTF8();
  5434. const char* t = src;
  5435. for (;;)
  5436. {
  5437. if (*t == '\n')
  5438. {
  5439. if (t > src)
  5440. write (src, (int) (t - src));
  5441. write ("\r\n", 2);
  5442. src = t + 1;
  5443. }
  5444. else if (*t == '\r')
  5445. {
  5446. if (t[1] == '\n')
  5447. ++t;
  5448. }
  5449. else if (*t == 0)
  5450. {
  5451. if (t > src)
  5452. write (src, (int) (t - src));
  5453. break;
  5454. }
  5455. ++t;
  5456. }
  5457. }
  5458. }
  5459. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5460. {
  5461. if (numBytesToWrite < 0)
  5462. numBytesToWrite = std::numeric_limits<int64>::max();
  5463. int numWritten = 0;
  5464. while (numBytesToWrite > 0 && ! source.isExhausted())
  5465. {
  5466. char buffer [8192];
  5467. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5468. if (num <= 0)
  5469. break;
  5470. write (buffer, num);
  5471. numBytesToWrite -= num;
  5472. numWritten += num;
  5473. }
  5474. return numWritten;
  5475. }
  5476. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5477. {
  5478. return stream << String (number);
  5479. }
  5480. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5481. {
  5482. return stream << String (number);
  5483. }
  5484. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5485. {
  5486. stream.writeByte (character);
  5487. return stream;
  5488. }
  5489. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5490. {
  5491. stream.write (text, (int) strlen (text));
  5492. return stream;
  5493. }
  5494. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5495. {
  5496. stream.write (data.getData(), (int) data.getSize());
  5497. return stream;
  5498. }
  5499. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5500. {
  5501. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5502. if (in != 0)
  5503. stream.writeFromInputStream (*in, -1);
  5504. return stream;
  5505. }
  5506. END_JUCE_NAMESPACE
  5507. /*** End of inlined file: juce_OutputStream.cpp ***/
  5508. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5509. BEGIN_JUCE_NAMESPACE
  5510. DirectoryIterator::DirectoryIterator (const File& directory,
  5511. bool isRecursive_,
  5512. const String& wildCard_,
  5513. const int whatToLookFor_)
  5514. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5515. wildCard (wildCard_),
  5516. path (File::addTrailingSeparator (directory.getFullPathName())),
  5517. index (-1),
  5518. totalNumFiles (-1),
  5519. whatToLookFor (whatToLookFor_),
  5520. isRecursive (isRecursive_)
  5521. {
  5522. // you have to specify the type of files you're looking for!
  5523. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5524. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5525. }
  5526. DirectoryIterator::~DirectoryIterator()
  5527. {
  5528. }
  5529. bool DirectoryIterator::next()
  5530. {
  5531. return next (0, 0, 0, 0, 0, 0);
  5532. }
  5533. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5534. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5535. {
  5536. if (subIterator != 0)
  5537. {
  5538. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5539. return true;
  5540. subIterator = 0;
  5541. }
  5542. String filename;
  5543. bool isDirectory, isHidden;
  5544. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5545. {
  5546. ++index;
  5547. if (! filename.containsOnly ("."))
  5548. {
  5549. const File fileFound (path + filename, 0);
  5550. bool matches = false;
  5551. if (isDirectory)
  5552. {
  5553. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5554. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5555. matches = (whatToLookFor & File::findDirectories) != 0;
  5556. }
  5557. else
  5558. {
  5559. matches = (whatToLookFor & File::findFiles) != 0;
  5560. }
  5561. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5562. if (matches && isRecursive)
  5563. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5564. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5565. matches = ! isHidden;
  5566. if (matches)
  5567. {
  5568. currentFile = fileFound;
  5569. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5570. if (isDirResult != 0) *isDirResult = isDirectory;
  5571. return true;
  5572. }
  5573. else if (subIterator != 0)
  5574. {
  5575. return next();
  5576. }
  5577. }
  5578. }
  5579. return false;
  5580. }
  5581. const File DirectoryIterator::getFile() const
  5582. {
  5583. if (subIterator != 0)
  5584. return subIterator->getFile();
  5585. return currentFile;
  5586. }
  5587. float DirectoryIterator::getEstimatedProgress() const
  5588. {
  5589. if (totalNumFiles < 0)
  5590. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5591. if (totalNumFiles <= 0)
  5592. return 0.0f;
  5593. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5594. : (float) index;
  5595. return detailedIndex / totalNumFiles;
  5596. }
  5597. END_JUCE_NAMESPACE
  5598. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5599. /*** Start of inlined file: juce_File.cpp ***/
  5600. #if ! JUCE_WINDOWS
  5601. #include <pwd.h>
  5602. #endif
  5603. BEGIN_JUCE_NAMESPACE
  5604. File::File (const String& fullPathName)
  5605. : fullPath (parseAbsolutePath (fullPathName))
  5606. {
  5607. }
  5608. File::File (const String& path, int)
  5609. : fullPath (path)
  5610. {
  5611. }
  5612. const File File::createFileWithoutCheckingPath (const String& path)
  5613. {
  5614. return File (path, 0);
  5615. }
  5616. File::File (const File& other)
  5617. : fullPath (other.fullPath)
  5618. {
  5619. }
  5620. File& File::operator= (const String& newPath)
  5621. {
  5622. fullPath = parseAbsolutePath (newPath);
  5623. return *this;
  5624. }
  5625. File& File::operator= (const File& other)
  5626. {
  5627. fullPath = other.fullPath;
  5628. return *this;
  5629. }
  5630. const File File::nonexistent;
  5631. const String File::parseAbsolutePath (const String& p)
  5632. {
  5633. if (p.isEmpty())
  5634. return String::empty;
  5635. #if JUCE_WINDOWS
  5636. // Windows..
  5637. String path (p.replaceCharacter ('/', '\\'));
  5638. if (path.startsWithChar (File::separator))
  5639. {
  5640. if (path[1] != File::separator)
  5641. {
  5642. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5643. If you're trying to parse a string that may be either a relative path or an absolute path,
  5644. you MUST provide a context against which the partial path can be evaluated - you can do
  5645. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5646. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5647. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5648. */
  5649. jassertfalse;
  5650. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5651. }
  5652. }
  5653. else if (! path.containsChar (':'))
  5654. {
  5655. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5656. If you're trying to parse a string that may be either a relative path or an absolute path,
  5657. you MUST provide a context against which the partial path can be evaluated - you can do
  5658. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5659. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5660. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5661. */
  5662. jassertfalse;
  5663. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5664. }
  5665. #else
  5666. // Mac or Linux..
  5667. String path (p.replaceCharacter ('\\', '/'));
  5668. if (path.startsWithChar ('~'))
  5669. {
  5670. if (path[1] == File::separator || path[1] == 0)
  5671. {
  5672. // expand a name of the form "~/abc"
  5673. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5674. + path.substring (1);
  5675. }
  5676. else
  5677. {
  5678. // expand a name of type "~dave/abc"
  5679. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5680. struct passwd* const pw = getpwnam (userName.toUTF8());
  5681. if (pw != 0)
  5682. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5683. }
  5684. }
  5685. else if (! path.startsWithChar (File::separator))
  5686. {
  5687. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5688. If you're trying to parse a string that may be either a relative path or an absolute path,
  5689. you MUST provide a context against which the partial path can be evaluated - you can do
  5690. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5691. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5692. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5693. */
  5694. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5695. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5696. }
  5697. #endif
  5698. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5699. path = path.dropLastCharacters (1);
  5700. return path;
  5701. }
  5702. const String File::addTrailingSeparator (const String& path)
  5703. {
  5704. return path.endsWithChar (File::separator) ? path
  5705. : path + File::separator;
  5706. }
  5707. #if JUCE_LINUX
  5708. #define NAMES_ARE_CASE_SENSITIVE 1
  5709. #endif
  5710. bool File::areFileNamesCaseSensitive()
  5711. {
  5712. #if NAMES_ARE_CASE_SENSITIVE
  5713. return true;
  5714. #else
  5715. return false;
  5716. #endif
  5717. }
  5718. bool File::operator== (const File& other) const
  5719. {
  5720. #if NAMES_ARE_CASE_SENSITIVE
  5721. return fullPath == other.fullPath;
  5722. #else
  5723. return fullPath.equalsIgnoreCase (other.fullPath);
  5724. #endif
  5725. }
  5726. bool File::operator!= (const File& other) const
  5727. {
  5728. return ! operator== (other);
  5729. }
  5730. bool File::operator< (const File& other) const
  5731. {
  5732. #if NAMES_ARE_CASE_SENSITIVE
  5733. return fullPath < other.fullPath;
  5734. #else
  5735. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5736. #endif
  5737. }
  5738. bool File::operator> (const File& other) const
  5739. {
  5740. #if NAMES_ARE_CASE_SENSITIVE
  5741. return fullPath > other.fullPath;
  5742. #else
  5743. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5744. #endif
  5745. }
  5746. bool File::setReadOnly (const bool shouldBeReadOnly,
  5747. const bool applyRecursively) const
  5748. {
  5749. bool worked = true;
  5750. if (applyRecursively && isDirectory())
  5751. {
  5752. Array <File> subFiles;
  5753. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5754. for (int i = subFiles.size(); --i >= 0;)
  5755. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5756. }
  5757. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5758. }
  5759. bool File::deleteRecursively() const
  5760. {
  5761. bool worked = true;
  5762. if (isDirectory())
  5763. {
  5764. Array<File> subFiles;
  5765. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5766. for (int i = subFiles.size(); --i >= 0;)
  5767. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5768. }
  5769. return deleteFile() && worked;
  5770. }
  5771. bool File::moveFileTo (const File& newFile) const
  5772. {
  5773. if (newFile.fullPath == fullPath)
  5774. return true;
  5775. #if ! NAMES_ARE_CASE_SENSITIVE
  5776. if (*this != newFile)
  5777. #endif
  5778. if (! newFile.deleteFile())
  5779. return false;
  5780. return moveInternal (newFile);
  5781. }
  5782. bool File::copyFileTo (const File& newFile) const
  5783. {
  5784. return (*this == newFile)
  5785. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5786. }
  5787. bool File::copyDirectoryTo (const File& newDirectory) const
  5788. {
  5789. if (isDirectory() && newDirectory.createDirectory())
  5790. {
  5791. Array<File> subFiles;
  5792. findChildFiles (subFiles, File::findFiles, false);
  5793. int i;
  5794. for (i = 0; i < subFiles.size(); ++i)
  5795. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5796. return false;
  5797. subFiles.clear();
  5798. findChildFiles (subFiles, File::findDirectories, false);
  5799. for (i = 0; i < subFiles.size(); ++i)
  5800. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5801. return false;
  5802. return true;
  5803. }
  5804. return false;
  5805. }
  5806. const String File::getPathUpToLastSlash() const
  5807. {
  5808. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5809. if (lastSlash > 0)
  5810. return fullPath.substring (0, lastSlash);
  5811. else if (lastSlash == 0)
  5812. return separatorString;
  5813. else
  5814. return fullPath;
  5815. }
  5816. const File File::getParentDirectory() const
  5817. {
  5818. return File (getPathUpToLastSlash(), (int) 0);
  5819. }
  5820. const String File::getFileName() const
  5821. {
  5822. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5823. }
  5824. int File::hashCode() const
  5825. {
  5826. return fullPath.hashCode();
  5827. }
  5828. int64 File::hashCode64() const
  5829. {
  5830. return fullPath.hashCode64();
  5831. }
  5832. const String File::getFileNameWithoutExtension() const
  5833. {
  5834. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5835. const int lastDot = fullPath.lastIndexOfChar ('.');
  5836. if (lastDot > lastSlash)
  5837. return fullPath.substring (lastSlash, lastDot);
  5838. else
  5839. return fullPath.substring (lastSlash);
  5840. }
  5841. bool File::isAChildOf (const File& potentialParent) const
  5842. {
  5843. if (potentialParent == File::nonexistent)
  5844. return false;
  5845. const String ourPath (getPathUpToLastSlash());
  5846. #if NAMES_ARE_CASE_SENSITIVE
  5847. if (potentialParent.fullPath == ourPath)
  5848. #else
  5849. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5850. #endif
  5851. {
  5852. return true;
  5853. }
  5854. else if (potentialParent.fullPath.length() >= ourPath.length())
  5855. {
  5856. return false;
  5857. }
  5858. else
  5859. {
  5860. return getParentDirectory().isAChildOf (potentialParent);
  5861. }
  5862. }
  5863. bool File::isAbsolutePath (const String& path)
  5864. {
  5865. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5866. #if JUCE_WINDOWS
  5867. || (path.isNotEmpty() && path[1] == ':');
  5868. #else
  5869. || path.startsWithChar ('~');
  5870. #endif
  5871. }
  5872. const File File::getChildFile (String relativePath) const
  5873. {
  5874. if (isAbsolutePath (relativePath))
  5875. {
  5876. // the path is really absolute..
  5877. return File (relativePath);
  5878. }
  5879. else
  5880. {
  5881. // it's relative, so remove any ../ or ./ bits at the start.
  5882. String path (fullPath);
  5883. if (relativePath[0] == '.')
  5884. {
  5885. #if JUCE_WINDOWS
  5886. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5887. #else
  5888. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5889. #endif
  5890. while (relativePath[0] == '.')
  5891. {
  5892. if (relativePath[1] == '.')
  5893. {
  5894. if (relativePath [2] == 0 || relativePath[2] == separator)
  5895. {
  5896. const int lastSlash = path.lastIndexOfChar (separator);
  5897. if (lastSlash >= 0)
  5898. path = path.substring (0, lastSlash);
  5899. relativePath = relativePath.substring (3);
  5900. }
  5901. else
  5902. {
  5903. break;
  5904. }
  5905. }
  5906. else if (relativePath[1] == separator)
  5907. {
  5908. relativePath = relativePath.substring (2);
  5909. }
  5910. else
  5911. {
  5912. break;
  5913. }
  5914. }
  5915. }
  5916. return File (addTrailingSeparator (path) + relativePath);
  5917. }
  5918. }
  5919. const File File::getSiblingFile (const String& fileName) const
  5920. {
  5921. return getParentDirectory().getChildFile (fileName);
  5922. }
  5923. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5924. {
  5925. if (bytes == 1)
  5926. {
  5927. return "1 byte";
  5928. }
  5929. else if (bytes < 1024)
  5930. {
  5931. return String ((int) bytes) + " bytes";
  5932. }
  5933. else if (bytes < 1024 * 1024)
  5934. {
  5935. return String (bytes / 1024.0, 1) + " KB";
  5936. }
  5937. else if (bytes < 1024 * 1024 * 1024)
  5938. {
  5939. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5940. }
  5941. else
  5942. {
  5943. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5944. }
  5945. }
  5946. bool File::create() const
  5947. {
  5948. if (exists())
  5949. return true;
  5950. {
  5951. const File parentDir (getParentDirectory());
  5952. if (parentDir == *this || ! parentDir.createDirectory())
  5953. return false;
  5954. FileOutputStream fo (*this, 8);
  5955. }
  5956. return exists();
  5957. }
  5958. bool File::createDirectory() const
  5959. {
  5960. if (! isDirectory())
  5961. {
  5962. const File parentDir (getParentDirectory());
  5963. if (parentDir == *this || ! parentDir.createDirectory())
  5964. return false;
  5965. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5966. return isDirectory();
  5967. }
  5968. return true;
  5969. }
  5970. const Time File::getCreationTime() const
  5971. {
  5972. int64 m, a, c;
  5973. getFileTimesInternal (m, a, c);
  5974. return Time (c);
  5975. }
  5976. const Time File::getLastModificationTime() const
  5977. {
  5978. int64 m, a, c;
  5979. getFileTimesInternal (m, a, c);
  5980. return Time (m);
  5981. }
  5982. const Time File::getLastAccessTime() const
  5983. {
  5984. int64 m, a, c;
  5985. getFileTimesInternal (m, a, c);
  5986. return Time (a);
  5987. }
  5988. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5989. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5990. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5991. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5992. {
  5993. if (! existsAsFile())
  5994. return false;
  5995. FileInputStream in (*this);
  5996. return getSize() == in.readIntoMemoryBlock (destBlock);
  5997. }
  5998. const String File::loadFileAsString() const
  5999. {
  6000. if (! existsAsFile())
  6001. return String::empty;
  6002. FileInputStream in (*this);
  6003. return in.readEntireStreamAsString();
  6004. }
  6005. int File::findChildFiles (Array<File>& results,
  6006. const int whatToLookFor,
  6007. const bool searchRecursively,
  6008. const String& wildCardPattern) const
  6009. {
  6010. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6011. int total = 0;
  6012. while (di.next())
  6013. {
  6014. results.add (di.getFile());
  6015. ++total;
  6016. }
  6017. return total;
  6018. }
  6019. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6020. {
  6021. DirectoryIterator di (*this, false, "*", whatToLookFor);
  6022. int total = 0;
  6023. while (di.next())
  6024. ++total;
  6025. return total;
  6026. }
  6027. bool File::containsSubDirectories() const
  6028. {
  6029. if (isDirectory())
  6030. {
  6031. DirectoryIterator di (*this, false, "*", findDirectories);
  6032. return di.next();
  6033. }
  6034. return false;
  6035. }
  6036. const File File::getNonexistentChildFile (const String& prefix_,
  6037. const String& suffix,
  6038. bool putNumbersInBrackets) const
  6039. {
  6040. File f (getChildFile (prefix_ + suffix));
  6041. if (f.exists())
  6042. {
  6043. int num = 2;
  6044. String prefix (prefix_);
  6045. // remove any bracketed numbers that may already be on the end..
  6046. if (prefix.trim().endsWithChar (')'))
  6047. {
  6048. putNumbersInBrackets = true;
  6049. const int openBracks = prefix.lastIndexOfChar ('(');
  6050. const int closeBracks = prefix.lastIndexOfChar (')');
  6051. if (openBracks > 0
  6052. && closeBracks > openBracks
  6053. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6054. {
  6055. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6056. prefix = prefix.substring (0, openBracks);
  6057. }
  6058. }
  6059. // also use brackets if it ends in a digit.
  6060. putNumbersInBrackets = putNumbersInBrackets
  6061. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6062. do
  6063. {
  6064. if (putNumbersInBrackets)
  6065. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6066. else
  6067. f = getChildFile (prefix + String (num++) + suffix);
  6068. } while (f.exists());
  6069. }
  6070. return f;
  6071. }
  6072. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6073. {
  6074. if (exists())
  6075. {
  6076. return getParentDirectory()
  6077. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6078. getFileExtension(),
  6079. putNumbersInBrackets);
  6080. }
  6081. else
  6082. {
  6083. return *this;
  6084. }
  6085. }
  6086. const String File::getFileExtension() const
  6087. {
  6088. String ext;
  6089. if (! isDirectory())
  6090. {
  6091. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6092. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6093. ext = fullPath.substring (indexOfDot);
  6094. }
  6095. return ext;
  6096. }
  6097. bool File::hasFileExtension (const String& possibleSuffix) const
  6098. {
  6099. if (possibleSuffix.isEmpty())
  6100. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6101. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6102. if (semicolon >= 0)
  6103. {
  6104. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6105. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6106. }
  6107. else
  6108. {
  6109. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6110. {
  6111. if (possibleSuffix.startsWithChar ('.'))
  6112. return true;
  6113. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6114. if (dotPos >= 0)
  6115. return fullPath [dotPos] == '.';
  6116. }
  6117. }
  6118. return false;
  6119. }
  6120. const File File::withFileExtension (const String& newExtension) const
  6121. {
  6122. if (fullPath.isEmpty())
  6123. return File::nonexistent;
  6124. String filePart (getFileName());
  6125. int i = filePart.lastIndexOfChar ('.');
  6126. if (i >= 0)
  6127. filePart = filePart.substring (0, i);
  6128. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6129. filePart << '.';
  6130. return getSiblingFile (filePart + newExtension);
  6131. }
  6132. bool File::startAsProcess (const String& parameters) const
  6133. {
  6134. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6135. }
  6136. FileInputStream* File::createInputStream() const
  6137. {
  6138. if (existsAsFile())
  6139. return new FileInputStream (*this);
  6140. return 0;
  6141. }
  6142. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6143. {
  6144. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6145. if (out->failedToOpen())
  6146. return 0;
  6147. return out.release();
  6148. }
  6149. bool File::appendData (const void* const dataToAppend,
  6150. const int numberOfBytes) const
  6151. {
  6152. if (numberOfBytes > 0)
  6153. {
  6154. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6155. if (out == 0)
  6156. return false;
  6157. out->write (dataToAppend, numberOfBytes);
  6158. }
  6159. return true;
  6160. }
  6161. bool File::replaceWithData (const void* const dataToWrite,
  6162. const int numberOfBytes) const
  6163. {
  6164. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6165. if (numberOfBytes <= 0)
  6166. return deleteFile();
  6167. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6168. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6169. return tempFile.overwriteTargetFileWithTemporary();
  6170. }
  6171. bool File::appendText (const String& text,
  6172. const bool asUnicode,
  6173. const bool writeUnicodeHeaderBytes) const
  6174. {
  6175. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6176. if (out != 0)
  6177. {
  6178. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6179. return true;
  6180. }
  6181. return false;
  6182. }
  6183. bool File::replaceWithText (const String& textToWrite,
  6184. const bool asUnicode,
  6185. const bool writeUnicodeHeaderBytes) const
  6186. {
  6187. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6188. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6189. return tempFile.overwriteTargetFileWithTemporary();
  6190. }
  6191. bool File::hasIdenticalContentTo (const File& other) const
  6192. {
  6193. if (other == *this)
  6194. return true;
  6195. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6196. {
  6197. FileInputStream in1 (*this), in2 (other);
  6198. const int bufferSize = 4096;
  6199. HeapBlock <char> buffer1, buffer2;
  6200. buffer1.malloc (bufferSize);
  6201. buffer2.malloc (bufferSize);
  6202. for (;;)
  6203. {
  6204. const int num1 = in1.read (buffer1, bufferSize);
  6205. const int num2 = in2.read (buffer2, bufferSize);
  6206. if (num1 != num2)
  6207. break;
  6208. if (num1 <= 0)
  6209. return true;
  6210. if (memcmp (buffer1, buffer2, num1) != 0)
  6211. break;
  6212. }
  6213. }
  6214. return false;
  6215. }
  6216. const String File::createLegalPathName (const String& original)
  6217. {
  6218. String s (original);
  6219. String start;
  6220. if (s[1] == ':')
  6221. {
  6222. start = s.substring (0, 2);
  6223. s = s.substring (2);
  6224. }
  6225. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6226. .substring (0, 1024);
  6227. }
  6228. const String File::createLegalFileName (const String& original)
  6229. {
  6230. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6231. const int maxLength = 128; // only the length of the filename, not the whole path
  6232. const int len = s.length();
  6233. if (len > maxLength)
  6234. {
  6235. const int lastDot = s.lastIndexOfChar ('.');
  6236. if (lastDot > jmax (0, len - 12))
  6237. {
  6238. s = s.substring (0, maxLength - (len - lastDot))
  6239. + s.substring (lastDot);
  6240. }
  6241. else
  6242. {
  6243. s = s.substring (0, maxLength);
  6244. }
  6245. }
  6246. return s;
  6247. }
  6248. const String File::getRelativePathFrom (const File& dir) const
  6249. {
  6250. String thisPath (fullPath);
  6251. {
  6252. int len = thisPath.length();
  6253. while (--len >= 0 && thisPath [len] == File::separator)
  6254. thisPath [len] = 0;
  6255. }
  6256. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6257. : dir.fullPath));
  6258. const int len = jmin (thisPath.length(), dirPath.length());
  6259. int commonBitLength = 0;
  6260. for (int i = 0; i < len; ++i)
  6261. {
  6262. #if NAMES_ARE_CASE_SENSITIVE
  6263. if (thisPath[i] != dirPath[i])
  6264. #else
  6265. if (CharacterFunctions::toLowerCase (thisPath[i])
  6266. != CharacterFunctions::toLowerCase (dirPath[i]))
  6267. #endif
  6268. {
  6269. break;
  6270. }
  6271. ++commonBitLength;
  6272. }
  6273. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6274. --commonBitLength;
  6275. // if the only common bit is the root, then just return the full path..
  6276. if (commonBitLength <= 0
  6277. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6278. return fullPath;
  6279. thisPath = thisPath.substring (commonBitLength);
  6280. dirPath = dirPath.substring (commonBitLength);
  6281. while (dirPath.isNotEmpty())
  6282. {
  6283. #if JUCE_WINDOWS
  6284. thisPath = "..\\" + thisPath;
  6285. #else
  6286. thisPath = "../" + thisPath;
  6287. #endif
  6288. const int sep = dirPath.indexOfChar (separator);
  6289. if (sep >= 0)
  6290. dirPath = dirPath.substring (sep + 1);
  6291. else
  6292. dirPath = String::empty;
  6293. }
  6294. return thisPath;
  6295. }
  6296. const File File::createTempFile (const String& fileNameEnding)
  6297. {
  6298. const File tempFile (getSpecialLocation (tempDirectory)
  6299. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6300. .withFileExtension (fileNameEnding));
  6301. if (tempFile.exists())
  6302. return createTempFile (fileNameEnding);
  6303. else
  6304. return tempFile;
  6305. }
  6306. #if JUCE_UNIT_TESTS
  6307. class FileTests : public UnitTest
  6308. {
  6309. public:
  6310. FileTests() : UnitTest ("Files") {}
  6311. void runTest()
  6312. {
  6313. beginTest ("Reading");
  6314. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6315. const File temp (File::getSpecialLocation (File::tempDirectory));
  6316. expect (! File::nonexistent.exists());
  6317. expect (home.isDirectory());
  6318. expect (home.exists());
  6319. expect (! home.existsAsFile());
  6320. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6321. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6322. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6323. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6324. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6325. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6326. expect (home.getBytesFreeOnVolume() > 0);
  6327. expect (! home.isHidden());
  6328. expect (home.isOnHardDisk());
  6329. expect (! home.isOnCDRomDrive());
  6330. expect (File::getCurrentWorkingDirectory().exists());
  6331. expect (home.setAsCurrentWorkingDirectory());
  6332. expect (File::getCurrentWorkingDirectory() == home);
  6333. {
  6334. Array<File> roots;
  6335. File::findFileSystemRoots (roots);
  6336. expect (roots.size() > 0);
  6337. for (int i = 0; i < roots.size(); ++i)
  6338. expect (roots[i].exists());
  6339. }
  6340. beginTest ("Writing");
  6341. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder"));
  6342. expect (demoFolder.deleteRecursively());
  6343. expect (demoFolder.createDirectory());
  6344. expect (demoFolder.isDirectory());
  6345. expect (demoFolder.getParentDirectory() == temp);
  6346. expect (temp.isDirectory());
  6347. {
  6348. Array<File> files;
  6349. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6350. expect (files.contains (demoFolder));
  6351. }
  6352. {
  6353. Array<File> files;
  6354. temp.findChildFiles (files, File::findDirectories, false, "*");
  6355. expect (files.contains (demoFolder));
  6356. }
  6357. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6358. expect (tempFile.getFileExtension() == ".txt");
  6359. expect (tempFile.hasFileExtension (".txt"));
  6360. expect (tempFile.hasFileExtension ("txt"));
  6361. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6362. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6363. expect (tempFile.hasWriteAccess());
  6364. {
  6365. FileOutputStream fo (tempFile);
  6366. fo.write ("0123456789", 10);
  6367. }
  6368. expect (tempFile.exists());
  6369. expect (tempFile.getSize() == 10);
  6370. expect (std::abs (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds()) < 3000);
  6371. expect (tempFile.loadFileAsString() == "0123456789");
  6372. expect (! demoFolder.containsSubDirectories());
  6373. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6374. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6375. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6376. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6377. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6378. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6379. expect (demoFolder.containsSubDirectories());
  6380. expect (tempFile.hasWriteAccess());
  6381. tempFile.setReadOnly (true);
  6382. expect (! tempFile.hasWriteAccess());
  6383. tempFile.setReadOnly (false);
  6384. expect (tempFile.hasWriteAccess());
  6385. Time t (Time::getCurrentTime());
  6386. tempFile.setLastModificationTime (t);
  6387. Time t2 = tempFile.getLastModificationTime();
  6388. expect (std::abs (t2.toMilliseconds() - t.toMilliseconds()) <= 1000);
  6389. {
  6390. MemoryBlock mb;
  6391. tempFile.loadFileAsData (mb);
  6392. expect (mb.getSize() == 10);
  6393. expect (mb[0] == '0');
  6394. }
  6395. expect (tempFile.appendData ("abcdefghij", 10));
  6396. expect (tempFile.getSize() == 20);
  6397. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6398. expect (tempFile.getSize() == 10);
  6399. File tempFile2 (tempFile.getNonexistentSibling (false));
  6400. expect (tempFile.copyFileTo (tempFile2));
  6401. expect (tempFile2.exists());
  6402. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6403. expect (tempFile.deleteFile());
  6404. expect (! tempFile.exists());
  6405. expect (tempFile2.moveFileTo (tempFile));
  6406. expect (tempFile.exists());
  6407. expect (! tempFile2.exists());
  6408. expect (demoFolder.deleteRecursively());
  6409. expect (! demoFolder.exists());
  6410. }
  6411. };
  6412. static FileTests fileUnitTests;
  6413. #endif
  6414. END_JUCE_NAMESPACE
  6415. /*** End of inlined file: juce_File.cpp ***/
  6416. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6417. BEGIN_JUCE_NAMESPACE
  6418. int64 juce_fileSetPosition (void* handle, int64 pos);
  6419. FileInputStream::FileInputStream (const File& f)
  6420. : file (f),
  6421. fileHandle (0),
  6422. currentPosition (0),
  6423. totalSize (0),
  6424. needToSeek (true)
  6425. {
  6426. openHandle();
  6427. }
  6428. FileInputStream::~FileInputStream()
  6429. {
  6430. closeHandle();
  6431. }
  6432. int64 FileInputStream::getTotalLength()
  6433. {
  6434. return totalSize;
  6435. }
  6436. int FileInputStream::read (void* buffer, int bytesToRead)
  6437. {
  6438. int num = 0;
  6439. if (needToSeek)
  6440. {
  6441. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6442. return 0;
  6443. needToSeek = false;
  6444. }
  6445. num = readInternal (buffer, bytesToRead);
  6446. currentPosition += num;
  6447. return num;
  6448. }
  6449. bool FileInputStream::isExhausted()
  6450. {
  6451. return currentPosition >= totalSize;
  6452. }
  6453. int64 FileInputStream::getPosition()
  6454. {
  6455. return currentPosition;
  6456. }
  6457. bool FileInputStream::setPosition (int64 pos)
  6458. {
  6459. pos = jlimit ((int64) 0, totalSize, pos);
  6460. needToSeek |= (currentPosition != pos);
  6461. currentPosition = pos;
  6462. return true;
  6463. }
  6464. END_JUCE_NAMESPACE
  6465. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6466. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6467. BEGIN_JUCE_NAMESPACE
  6468. int64 juce_fileSetPosition (void* handle, int64 pos);
  6469. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6470. : file (f),
  6471. fileHandle (0),
  6472. currentPosition (0),
  6473. bufferSize (bufferSize_),
  6474. bytesInBuffer (0),
  6475. buffer (jmax (bufferSize_, 16))
  6476. {
  6477. openHandle();
  6478. }
  6479. FileOutputStream::~FileOutputStream()
  6480. {
  6481. flush();
  6482. closeHandle();
  6483. }
  6484. int64 FileOutputStream::getPosition()
  6485. {
  6486. return currentPosition;
  6487. }
  6488. bool FileOutputStream::setPosition (int64 newPosition)
  6489. {
  6490. if (newPosition != currentPosition)
  6491. {
  6492. flush();
  6493. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6494. }
  6495. return newPosition == currentPosition;
  6496. }
  6497. void FileOutputStream::flush()
  6498. {
  6499. if (bytesInBuffer > 0)
  6500. {
  6501. writeInternal (buffer, bytesInBuffer);
  6502. bytesInBuffer = 0;
  6503. }
  6504. flushInternal();
  6505. }
  6506. bool FileOutputStream::write (const void* const src, const int numBytes)
  6507. {
  6508. if (bytesInBuffer + numBytes < bufferSize)
  6509. {
  6510. memcpy (buffer + bytesInBuffer, src, numBytes);
  6511. bytesInBuffer += numBytes;
  6512. currentPosition += numBytes;
  6513. }
  6514. else
  6515. {
  6516. if (bytesInBuffer > 0)
  6517. {
  6518. // flush the reservoir
  6519. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6520. bytesInBuffer = 0;
  6521. if (! wroteOk)
  6522. return false;
  6523. }
  6524. if (numBytes < bufferSize)
  6525. {
  6526. memcpy (buffer + bytesInBuffer, src, numBytes);
  6527. bytesInBuffer += numBytes;
  6528. currentPosition += numBytes;
  6529. }
  6530. else
  6531. {
  6532. const int bytesWritten = writeInternal (src, numBytes);
  6533. if (bytesWritten < 0)
  6534. return false;
  6535. currentPosition += bytesWritten;
  6536. return bytesWritten == numBytes;
  6537. }
  6538. }
  6539. return true;
  6540. }
  6541. END_JUCE_NAMESPACE
  6542. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6543. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6544. BEGIN_JUCE_NAMESPACE
  6545. FileSearchPath::FileSearchPath()
  6546. {
  6547. }
  6548. FileSearchPath::FileSearchPath (const String& path)
  6549. {
  6550. init (path);
  6551. }
  6552. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6553. : directories (other.directories)
  6554. {
  6555. }
  6556. FileSearchPath::~FileSearchPath()
  6557. {
  6558. }
  6559. FileSearchPath& FileSearchPath::operator= (const String& path)
  6560. {
  6561. init (path);
  6562. return *this;
  6563. }
  6564. void FileSearchPath::init (const String& path)
  6565. {
  6566. directories.clear();
  6567. directories.addTokens (path, ";", "\"");
  6568. directories.trim();
  6569. directories.removeEmptyStrings();
  6570. for (int i = directories.size(); --i >= 0;)
  6571. directories.set (i, directories[i].unquoted());
  6572. }
  6573. int FileSearchPath::getNumPaths() const
  6574. {
  6575. return directories.size();
  6576. }
  6577. const File FileSearchPath::operator[] (const int index) const
  6578. {
  6579. return File (directories [index]);
  6580. }
  6581. const String FileSearchPath::toString() const
  6582. {
  6583. StringArray directories2 (directories);
  6584. for (int i = directories2.size(); --i >= 0;)
  6585. if (directories2[i].containsChar (';'))
  6586. directories2.set (i, directories2[i].quoted());
  6587. return directories2.joinIntoString (";");
  6588. }
  6589. void FileSearchPath::add (const File& dir, const int insertIndex)
  6590. {
  6591. directories.insert (insertIndex, dir.getFullPathName());
  6592. }
  6593. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6594. {
  6595. for (int i = 0; i < directories.size(); ++i)
  6596. if (File (directories[i]) == dir)
  6597. return;
  6598. add (dir);
  6599. }
  6600. void FileSearchPath::remove (const int index)
  6601. {
  6602. directories.remove (index);
  6603. }
  6604. void FileSearchPath::addPath (const FileSearchPath& other)
  6605. {
  6606. for (int i = 0; i < other.getNumPaths(); ++i)
  6607. addIfNotAlreadyThere (other[i]);
  6608. }
  6609. void FileSearchPath::removeRedundantPaths()
  6610. {
  6611. for (int i = directories.size(); --i >= 0;)
  6612. {
  6613. const File d1 (directories[i]);
  6614. for (int j = directories.size(); --j >= 0;)
  6615. {
  6616. const File d2 (directories[j]);
  6617. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6618. {
  6619. directories.remove (i);
  6620. break;
  6621. }
  6622. }
  6623. }
  6624. }
  6625. void FileSearchPath::removeNonExistentPaths()
  6626. {
  6627. for (int i = directories.size(); --i >= 0;)
  6628. if (! File (directories[i]).isDirectory())
  6629. directories.remove (i);
  6630. }
  6631. int FileSearchPath::findChildFiles (Array<File>& results,
  6632. const int whatToLookFor,
  6633. const bool searchRecursively,
  6634. const String& wildCardPattern) const
  6635. {
  6636. int total = 0;
  6637. for (int i = 0; i < directories.size(); ++i)
  6638. total += operator[] (i).findChildFiles (results,
  6639. whatToLookFor,
  6640. searchRecursively,
  6641. wildCardPattern);
  6642. return total;
  6643. }
  6644. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6645. const bool checkRecursively) const
  6646. {
  6647. for (int i = directories.size(); --i >= 0;)
  6648. {
  6649. const File d (directories[i]);
  6650. if (checkRecursively)
  6651. {
  6652. if (fileToCheck.isAChildOf (d))
  6653. return true;
  6654. }
  6655. else
  6656. {
  6657. if (fileToCheck.getParentDirectory() == d)
  6658. return true;
  6659. }
  6660. }
  6661. return false;
  6662. }
  6663. END_JUCE_NAMESPACE
  6664. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6665. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6666. BEGIN_JUCE_NAMESPACE
  6667. NamedPipe::NamedPipe()
  6668. : internal (0)
  6669. {
  6670. }
  6671. NamedPipe::~NamedPipe()
  6672. {
  6673. close();
  6674. }
  6675. bool NamedPipe::openExisting (const String& pipeName)
  6676. {
  6677. currentPipeName = pipeName;
  6678. return openInternal (pipeName, false);
  6679. }
  6680. bool NamedPipe::createNewPipe (const String& pipeName)
  6681. {
  6682. currentPipeName = pipeName;
  6683. return openInternal (pipeName, true);
  6684. }
  6685. bool NamedPipe::isOpen() const
  6686. {
  6687. return internal != 0;
  6688. }
  6689. const String NamedPipe::getName() const
  6690. {
  6691. return currentPipeName;
  6692. }
  6693. // other methods for this class are implemented in the platform-specific files
  6694. END_JUCE_NAMESPACE
  6695. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6696. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6697. BEGIN_JUCE_NAMESPACE
  6698. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6699. {
  6700. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6701. "temp_" + String (Random::getSystemRandom().nextInt()),
  6702. suffix,
  6703. optionFlags);
  6704. }
  6705. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6706. : targetFile (targetFile_)
  6707. {
  6708. // If you use this constructor, you need to give it a valid target file!
  6709. jassert (targetFile != File::nonexistent);
  6710. createTempFile (targetFile.getParentDirectory(),
  6711. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6712. targetFile.getFileExtension(),
  6713. optionFlags);
  6714. }
  6715. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6716. const String& suffix, const int optionFlags)
  6717. {
  6718. if ((optionFlags & useHiddenFile) != 0)
  6719. name = "." + name;
  6720. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6721. }
  6722. TemporaryFile::~TemporaryFile()
  6723. {
  6724. if (! deleteTemporaryFile())
  6725. {
  6726. /* Failed to delete our temporary file! The most likely reason for this would be
  6727. that you've not closed an output stream that was being used to write to file.
  6728. If you find that something beyond your control is changing permissions on
  6729. your temporary files and preventing them from being deleted, you may want to
  6730. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6731. handle them appropriately.
  6732. */
  6733. jassertfalse;
  6734. }
  6735. }
  6736. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6737. {
  6738. // This method only works if you created this object with the constructor
  6739. // that takes a target file!
  6740. jassert (targetFile != File::nonexistent);
  6741. if (temporaryFile.exists())
  6742. {
  6743. // Have a few attempts at overwriting the file before giving up..
  6744. for (int i = 5; --i >= 0;)
  6745. {
  6746. if (temporaryFile.moveFileTo (targetFile))
  6747. return true;
  6748. Thread::sleep (100);
  6749. }
  6750. }
  6751. else
  6752. {
  6753. // There's no temporary file to use. If your write failed, you should
  6754. // probably check, and not bother calling this method.
  6755. jassertfalse;
  6756. }
  6757. return false;
  6758. }
  6759. bool TemporaryFile::deleteTemporaryFile() const
  6760. {
  6761. // Have a few attempts at deleting the file before giving up..
  6762. for (int i = 5; --i >= 0;)
  6763. {
  6764. if (temporaryFile.deleteFile())
  6765. return true;
  6766. Thread::sleep (50);
  6767. }
  6768. return false;
  6769. }
  6770. END_JUCE_NAMESPACE
  6771. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6772. /*** Start of inlined file: juce_Socket.cpp ***/
  6773. #if JUCE_WINDOWS
  6774. #include <winsock2.h>
  6775. #if JUCE_MSVC
  6776. #pragma warning (push)
  6777. #pragma warning (disable : 4127 4389 4018)
  6778. #endif
  6779. #else
  6780. #if JUCE_LINUX
  6781. #include <sys/types.h>
  6782. #include <sys/socket.h>
  6783. #include <sys/errno.h>
  6784. #include <unistd.h>
  6785. #include <netinet/in.h>
  6786. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6787. #include <CoreServices/CoreServices.h>
  6788. #endif
  6789. #include <fcntl.h>
  6790. #include <netdb.h>
  6791. #include <arpa/inet.h>
  6792. #include <netinet/tcp.h>
  6793. #endif
  6794. BEGIN_JUCE_NAMESPACE
  6795. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6796. typedef socklen_t juce_socklen_t;
  6797. #else
  6798. typedef int juce_socklen_t;
  6799. #endif
  6800. #if JUCE_WINDOWS
  6801. namespace SocketHelpers
  6802. {
  6803. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6804. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6805. }
  6806. static void initWin32Sockets()
  6807. {
  6808. static CriticalSection lock;
  6809. const ScopedLock sl (lock);
  6810. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6811. {
  6812. WSADATA wsaData;
  6813. const WORD wVersionRequested = MAKEWORD (1, 1);
  6814. WSAStartup (wVersionRequested, &wsaData);
  6815. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6816. }
  6817. }
  6818. void juce_shutdownWin32Sockets()
  6819. {
  6820. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6821. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6822. }
  6823. #endif
  6824. namespace SocketHelpers
  6825. {
  6826. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6827. {
  6828. const int sndBufSize = 65536;
  6829. const int rcvBufSize = 65536;
  6830. const int one = 1;
  6831. return handle > 0
  6832. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6833. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6834. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6835. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6836. }
  6837. static bool bindSocketToPort (const int handle, const int port) throw()
  6838. {
  6839. if (handle <= 0 || port <= 0)
  6840. return false;
  6841. struct sockaddr_in servTmpAddr;
  6842. zerostruct (servTmpAddr);
  6843. servTmpAddr.sin_family = PF_INET;
  6844. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6845. servTmpAddr.sin_port = htons ((uint16) port);
  6846. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6847. }
  6848. static int readSocket (const int handle,
  6849. void* const destBuffer, const int maxBytesToRead,
  6850. bool volatile& connected,
  6851. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6852. {
  6853. int bytesRead = 0;
  6854. while (bytesRead < maxBytesToRead)
  6855. {
  6856. int bytesThisTime;
  6857. #if JUCE_WINDOWS
  6858. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6859. #else
  6860. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6861. && errno == EINTR
  6862. && connected)
  6863. {
  6864. }
  6865. #endif
  6866. if (bytesThisTime <= 0 || ! connected)
  6867. {
  6868. if (bytesRead == 0)
  6869. bytesRead = -1;
  6870. break;
  6871. }
  6872. bytesRead += bytesThisTime;
  6873. if (! blockUntilSpecifiedAmountHasArrived)
  6874. break;
  6875. }
  6876. return bytesRead;
  6877. }
  6878. static int waitForReadiness (const int handle, const bool forReading,
  6879. const int timeoutMsecs) throw()
  6880. {
  6881. struct timeval timeout;
  6882. struct timeval* timeoutp;
  6883. if (timeoutMsecs >= 0)
  6884. {
  6885. timeout.tv_sec = timeoutMsecs / 1000;
  6886. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6887. timeoutp = &timeout;
  6888. }
  6889. else
  6890. {
  6891. timeoutp = 0;
  6892. }
  6893. fd_set rset, wset;
  6894. FD_ZERO (&rset);
  6895. FD_SET (handle, &rset);
  6896. FD_ZERO (&wset);
  6897. FD_SET (handle, &wset);
  6898. fd_set* const prset = forReading ? &rset : 0;
  6899. fd_set* const pwset = forReading ? 0 : &wset;
  6900. #if JUCE_WINDOWS
  6901. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6902. return -1;
  6903. #else
  6904. {
  6905. int result;
  6906. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6907. && errno == EINTR)
  6908. {
  6909. }
  6910. if (result < 0)
  6911. return -1;
  6912. }
  6913. #endif
  6914. {
  6915. int opt;
  6916. juce_socklen_t len = sizeof (opt);
  6917. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6918. || opt != 0)
  6919. return -1;
  6920. }
  6921. if ((forReading && FD_ISSET (handle, &rset))
  6922. || ((! forReading) && FD_ISSET (handle, &wset)))
  6923. return 1;
  6924. return 0;
  6925. }
  6926. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6927. {
  6928. #if JUCE_WINDOWS
  6929. u_long nonBlocking = shouldBlock ? 0 : 1;
  6930. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6931. return false;
  6932. #else
  6933. int socketFlags = fcntl (handle, F_GETFL, 0);
  6934. if (socketFlags == -1)
  6935. return false;
  6936. if (shouldBlock)
  6937. socketFlags &= ~O_NONBLOCK;
  6938. else
  6939. socketFlags |= O_NONBLOCK;
  6940. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6941. return false;
  6942. #endif
  6943. return true;
  6944. }
  6945. static bool connectSocket (int volatile& handle,
  6946. const bool isDatagram,
  6947. void** serverAddress,
  6948. const String& hostName,
  6949. const int portNumber,
  6950. const int timeOutMillisecs) throw()
  6951. {
  6952. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6953. if (hostEnt == 0)
  6954. return false;
  6955. struct in_addr targetAddress;
  6956. memcpy (&targetAddress.s_addr,
  6957. *(hostEnt->h_addr_list),
  6958. sizeof (targetAddress.s_addr));
  6959. struct sockaddr_in servTmpAddr;
  6960. zerostruct (servTmpAddr);
  6961. servTmpAddr.sin_family = PF_INET;
  6962. servTmpAddr.sin_addr = targetAddress;
  6963. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6964. if (handle < 0)
  6965. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6966. if (handle < 0)
  6967. return false;
  6968. if (isDatagram)
  6969. {
  6970. *serverAddress = new struct sockaddr_in();
  6971. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6972. return true;
  6973. }
  6974. setSocketBlockingState (handle, false);
  6975. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6976. if (result < 0)
  6977. {
  6978. #if JUCE_WINDOWS
  6979. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6980. #else
  6981. if (errno == EINPROGRESS)
  6982. #endif
  6983. {
  6984. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6985. {
  6986. setSocketBlockingState (handle, true);
  6987. return false;
  6988. }
  6989. }
  6990. }
  6991. setSocketBlockingState (handle, true);
  6992. resetSocketOptions (handle, false, false);
  6993. return true;
  6994. }
  6995. }
  6996. StreamingSocket::StreamingSocket()
  6997. : portNumber (0),
  6998. handle (-1),
  6999. connected (false),
  7000. isListener (false)
  7001. {
  7002. #if JUCE_WINDOWS
  7003. initWin32Sockets();
  7004. #endif
  7005. }
  7006. StreamingSocket::StreamingSocket (const String& hostName_,
  7007. const int portNumber_,
  7008. const int handle_)
  7009. : hostName (hostName_),
  7010. portNumber (portNumber_),
  7011. handle (handle_),
  7012. connected (true),
  7013. isListener (false)
  7014. {
  7015. #if JUCE_WINDOWS
  7016. initWin32Sockets();
  7017. #endif
  7018. SocketHelpers::resetSocketOptions (handle_, false, false);
  7019. }
  7020. StreamingSocket::~StreamingSocket()
  7021. {
  7022. close();
  7023. }
  7024. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7025. {
  7026. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7027. : -1;
  7028. }
  7029. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7030. {
  7031. if (isListener || ! connected)
  7032. return -1;
  7033. #if JUCE_WINDOWS
  7034. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7035. #else
  7036. int result;
  7037. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7038. && errno == EINTR)
  7039. {
  7040. }
  7041. return result;
  7042. #endif
  7043. }
  7044. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7045. const int timeoutMsecs) const
  7046. {
  7047. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7048. : -1;
  7049. }
  7050. bool StreamingSocket::bindToPort (const int port)
  7051. {
  7052. return SocketHelpers::bindSocketToPort (handle, port);
  7053. }
  7054. bool StreamingSocket::connect (const String& remoteHostName,
  7055. const int remotePortNumber,
  7056. const int timeOutMillisecs)
  7057. {
  7058. if (isListener)
  7059. {
  7060. jassertfalse; // a listener socket can't connect to another one!
  7061. return false;
  7062. }
  7063. if (connected)
  7064. close();
  7065. hostName = remoteHostName;
  7066. portNumber = remotePortNumber;
  7067. isListener = false;
  7068. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7069. remotePortNumber, timeOutMillisecs);
  7070. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7071. {
  7072. close();
  7073. return false;
  7074. }
  7075. return true;
  7076. }
  7077. void StreamingSocket::close()
  7078. {
  7079. #if JUCE_WINDOWS
  7080. if (handle != SOCKET_ERROR || connected)
  7081. closesocket (handle);
  7082. connected = false;
  7083. #else
  7084. if (connected)
  7085. {
  7086. connected = false;
  7087. if (isListener)
  7088. {
  7089. // need to do this to interrupt the accept() function..
  7090. StreamingSocket temp;
  7091. temp.connect ("localhost", portNumber, 1000);
  7092. }
  7093. }
  7094. if (handle != -1)
  7095. ::close (handle);
  7096. #endif
  7097. hostName = String::empty;
  7098. portNumber = 0;
  7099. handle = -1;
  7100. isListener = false;
  7101. }
  7102. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7103. {
  7104. if (connected)
  7105. close();
  7106. hostName = "listener";
  7107. portNumber = newPortNumber;
  7108. isListener = true;
  7109. struct sockaddr_in servTmpAddr;
  7110. zerostruct (servTmpAddr);
  7111. servTmpAddr.sin_family = PF_INET;
  7112. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7113. if (localHostName.isNotEmpty())
  7114. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7115. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7116. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7117. if (handle < 0)
  7118. return false;
  7119. const int reuse = 1;
  7120. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7121. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7122. || listen (handle, SOMAXCONN) < 0)
  7123. {
  7124. close();
  7125. return false;
  7126. }
  7127. connected = true;
  7128. return true;
  7129. }
  7130. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7131. {
  7132. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7133. // prepare this socket as a listener.
  7134. if (connected && isListener)
  7135. {
  7136. struct sockaddr address;
  7137. juce_socklen_t len = sizeof (sockaddr);
  7138. const int newSocket = (int) accept (handle, &address, &len);
  7139. if (newSocket >= 0 && connected)
  7140. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7141. portNumber, newSocket);
  7142. }
  7143. return 0;
  7144. }
  7145. bool StreamingSocket::isLocal() const throw()
  7146. {
  7147. return hostName == "127.0.0.1";
  7148. }
  7149. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7150. : portNumber (0),
  7151. handle (-1),
  7152. connected (true),
  7153. allowBroadcast (allowBroadcast_),
  7154. serverAddress (0)
  7155. {
  7156. #if JUCE_WINDOWS
  7157. initWin32Sockets();
  7158. #endif
  7159. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7160. bindToPort (localPortNumber);
  7161. }
  7162. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7163. const int handle_, const int localPortNumber)
  7164. : hostName (hostName_),
  7165. portNumber (portNumber_),
  7166. handle (handle_),
  7167. connected (true),
  7168. allowBroadcast (false),
  7169. serverAddress (0)
  7170. {
  7171. #if JUCE_WINDOWS
  7172. initWin32Sockets();
  7173. #endif
  7174. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7175. bindToPort (localPortNumber);
  7176. }
  7177. DatagramSocket::~DatagramSocket()
  7178. {
  7179. close();
  7180. delete static_cast <struct sockaddr_in*> (serverAddress);
  7181. serverAddress = 0;
  7182. }
  7183. void DatagramSocket::close()
  7184. {
  7185. #if JUCE_WINDOWS
  7186. closesocket (handle);
  7187. connected = false;
  7188. #else
  7189. connected = false;
  7190. ::close (handle);
  7191. #endif
  7192. hostName = String::empty;
  7193. portNumber = 0;
  7194. handle = -1;
  7195. }
  7196. bool DatagramSocket::bindToPort (const int port)
  7197. {
  7198. return SocketHelpers::bindSocketToPort (handle, port);
  7199. }
  7200. bool DatagramSocket::connect (const String& remoteHostName,
  7201. const int remotePortNumber,
  7202. const int timeOutMillisecs)
  7203. {
  7204. if (connected)
  7205. close();
  7206. hostName = remoteHostName;
  7207. portNumber = remotePortNumber;
  7208. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7209. remoteHostName, remotePortNumber,
  7210. timeOutMillisecs);
  7211. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7212. {
  7213. close();
  7214. return false;
  7215. }
  7216. return true;
  7217. }
  7218. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7219. {
  7220. struct sockaddr address;
  7221. juce_socklen_t len = sizeof (sockaddr);
  7222. while (waitUntilReady (true, -1) == 1)
  7223. {
  7224. char buf[1];
  7225. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7226. {
  7227. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7228. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7229. -1, -1);
  7230. }
  7231. }
  7232. return 0;
  7233. }
  7234. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7235. const int timeoutMsecs) const
  7236. {
  7237. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7238. : -1;
  7239. }
  7240. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7241. {
  7242. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7243. : -1;
  7244. }
  7245. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7246. {
  7247. // You need to call connect() first to set the server address..
  7248. jassert (serverAddress != 0 && connected);
  7249. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7250. numBytesToWrite, 0,
  7251. (const struct sockaddr*) serverAddress,
  7252. sizeof (struct sockaddr_in))
  7253. : -1;
  7254. }
  7255. bool DatagramSocket::isLocal() const throw()
  7256. {
  7257. return hostName == "127.0.0.1";
  7258. }
  7259. #if JUCE_MSVC
  7260. #pragma warning (pop)
  7261. #endif
  7262. END_JUCE_NAMESPACE
  7263. /*** End of inlined file: juce_Socket.cpp ***/
  7264. /*** Start of inlined file: juce_URL.cpp ***/
  7265. BEGIN_JUCE_NAMESPACE
  7266. URL::URL()
  7267. {
  7268. }
  7269. URL::URL (const String& url_)
  7270. : url (url_)
  7271. {
  7272. int i = url.indexOfChar ('?');
  7273. if (i >= 0)
  7274. {
  7275. do
  7276. {
  7277. const int nextAmp = url.indexOfChar (i + 1, '&');
  7278. const int equalsPos = url.indexOfChar (i + 1, '=');
  7279. if (equalsPos > i + 1)
  7280. {
  7281. if (nextAmp < 0)
  7282. {
  7283. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7284. removeEscapeChars (url.substring (equalsPos + 1)));
  7285. }
  7286. else if (nextAmp > 0 && equalsPos < nextAmp)
  7287. {
  7288. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7289. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7290. }
  7291. }
  7292. i = nextAmp;
  7293. }
  7294. while (i >= 0);
  7295. url = url.upToFirstOccurrenceOf ("?", false, false);
  7296. }
  7297. }
  7298. URL::URL (const URL& other)
  7299. : url (other.url),
  7300. postData (other.postData),
  7301. parameters (other.parameters),
  7302. filesToUpload (other.filesToUpload),
  7303. mimeTypes (other.mimeTypes)
  7304. {
  7305. }
  7306. URL& URL::operator= (const URL& other)
  7307. {
  7308. url = other.url;
  7309. postData = other.postData;
  7310. parameters = other.parameters;
  7311. filesToUpload = other.filesToUpload;
  7312. mimeTypes = other.mimeTypes;
  7313. return *this;
  7314. }
  7315. URL::~URL()
  7316. {
  7317. }
  7318. static const String getMangledParameters (const StringPairArray& parameters)
  7319. {
  7320. String p;
  7321. for (int i = 0; i < parameters.size(); ++i)
  7322. {
  7323. if (i > 0)
  7324. p << '&';
  7325. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7326. << '='
  7327. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7328. }
  7329. return p;
  7330. }
  7331. const String URL::toString (const bool includeGetParameters) const
  7332. {
  7333. if (includeGetParameters && parameters.size() > 0)
  7334. return url + "?" + getMangledParameters (parameters);
  7335. else
  7336. return url;
  7337. }
  7338. bool URL::isWellFormed() const
  7339. {
  7340. //xxx TODO
  7341. return url.isNotEmpty();
  7342. }
  7343. static int findStartOfDomain (const String& url)
  7344. {
  7345. int i = 0;
  7346. while (CharacterFunctions::isLetterOrDigit (url[i])
  7347. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7348. ++i;
  7349. return url[i] == ':' ? i + 1 : 0;
  7350. }
  7351. const String URL::getDomain() const
  7352. {
  7353. int start = findStartOfDomain (url);
  7354. while (url[start] == '/')
  7355. ++start;
  7356. const int end1 = url.indexOfChar (start, '/');
  7357. const int end2 = url.indexOfChar (start, ':');
  7358. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7359. : jmin (end1, end2);
  7360. return url.substring (start, end);
  7361. }
  7362. const String URL::getSubPath() const
  7363. {
  7364. int start = findStartOfDomain (url);
  7365. while (url[start] == '/')
  7366. ++start;
  7367. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7368. return startOfPath <= 0 ? String::empty
  7369. : url.substring (startOfPath);
  7370. }
  7371. const String URL::getScheme() const
  7372. {
  7373. return url.substring (0, findStartOfDomain (url) - 1);
  7374. }
  7375. const URL URL::withNewSubPath (const String& newPath) const
  7376. {
  7377. int start = findStartOfDomain (url);
  7378. while (url[start] == '/')
  7379. ++start;
  7380. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7381. URL u (*this);
  7382. if (startOfPath > 0)
  7383. u.url = url.substring (0, startOfPath);
  7384. if (! u.url.endsWithChar ('/'))
  7385. u.url << '/';
  7386. if (newPath.startsWithChar ('/'))
  7387. u.url << newPath.substring (1);
  7388. else
  7389. u.url << newPath;
  7390. return u;
  7391. }
  7392. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7393. {
  7394. if (possibleURL.startsWithIgnoreCase ("http:")
  7395. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7396. return true;
  7397. if (possibleURL.startsWithIgnoreCase ("file:")
  7398. || possibleURL.containsChar ('@')
  7399. || possibleURL.endsWithChar ('.')
  7400. || (! possibleURL.containsChar ('.')))
  7401. return false;
  7402. if (possibleURL.startsWithIgnoreCase ("www.")
  7403. && possibleURL.substring (5).containsChar ('.'))
  7404. return true;
  7405. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7406. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7407. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7408. return true;
  7409. return false;
  7410. }
  7411. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7412. {
  7413. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7414. return atSign > 0
  7415. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7416. && (! possibleEmailAddress.endsWithChar ('.'));
  7417. }
  7418. void* juce_openInternetFile (const String& url,
  7419. const String& headers,
  7420. const MemoryBlock& optionalPostData,
  7421. const bool isPost,
  7422. URL::OpenStreamProgressCallback* callback,
  7423. void* callbackContext,
  7424. int timeOutMs);
  7425. void juce_closeInternetFile (void* handle);
  7426. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7427. int juce_seekInInternetFile (void* handle, int newPosition);
  7428. int64 juce_getInternetFileContentLength (void* handle);
  7429. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7430. class WebInputStream : public InputStream
  7431. {
  7432. public:
  7433. WebInputStream (const URL& url,
  7434. const bool isPost_,
  7435. URL::OpenStreamProgressCallback* const progressCallback_,
  7436. void* const progressCallbackContext_,
  7437. const String& extraHeaders,
  7438. const int timeOutMs_,
  7439. StringPairArray* const responseHeaders)
  7440. : position (0),
  7441. finished (false),
  7442. isPost (isPost_),
  7443. progressCallback (progressCallback_),
  7444. progressCallbackContext (progressCallbackContext_),
  7445. timeOutMs (timeOutMs_)
  7446. {
  7447. server = url.toString (! isPost);
  7448. if (isPost_)
  7449. createHeadersAndPostData (url);
  7450. headers += extraHeaders;
  7451. if (! headers.endsWithChar ('\n'))
  7452. headers << "\r\n";
  7453. handle = juce_openInternetFile (server, headers, postData, isPost,
  7454. progressCallback_, progressCallbackContext_,
  7455. timeOutMs);
  7456. if (responseHeaders != 0)
  7457. juce_getInternetFileHeaders (handle, *responseHeaders);
  7458. }
  7459. ~WebInputStream()
  7460. {
  7461. juce_closeInternetFile (handle);
  7462. }
  7463. bool isError() const { return handle == 0; }
  7464. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7465. bool isExhausted() { return finished; }
  7466. int64 getPosition() { return position; }
  7467. int read (void* dest, int bytes)
  7468. {
  7469. if (finished || isError())
  7470. {
  7471. return 0;
  7472. }
  7473. else
  7474. {
  7475. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7476. position += bytesRead;
  7477. if (bytesRead == 0)
  7478. finished = true;
  7479. return bytesRead;
  7480. }
  7481. }
  7482. bool setPosition (int64 wantedPos)
  7483. {
  7484. if (wantedPos != position)
  7485. {
  7486. finished = false;
  7487. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7488. if (actualPos == wantedPos)
  7489. {
  7490. position = wantedPos;
  7491. }
  7492. else
  7493. {
  7494. if (wantedPos < position)
  7495. {
  7496. juce_closeInternetFile (handle);
  7497. position = 0;
  7498. finished = false;
  7499. handle = juce_openInternetFile (server, headers, postData, isPost,
  7500. progressCallback, progressCallbackContext,
  7501. timeOutMs);
  7502. }
  7503. skipNextBytes (wantedPos - position);
  7504. }
  7505. }
  7506. return true;
  7507. }
  7508. juce_UseDebuggingNewOperator
  7509. private:
  7510. String server, headers;
  7511. MemoryBlock postData;
  7512. int64 position;
  7513. bool finished;
  7514. const bool isPost;
  7515. void* handle;
  7516. URL::OpenStreamProgressCallback* const progressCallback;
  7517. void* const progressCallbackContext;
  7518. const int timeOutMs;
  7519. void createHeadersAndPostData (const URL& url)
  7520. {
  7521. MemoryOutputStream data (postData, false);
  7522. if (url.getFilesToUpload().size() > 0)
  7523. {
  7524. // need to upload some files, so do it as multi-part...
  7525. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7526. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7527. data << "--" << boundary;
  7528. int i;
  7529. for (i = 0; i < url.getParameters().size(); ++i)
  7530. {
  7531. data << "\r\nContent-Disposition: form-data; name=\""
  7532. << url.getParameters().getAllKeys() [i]
  7533. << "\"\r\n\r\n"
  7534. << url.getParameters().getAllValues() [i]
  7535. << "\r\n--"
  7536. << boundary;
  7537. }
  7538. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7539. {
  7540. const File file (url.getFilesToUpload().getAllValues() [i]);
  7541. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7542. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7543. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7544. const String mimeType (url.getMimeTypesOfUploadFiles()
  7545. .getValue (paramName, String::empty));
  7546. if (mimeType.isNotEmpty())
  7547. data << "Content-Type: " << mimeType << "\r\n";
  7548. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7549. << file << "\r\n--" << boundary;
  7550. }
  7551. data << "--\r\n";
  7552. data.flush();
  7553. }
  7554. else
  7555. {
  7556. data << getMangledParameters (url.getParameters())
  7557. << url.getPostData();
  7558. data.flush();
  7559. // just a short text attachment, so use simple url encoding..
  7560. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7561. + String ((unsigned int) postData.getSize())
  7562. + "\r\n";
  7563. }
  7564. }
  7565. WebInputStream (const WebInputStream&);
  7566. WebInputStream& operator= (const WebInputStream&);
  7567. };
  7568. InputStream* URL::createInputStream (const bool usePostCommand,
  7569. OpenStreamProgressCallback* const progressCallback,
  7570. void* const progressCallbackContext,
  7571. const String& extraHeaders,
  7572. const int timeOutMs,
  7573. StringPairArray* const responseHeaders) const
  7574. {
  7575. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7576. progressCallback, progressCallbackContext,
  7577. extraHeaders, timeOutMs, responseHeaders));
  7578. return wi->isError() ? 0 : wi.release();
  7579. }
  7580. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7581. const bool usePostCommand) const
  7582. {
  7583. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7584. if (in != 0)
  7585. {
  7586. in->readIntoMemoryBlock (destData);
  7587. return true;
  7588. }
  7589. return false;
  7590. }
  7591. const String URL::readEntireTextStream (const bool usePostCommand) const
  7592. {
  7593. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7594. if (in != 0)
  7595. return in->readEntireStreamAsString();
  7596. return String::empty;
  7597. }
  7598. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7599. {
  7600. XmlDocument doc (readEntireTextStream (usePostCommand));
  7601. return doc.getDocumentElement();
  7602. }
  7603. const URL URL::withParameter (const String& parameterName,
  7604. const String& parameterValue) const
  7605. {
  7606. URL u (*this);
  7607. u.parameters.set (parameterName, parameterValue);
  7608. return u;
  7609. }
  7610. const URL URL::withFileToUpload (const String& parameterName,
  7611. const File& fileToUpload,
  7612. const String& mimeType) const
  7613. {
  7614. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7615. URL u (*this);
  7616. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7617. u.mimeTypes.set (parameterName, mimeType);
  7618. return u;
  7619. }
  7620. const URL URL::withPOSTData (const String& postData_) const
  7621. {
  7622. URL u (*this);
  7623. u.postData = postData_;
  7624. return u;
  7625. }
  7626. const StringPairArray& URL::getParameters() const
  7627. {
  7628. return parameters;
  7629. }
  7630. const StringPairArray& URL::getFilesToUpload() const
  7631. {
  7632. return filesToUpload;
  7633. }
  7634. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7635. {
  7636. return mimeTypes;
  7637. }
  7638. const String URL::removeEscapeChars (const String& s)
  7639. {
  7640. String result (s.replaceCharacter ('+', ' '));
  7641. int nextPercent = 0;
  7642. for (;;)
  7643. {
  7644. nextPercent = result.indexOfChar (nextPercent, '%');
  7645. if (nextPercent < 0)
  7646. break;
  7647. int hexDigit1 = 0, hexDigit2 = 0;
  7648. if ((hexDigit1 = CharacterFunctions::getHexDigitValue (result [nextPercent + 1])) >= 0
  7649. && (hexDigit2 = CharacterFunctions::getHexDigitValue (result [nextPercent + 2])) >= 0)
  7650. {
  7651. const juce_wchar replacementChar = (juce_wchar) ((hexDigit1 << 4) + hexDigit2);
  7652. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  7653. }
  7654. ++nextPercent;
  7655. }
  7656. return result;
  7657. }
  7658. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7659. {
  7660. String result;
  7661. result.preallocateStorage (s.length() + 8);
  7662. const char* utf8 = s.toUTF8();
  7663. const char* legalChars = isParameter ? "_-.*!'()"
  7664. : "_-$.*!'(),";
  7665. while (*utf8 != 0)
  7666. {
  7667. const char c = *utf8++;
  7668. if (CharacterFunctions::isLetterOrDigit (c)
  7669. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  7670. {
  7671. result << c;
  7672. }
  7673. else
  7674. {
  7675. const int v = (int) (uint8) c;
  7676. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  7677. }
  7678. }
  7679. return result;
  7680. }
  7681. bool URL::launchInDefaultBrowser() const
  7682. {
  7683. String u (toString (true));
  7684. if (u.containsChar ('@') && ! u.containsChar (':'))
  7685. u = "mailto:" + u;
  7686. return PlatformUtilities::openDocument (u, String::empty);
  7687. }
  7688. END_JUCE_NAMESPACE
  7689. /*** End of inlined file: juce_URL.cpp ***/
  7690. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7691. BEGIN_JUCE_NAMESPACE
  7692. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7693. const int bufferSize_,
  7694. const bool deleteSourceWhenDestroyed)
  7695. : source (source_),
  7696. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7697. bufferSize (jmax (256, bufferSize_)),
  7698. position (source_->getPosition()),
  7699. lastReadPos (0),
  7700. bufferOverlap (128)
  7701. {
  7702. const int sourceSize = (int) source_->getTotalLength();
  7703. if (sourceSize >= 0)
  7704. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7705. bufferStart = position;
  7706. buffer.malloc (bufferSize);
  7707. }
  7708. BufferedInputStream::~BufferedInputStream()
  7709. {
  7710. }
  7711. int64 BufferedInputStream::getTotalLength()
  7712. {
  7713. return source->getTotalLength();
  7714. }
  7715. int64 BufferedInputStream::getPosition()
  7716. {
  7717. return position;
  7718. }
  7719. bool BufferedInputStream::setPosition (int64 newPosition)
  7720. {
  7721. position = jmax ((int64) 0, newPosition);
  7722. return true;
  7723. }
  7724. bool BufferedInputStream::isExhausted()
  7725. {
  7726. return (position >= lastReadPos)
  7727. && source->isExhausted();
  7728. }
  7729. void BufferedInputStream::ensureBuffered()
  7730. {
  7731. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7732. if (position < bufferStart || position >= bufferEndOverlap)
  7733. {
  7734. int bytesRead;
  7735. if (position < lastReadPos
  7736. && position >= bufferEndOverlap
  7737. && position >= bufferStart)
  7738. {
  7739. const int bytesToKeep = (int) (lastReadPos - position);
  7740. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7741. bufferStart = position;
  7742. bytesRead = source->read (buffer + bytesToKeep,
  7743. bufferSize - bytesToKeep);
  7744. lastReadPos += bytesRead;
  7745. bytesRead += bytesToKeep;
  7746. }
  7747. else
  7748. {
  7749. bufferStart = position;
  7750. source->setPosition (bufferStart);
  7751. bytesRead = source->read (buffer, bufferSize);
  7752. lastReadPos = bufferStart + bytesRead;
  7753. }
  7754. while (bytesRead < bufferSize)
  7755. buffer [bytesRead++] = 0;
  7756. }
  7757. }
  7758. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7759. {
  7760. if (position >= bufferStart
  7761. && position + maxBytesToRead <= lastReadPos)
  7762. {
  7763. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7764. position += maxBytesToRead;
  7765. return maxBytesToRead;
  7766. }
  7767. else
  7768. {
  7769. if (position < bufferStart || position >= lastReadPos)
  7770. ensureBuffered();
  7771. int bytesRead = 0;
  7772. while (maxBytesToRead > 0)
  7773. {
  7774. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7775. if (bytesAvailable > 0)
  7776. {
  7777. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7778. maxBytesToRead -= bytesAvailable;
  7779. bytesRead += bytesAvailable;
  7780. position += bytesAvailable;
  7781. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7782. }
  7783. const int64 oldLastReadPos = lastReadPos;
  7784. ensureBuffered();
  7785. if (oldLastReadPos == lastReadPos)
  7786. break; // if ensureBuffered() failed to read any more data, bail out
  7787. if (isExhausted())
  7788. break;
  7789. }
  7790. return bytesRead;
  7791. }
  7792. }
  7793. const String BufferedInputStream::readString()
  7794. {
  7795. if (position >= bufferStart
  7796. && position < lastReadPos)
  7797. {
  7798. const int maxChars = (int) (lastReadPos - position);
  7799. const char* const src = buffer + (int) (position - bufferStart);
  7800. for (int i = 0; i < maxChars; ++i)
  7801. {
  7802. if (src[i] == 0)
  7803. {
  7804. position += i + 1;
  7805. return String::fromUTF8 (src, i);
  7806. }
  7807. }
  7808. }
  7809. return InputStream::readString();
  7810. }
  7811. END_JUCE_NAMESPACE
  7812. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7813. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7814. BEGIN_JUCE_NAMESPACE
  7815. FileInputSource::FileInputSource (const File& file_)
  7816. : file (file_)
  7817. {
  7818. }
  7819. FileInputSource::~FileInputSource()
  7820. {
  7821. }
  7822. InputStream* FileInputSource::createInputStream()
  7823. {
  7824. return file.createInputStream();
  7825. }
  7826. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7827. {
  7828. return file.getSiblingFile (relatedItemPath).createInputStream();
  7829. }
  7830. int64 FileInputSource::hashCode() const
  7831. {
  7832. return file.hashCode();
  7833. }
  7834. END_JUCE_NAMESPACE
  7835. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7836. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7837. BEGIN_JUCE_NAMESPACE
  7838. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7839. const size_t sourceDataSize,
  7840. const bool keepInternalCopy)
  7841. : data (static_cast <const char*> (sourceData)),
  7842. dataSize (sourceDataSize),
  7843. position (0)
  7844. {
  7845. if (keepInternalCopy)
  7846. {
  7847. internalCopy.append (data, sourceDataSize);
  7848. data = static_cast <const char*> (internalCopy.getData());
  7849. }
  7850. }
  7851. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7852. const bool keepInternalCopy)
  7853. : data (static_cast <const char*> (sourceData.getData())),
  7854. dataSize (sourceData.getSize()),
  7855. position (0)
  7856. {
  7857. if (keepInternalCopy)
  7858. {
  7859. internalCopy = sourceData;
  7860. data = static_cast <const char*> (internalCopy.getData());
  7861. }
  7862. }
  7863. MemoryInputStream::~MemoryInputStream()
  7864. {
  7865. }
  7866. int64 MemoryInputStream::getTotalLength()
  7867. {
  7868. return dataSize;
  7869. }
  7870. int MemoryInputStream::read (void* const buffer, const int howMany)
  7871. {
  7872. jassert (howMany >= 0);
  7873. const int num = jmin (howMany, (int) (dataSize - position));
  7874. memcpy (buffer, data + position, num);
  7875. position += num;
  7876. return (int) num;
  7877. }
  7878. bool MemoryInputStream::isExhausted()
  7879. {
  7880. return (position >= dataSize);
  7881. }
  7882. bool MemoryInputStream::setPosition (const int64 pos)
  7883. {
  7884. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7885. return true;
  7886. }
  7887. int64 MemoryInputStream::getPosition()
  7888. {
  7889. return position;
  7890. }
  7891. #if JUCE_UNIT_TESTS
  7892. class MemoryStreamTests : public UnitTest
  7893. {
  7894. public:
  7895. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  7896. void runTest()
  7897. {
  7898. beginTest ("Basics");
  7899. int randomInt = Random::getSystemRandom().nextInt();
  7900. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  7901. double randomDouble = Random::getSystemRandom().nextDouble();
  7902. String randomString;
  7903. for (int i = 50; --i >= 0;)
  7904. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  7905. MemoryOutputStream mo;
  7906. mo.writeInt (randomInt);
  7907. mo.writeIntBigEndian (randomInt);
  7908. mo.writeCompressedInt (randomInt);
  7909. mo.writeString (randomString);
  7910. mo.writeInt64 (randomInt64);
  7911. mo.writeInt64BigEndian (randomInt64);
  7912. mo.writeDouble (randomDouble);
  7913. mo.writeDoubleBigEndian (randomDouble);
  7914. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  7915. expect (mi.readInt() == randomInt);
  7916. expect (mi.readIntBigEndian() == randomInt);
  7917. expect (mi.readCompressedInt() == randomInt);
  7918. expect (mi.readString() == randomString);
  7919. expect (mi.readInt64() == randomInt64);
  7920. expect (mi.readInt64BigEndian() == randomInt64);
  7921. expect (mi.readDouble() == randomDouble);
  7922. expect (mi.readDoubleBigEndian() == randomDouble);
  7923. }
  7924. };
  7925. static MemoryStreamTests memoryInputStreamUnitTests;
  7926. #endif
  7927. END_JUCE_NAMESPACE
  7928. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7929. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7930. BEGIN_JUCE_NAMESPACE
  7931. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  7932. : data (internalBlock),
  7933. position (0),
  7934. size (0)
  7935. {
  7936. internalBlock.setSize (initialSize, false);
  7937. }
  7938. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  7939. const bool appendToExistingBlockContent)
  7940. : data (memoryBlockToWriteTo),
  7941. position (0),
  7942. size (0)
  7943. {
  7944. if (appendToExistingBlockContent)
  7945. position = size = memoryBlockToWriteTo.getSize();
  7946. }
  7947. MemoryOutputStream::~MemoryOutputStream()
  7948. {
  7949. flush();
  7950. }
  7951. void MemoryOutputStream::flush()
  7952. {
  7953. if (&data != &internalBlock)
  7954. data.setSize (size, false);
  7955. }
  7956. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  7957. {
  7958. data.ensureSize (bytesToPreallocate + 1);
  7959. }
  7960. void MemoryOutputStream::reset() throw()
  7961. {
  7962. position = 0;
  7963. size = 0;
  7964. }
  7965. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7966. {
  7967. if (howMany > 0)
  7968. {
  7969. const size_t storageNeeded = position + howMany;
  7970. if (storageNeeded >= data.getSize())
  7971. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  7972. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  7973. position += howMany;
  7974. size = jmax (size, position);
  7975. }
  7976. return true;
  7977. }
  7978. const void* MemoryOutputStream::getData() const throw()
  7979. {
  7980. void* const d = data.getData();
  7981. if (data.getSize() > size)
  7982. static_cast <char*> (d) [size] = 0;
  7983. return d;
  7984. }
  7985. bool MemoryOutputStream::setPosition (int64 newPosition)
  7986. {
  7987. if (newPosition <= (int64) size)
  7988. {
  7989. // ok to seek backwards
  7990. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7991. return true;
  7992. }
  7993. else
  7994. {
  7995. // trying to make it bigger isn't a good thing to do..
  7996. return false;
  7997. }
  7998. }
  7999. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8000. {
  8001. // before writing from an input, see if we can preallocate to make it more efficient..
  8002. int64 availableData = source.getTotalLength() - source.getPosition();
  8003. if (availableData > 0)
  8004. {
  8005. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8006. availableData = maxNumBytesToWrite;
  8007. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8008. }
  8009. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8010. }
  8011. const String MemoryOutputStream::toUTF8() const
  8012. {
  8013. return String (static_cast <const char*> (getData()), getDataSize());
  8014. }
  8015. const String MemoryOutputStream::toString() const
  8016. {
  8017. return String::createStringFromData (getData(), getDataSize());
  8018. }
  8019. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8020. {
  8021. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8022. return stream;
  8023. }
  8024. END_JUCE_NAMESPACE
  8025. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8026. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8027. BEGIN_JUCE_NAMESPACE
  8028. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8029. const int64 startPositionInSourceStream_,
  8030. const int64 lengthOfSourceStream_,
  8031. const bool deleteSourceWhenDestroyed)
  8032. : source (sourceStream),
  8033. startPositionInSourceStream (startPositionInSourceStream_),
  8034. lengthOfSourceStream (lengthOfSourceStream_)
  8035. {
  8036. if (deleteSourceWhenDestroyed)
  8037. sourceToDelete = source;
  8038. setPosition (0);
  8039. }
  8040. SubregionStream::~SubregionStream()
  8041. {
  8042. }
  8043. int64 SubregionStream::getTotalLength()
  8044. {
  8045. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8046. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8047. : srcLen;
  8048. }
  8049. int64 SubregionStream::getPosition()
  8050. {
  8051. return source->getPosition() - startPositionInSourceStream;
  8052. }
  8053. bool SubregionStream::setPosition (int64 newPosition)
  8054. {
  8055. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8056. }
  8057. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8058. {
  8059. if (lengthOfSourceStream < 0)
  8060. {
  8061. return source->read (destBuffer, maxBytesToRead);
  8062. }
  8063. else
  8064. {
  8065. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8066. if (maxBytesToRead <= 0)
  8067. return 0;
  8068. return source->read (destBuffer, maxBytesToRead);
  8069. }
  8070. }
  8071. bool SubregionStream::isExhausted()
  8072. {
  8073. if (lengthOfSourceStream >= 0)
  8074. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8075. else
  8076. return source->isExhausted();
  8077. }
  8078. END_JUCE_NAMESPACE
  8079. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8080. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8081. BEGIN_JUCE_NAMESPACE
  8082. PerformanceCounter::PerformanceCounter (const String& name_,
  8083. int runsPerPrintout,
  8084. const File& loggingFile)
  8085. : name (name_),
  8086. numRuns (0),
  8087. runsPerPrint (runsPerPrintout),
  8088. totalTime (0),
  8089. outputFile (loggingFile)
  8090. {
  8091. if (outputFile != File::nonexistent)
  8092. {
  8093. String s ("**** Counter for \"");
  8094. s << name_ << "\" started at: "
  8095. << Time::getCurrentTime().toString (true, true)
  8096. << "\r\n";
  8097. outputFile.appendText (s, false, false);
  8098. }
  8099. }
  8100. PerformanceCounter::~PerformanceCounter()
  8101. {
  8102. printStatistics();
  8103. }
  8104. void PerformanceCounter::start()
  8105. {
  8106. started = Time::getHighResolutionTicks();
  8107. }
  8108. void PerformanceCounter::stop()
  8109. {
  8110. const int64 now = Time::getHighResolutionTicks();
  8111. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8112. if (++numRuns == runsPerPrint)
  8113. printStatistics();
  8114. }
  8115. void PerformanceCounter::printStatistics()
  8116. {
  8117. if (numRuns > 0)
  8118. {
  8119. String s ("Performance count for \"");
  8120. s << name << "\" - average over " << numRuns << " run(s) = ";
  8121. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8122. if (micros > 10000)
  8123. s << (micros/1000) << " millisecs";
  8124. else
  8125. s << micros << " microsecs";
  8126. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8127. Logger::outputDebugString (s);
  8128. s << "\r\n";
  8129. if (outputFile != File::nonexistent)
  8130. outputFile.appendText (s, false, false);
  8131. numRuns = 0;
  8132. totalTime = 0;
  8133. }
  8134. }
  8135. END_JUCE_NAMESPACE
  8136. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8137. /*** Start of inlined file: juce_Uuid.cpp ***/
  8138. BEGIN_JUCE_NAMESPACE
  8139. Uuid::Uuid()
  8140. {
  8141. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8142. // to make it very very unlikely that two UUIDs will ever be the same..
  8143. static int64 macAddresses[2];
  8144. static bool hasCheckedMacAddresses = false;
  8145. if (! hasCheckedMacAddresses)
  8146. {
  8147. hasCheckedMacAddresses = true;
  8148. SystemStats::getMACAddresses (macAddresses, 2);
  8149. }
  8150. value.asInt64[0] = macAddresses[0];
  8151. value.asInt64[1] = macAddresses[1];
  8152. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8153. // whose seed will carry over between calls to this method.
  8154. Random r (macAddresses[0] ^ macAddresses[1]
  8155. ^ Random::getSystemRandom().nextInt64());
  8156. for (int i = 4; --i >= 0;)
  8157. {
  8158. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8159. value.asInt[i] ^= r.nextInt();
  8160. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8161. }
  8162. }
  8163. Uuid::~Uuid() throw()
  8164. {
  8165. }
  8166. Uuid::Uuid (const Uuid& other)
  8167. : value (other.value)
  8168. {
  8169. }
  8170. Uuid& Uuid::operator= (const Uuid& other)
  8171. {
  8172. value = other.value;
  8173. return *this;
  8174. }
  8175. bool Uuid::operator== (const Uuid& other) const
  8176. {
  8177. return value.asInt64[0] == other.value.asInt64[0]
  8178. && value.asInt64[1] == other.value.asInt64[1];
  8179. }
  8180. bool Uuid::operator!= (const Uuid& other) const
  8181. {
  8182. return ! operator== (other);
  8183. }
  8184. bool Uuid::isNull() const throw()
  8185. {
  8186. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8187. }
  8188. const String Uuid::toString() const
  8189. {
  8190. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8191. }
  8192. Uuid::Uuid (const String& uuidString)
  8193. {
  8194. operator= (uuidString);
  8195. }
  8196. Uuid& Uuid::operator= (const String& uuidString)
  8197. {
  8198. MemoryBlock mb;
  8199. mb.loadFromHexString (uuidString);
  8200. mb.ensureSize (sizeof (value.asBytes), true);
  8201. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8202. return *this;
  8203. }
  8204. Uuid::Uuid (const uint8* const rawData)
  8205. {
  8206. operator= (rawData);
  8207. }
  8208. Uuid& Uuid::operator= (const uint8* const rawData)
  8209. {
  8210. if (rawData != 0)
  8211. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8212. else
  8213. zeromem (value.asBytes, sizeof (value.asBytes));
  8214. return *this;
  8215. }
  8216. END_JUCE_NAMESPACE
  8217. /*** End of inlined file: juce_Uuid.cpp ***/
  8218. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8219. BEGIN_JUCE_NAMESPACE
  8220. class ZipFile::ZipEntryInfo
  8221. {
  8222. public:
  8223. ZipFile::ZipEntry entry;
  8224. int streamOffset;
  8225. int compressedSize;
  8226. bool compressed;
  8227. };
  8228. class ZipFile::ZipInputStream : public InputStream
  8229. {
  8230. public:
  8231. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8232. : file (file_),
  8233. zipEntryInfo (zei),
  8234. pos (0),
  8235. headerSize (0),
  8236. inputStream (0)
  8237. {
  8238. inputStream = file_.inputStream;
  8239. if (file_.inputSource != 0)
  8240. {
  8241. inputStream = file.inputSource->createInputStream();
  8242. }
  8243. else
  8244. {
  8245. #if JUCE_DEBUG
  8246. file_.numOpenStreams++;
  8247. #endif
  8248. }
  8249. char buffer [30];
  8250. if (inputStream != 0
  8251. && inputStream->setPosition (zei.streamOffset)
  8252. && inputStream->read (buffer, 30) == 30
  8253. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8254. {
  8255. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8256. + ByteOrder::littleEndianShort (buffer + 28);
  8257. }
  8258. }
  8259. ~ZipInputStream()
  8260. {
  8261. #if JUCE_DEBUG
  8262. if (inputStream != 0 && inputStream == file.inputStream)
  8263. file.numOpenStreams--;
  8264. #endif
  8265. if (inputStream != file.inputStream)
  8266. delete inputStream;
  8267. }
  8268. int64 getTotalLength()
  8269. {
  8270. return zipEntryInfo.compressedSize;
  8271. }
  8272. int read (void* buffer, int howMany)
  8273. {
  8274. if (headerSize <= 0)
  8275. return 0;
  8276. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8277. if (inputStream == 0)
  8278. return 0;
  8279. int num;
  8280. if (inputStream == file.inputStream)
  8281. {
  8282. const ScopedLock sl (file.lock);
  8283. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8284. num = inputStream->read (buffer, howMany);
  8285. }
  8286. else
  8287. {
  8288. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8289. num = inputStream->read (buffer, howMany);
  8290. }
  8291. pos += num;
  8292. return num;
  8293. }
  8294. bool isExhausted()
  8295. {
  8296. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8297. }
  8298. int64 getPosition()
  8299. {
  8300. return pos;
  8301. }
  8302. bool setPosition (int64 newPos)
  8303. {
  8304. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8305. return true;
  8306. }
  8307. private:
  8308. ZipFile& file;
  8309. ZipEntryInfo zipEntryInfo;
  8310. int64 pos;
  8311. int headerSize;
  8312. InputStream* inputStream;
  8313. ZipInputStream (const ZipInputStream&);
  8314. ZipInputStream& operator= (const ZipInputStream&);
  8315. };
  8316. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8317. : inputStream (source_)
  8318. #if JUCE_DEBUG
  8319. , numOpenStreams (0)
  8320. #endif
  8321. {
  8322. if (deleteStreamWhenDestroyed)
  8323. streamToDelete = inputStream;
  8324. init();
  8325. }
  8326. ZipFile::ZipFile (const File& file)
  8327. : inputStream (0)
  8328. #if JUCE_DEBUG
  8329. , numOpenStreams (0)
  8330. #endif
  8331. {
  8332. inputSource = new FileInputSource (file);
  8333. init();
  8334. }
  8335. ZipFile::ZipFile (InputSource* const inputSource_)
  8336. : inputStream (0),
  8337. inputSource (inputSource_)
  8338. #if JUCE_DEBUG
  8339. , numOpenStreams (0)
  8340. #endif
  8341. {
  8342. init();
  8343. }
  8344. ZipFile::~ZipFile()
  8345. {
  8346. #if JUCE_DEBUG
  8347. entries.clear();
  8348. // If you hit this assertion, it means you've created a stream to read
  8349. // one of the items in the zipfile, but you've forgotten to delete that
  8350. // stream object before deleting the file.. Streams can't be kept open
  8351. // after the file is deleted because they need to share the input
  8352. // stream that the file uses to read itself.
  8353. jassert (numOpenStreams == 0);
  8354. #endif
  8355. }
  8356. int ZipFile::getNumEntries() const throw()
  8357. {
  8358. return entries.size();
  8359. }
  8360. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8361. {
  8362. ZipEntryInfo* const zei = entries [index];
  8363. return zei != 0 ? &(zei->entry) : 0;
  8364. }
  8365. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8366. {
  8367. for (int i = 0; i < entries.size(); ++i)
  8368. if (entries.getUnchecked (i)->entry.filename == fileName)
  8369. return i;
  8370. return -1;
  8371. }
  8372. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8373. {
  8374. return getEntry (getIndexOfFileName (fileName));
  8375. }
  8376. InputStream* ZipFile::createStreamForEntry (const int index)
  8377. {
  8378. ZipEntryInfo* const zei = entries[index];
  8379. InputStream* stream = 0;
  8380. if (zei != 0)
  8381. {
  8382. stream = new ZipInputStream (*this, *zei);
  8383. if (zei->compressed)
  8384. {
  8385. stream = new GZIPDecompressorInputStream (stream, true, true,
  8386. zei->entry.uncompressedSize);
  8387. // (much faster to unzip in big blocks using a buffer..)
  8388. stream = new BufferedInputStream (stream, 32768, true);
  8389. }
  8390. }
  8391. return stream;
  8392. }
  8393. class ZipFile::ZipFilenameComparator
  8394. {
  8395. public:
  8396. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8397. {
  8398. return first->entry.filename.compare (second->entry.filename);
  8399. }
  8400. };
  8401. void ZipFile::sortEntriesByFilename()
  8402. {
  8403. ZipFilenameComparator sorter;
  8404. entries.sort (sorter);
  8405. }
  8406. void ZipFile::init()
  8407. {
  8408. ScopedPointer <InputStream> toDelete;
  8409. InputStream* in = inputStream;
  8410. if (inputSource != 0)
  8411. {
  8412. in = inputSource->createInputStream();
  8413. toDelete = in;
  8414. }
  8415. if (in != 0)
  8416. {
  8417. int numEntries = 0;
  8418. int pos = findEndOfZipEntryTable (in, numEntries);
  8419. if (pos >= 0 && pos < in->getTotalLength())
  8420. {
  8421. const int size = (int) (in->getTotalLength() - pos);
  8422. in->setPosition (pos);
  8423. MemoryBlock headerData;
  8424. if (in->readIntoMemoryBlock (headerData, size) == size)
  8425. {
  8426. pos = 0;
  8427. for (int i = 0; i < numEntries; ++i)
  8428. {
  8429. if (pos + 46 > size)
  8430. break;
  8431. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8432. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8433. if (pos + 46 + fileNameLen > size)
  8434. break;
  8435. ZipEntryInfo* const zei = new ZipEntryInfo();
  8436. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8437. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8438. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8439. const int year = 1980 + (date >> 9);
  8440. const int month = ((date >> 5) & 15) - 1;
  8441. const int day = date & 31;
  8442. const int hours = time >> 11;
  8443. const int minutes = (time >> 5) & 63;
  8444. const int seconds = (time & 31) << 1;
  8445. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8446. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8447. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8448. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8449. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8450. entries.add (zei);
  8451. pos += 46 + fileNameLen
  8452. + ByteOrder::littleEndianShort (buffer + 30)
  8453. + ByteOrder::littleEndianShort (buffer + 32);
  8454. }
  8455. }
  8456. }
  8457. }
  8458. }
  8459. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8460. {
  8461. BufferedInputStream in (input, 8192, false);
  8462. in.setPosition (in.getTotalLength());
  8463. int64 pos = in.getPosition();
  8464. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8465. char buffer [32];
  8466. zeromem (buffer, sizeof (buffer));
  8467. while (pos > lowestPos)
  8468. {
  8469. in.setPosition (pos - 22);
  8470. pos = in.getPosition();
  8471. memcpy (buffer + 22, buffer, 4);
  8472. if (in.read (buffer, 22) != 22)
  8473. return 0;
  8474. for (int i = 0; i < 22; ++i)
  8475. {
  8476. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8477. {
  8478. in.setPosition (pos + i);
  8479. in.read (buffer, 22);
  8480. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8481. return ByteOrder::littleEndianInt (buffer + 16);
  8482. }
  8483. }
  8484. }
  8485. return 0;
  8486. }
  8487. bool ZipFile::uncompressTo (const File& targetDirectory,
  8488. const bool shouldOverwriteFiles)
  8489. {
  8490. for (int i = 0; i < entries.size(); ++i)
  8491. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8492. return false;
  8493. return true;
  8494. }
  8495. bool ZipFile::uncompressEntry (const int index,
  8496. const File& targetDirectory,
  8497. bool shouldOverwriteFiles)
  8498. {
  8499. const ZipEntryInfo* zei = entries [index];
  8500. if (zei != 0)
  8501. {
  8502. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8503. if (zei->entry.filename.endsWithChar ('/'))
  8504. {
  8505. targetFile.createDirectory(); // (entry is a directory, not a file)
  8506. }
  8507. else
  8508. {
  8509. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8510. if (in != 0)
  8511. {
  8512. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8513. return false;
  8514. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8515. {
  8516. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8517. if (out != 0)
  8518. {
  8519. out->writeFromInputStream (*in, -1);
  8520. out = 0;
  8521. targetFile.setCreationTime (zei->entry.fileTime);
  8522. targetFile.setLastModificationTime (zei->entry.fileTime);
  8523. targetFile.setLastAccessTime (zei->entry.fileTime);
  8524. return true;
  8525. }
  8526. }
  8527. }
  8528. }
  8529. }
  8530. return false;
  8531. }
  8532. END_JUCE_NAMESPACE
  8533. /*** End of inlined file: juce_ZipFile.cpp ***/
  8534. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8535. #if JUCE_MSVC
  8536. #pragma warning (push)
  8537. #pragma warning (disable: 4514 4996)
  8538. #endif
  8539. #include <cwctype>
  8540. #include <cctype>
  8541. #include <ctime>
  8542. BEGIN_JUCE_NAMESPACE
  8543. int CharacterFunctions::length (const char* const s) throw()
  8544. {
  8545. return (int) strlen (s);
  8546. }
  8547. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8548. {
  8549. return (int) wcslen (s);
  8550. }
  8551. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8552. {
  8553. strncpy (dest, src, maxChars);
  8554. }
  8555. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8556. {
  8557. wcsncpy (dest, src, maxChars);
  8558. }
  8559. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8560. {
  8561. mbstowcs (dest, src, maxChars);
  8562. }
  8563. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8564. {
  8565. wcstombs (dest, src, maxChars);
  8566. }
  8567. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8568. {
  8569. return (int) wcstombs (0, src, 0);
  8570. }
  8571. void CharacterFunctions::append (char* dest, const char* src) throw()
  8572. {
  8573. strcat (dest, src);
  8574. }
  8575. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8576. {
  8577. wcscat (dest, src);
  8578. }
  8579. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8580. {
  8581. return strcmp (s1, s2);
  8582. }
  8583. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8584. {
  8585. jassert (s1 != 0 && s2 != 0);
  8586. return wcscmp (s1, s2);
  8587. }
  8588. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8589. {
  8590. jassert (s1 != 0 && s2 != 0);
  8591. return strncmp (s1, s2, maxChars);
  8592. }
  8593. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8594. {
  8595. jassert (s1 != 0 && s2 != 0);
  8596. return wcsncmp (s1, s2, maxChars);
  8597. }
  8598. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8599. {
  8600. jassert (s1 != 0 && s2 != 0);
  8601. for (;;)
  8602. {
  8603. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8604. if (diff != 0)
  8605. return diff;
  8606. else if (*s1 == 0)
  8607. break;
  8608. ++s1;
  8609. ++s2;
  8610. }
  8611. return 0;
  8612. }
  8613. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8614. {
  8615. return -compare (s2, s1);
  8616. }
  8617. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8618. {
  8619. jassert (s1 != 0 && s2 != 0);
  8620. #if JUCE_WINDOWS
  8621. return stricmp (s1, s2);
  8622. #else
  8623. return strcasecmp (s1, s2);
  8624. #endif
  8625. }
  8626. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8627. {
  8628. jassert (s1 != 0 && s2 != 0);
  8629. #if JUCE_WINDOWS
  8630. return _wcsicmp (s1, s2);
  8631. #else
  8632. for (;;)
  8633. {
  8634. if (*s1 != *s2)
  8635. {
  8636. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8637. if (diff != 0)
  8638. return diff < 0 ? -1 : 1;
  8639. }
  8640. else if (*s1 == 0)
  8641. break;
  8642. ++s1;
  8643. ++s2;
  8644. }
  8645. return 0;
  8646. #endif
  8647. }
  8648. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8649. {
  8650. jassert (s1 != 0 && s2 != 0);
  8651. for (;;)
  8652. {
  8653. if (*s1 != *s2)
  8654. {
  8655. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8656. if (diff != 0)
  8657. return diff < 0 ? -1 : 1;
  8658. }
  8659. else if (*s1 == 0)
  8660. break;
  8661. ++s1;
  8662. ++s2;
  8663. }
  8664. return 0;
  8665. }
  8666. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8667. {
  8668. jassert (s1 != 0 && s2 != 0);
  8669. #if JUCE_WINDOWS
  8670. return strnicmp (s1, s2, maxChars);
  8671. #else
  8672. return strncasecmp (s1, s2, maxChars);
  8673. #endif
  8674. }
  8675. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8676. {
  8677. jassert (s1 != 0 && s2 != 0);
  8678. #if JUCE_WINDOWS
  8679. return _wcsnicmp (s1, s2, maxChars);
  8680. #else
  8681. while (--maxChars >= 0)
  8682. {
  8683. if (*s1 != *s2)
  8684. {
  8685. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8686. if (diff != 0)
  8687. return diff < 0 ? -1 : 1;
  8688. }
  8689. else if (*s1 == 0)
  8690. break;
  8691. ++s1;
  8692. ++s2;
  8693. }
  8694. return 0;
  8695. #endif
  8696. }
  8697. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8698. {
  8699. return strstr (haystack, needle);
  8700. }
  8701. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8702. {
  8703. return wcsstr (haystack, needle);
  8704. }
  8705. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8706. {
  8707. if (haystack != 0)
  8708. {
  8709. int i = 0;
  8710. if (ignoreCase)
  8711. {
  8712. const char n1 = toLowerCase (needle);
  8713. const char n2 = toUpperCase (needle);
  8714. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8715. {
  8716. while (haystack[i] != 0)
  8717. {
  8718. if (haystack[i] == n1 || haystack[i] == n2)
  8719. return i;
  8720. ++i;
  8721. }
  8722. return -1;
  8723. }
  8724. jassert (n1 == needle);
  8725. }
  8726. while (haystack[i] != 0)
  8727. {
  8728. if (haystack[i] == needle)
  8729. return i;
  8730. ++i;
  8731. }
  8732. }
  8733. return -1;
  8734. }
  8735. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8736. {
  8737. if (haystack != 0)
  8738. {
  8739. int i = 0;
  8740. if (ignoreCase)
  8741. {
  8742. const juce_wchar n1 = toLowerCase (needle);
  8743. const juce_wchar n2 = toUpperCase (needle);
  8744. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8745. {
  8746. while (haystack[i] != 0)
  8747. {
  8748. if (haystack[i] == n1 || haystack[i] == n2)
  8749. return i;
  8750. ++i;
  8751. }
  8752. return -1;
  8753. }
  8754. jassert (n1 == needle);
  8755. }
  8756. while (haystack[i] != 0)
  8757. {
  8758. if (haystack[i] == needle)
  8759. return i;
  8760. ++i;
  8761. }
  8762. }
  8763. return -1;
  8764. }
  8765. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8766. {
  8767. jassert (haystack != 0);
  8768. int i = 0;
  8769. while (haystack[i] != 0)
  8770. {
  8771. if (haystack[i] == needle)
  8772. return i;
  8773. ++i;
  8774. }
  8775. return -1;
  8776. }
  8777. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8778. {
  8779. jassert (haystack != 0);
  8780. int i = 0;
  8781. while (haystack[i] != 0)
  8782. {
  8783. if (haystack[i] == needle)
  8784. return i;
  8785. ++i;
  8786. }
  8787. return -1;
  8788. }
  8789. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8790. {
  8791. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8792. }
  8793. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8794. {
  8795. if (allowedChars == 0)
  8796. return 0;
  8797. int i = 0;
  8798. for (;;)
  8799. {
  8800. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8801. break;
  8802. ++i;
  8803. }
  8804. return i;
  8805. }
  8806. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8807. {
  8808. return (int) strftime (dest, maxChars, format, tm);
  8809. }
  8810. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8811. {
  8812. return (int) wcsftime (dest, maxChars, format, tm);
  8813. }
  8814. int CharacterFunctions::getIntValue (const char* const s) throw()
  8815. {
  8816. return atoi (s);
  8817. }
  8818. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8819. {
  8820. #if JUCE_WINDOWS
  8821. return _wtoi (s);
  8822. #else
  8823. int v = 0;
  8824. while (isWhitespace (*s))
  8825. ++s;
  8826. const bool isNeg = *s == '-';
  8827. if (isNeg)
  8828. ++s;
  8829. for (;;)
  8830. {
  8831. const wchar_t c = *s++;
  8832. if (c >= '0' && c <= '9')
  8833. v = v * 10 + (int) (c - '0');
  8834. else
  8835. break;
  8836. }
  8837. return isNeg ? -v : v;
  8838. #endif
  8839. }
  8840. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8841. {
  8842. #if JUCE_LINUX
  8843. return atoll (s);
  8844. #elif JUCE_WINDOWS
  8845. return _atoi64 (s);
  8846. #else
  8847. int64 v = 0;
  8848. while (isWhitespace (*s))
  8849. ++s;
  8850. const bool isNeg = *s == '-';
  8851. if (isNeg)
  8852. ++s;
  8853. for (;;)
  8854. {
  8855. const char c = *s++;
  8856. if (c >= '0' && c <= '9')
  8857. v = v * 10 + (int64) (c - '0');
  8858. else
  8859. break;
  8860. }
  8861. return isNeg ? -v : v;
  8862. #endif
  8863. }
  8864. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8865. {
  8866. #if JUCE_WINDOWS
  8867. return _wtoi64 (s);
  8868. #else
  8869. int64 v = 0;
  8870. while (isWhitespace (*s))
  8871. ++s;
  8872. const bool isNeg = *s == '-';
  8873. if (isNeg)
  8874. ++s;
  8875. for (;;)
  8876. {
  8877. const juce_wchar c = *s++;
  8878. if (c >= '0' && c <= '9')
  8879. v = v * 10 + (int64) (c - '0');
  8880. else
  8881. break;
  8882. }
  8883. return isNeg ? -v : v;
  8884. #endif
  8885. }
  8886. static double juce_mulexp10 (const double value, int exponent) throw()
  8887. {
  8888. if (exponent == 0)
  8889. return value;
  8890. if (value == 0)
  8891. return 0;
  8892. const bool negative = (exponent < 0);
  8893. if (negative)
  8894. exponent = -exponent;
  8895. double result = 1.0, power = 10.0;
  8896. for (int bit = 1; exponent != 0; bit <<= 1)
  8897. {
  8898. if ((exponent & bit) != 0)
  8899. {
  8900. exponent ^= bit;
  8901. result *= power;
  8902. if (exponent == 0)
  8903. break;
  8904. }
  8905. power *= power;
  8906. }
  8907. return negative ? (value / result) : (value * result);
  8908. }
  8909. template <class CharType>
  8910. double juce_atof (const CharType* const original) throw()
  8911. {
  8912. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  8913. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  8914. int exponent = 0, decPointIndex = 0, digit = 0;
  8915. int lastDigit = 0, numSignificantDigits = 0;
  8916. bool isNegative = false, digitsFound = false;
  8917. const int maxSignificantDigits = 15 + 2;
  8918. const CharType* s = original;
  8919. while (CharacterFunctions::isWhitespace (*s))
  8920. ++s;
  8921. switch (*s)
  8922. {
  8923. case '-': isNegative = true; // fall-through..
  8924. case '+': ++s;
  8925. }
  8926. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8927. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8928. for (;;)
  8929. {
  8930. if (CharacterFunctions::isDigit (*s))
  8931. {
  8932. lastDigit = digit;
  8933. digit = *s++ - '0';
  8934. digitsFound = true;
  8935. if (decPointIndex != 0)
  8936. exponentAdjustment[1]++;
  8937. if (numSignificantDigits == 0 && digit == 0)
  8938. continue;
  8939. if (++numSignificantDigits > maxSignificantDigits)
  8940. {
  8941. if (digit > 5)
  8942. ++accumulator [decPointIndex];
  8943. else if (digit == 5 && (lastDigit & 1) != 0)
  8944. ++accumulator [decPointIndex];
  8945. if (decPointIndex > 0)
  8946. exponentAdjustment[1]--;
  8947. else
  8948. exponentAdjustment[0]++;
  8949. while (CharacterFunctions::isDigit (*s))
  8950. {
  8951. ++s;
  8952. if (decPointIndex == 0)
  8953. exponentAdjustment[0]++;
  8954. }
  8955. }
  8956. else
  8957. {
  8958. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8959. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8960. {
  8961. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8962. + accumulator [decPointIndex];
  8963. accumulator [decPointIndex] = 0;
  8964. exponentAccumulator [decPointIndex] = 0;
  8965. }
  8966. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8967. exponentAccumulator [decPointIndex]++;
  8968. }
  8969. }
  8970. else if (decPointIndex == 0 && *s == '.')
  8971. {
  8972. ++s;
  8973. decPointIndex = 1;
  8974. if (numSignificantDigits > maxSignificantDigits)
  8975. {
  8976. while (CharacterFunctions::isDigit (*s))
  8977. ++s;
  8978. break;
  8979. }
  8980. }
  8981. else
  8982. {
  8983. break;
  8984. }
  8985. }
  8986. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8987. if (decPointIndex != 0)
  8988. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8989. if ((*s == 'e' || *s == 'E') && digitsFound)
  8990. {
  8991. bool negativeExponent = false;
  8992. switch (*++s)
  8993. {
  8994. case '-': negativeExponent = true; // fall-through..
  8995. case '+': ++s;
  8996. }
  8997. while (CharacterFunctions::isDigit (*s))
  8998. exponent = (exponent * 10) + (*s++ - '0');
  8999. if (negativeExponent)
  9000. exponent = -exponent;
  9001. }
  9002. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9003. if (decPointIndex != 0)
  9004. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9005. return isNegative ? -r : r;
  9006. }
  9007. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9008. {
  9009. return juce_atof <char> (s);
  9010. }
  9011. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9012. {
  9013. return juce_atof <juce_wchar> (s);
  9014. }
  9015. char CharacterFunctions::toUpperCase (const char character) throw()
  9016. {
  9017. return (char) toupper (character);
  9018. }
  9019. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9020. {
  9021. return towupper (character);
  9022. }
  9023. void CharacterFunctions::toUpperCase (char* s) throw()
  9024. {
  9025. #if JUCE_WINDOWS
  9026. strupr (s);
  9027. #else
  9028. while (*s != 0)
  9029. {
  9030. *s = toUpperCase (*s);
  9031. ++s;
  9032. }
  9033. #endif
  9034. }
  9035. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9036. {
  9037. #if JUCE_WINDOWS
  9038. _wcsupr (s);
  9039. #else
  9040. while (*s != 0)
  9041. {
  9042. *s = toUpperCase (*s);
  9043. ++s;
  9044. }
  9045. #endif
  9046. }
  9047. bool CharacterFunctions::isUpperCase (const char character) throw()
  9048. {
  9049. return isupper (character) != 0;
  9050. }
  9051. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9052. {
  9053. #if JUCE_WINDOWS
  9054. return iswupper (character) != 0;
  9055. #else
  9056. return toLowerCase (character) != character;
  9057. #endif
  9058. }
  9059. char CharacterFunctions::toLowerCase (const char character) throw()
  9060. {
  9061. return (char) tolower (character);
  9062. }
  9063. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9064. {
  9065. return towlower (character);
  9066. }
  9067. void CharacterFunctions::toLowerCase (char* s) throw()
  9068. {
  9069. #if JUCE_WINDOWS
  9070. strlwr (s);
  9071. #else
  9072. while (*s != 0)
  9073. {
  9074. *s = toLowerCase (*s);
  9075. ++s;
  9076. }
  9077. #endif
  9078. }
  9079. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9080. {
  9081. #if JUCE_WINDOWS
  9082. _wcslwr (s);
  9083. #else
  9084. while (*s != 0)
  9085. {
  9086. *s = toLowerCase (*s);
  9087. ++s;
  9088. }
  9089. #endif
  9090. }
  9091. bool CharacterFunctions::isLowerCase (const char character) throw()
  9092. {
  9093. return islower (character) != 0;
  9094. }
  9095. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9096. {
  9097. #if JUCE_WINDOWS
  9098. return iswlower (character) != 0;
  9099. #else
  9100. return toUpperCase (character) != character;
  9101. #endif
  9102. }
  9103. bool CharacterFunctions::isWhitespace (const char character) throw()
  9104. {
  9105. return character == ' ' || (character <= 13 && character >= 9);
  9106. }
  9107. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9108. {
  9109. return iswspace (character) != 0;
  9110. }
  9111. bool CharacterFunctions::isDigit (const char character) throw()
  9112. {
  9113. return (character >= '0' && character <= '9');
  9114. }
  9115. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9116. {
  9117. return iswdigit (character) != 0;
  9118. }
  9119. bool CharacterFunctions::isLetter (const char character) throw()
  9120. {
  9121. return (character >= 'a' && character <= 'z')
  9122. || (character >= 'A' && character <= 'Z');
  9123. }
  9124. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9125. {
  9126. return iswalpha (character) != 0;
  9127. }
  9128. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9129. {
  9130. return (character >= 'a' && character <= 'z')
  9131. || (character >= 'A' && character <= 'Z')
  9132. || (character >= '0' && character <= '9');
  9133. }
  9134. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9135. {
  9136. return iswalnum (character) != 0;
  9137. }
  9138. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9139. {
  9140. unsigned int d = digit - '0';
  9141. if (d < (unsigned int) 10)
  9142. return (int) d;
  9143. d += (unsigned int) ('0' - 'a');
  9144. if (d < (unsigned int) 6)
  9145. return (int) d + 10;
  9146. d += (unsigned int) ('a' - 'A');
  9147. if (d < (unsigned int) 6)
  9148. return (int) d + 10;
  9149. return -1;
  9150. }
  9151. #if JUCE_MSVC
  9152. #pragma warning (pop)
  9153. #endif
  9154. END_JUCE_NAMESPACE
  9155. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9156. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9157. BEGIN_JUCE_NAMESPACE
  9158. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9159. {
  9160. loadFromText (fileContents);
  9161. }
  9162. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9163. {
  9164. loadFromText (fileToLoad.loadFileAsString());
  9165. }
  9166. LocalisedStrings::~LocalisedStrings()
  9167. {
  9168. }
  9169. const String LocalisedStrings::translate (const String& text) const
  9170. {
  9171. return translations.getValue (text, text);
  9172. }
  9173. static int findCloseQuote (const String& text, int startPos)
  9174. {
  9175. juce_wchar lastChar = 0;
  9176. for (;;)
  9177. {
  9178. const juce_wchar c = text [startPos];
  9179. if (c == 0 || (c == '"' && lastChar != '\\'))
  9180. break;
  9181. lastChar = c;
  9182. ++startPos;
  9183. }
  9184. return startPos;
  9185. }
  9186. static const String unescapeString (const String& s)
  9187. {
  9188. return s.replace ("\\\"", "\"")
  9189. .replace ("\\\'", "\'")
  9190. .replace ("\\t", "\t")
  9191. .replace ("\\r", "\r")
  9192. .replace ("\\n", "\n");
  9193. }
  9194. void LocalisedStrings::loadFromText (const String& fileContents)
  9195. {
  9196. StringArray lines;
  9197. lines.addLines (fileContents);
  9198. for (int i = 0; i < lines.size(); ++i)
  9199. {
  9200. String line (lines[i].trim());
  9201. if (line.startsWithChar ('"'))
  9202. {
  9203. int closeQuote = findCloseQuote (line, 1);
  9204. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9205. if (originalText.isNotEmpty())
  9206. {
  9207. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9208. closeQuote = findCloseQuote (line, openingQuote + 1);
  9209. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9210. if (newText.isNotEmpty())
  9211. translations.set (originalText, newText);
  9212. }
  9213. }
  9214. else if (line.startsWithIgnoreCase ("language:"))
  9215. {
  9216. languageName = line.substring (9).trim();
  9217. }
  9218. else if (line.startsWithIgnoreCase ("countries:"))
  9219. {
  9220. countryCodes.addTokens (line.substring (10).trim(), true);
  9221. countryCodes.trim();
  9222. countryCodes.removeEmptyStrings();
  9223. }
  9224. }
  9225. }
  9226. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9227. {
  9228. translations.setIgnoresCase (shouldIgnoreCase);
  9229. }
  9230. static CriticalSection currentMappingsLock;
  9231. static LocalisedStrings* currentMappings = 0;
  9232. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9233. {
  9234. const ScopedLock sl (currentMappingsLock);
  9235. delete currentMappings;
  9236. currentMappings = newTranslations;
  9237. }
  9238. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9239. {
  9240. return currentMappings;
  9241. }
  9242. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9243. {
  9244. const ScopedLock sl (currentMappingsLock);
  9245. if (currentMappings != 0)
  9246. return currentMappings->translate (text);
  9247. return text;
  9248. }
  9249. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9250. {
  9251. return translateWithCurrentMappings (String (text));
  9252. }
  9253. END_JUCE_NAMESPACE
  9254. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9255. /*** Start of inlined file: juce_String.cpp ***/
  9256. #if JUCE_MSVC
  9257. #pragma warning (push)
  9258. #pragma warning (disable: 4514)
  9259. #endif
  9260. #include <locale>
  9261. BEGIN_JUCE_NAMESPACE
  9262. #if JUCE_MSVC
  9263. #pragma warning (pop)
  9264. #endif
  9265. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9266. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9267. #endif
  9268. class StringHolder
  9269. {
  9270. public:
  9271. StringHolder()
  9272. : refCount (0x3fffffff), allocatedNumChars (0)
  9273. {
  9274. text[0] = 0;
  9275. }
  9276. static juce_wchar* createUninitialised (const size_t numChars)
  9277. {
  9278. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9279. s->refCount.value = 0;
  9280. s->allocatedNumChars = numChars;
  9281. return &(s->text[0]);
  9282. }
  9283. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9284. {
  9285. juce_wchar* const dest = createUninitialised (numChars);
  9286. copyChars (dest, src, numChars);
  9287. return dest;
  9288. }
  9289. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9290. {
  9291. juce_wchar* const dest = createUninitialised (numChars);
  9292. CharacterFunctions::copy (dest, src, (int) numChars);
  9293. dest [numChars] = 0;
  9294. return dest;
  9295. }
  9296. static inline juce_wchar* getEmpty() throw()
  9297. {
  9298. return &(empty.text[0]);
  9299. }
  9300. static void retain (juce_wchar* const text) throw()
  9301. {
  9302. ++(bufferFromText (text)->refCount);
  9303. }
  9304. static inline void release (StringHolder* const b) throw()
  9305. {
  9306. if (--(b->refCount) == -1 && b != &empty)
  9307. delete[] reinterpret_cast <char*> (b);
  9308. }
  9309. static void release (juce_wchar* const text) throw()
  9310. {
  9311. release (bufferFromText (text));
  9312. }
  9313. static juce_wchar* makeUnique (juce_wchar* const text)
  9314. {
  9315. StringHolder* const b = bufferFromText (text);
  9316. if (b->refCount.get() <= 0)
  9317. return text;
  9318. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9319. release (b);
  9320. return newText;
  9321. }
  9322. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9323. {
  9324. StringHolder* const b = bufferFromText (text);
  9325. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9326. return text;
  9327. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9328. copyChars (newText, text, b->allocatedNumChars);
  9329. release (b);
  9330. return newText;
  9331. }
  9332. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9333. {
  9334. return bufferFromText (text)->allocatedNumChars;
  9335. }
  9336. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9337. {
  9338. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9339. dest [numChars] = 0;
  9340. }
  9341. Atomic<int> refCount;
  9342. size_t allocatedNumChars;
  9343. juce_wchar text[1];
  9344. static StringHolder empty;
  9345. private:
  9346. static inline StringHolder* bufferFromText (void* const text) throw()
  9347. {
  9348. // (Can't use offsetof() here because of warnings about this not being a POD)
  9349. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9350. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9351. }
  9352. };
  9353. StringHolder StringHolder::empty;
  9354. const String String::empty;
  9355. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9356. {
  9357. jassert (t[numChars] == 0); // must have a null terminator
  9358. text = StringHolder::createCopy (t, numChars);
  9359. }
  9360. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9361. {
  9362. if (numExtraChars > 0)
  9363. {
  9364. const int oldLen = length();
  9365. const int newTotalLen = oldLen + numExtraChars;
  9366. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9367. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9368. }
  9369. }
  9370. void String::preallocateStorage (const size_t numChars)
  9371. {
  9372. text = StringHolder::makeUniqueWithSize (text, numChars);
  9373. }
  9374. String::String() throw()
  9375. : text (StringHolder::getEmpty())
  9376. {
  9377. }
  9378. String::~String() throw()
  9379. {
  9380. StringHolder::release (text);
  9381. }
  9382. String::String (const String& other) throw()
  9383. : text (other.text)
  9384. {
  9385. StringHolder::retain (text);
  9386. }
  9387. void String::swapWith (String& other) throw()
  9388. {
  9389. swapVariables (text, other.text);
  9390. }
  9391. String& String::operator= (const String& other) throw()
  9392. {
  9393. juce_wchar* const newText = other.text;
  9394. StringHolder::retain (newText);
  9395. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9396. return *this;
  9397. }
  9398. String::String (const size_t numChars, const int /*dummyVariable*/)
  9399. : text (StringHolder::createUninitialised (numChars))
  9400. {
  9401. }
  9402. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9403. {
  9404. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9405. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9406. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9407. }
  9408. String::String (const char* const t)
  9409. {
  9410. if (t != 0 && *t != 0)
  9411. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9412. else
  9413. text = StringHolder::getEmpty();
  9414. }
  9415. String::String (const juce_wchar* const t)
  9416. {
  9417. if (t != 0 && *t != 0)
  9418. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9419. else
  9420. text = StringHolder::getEmpty();
  9421. }
  9422. String::String (const char* const t, const size_t maxChars)
  9423. {
  9424. int i;
  9425. for (i = 0; (size_t) i < maxChars; ++i)
  9426. if (t[i] == 0)
  9427. break;
  9428. if (i > 0)
  9429. text = StringHolder::createCopy (t, i);
  9430. else
  9431. text = StringHolder::getEmpty();
  9432. }
  9433. String::String (const juce_wchar* const t, const size_t maxChars)
  9434. {
  9435. int i;
  9436. for (i = 0; (size_t) i < maxChars; ++i)
  9437. if (t[i] == 0)
  9438. break;
  9439. if (i > 0)
  9440. text = StringHolder::createCopy (t, i);
  9441. else
  9442. text = StringHolder::getEmpty();
  9443. }
  9444. const String String::charToString (const juce_wchar character)
  9445. {
  9446. String result ((size_t) 1, (int) 0);
  9447. result.text[0] = character;
  9448. result.text[1] = 0;
  9449. return result;
  9450. }
  9451. namespace NumberToStringConverters
  9452. {
  9453. // pass in a pointer to the END of a buffer..
  9454. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9455. {
  9456. *--t = 0;
  9457. int64 v = (n >= 0) ? n : -n;
  9458. do
  9459. {
  9460. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9461. v /= 10;
  9462. } while (v > 0);
  9463. if (n < 0)
  9464. *--t = '-';
  9465. return t;
  9466. }
  9467. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9468. {
  9469. *--t = 0;
  9470. do
  9471. {
  9472. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9473. v /= 10;
  9474. } while (v > 0);
  9475. return t;
  9476. }
  9477. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9478. {
  9479. if (n == (int) 0x80000000) // (would cause an overflow)
  9480. return int64ToString (t, n);
  9481. *--t = 0;
  9482. int v = abs (n);
  9483. do
  9484. {
  9485. *--t = (juce_wchar) ('0' + (v % 10));
  9486. v /= 10;
  9487. } while (v > 0);
  9488. if (n < 0)
  9489. *--t = '-';
  9490. return t;
  9491. }
  9492. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9493. {
  9494. *--t = 0;
  9495. do
  9496. {
  9497. *--t = (juce_wchar) ('0' + (v % 10));
  9498. v /= 10;
  9499. } while (v > 0);
  9500. return t;
  9501. }
  9502. static juce_wchar getDecimalPoint()
  9503. {
  9504. #if JUCE_WINDOWS && _MSC_VER < 1400
  9505. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9506. #else
  9507. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9508. #endif
  9509. return dp;
  9510. }
  9511. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9512. {
  9513. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9514. {
  9515. juce_wchar* const end = buffer + numChars;
  9516. juce_wchar* t = end;
  9517. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9518. *--t = (juce_wchar) 0;
  9519. while (numDecPlaces >= 0 || v > 0)
  9520. {
  9521. if (numDecPlaces == 0)
  9522. *--t = getDecimalPoint();
  9523. *--t = (juce_wchar) ('0' + (v % 10));
  9524. v /= 10;
  9525. --numDecPlaces;
  9526. }
  9527. if (n < 0)
  9528. *--t = '-';
  9529. len = end - t - 1;
  9530. return t;
  9531. }
  9532. else
  9533. {
  9534. #if JUCE_WINDOWS
  9535. #if _MSC_VER <= 1400
  9536. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9537. #else
  9538. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9539. #endif
  9540. #else
  9541. len = swprintf (buffer, numChars, L"%.9g", n);
  9542. #endif
  9543. return buffer;
  9544. }
  9545. }
  9546. }
  9547. String::String (const int number)
  9548. {
  9549. juce_wchar buffer [16];
  9550. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9551. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9552. createInternal (start, end - start - 1);
  9553. }
  9554. String::String (const unsigned int number)
  9555. {
  9556. juce_wchar buffer [16];
  9557. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9558. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9559. createInternal (start, end - start - 1);
  9560. }
  9561. String::String (const short number)
  9562. {
  9563. juce_wchar buffer [16];
  9564. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9565. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9566. createInternal (start, end - start - 1);
  9567. }
  9568. String::String (const unsigned short number)
  9569. {
  9570. juce_wchar buffer [16];
  9571. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9572. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9573. createInternal (start, end - start - 1);
  9574. }
  9575. String::String (const int64 number)
  9576. {
  9577. juce_wchar buffer [32];
  9578. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9579. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9580. createInternal (start, end - start - 1);
  9581. }
  9582. String::String (const uint64 number)
  9583. {
  9584. juce_wchar buffer [32];
  9585. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9586. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9587. createInternal (start, end - start - 1);
  9588. }
  9589. String::String (const float number, const int numberOfDecimalPlaces)
  9590. {
  9591. juce_wchar buffer [48];
  9592. size_t len;
  9593. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9594. createInternal (start, len);
  9595. }
  9596. String::String (const double number, const int numberOfDecimalPlaces)
  9597. {
  9598. juce_wchar buffer [48];
  9599. size_t len;
  9600. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9601. createInternal (start, len);
  9602. }
  9603. int String::length() const throw()
  9604. {
  9605. return CharacterFunctions::length (text);
  9606. }
  9607. int String::hashCode() const throw()
  9608. {
  9609. const juce_wchar* t = text;
  9610. int result = 0;
  9611. while (*t != (juce_wchar) 0)
  9612. result = 31 * result + *t++;
  9613. return result;
  9614. }
  9615. int64 String::hashCode64() const throw()
  9616. {
  9617. const juce_wchar* t = text;
  9618. int64 result = 0;
  9619. while (*t != (juce_wchar) 0)
  9620. result = 101 * result + *t++;
  9621. return result;
  9622. }
  9623. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  9624. {
  9625. return string1.compare (string2) == 0;
  9626. }
  9627. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  9628. {
  9629. return string1.compare (string2) == 0;
  9630. }
  9631. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  9632. {
  9633. return string1.compare (string2) == 0;
  9634. }
  9635. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  9636. {
  9637. return string1.compare (string2) != 0;
  9638. }
  9639. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  9640. {
  9641. return string1.compare (string2) != 0;
  9642. }
  9643. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  9644. {
  9645. return string1.compare (string2) != 0;
  9646. }
  9647. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  9648. {
  9649. return string1.compare (string2) > 0;
  9650. }
  9651. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  9652. {
  9653. return string1.compare (string2) < 0;
  9654. }
  9655. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  9656. {
  9657. return string1.compare (string2) >= 0;
  9658. }
  9659. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  9660. {
  9661. return string1.compare (string2) <= 0;
  9662. }
  9663. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9664. {
  9665. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9666. : isEmpty();
  9667. }
  9668. bool String::equalsIgnoreCase (const char* t) const throw()
  9669. {
  9670. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9671. : isEmpty();
  9672. }
  9673. bool String::equalsIgnoreCase (const String& other) const throw()
  9674. {
  9675. return text == other.text
  9676. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9677. }
  9678. int String::compare (const String& other) const throw()
  9679. {
  9680. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9681. }
  9682. int String::compare (const char* other) const throw()
  9683. {
  9684. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9685. }
  9686. int String::compare (const juce_wchar* other) const throw()
  9687. {
  9688. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9689. }
  9690. int String::compareIgnoreCase (const String& other) const throw()
  9691. {
  9692. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9693. }
  9694. int String::compareLexicographically (const String& other) const throw()
  9695. {
  9696. const juce_wchar* s1 = text;
  9697. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9698. ++s1;
  9699. const juce_wchar* s2 = other.text;
  9700. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9701. ++s2;
  9702. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9703. }
  9704. String& String::operator+= (const juce_wchar* const t)
  9705. {
  9706. if (t != 0)
  9707. appendInternal (t, CharacterFunctions::length (t));
  9708. return *this;
  9709. }
  9710. String& String::operator+= (const String& other)
  9711. {
  9712. if (isEmpty())
  9713. operator= (other);
  9714. else
  9715. appendInternal (other.text, other.length());
  9716. return *this;
  9717. }
  9718. String& String::operator+= (const char ch)
  9719. {
  9720. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9721. return operator+= (static_cast <const juce_wchar*> (asString));
  9722. }
  9723. String& String::operator+= (const juce_wchar ch)
  9724. {
  9725. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9726. return operator+= (static_cast <const juce_wchar*> (asString));
  9727. }
  9728. String& String::operator+= (const int number)
  9729. {
  9730. juce_wchar buffer [16];
  9731. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9732. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9733. appendInternal (start, (int) (end - start));
  9734. return *this;
  9735. }
  9736. String& String::operator+= (const unsigned int number)
  9737. {
  9738. juce_wchar buffer [16];
  9739. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9740. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9741. appendInternal (start, (int) (end - start));
  9742. return *this;
  9743. }
  9744. void String::append (const juce_wchar* const other, const int howMany)
  9745. {
  9746. if (howMany > 0)
  9747. {
  9748. int i;
  9749. for (i = 0; i < howMany; ++i)
  9750. if (other[i] == 0)
  9751. break;
  9752. appendInternal (other, i);
  9753. }
  9754. }
  9755. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  9756. {
  9757. String s (string1);
  9758. return s += string2;
  9759. }
  9760. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  9761. {
  9762. String s (string1);
  9763. return s += string2;
  9764. }
  9765. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  9766. {
  9767. return String::charToString (string1) + string2;
  9768. }
  9769. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  9770. {
  9771. return String::charToString (string1) + string2;
  9772. }
  9773. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  9774. {
  9775. return string1 += string2;
  9776. }
  9777. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  9778. {
  9779. return string1 += string2;
  9780. }
  9781. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  9782. {
  9783. return string1 += string2;
  9784. }
  9785. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  9786. {
  9787. return string1 += string2;
  9788. }
  9789. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  9790. {
  9791. return string1 += string2;
  9792. }
  9793. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  9794. {
  9795. return string1 += characterToAppend;
  9796. }
  9797. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  9798. {
  9799. return string1 += characterToAppend;
  9800. }
  9801. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  9802. {
  9803. return string1 += string2;
  9804. }
  9805. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  9806. {
  9807. return string1 += string2;
  9808. }
  9809. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  9810. {
  9811. return string1 += string2;
  9812. }
  9813. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  9814. {
  9815. return string1 += (int) number;
  9816. }
  9817. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  9818. {
  9819. return string1 += number;
  9820. }
  9821. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  9822. {
  9823. return string1 += number;
  9824. }
  9825. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  9826. {
  9827. return string1 += (int) number;
  9828. }
  9829. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  9830. {
  9831. return string1 += (unsigned int) number;
  9832. }
  9833. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9834. {
  9835. return string1 += String (number);
  9836. }
  9837. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9838. {
  9839. return string1 += String (number);
  9840. }
  9841. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9842. {
  9843. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9844. // if lots of large, persistent strings were to be written to streams).
  9845. const int numBytes = text.getNumBytesAsUTF8();
  9846. HeapBlock<char> temp (numBytes + 1);
  9847. text.copyToUTF8 (temp, numBytes + 1);
  9848. stream.write (temp, numBytes);
  9849. return stream;
  9850. }
  9851. int String::indexOfChar (const juce_wchar character) const throw()
  9852. {
  9853. const juce_wchar* t = text;
  9854. for (;;)
  9855. {
  9856. if (*t == character)
  9857. return (int) (t - text);
  9858. if (*t++ == 0)
  9859. return -1;
  9860. }
  9861. }
  9862. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9863. {
  9864. for (int i = length(); --i >= 0;)
  9865. if (text[i] == character)
  9866. return i;
  9867. return -1;
  9868. }
  9869. int String::indexOf (const String& t) const throw()
  9870. {
  9871. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9872. return r == 0 ? -1 : (int) (r - text);
  9873. }
  9874. int String::indexOfChar (const int startIndex,
  9875. const juce_wchar character) const throw()
  9876. {
  9877. if (startIndex > 0 && startIndex >= length())
  9878. return -1;
  9879. const juce_wchar* t = text + jmax (0, startIndex);
  9880. for (;;)
  9881. {
  9882. if (*t == character)
  9883. return (int) (t - text);
  9884. if (*t == 0)
  9885. return -1;
  9886. ++t;
  9887. }
  9888. }
  9889. int String::indexOfAnyOf (const String& charactersToLookFor,
  9890. const int startIndex,
  9891. const bool ignoreCase) const throw()
  9892. {
  9893. if (startIndex > 0 && startIndex >= length())
  9894. return -1;
  9895. const juce_wchar* t = text + jmax (0, startIndex);
  9896. while (*t != 0)
  9897. {
  9898. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  9899. return (int) (t - text);
  9900. ++t;
  9901. }
  9902. return -1;
  9903. }
  9904. int String::indexOf (const int startIndex, const String& other) const throw()
  9905. {
  9906. if (startIndex > 0 && startIndex >= length())
  9907. return -1;
  9908. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  9909. return found == 0 ? -1 : (int) (found - text);
  9910. }
  9911. int String::indexOfIgnoreCase (const String& other) const throw()
  9912. {
  9913. if (other.isNotEmpty())
  9914. {
  9915. const int len = other.length();
  9916. const int end = length() - len;
  9917. for (int i = 0; i <= end; ++i)
  9918. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9919. return i;
  9920. }
  9921. return -1;
  9922. }
  9923. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9924. {
  9925. if (other.isNotEmpty())
  9926. {
  9927. const int len = other.length();
  9928. const int end = length() - len;
  9929. for (int i = jmax (0, startIndex); i <= end; ++i)
  9930. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9931. return i;
  9932. }
  9933. return -1;
  9934. }
  9935. int String::lastIndexOf (const String& other) const throw()
  9936. {
  9937. if (other.isNotEmpty())
  9938. {
  9939. const int len = other.length();
  9940. int i = length() - len;
  9941. if (i >= 0)
  9942. {
  9943. const juce_wchar* n = text + i;
  9944. while (i >= 0)
  9945. {
  9946. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9947. return i;
  9948. --i;
  9949. }
  9950. }
  9951. }
  9952. return -1;
  9953. }
  9954. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9955. {
  9956. if (other.isNotEmpty())
  9957. {
  9958. const int len = other.length();
  9959. int i = length() - len;
  9960. if (i >= 0)
  9961. {
  9962. const juce_wchar* n = text + i;
  9963. while (i >= 0)
  9964. {
  9965. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9966. return i;
  9967. --i;
  9968. }
  9969. }
  9970. }
  9971. return -1;
  9972. }
  9973. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9974. {
  9975. for (int i = length(); --i >= 0;)
  9976. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9977. return i;
  9978. return -1;
  9979. }
  9980. bool String::contains (const String& other) const throw()
  9981. {
  9982. return indexOf (other) >= 0;
  9983. }
  9984. bool String::containsChar (const juce_wchar character) const throw()
  9985. {
  9986. const juce_wchar* t = text;
  9987. for (;;)
  9988. {
  9989. if (*t == 0)
  9990. return false;
  9991. if (*t == character)
  9992. return true;
  9993. ++t;
  9994. }
  9995. }
  9996. bool String::containsIgnoreCase (const String& t) const throw()
  9997. {
  9998. return indexOfIgnoreCase (t) >= 0;
  9999. }
  10000. int String::indexOfWholeWord (const String& word) const throw()
  10001. {
  10002. if (word.isNotEmpty())
  10003. {
  10004. const int wordLen = word.length();
  10005. const int end = length() - wordLen;
  10006. const juce_wchar* t = text;
  10007. for (int i = 0; i <= end; ++i)
  10008. {
  10009. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10010. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10011. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10012. {
  10013. return i;
  10014. }
  10015. ++t;
  10016. }
  10017. }
  10018. return -1;
  10019. }
  10020. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10021. {
  10022. if (word.isNotEmpty())
  10023. {
  10024. const int wordLen = word.length();
  10025. const int end = length() - wordLen;
  10026. const juce_wchar* t = text;
  10027. for (int i = 0; i <= end; ++i)
  10028. {
  10029. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10030. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10031. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10032. {
  10033. return i;
  10034. }
  10035. ++t;
  10036. }
  10037. }
  10038. return -1;
  10039. }
  10040. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10041. {
  10042. return indexOfWholeWord (wordToLookFor) >= 0;
  10043. }
  10044. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10045. {
  10046. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10047. }
  10048. static int indexOfMatch (const juce_wchar* const wildcard,
  10049. const juce_wchar* const test,
  10050. const bool ignoreCase) throw()
  10051. {
  10052. int start = 0;
  10053. while (test [start] != 0)
  10054. {
  10055. int i = 0;
  10056. for (;;)
  10057. {
  10058. const juce_wchar wc = wildcard [i];
  10059. const juce_wchar c = test [i + start];
  10060. if (wc == c
  10061. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10062. || (wc == '?' && c != 0))
  10063. {
  10064. if (wc == 0)
  10065. return start;
  10066. ++i;
  10067. }
  10068. else
  10069. {
  10070. if (wc == '*' && (wildcard [i + 1] == 0
  10071. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10072. {
  10073. return start;
  10074. }
  10075. break;
  10076. }
  10077. }
  10078. ++start;
  10079. }
  10080. return -1;
  10081. }
  10082. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10083. {
  10084. int i = 0;
  10085. for (;;)
  10086. {
  10087. const juce_wchar wc = wildcard.text [i];
  10088. const juce_wchar c = text [i];
  10089. if (wc == c
  10090. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10091. || (wc == '?' && c != 0))
  10092. {
  10093. if (wc == 0)
  10094. return true;
  10095. ++i;
  10096. }
  10097. else
  10098. {
  10099. return wc == '*' && (wildcard [i + 1] == 0
  10100. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10101. }
  10102. }
  10103. }
  10104. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10105. {
  10106. const int len = stringToRepeat.length();
  10107. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10108. juce_wchar* n = result.text;
  10109. *n = 0;
  10110. while (--numberOfTimesToRepeat >= 0)
  10111. {
  10112. StringHolder::copyChars (n, stringToRepeat.text, len);
  10113. n += len;
  10114. }
  10115. return result;
  10116. }
  10117. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10118. {
  10119. jassert (padCharacter != 0);
  10120. const int len = length();
  10121. if (len >= minimumLength || padCharacter == 0)
  10122. return *this;
  10123. String result ((size_t) minimumLength + 1, (int) 0);
  10124. juce_wchar* n = result.text;
  10125. minimumLength -= len;
  10126. while (--minimumLength >= 0)
  10127. *n++ = padCharacter;
  10128. StringHolder::copyChars (n, text, len);
  10129. return result;
  10130. }
  10131. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10132. {
  10133. jassert (padCharacter != 0);
  10134. const int len = length();
  10135. if (len >= minimumLength || padCharacter == 0)
  10136. return *this;
  10137. String result (*this, (size_t) minimumLength);
  10138. juce_wchar* n = result.text + len;
  10139. minimumLength -= len;
  10140. while (--minimumLength >= 0)
  10141. *n++ = padCharacter;
  10142. *n = 0;
  10143. return result;
  10144. }
  10145. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10146. {
  10147. if (index < 0)
  10148. {
  10149. // a negative index to replace from?
  10150. jassertfalse;
  10151. index = 0;
  10152. }
  10153. if (numCharsToReplace < 0)
  10154. {
  10155. // replacing a negative number of characters?
  10156. numCharsToReplace = 0;
  10157. jassertfalse;
  10158. }
  10159. const int len = length();
  10160. if (index + numCharsToReplace > len)
  10161. {
  10162. if (index > len)
  10163. {
  10164. // replacing beyond the end of the string?
  10165. index = len;
  10166. jassertfalse;
  10167. }
  10168. numCharsToReplace = len - index;
  10169. }
  10170. const int newStringLen = stringToInsert.length();
  10171. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10172. if (newTotalLen <= 0)
  10173. return String::empty;
  10174. String result ((size_t) newTotalLen, (int) 0);
  10175. StringHolder::copyChars (result.text, text, index);
  10176. if (newStringLen > 0)
  10177. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10178. const int endStringLen = newTotalLen - (index + newStringLen);
  10179. if (endStringLen > 0)
  10180. StringHolder::copyChars (result.text + (index + newStringLen),
  10181. text + (index + numCharsToReplace),
  10182. endStringLen);
  10183. return result;
  10184. }
  10185. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10186. {
  10187. const int stringToReplaceLen = stringToReplace.length();
  10188. const int stringToInsertLen = stringToInsert.length();
  10189. int i = 0;
  10190. String result (*this);
  10191. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10192. : result.indexOf (i, stringToReplace))) >= 0)
  10193. {
  10194. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10195. i += stringToInsertLen;
  10196. }
  10197. return result;
  10198. }
  10199. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10200. {
  10201. const int index = indexOfChar (charToReplace);
  10202. if (index < 0)
  10203. return *this;
  10204. String result (*this, size_t());
  10205. juce_wchar* t = result.text + index;
  10206. while (*t != 0)
  10207. {
  10208. if (*t == charToReplace)
  10209. *t = charToInsert;
  10210. ++t;
  10211. }
  10212. return result;
  10213. }
  10214. const String String::replaceCharacters (const String& charactersToReplace,
  10215. const String& charactersToInsertInstead) const
  10216. {
  10217. String result (*this, size_t());
  10218. juce_wchar* t = result.text;
  10219. const int len2 = charactersToInsertInstead.length();
  10220. // the two strings passed in are supposed to be the same length!
  10221. jassert (len2 == charactersToReplace.length());
  10222. while (*t != 0)
  10223. {
  10224. const int index = charactersToReplace.indexOfChar (*t);
  10225. if (((unsigned int) index) < (unsigned int) len2)
  10226. *t = charactersToInsertInstead [index];
  10227. ++t;
  10228. }
  10229. return result;
  10230. }
  10231. bool String::startsWith (const String& other) const throw()
  10232. {
  10233. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10234. }
  10235. bool String::startsWithIgnoreCase (const String& other) const throw()
  10236. {
  10237. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10238. }
  10239. bool String::startsWithChar (const juce_wchar character) const throw()
  10240. {
  10241. jassert (character != 0); // strings can't contain a null character!
  10242. return text[0] == character;
  10243. }
  10244. bool String::endsWithChar (const juce_wchar character) const throw()
  10245. {
  10246. jassert (character != 0); // strings can't contain a null character!
  10247. return text[0] != 0
  10248. && text [length() - 1] == character;
  10249. }
  10250. bool String::endsWith (const String& other) const throw()
  10251. {
  10252. const int thisLen = length();
  10253. const int otherLen = other.length();
  10254. return thisLen >= otherLen
  10255. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10256. }
  10257. bool String::endsWithIgnoreCase (const String& other) const throw()
  10258. {
  10259. const int thisLen = length();
  10260. const int otherLen = other.length();
  10261. return thisLen >= otherLen
  10262. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10263. }
  10264. const String String::toUpperCase() const
  10265. {
  10266. String result (*this, size_t());
  10267. CharacterFunctions::toUpperCase (result.text);
  10268. return result;
  10269. }
  10270. const String String::toLowerCase() const
  10271. {
  10272. String result (*this, size_t());
  10273. CharacterFunctions::toLowerCase (result.text);
  10274. return result;
  10275. }
  10276. juce_wchar& String::operator[] (const int index)
  10277. {
  10278. jassert (((unsigned int) index) <= (unsigned int) length());
  10279. text = StringHolder::makeUnique (text);
  10280. return text [index];
  10281. }
  10282. juce_wchar String::getLastCharacter() const throw()
  10283. {
  10284. return isEmpty() ? juce_wchar() : text [length() - 1];
  10285. }
  10286. const String String::substring (int start, int end) const
  10287. {
  10288. if (start < 0)
  10289. start = 0;
  10290. else if (end <= start)
  10291. return empty;
  10292. int len = 0;
  10293. while (len <= end && text [len] != 0)
  10294. ++len;
  10295. if (end >= len)
  10296. {
  10297. if (start == 0)
  10298. return *this;
  10299. end = len;
  10300. }
  10301. return String (text + start, end - start);
  10302. }
  10303. const String String::substring (const int start) const
  10304. {
  10305. if (start <= 0)
  10306. return *this;
  10307. const int len = length();
  10308. if (start >= len)
  10309. return empty;
  10310. return String (text + start, len - start);
  10311. }
  10312. const String String::dropLastCharacters (const int numberToDrop) const
  10313. {
  10314. return String (text, jmax (0, length() - numberToDrop));
  10315. }
  10316. const String String::getLastCharacters (const int numCharacters) const
  10317. {
  10318. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10319. }
  10320. const String String::fromFirstOccurrenceOf (const String& sub,
  10321. const bool includeSubString,
  10322. const bool ignoreCase) const
  10323. {
  10324. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10325. : indexOf (sub);
  10326. if (i < 0)
  10327. return empty;
  10328. return substring (includeSubString ? i : i + sub.length());
  10329. }
  10330. const String String::fromLastOccurrenceOf (const String& sub,
  10331. const bool includeSubString,
  10332. const bool ignoreCase) const
  10333. {
  10334. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10335. : lastIndexOf (sub);
  10336. if (i < 0)
  10337. return *this;
  10338. return substring (includeSubString ? i : i + sub.length());
  10339. }
  10340. const String String::upToFirstOccurrenceOf (const String& sub,
  10341. const bool includeSubString,
  10342. const bool ignoreCase) const
  10343. {
  10344. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10345. : indexOf (sub);
  10346. if (i < 0)
  10347. return *this;
  10348. return substring (0, includeSubString ? i + sub.length() : i);
  10349. }
  10350. const String String::upToLastOccurrenceOf (const String& sub,
  10351. const bool includeSubString,
  10352. const bool ignoreCase) const
  10353. {
  10354. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10355. : lastIndexOf (sub);
  10356. if (i < 0)
  10357. return *this;
  10358. return substring (0, includeSubString ? i + sub.length() : i);
  10359. }
  10360. bool String::isQuotedString() const
  10361. {
  10362. const String trimmed (trimStart());
  10363. return trimmed[0] == '"'
  10364. || trimmed[0] == '\'';
  10365. }
  10366. const String String::unquoted() const
  10367. {
  10368. String s (*this);
  10369. if (s.text[0] == '"' || s.text[0] == '\'')
  10370. s = s.substring (1);
  10371. const int lastCharIndex = s.length() - 1;
  10372. if (lastCharIndex >= 0
  10373. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10374. s [lastCharIndex] = 0;
  10375. return s;
  10376. }
  10377. const String String::quoted (const juce_wchar quoteCharacter) const
  10378. {
  10379. if (isEmpty())
  10380. return charToString (quoteCharacter) + quoteCharacter;
  10381. String t (*this);
  10382. if (! t.startsWithChar (quoteCharacter))
  10383. t = charToString (quoteCharacter) + t;
  10384. if (! t.endsWithChar (quoteCharacter))
  10385. t += quoteCharacter;
  10386. return t;
  10387. }
  10388. const String String::trim() const
  10389. {
  10390. if (isEmpty())
  10391. return empty;
  10392. int start = 0;
  10393. while (CharacterFunctions::isWhitespace (text [start]))
  10394. ++start;
  10395. const int len = length();
  10396. int end = len - 1;
  10397. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10398. --end;
  10399. ++end;
  10400. if (end <= start)
  10401. return empty;
  10402. else if (start > 0 || end < len)
  10403. return String (text + start, end - start);
  10404. return *this;
  10405. }
  10406. const String String::trimStart() const
  10407. {
  10408. if (isEmpty())
  10409. return empty;
  10410. const juce_wchar* t = text;
  10411. while (CharacterFunctions::isWhitespace (*t))
  10412. ++t;
  10413. if (t == text)
  10414. return *this;
  10415. return String (t);
  10416. }
  10417. const String String::trimEnd() const
  10418. {
  10419. if (isEmpty())
  10420. return empty;
  10421. const juce_wchar* endT = text + (length() - 1);
  10422. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10423. --endT;
  10424. return String (text, (int) (++endT - text));
  10425. }
  10426. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10427. {
  10428. const juce_wchar* t = text;
  10429. while (charactersToTrim.containsChar (*t))
  10430. ++t;
  10431. return t == text ? *this : String (t);
  10432. }
  10433. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10434. {
  10435. if (isEmpty())
  10436. return empty;
  10437. const int len = length();
  10438. const juce_wchar* endT = text + (len - 1);
  10439. int numToRemove = 0;
  10440. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10441. {
  10442. ++numToRemove;
  10443. --endT;
  10444. }
  10445. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10446. }
  10447. const String String::retainCharacters (const String& charactersToRetain) const
  10448. {
  10449. if (isEmpty())
  10450. return empty;
  10451. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10452. juce_wchar* dst = result.text;
  10453. const juce_wchar* src = text;
  10454. while (*src != 0)
  10455. {
  10456. if (charactersToRetain.containsChar (*src))
  10457. *dst++ = *src;
  10458. ++src;
  10459. }
  10460. *dst = 0;
  10461. return result;
  10462. }
  10463. const String String::removeCharacters (const String& charactersToRemove) const
  10464. {
  10465. if (isEmpty())
  10466. return empty;
  10467. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10468. juce_wchar* dst = result.text;
  10469. const juce_wchar* src = text;
  10470. while (*src != 0)
  10471. {
  10472. if (! charactersToRemove.containsChar (*src))
  10473. *dst++ = *src;
  10474. ++src;
  10475. }
  10476. *dst = 0;
  10477. return result;
  10478. }
  10479. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10480. {
  10481. int i = 0;
  10482. for (;;)
  10483. {
  10484. if (! permittedCharacters.containsChar (text[i]))
  10485. break;
  10486. ++i;
  10487. }
  10488. return substring (0, i);
  10489. }
  10490. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10491. {
  10492. const juce_wchar* const t = text;
  10493. int i = 0;
  10494. while (t[i] != 0)
  10495. {
  10496. if (charactersToStopAt.containsChar (t[i]))
  10497. return String (text, i);
  10498. ++i;
  10499. }
  10500. return empty;
  10501. }
  10502. bool String::containsOnly (const String& chars) const throw()
  10503. {
  10504. const juce_wchar* t = text;
  10505. while (*t != 0)
  10506. if (! chars.containsChar (*t++))
  10507. return false;
  10508. return true;
  10509. }
  10510. bool String::containsAnyOf (const String& chars) const throw()
  10511. {
  10512. const juce_wchar* t = text;
  10513. while (*t != 0)
  10514. if (chars.containsChar (*t++))
  10515. return true;
  10516. return false;
  10517. }
  10518. bool String::containsNonWhitespaceChars() const throw()
  10519. {
  10520. const juce_wchar* t = text;
  10521. while (*t != 0)
  10522. if (! CharacterFunctions::isWhitespace (*t++))
  10523. return true;
  10524. return false;
  10525. }
  10526. const String String::formatted (const juce_wchar* const pf, ... )
  10527. {
  10528. jassert (pf != 0);
  10529. va_list args;
  10530. va_start (args, pf);
  10531. size_t bufferSize = 256;
  10532. String result (bufferSize, (int) 0);
  10533. result.text[0] = 0;
  10534. for (;;)
  10535. {
  10536. #if JUCE_LINUX && JUCE_64BIT
  10537. va_list tempArgs;
  10538. va_copy (tempArgs, args);
  10539. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10540. va_end (tempArgs);
  10541. #elif JUCE_WINDOWS
  10542. #if JUCE_MSVC
  10543. #pragma warning (push)
  10544. #pragma warning (disable: 4996)
  10545. #endif
  10546. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10547. #if JUCE_MSVC
  10548. #pragma warning (pop)
  10549. #endif
  10550. #else
  10551. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10552. #endif
  10553. if (num > 0)
  10554. return result;
  10555. bufferSize += 256;
  10556. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10557. break; // returns -1 because of an error rather than because it needs more space.
  10558. result.preallocateStorage (bufferSize);
  10559. }
  10560. return empty;
  10561. }
  10562. int String::getIntValue() const throw()
  10563. {
  10564. return CharacterFunctions::getIntValue (text);
  10565. }
  10566. int String::getTrailingIntValue() const throw()
  10567. {
  10568. int n = 0;
  10569. int mult = 1;
  10570. const juce_wchar* t = text + length();
  10571. while (--t >= text)
  10572. {
  10573. const juce_wchar c = *t;
  10574. if (! CharacterFunctions::isDigit (c))
  10575. {
  10576. if (c == '-')
  10577. n = -n;
  10578. break;
  10579. }
  10580. n += mult * (c - '0');
  10581. mult *= 10;
  10582. }
  10583. return n;
  10584. }
  10585. int64 String::getLargeIntValue() const throw()
  10586. {
  10587. return CharacterFunctions::getInt64Value (text);
  10588. }
  10589. float String::getFloatValue() const throw()
  10590. {
  10591. return (float) CharacterFunctions::getDoubleValue (text);
  10592. }
  10593. double String::getDoubleValue() const throw()
  10594. {
  10595. return CharacterFunctions::getDoubleValue (text);
  10596. }
  10597. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10598. const String String::toHexString (const int number)
  10599. {
  10600. juce_wchar buffer[32];
  10601. juce_wchar* const end = buffer + 32;
  10602. juce_wchar* t = end;
  10603. *--t = 0;
  10604. unsigned int v = (unsigned int) number;
  10605. do
  10606. {
  10607. *--t = hexDigits [v & 15];
  10608. v >>= 4;
  10609. } while (v != 0);
  10610. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10611. }
  10612. const String String::toHexString (const int64 number)
  10613. {
  10614. juce_wchar buffer[32];
  10615. juce_wchar* const end = buffer + 32;
  10616. juce_wchar* t = end;
  10617. *--t = 0;
  10618. uint64 v = (uint64) number;
  10619. do
  10620. {
  10621. *--t = hexDigits [(int) (v & 15)];
  10622. v >>= 4;
  10623. } while (v != 0);
  10624. return String (t, (int) (((char*) end) - (char*) t));
  10625. }
  10626. const String String::toHexString (const short number)
  10627. {
  10628. return toHexString ((int) (unsigned short) number);
  10629. }
  10630. const String String::toHexString (const unsigned char* data,
  10631. const int size,
  10632. const int groupSize)
  10633. {
  10634. if (size <= 0)
  10635. return empty;
  10636. int numChars = (size * 2) + 2;
  10637. if (groupSize > 0)
  10638. numChars += size / groupSize;
  10639. String s ((size_t) numChars, (int) 0);
  10640. juce_wchar* d = s.text;
  10641. for (int i = 0; i < size; ++i)
  10642. {
  10643. *d++ = hexDigits [(*data) >> 4];
  10644. *d++ = hexDigits [(*data) & 0xf];
  10645. ++data;
  10646. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10647. *d++ = ' ';
  10648. }
  10649. *d = 0;
  10650. return s;
  10651. }
  10652. int String::getHexValue32() const throw()
  10653. {
  10654. int result = 0;
  10655. const juce_wchar* c = text;
  10656. for (;;)
  10657. {
  10658. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10659. if (hexValue >= 0)
  10660. result = (result << 4) | hexValue;
  10661. else if (*c == 0)
  10662. break;
  10663. ++c;
  10664. }
  10665. return result;
  10666. }
  10667. int64 String::getHexValue64() const throw()
  10668. {
  10669. int64 result = 0;
  10670. const juce_wchar* c = text;
  10671. for (;;)
  10672. {
  10673. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10674. if (hexValue >= 0)
  10675. result = (result << 4) | hexValue;
  10676. else if (*c == 0)
  10677. break;
  10678. ++c;
  10679. }
  10680. return result;
  10681. }
  10682. const String String::createStringFromData (const void* const data_, const int size)
  10683. {
  10684. const char* const data = static_cast <const char*> (data_);
  10685. if (size <= 0 || data == 0)
  10686. {
  10687. return empty;
  10688. }
  10689. else if (size < 2)
  10690. {
  10691. return charToString (data[0]);
  10692. }
  10693. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10694. || (data[0] == (char)-1 && data[1] == (char)-2))
  10695. {
  10696. // assume it's 16-bit unicode
  10697. const bool bigEndian = (data[0] == (char)-2);
  10698. const int numChars = size / 2 - 1;
  10699. String result;
  10700. result.preallocateStorage (numChars + 2);
  10701. const uint16* const src = (const uint16*) (data + 2);
  10702. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10703. if (bigEndian)
  10704. {
  10705. for (int i = 0; i < numChars; ++i)
  10706. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10707. }
  10708. else
  10709. {
  10710. for (int i = 0; i < numChars; ++i)
  10711. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10712. }
  10713. dst [numChars] = 0;
  10714. return result;
  10715. }
  10716. else
  10717. {
  10718. return String::fromUTF8 (data, size);
  10719. }
  10720. }
  10721. const char* String::toUTF8() const
  10722. {
  10723. if (isEmpty())
  10724. {
  10725. return reinterpret_cast <const char*> (text);
  10726. }
  10727. else
  10728. {
  10729. const int currentLen = length() + 1;
  10730. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10731. String* const mutableThis = const_cast <String*> (this);
  10732. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10733. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10734. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10735. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10736. #endif
  10737. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10738. return otherCopy;
  10739. }
  10740. }
  10741. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10742. {
  10743. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10744. int num = 0, index = 0;
  10745. for (;;)
  10746. {
  10747. const uint32 c = (uint32) text [index++];
  10748. if (c >= 0x80)
  10749. {
  10750. int numExtraBytes = 1;
  10751. if (c >= 0x800)
  10752. {
  10753. ++numExtraBytes;
  10754. if (c >= 0x10000)
  10755. {
  10756. ++numExtraBytes;
  10757. if (c >= 0x200000)
  10758. {
  10759. ++numExtraBytes;
  10760. if (c >= 0x4000000)
  10761. ++numExtraBytes;
  10762. }
  10763. }
  10764. }
  10765. if (buffer != 0)
  10766. {
  10767. if (num + numExtraBytes >= maxBufferSizeBytes)
  10768. {
  10769. buffer [num++] = 0;
  10770. break;
  10771. }
  10772. else
  10773. {
  10774. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10775. while (--numExtraBytes >= 0)
  10776. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10777. }
  10778. }
  10779. else
  10780. {
  10781. num += numExtraBytes + 1;
  10782. }
  10783. }
  10784. else
  10785. {
  10786. if (buffer != 0)
  10787. {
  10788. if (num + 1 >= maxBufferSizeBytes)
  10789. {
  10790. buffer [num++] = 0;
  10791. break;
  10792. }
  10793. buffer [num] = (uint8) c;
  10794. }
  10795. ++num;
  10796. }
  10797. if (c == 0)
  10798. break;
  10799. }
  10800. return num;
  10801. }
  10802. int String::getNumBytesAsUTF8() const throw()
  10803. {
  10804. int num = 0;
  10805. const juce_wchar* t = text;
  10806. for (;;)
  10807. {
  10808. const uint32 c = (uint32) *t;
  10809. if (c >= 0x80)
  10810. {
  10811. ++num;
  10812. if (c >= 0x800)
  10813. {
  10814. ++num;
  10815. if (c >= 0x10000)
  10816. {
  10817. ++num;
  10818. if (c >= 0x200000)
  10819. {
  10820. ++num;
  10821. if (c >= 0x4000000)
  10822. ++num;
  10823. }
  10824. }
  10825. }
  10826. }
  10827. else if (c == 0)
  10828. break;
  10829. ++num;
  10830. ++t;
  10831. }
  10832. return num;
  10833. }
  10834. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10835. {
  10836. if (buffer == 0)
  10837. return empty;
  10838. if (bufferSizeBytes < 0)
  10839. bufferSizeBytes = std::numeric_limits<int>::max();
  10840. size_t numBytes;
  10841. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10842. if (buffer [numBytes] == 0)
  10843. break;
  10844. String result ((size_t) numBytes + 1, (int) 0);
  10845. juce_wchar* dest = result.text;
  10846. size_t i = 0;
  10847. while (i < numBytes)
  10848. {
  10849. const char c = buffer [i++];
  10850. if (c < 0)
  10851. {
  10852. unsigned int mask = 0x7f;
  10853. int bit = 0x40;
  10854. int numExtraValues = 0;
  10855. while (bit != 0 && (c & bit) != 0)
  10856. {
  10857. bit >>= 1;
  10858. mask >>= 1;
  10859. ++numExtraValues;
  10860. }
  10861. int n = (mask & (unsigned char) c);
  10862. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10863. {
  10864. const char nextByte = buffer[i];
  10865. if ((nextByte & 0xc0) != 0x80)
  10866. break;
  10867. n <<= 6;
  10868. n |= (nextByte & 0x3f);
  10869. ++i;
  10870. }
  10871. *dest++ = (juce_wchar) n;
  10872. }
  10873. else
  10874. {
  10875. *dest++ = (juce_wchar) c;
  10876. }
  10877. }
  10878. *dest = 0;
  10879. return result;
  10880. }
  10881. const char* String::toCString() const
  10882. {
  10883. if (isEmpty())
  10884. {
  10885. return reinterpret_cast <const char*> (text);
  10886. }
  10887. else
  10888. {
  10889. const int len = length();
  10890. String* const mutableThis = const_cast <String*> (this);
  10891. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  10892. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  10893. CharacterFunctions::copy (otherCopy, text, len);
  10894. otherCopy [len] = 0;
  10895. return otherCopy;
  10896. }
  10897. }
  10898. #if JUCE_MSVC
  10899. #pragma warning (push)
  10900. #pragma warning (disable: 4514 4996)
  10901. #endif
  10902. int String::getNumBytesAsCString() const throw()
  10903. {
  10904. return (int) wcstombs (0, text, 0);
  10905. }
  10906. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10907. {
  10908. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10909. if (destBuffer != 0 && numBytes >= 0)
  10910. destBuffer [numBytes] = 0;
  10911. return numBytes;
  10912. }
  10913. #if JUCE_MSVC
  10914. #pragma warning (pop)
  10915. #endif
  10916. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  10917. {
  10918. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  10919. }
  10920. String::Concatenator::Concatenator (String& stringToAppendTo)
  10921. : result (stringToAppendTo),
  10922. nextIndex (stringToAppendTo.length())
  10923. {
  10924. }
  10925. String::Concatenator::~Concatenator()
  10926. {
  10927. }
  10928. void String::Concatenator::append (const String& s)
  10929. {
  10930. const int len = s.length();
  10931. if (len > 0)
  10932. {
  10933. result.preallocateStorage (nextIndex + len);
  10934. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10935. nextIndex += len;
  10936. }
  10937. }
  10938. #if JUCE_UNIT_TESTS
  10939. class StringTests : public UnitTest
  10940. {
  10941. public:
  10942. StringTests() : UnitTest ("String class") {}
  10943. void runTest()
  10944. {
  10945. {
  10946. beginTest ("Basics");
  10947. expect (String().length() == 0);
  10948. expect (String() == String::empty);
  10949. String s1, s2 ("abcd");
  10950. expect (s1.isEmpty() && ! s1.isNotEmpty());
  10951. expect (s2.isNotEmpty() && ! s2.isEmpty());
  10952. expect (s2.length() == 4);
  10953. s1 = "abcd";
  10954. expect (s2 == s1 && s1 == s2);
  10955. expect (s1 == "abcd" && s1 == L"abcd");
  10956. expect (String ("abcd") == String (L"abcd"));
  10957. expect (String ("abcdefg", 4) == L"abcd");
  10958. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  10959. expect (String::charToString ('x') == "x");
  10960. expect (String::charToString (0) == String::empty);
  10961. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  10962. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  10963. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  10964. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  10965. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  10966. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  10967. expect (s1.indexOf (String::empty) == 0);
  10968. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  10969. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  10970. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  10971. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  10972. }
  10973. {
  10974. beginTest ("Operations");
  10975. String s ("012345678");
  10976. expect (s.hashCode() != 0);
  10977. expect (s.hashCode64() != 0);
  10978. expect (s.hashCode() != (s + s).hashCode());
  10979. expect (s.hashCode64() != (s + s).hashCode64());
  10980. expect (s.compare (String ("012345678")) == 0);
  10981. expect (s.compare (String ("012345679")) < 0);
  10982. expect (s.compare (String ("012345676")) > 0);
  10983. expect (s.substring (2, 3) == String::charToString (s[2]));
  10984. expect (s.substring (0, 1) == String::charToString (s[0]));
  10985. expect (s.getLastCharacter() == s [s.length() - 1]);
  10986. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  10987. expect (s.substring (0, 3) == L"012");
  10988. expect (s.substring (0, 100) == s);
  10989. expect (s.substring (-1, 100) == s);
  10990. expect (s.substring (3) == "345678");
  10991. expect (s.indexOf (L"45") == 4);
  10992. expect (String ("444445").indexOf ("45") == 4);
  10993. expect (String ("444445").lastIndexOfChar ('4') == 4);
  10994. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  10995. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  10996. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  10997. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  10998. expect (s.indexOfChar (L'4') == 4);
  10999. expect (s + s == "012345678012345678");
  11000. expect (s.startsWith (s));
  11001. expect (s.startsWith (s.substring (0, 4)));
  11002. expect (s.startsWith (s.dropLastCharacters (4)));
  11003. expect (s.endsWith (s.substring (5)));
  11004. expect (s.endsWith (s));
  11005. expect (s.contains (s.substring (3, 6)));
  11006. expect (s.contains (s.substring (3)));
  11007. expect (s.startsWithChar (s[0]));
  11008. expect (s.endsWithChar (s.getLastCharacter()));
  11009. expect (s [s.length()] == 0);
  11010. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11011. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11012. String s2 ("123");
  11013. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11014. s2 += "xyz";
  11015. expect (s2 == "1234567890xyz");
  11016. beginTest ("Numeric conversions");
  11017. expect (String::empty.getIntValue() == 0);
  11018. expect (String::empty.getDoubleValue() == 0.0);
  11019. expect (String::empty.getFloatValue() == 0.0f);
  11020. expect (s.getIntValue() == 12345678);
  11021. expect (s.getLargeIntValue() == (int64) 12345678);
  11022. expect (s.getDoubleValue() == 12345678.0);
  11023. expect (s.getFloatValue() == 12345678.0f);
  11024. expect (String (-1234).getIntValue() == -1234);
  11025. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11026. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11027. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11028. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11029. expect (s.getHexValue32() == 0x12345678);
  11030. expect (s.getHexValue64() == (int64) 0x12345678);
  11031. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11032. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11033. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11034. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11035. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11036. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11037. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11038. beginTest ("Subsections");
  11039. String s3;
  11040. s3 = "abcdeFGHIJ";
  11041. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11042. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11043. expect (s3.containsIgnoreCase (s3.substring (3)));
  11044. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11045. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11046. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11047. expect (s3.containsAnyOf (L"zzzFs"));
  11048. expect (s3.startsWith ("abcd"));
  11049. expect (s3.startsWithIgnoreCase (L"abCD"));
  11050. expect (s3.startsWith (String::empty));
  11051. expect (s3.startsWithChar ('a'));
  11052. expect (s3.endsWith (String ("HIJ")));
  11053. expect (s3.endsWithIgnoreCase (L"Hij"));
  11054. expect (s3.endsWith (String::empty));
  11055. expect (s3.endsWithChar (L'J'));
  11056. expect (s3.indexOf ("HIJ") == 7);
  11057. expect (s3.indexOf (L"HIJK") == -1);
  11058. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11059. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11060. String s4 (s3);
  11061. s4.append (String ("xyz123"), 3);
  11062. expect (s4 == s3 + "xyz");
  11063. expect (String (1234) < String (1235));
  11064. expect (String (1235) > String (1234));
  11065. expect (String (1234) >= String (1234));
  11066. expect (String (1234) <= String (1234));
  11067. expect (String (1235) >= String (1234));
  11068. expect (String (1234) <= String (1235));
  11069. String s5 ("word word2 word3");
  11070. expect (s5.containsWholeWord (String ("word2")));
  11071. expect (s5.indexOfWholeWord ("word2") == 5);
  11072. expect (s5.containsWholeWord (L"word"));
  11073. expect (s5.containsWholeWord ("word3"));
  11074. expect (s5.containsWholeWord (s5));
  11075. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11076. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11077. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11078. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11079. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11080. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11081. expect (s5.containsNonWhitespaceChars());
  11082. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11083. expect (s5.matchesWildcard (L"wor*", false));
  11084. expect (s5.matchesWildcard ("wOr*", true));
  11085. expect (s5.matchesWildcard (L"*word3", true));
  11086. expect (s5.matchesWildcard ("*word?", true));
  11087. expect (s5.matchesWildcard (L"Word*3", true));
  11088. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11089. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11090. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11091. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11092. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11093. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11094. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11095. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11096. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11097. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11098. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11099. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11100. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11101. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11102. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11103. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11104. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11105. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11106. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11107. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11108. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11109. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11110. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11111. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11112. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11113. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11114. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11115. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11116. expect (s5.replace ("Word", "", true) == " 2 3");
  11117. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11118. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11119. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11120. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11121. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11122. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11123. expect (s5.retainCharacters (String::empty).isEmpty());
  11124. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11125. expect (s5.removeCharacters (String::empty) == s5);
  11126. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11127. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11128. expect (! s5.isQuotedString());
  11129. expect (s5.quoted().isQuotedString());
  11130. expect (! s5.quoted().unquoted().isQuotedString());
  11131. expect (! String ("x'").isQuotedString());
  11132. expect (String ("'x").isQuotedString());
  11133. String s6 (" \t xyz \t\r\n");
  11134. expect (s6.trim() == String ("xyz"));
  11135. expect (s6.trim().trim() == "xyz");
  11136. expect (s5.trim() == s5);
  11137. expect (s6.trimStart().trimEnd() == s6.trim());
  11138. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11139. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11140. expect (s6.trimStart() != s6.trimEnd());
  11141. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11142. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11143. }
  11144. {
  11145. beginTest ("UTF8");
  11146. String s ("word word2 word3");
  11147. {
  11148. char buffer [100];
  11149. memset (buffer, 0xff, sizeof (buffer));
  11150. s.copyToUTF8 (buffer, 100);
  11151. expect (String::fromUTF8 (buffer, 100) == s);
  11152. juce_wchar bufferUnicode [100];
  11153. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11154. s.copyToUnicode (bufferUnicode, 100);
  11155. expect (String (bufferUnicode, 100) == s);
  11156. }
  11157. {
  11158. juce_wchar wideBuffer [50];
  11159. zerostruct (wideBuffer);
  11160. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11161. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11162. String wide (wideBuffer);
  11163. expect (wide == (const juce_wchar*) wideBuffer);
  11164. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11165. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11166. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11167. }
  11168. }
  11169. }
  11170. };
  11171. static StringTests stringUnitTests;
  11172. #endif
  11173. END_JUCE_NAMESPACE
  11174. /*** End of inlined file: juce_String.cpp ***/
  11175. /*** Start of inlined file: juce_StringArray.cpp ***/
  11176. BEGIN_JUCE_NAMESPACE
  11177. StringArray::StringArray() throw()
  11178. {
  11179. }
  11180. StringArray::StringArray (const StringArray& other)
  11181. : strings (other.strings)
  11182. {
  11183. }
  11184. StringArray::StringArray (const String& firstValue)
  11185. {
  11186. strings.add (firstValue);
  11187. }
  11188. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11189. const int numberOfStrings)
  11190. {
  11191. for (int i = 0; i < numberOfStrings; ++i)
  11192. strings.add (initialStrings [i]);
  11193. }
  11194. StringArray::StringArray (const char* const* const initialStrings,
  11195. const int numberOfStrings)
  11196. {
  11197. for (int i = 0; i < numberOfStrings; ++i)
  11198. strings.add (initialStrings [i]);
  11199. }
  11200. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11201. {
  11202. int i = 0;
  11203. while (initialStrings[i] != 0)
  11204. strings.add (initialStrings [i++]);
  11205. }
  11206. StringArray::StringArray (const char* const* const initialStrings)
  11207. {
  11208. int i = 0;
  11209. while (initialStrings[i] != 0)
  11210. strings.add (initialStrings [i++]);
  11211. }
  11212. StringArray& StringArray::operator= (const StringArray& other)
  11213. {
  11214. strings = other.strings;
  11215. return *this;
  11216. }
  11217. StringArray::~StringArray()
  11218. {
  11219. }
  11220. bool StringArray::operator== (const StringArray& other) const throw()
  11221. {
  11222. if (other.size() != size())
  11223. return false;
  11224. for (int i = size(); --i >= 0;)
  11225. if (other.strings.getReference(i) != strings.getReference(i))
  11226. return false;
  11227. return true;
  11228. }
  11229. bool StringArray::operator!= (const StringArray& other) const throw()
  11230. {
  11231. return ! operator== (other);
  11232. }
  11233. void StringArray::clear()
  11234. {
  11235. strings.clear();
  11236. }
  11237. const String& StringArray::operator[] (const int index) const throw()
  11238. {
  11239. if (((unsigned int) index) < (unsigned int) strings.size())
  11240. return strings.getReference (index);
  11241. return String::empty;
  11242. }
  11243. String& StringArray::getReference (const int index) throw()
  11244. {
  11245. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11246. return strings.getReference (index);
  11247. }
  11248. void StringArray::add (const String& newString)
  11249. {
  11250. strings.add (newString);
  11251. }
  11252. void StringArray::insert (const int index, const String& newString)
  11253. {
  11254. strings.insert (index, newString);
  11255. }
  11256. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11257. {
  11258. if (! contains (newString, ignoreCase))
  11259. add (newString);
  11260. }
  11261. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11262. {
  11263. if (startIndex < 0)
  11264. {
  11265. jassertfalse;
  11266. startIndex = 0;
  11267. }
  11268. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11269. numElementsToAdd = otherArray.size() - startIndex;
  11270. while (--numElementsToAdd >= 0)
  11271. strings.add (otherArray.strings.getReference (startIndex++));
  11272. }
  11273. void StringArray::set (const int index, const String& newString)
  11274. {
  11275. strings.set (index, newString);
  11276. }
  11277. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11278. {
  11279. if (ignoreCase)
  11280. {
  11281. for (int i = size(); --i >= 0;)
  11282. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11283. return true;
  11284. }
  11285. else
  11286. {
  11287. for (int i = size(); --i >= 0;)
  11288. if (stringToLookFor == strings.getReference(i))
  11289. return true;
  11290. }
  11291. return false;
  11292. }
  11293. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11294. {
  11295. if (i < 0)
  11296. i = 0;
  11297. const int numElements = size();
  11298. if (ignoreCase)
  11299. {
  11300. while (i < numElements)
  11301. {
  11302. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11303. return i;
  11304. ++i;
  11305. }
  11306. }
  11307. else
  11308. {
  11309. while (i < numElements)
  11310. {
  11311. if (stringToLookFor == strings.getReference (i))
  11312. return i;
  11313. ++i;
  11314. }
  11315. }
  11316. return -1;
  11317. }
  11318. void StringArray::remove (const int index)
  11319. {
  11320. strings.remove (index);
  11321. }
  11322. void StringArray::removeString (const String& stringToRemove,
  11323. const bool ignoreCase)
  11324. {
  11325. if (ignoreCase)
  11326. {
  11327. for (int i = size(); --i >= 0;)
  11328. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11329. strings.remove (i);
  11330. }
  11331. else
  11332. {
  11333. for (int i = size(); --i >= 0;)
  11334. if (stringToRemove == strings.getReference (i))
  11335. strings.remove (i);
  11336. }
  11337. }
  11338. void StringArray::removeRange (int startIndex, int numberToRemove)
  11339. {
  11340. strings.removeRange (startIndex, numberToRemove);
  11341. }
  11342. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11343. {
  11344. if (removeWhitespaceStrings)
  11345. {
  11346. for (int i = size(); --i >= 0;)
  11347. if (! strings.getReference(i).containsNonWhitespaceChars())
  11348. strings.remove (i);
  11349. }
  11350. else
  11351. {
  11352. for (int i = size(); --i >= 0;)
  11353. if (strings.getReference(i).isEmpty())
  11354. strings.remove (i);
  11355. }
  11356. }
  11357. void StringArray::trim()
  11358. {
  11359. for (int i = size(); --i >= 0;)
  11360. {
  11361. String& s = strings.getReference(i);
  11362. s = s.trim();
  11363. }
  11364. }
  11365. class InternalStringArrayComparator_CaseSensitive
  11366. {
  11367. public:
  11368. static int compareElements (String& first, String& second) { return first.compare (second); }
  11369. };
  11370. class InternalStringArrayComparator_CaseInsensitive
  11371. {
  11372. public:
  11373. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11374. };
  11375. void StringArray::sort (const bool ignoreCase)
  11376. {
  11377. if (ignoreCase)
  11378. {
  11379. InternalStringArrayComparator_CaseInsensitive comp;
  11380. strings.sort (comp);
  11381. }
  11382. else
  11383. {
  11384. InternalStringArrayComparator_CaseSensitive comp;
  11385. strings.sort (comp);
  11386. }
  11387. }
  11388. void StringArray::move (const int currentIndex, int newIndex) throw()
  11389. {
  11390. strings.move (currentIndex, newIndex);
  11391. }
  11392. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11393. {
  11394. const int last = (numberToJoin < 0) ? size()
  11395. : jmin (size(), start + numberToJoin);
  11396. if (start < 0)
  11397. start = 0;
  11398. if (start >= last)
  11399. return String::empty;
  11400. if (start == last - 1)
  11401. return strings.getReference (start);
  11402. const int separatorLen = separator.length();
  11403. int charsNeeded = separatorLen * (last - start - 1);
  11404. for (int i = start; i < last; ++i)
  11405. charsNeeded += strings.getReference(i).length();
  11406. String result;
  11407. result.preallocateStorage (charsNeeded);
  11408. juce_wchar* dest = result;
  11409. while (start < last)
  11410. {
  11411. const String& s = strings.getReference (start);
  11412. const int len = s.length();
  11413. if (len > 0)
  11414. {
  11415. s.copyToUnicode (dest, len);
  11416. dest += len;
  11417. }
  11418. if (++start < last && separatorLen > 0)
  11419. {
  11420. separator.copyToUnicode (dest, separatorLen);
  11421. dest += separatorLen;
  11422. }
  11423. }
  11424. *dest = 0;
  11425. return result;
  11426. }
  11427. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11428. {
  11429. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11430. }
  11431. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11432. {
  11433. int num = 0;
  11434. if (text.isNotEmpty())
  11435. {
  11436. bool insideQuotes = false;
  11437. juce_wchar currentQuoteChar = 0;
  11438. int i = 0;
  11439. int tokenStart = 0;
  11440. for (;;)
  11441. {
  11442. const juce_wchar c = text[i];
  11443. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11444. if (! isBreak)
  11445. {
  11446. if (quoteCharacters.containsChar (c))
  11447. {
  11448. if (insideQuotes)
  11449. {
  11450. // only break out of quotes-mode if we find a matching quote to the
  11451. // one that we opened with..
  11452. if (currentQuoteChar == c)
  11453. insideQuotes = false;
  11454. }
  11455. else
  11456. {
  11457. insideQuotes = true;
  11458. currentQuoteChar = c;
  11459. }
  11460. }
  11461. }
  11462. else
  11463. {
  11464. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11465. ++num;
  11466. tokenStart = i + 1;
  11467. }
  11468. if (c == 0)
  11469. break;
  11470. ++i;
  11471. }
  11472. }
  11473. return num;
  11474. }
  11475. int StringArray::addLines (const String& sourceText)
  11476. {
  11477. int numLines = 0;
  11478. const juce_wchar* text = sourceText;
  11479. while (*text != 0)
  11480. {
  11481. const juce_wchar* const startOfLine = text;
  11482. while (*text != 0)
  11483. {
  11484. if (*text == '\r')
  11485. {
  11486. ++text;
  11487. if (*text == '\n')
  11488. ++text;
  11489. break;
  11490. }
  11491. if (*text == '\n')
  11492. {
  11493. ++text;
  11494. break;
  11495. }
  11496. ++text;
  11497. }
  11498. const juce_wchar* endOfLine = text;
  11499. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11500. --endOfLine;
  11501. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11502. --endOfLine;
  11503. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11504. ++numLines;
  11505. }
  11506. return numLines;
  11507. }
  11508. void StringArray::removeDuplicates (const bool ignoreCase)
  11509. {
  11510. for (int i = 0; i < size() - 1; ++i)
  11511. {
  11512. const String s (strings.getReference(i));
  11513. int nextIndex = i + 1;
  11514. for (;;)
  11515. {
  11516. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11517. if (nextIndex < 0)
  11518. break;
  11519. strings.remove (nextIndex);
  11520. }
  11521. }
  11522. }
  11523. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11524. const bool appendNumberToFirstInstance,
  11525. const juce_wchar* preNumberString,
  11526. const juce_wchar* postNumberString)
  11527. {
  11528. if (preNumberString == 0)
  11529. preNumberString = L" (";
  11530. if (postNumberString == 0)
  11531. postNumberString = L")";
  11532. for (int i = 0; i < size() - 1; ++i)
  11533. {
  11534. String& s = strings.getReference(i);
  11535. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11536. if (nextIndex >= 0)
  11537. {
  11538. const String original (s);
  11539. int number = 0;
  11540. if (appendNumberToFirstInstance)
  11541. s = original + preNumberString + String (++number) + postNumberString;
  11542. else
  11543. ++number;
  11544. while (nextIndex >= 0)
  11545. {
  11546. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11547. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11548. }
  11549. }
  11550. }
  11551. }
  11552. void StringArray::minimiseStorageOverheads()
  11553. {
  11554. strings.minimiseStorageOverheads();
  11555. }
  11556. END_JUCE_NAMESPACE
  11557. /*** End of inlined file: juce_StringArray.cpp ***/
  11558. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11559. BEGIN_JUCE_NAMESPACE
  11560. StringPairArray::StringPairArray (const bool ignoreCase_)
  11561. : ignoreCase (ignoreCase_)
  11562. {
  11563. }
  11564. StringPairArray::StringPairArray (const StringPairArray& other)
  11565. : keys (other.keys),
  11566. values (other.values),
  11567. ignoreCase (other.ignoreCase)
  11568. {
  11569. }
  11570. StringPairArray::~StringPairArray()
  11571. {
  11572. }
  11573. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11574. {
  11575. keys = other.keys;
  11576. values = other.values;
  11577. return *this;
  11578. }
  11579. bool StringPairArray::operator== (const StringPairArray& other) const
  11580. {
  11581. for (int i = keys.size(); --i >= 0;)
  11582. if (other [keys[i]] != values[i])
  11583. return false;
  11584. return true;
  11585. }
  11586. bool StringPairArray::operator!= (const StringPairArray& other) const
  11587. {
  11588. return ! operator== (other);
  11589. }
  11590. const String& StringPairArray::operator[] (const String& key) const
  11591. {
  11592. return values [keys.indexOf (key, ignoreCase)];
  11593. }
  11594. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11595. {
  11596. const int i = keys.indexOf (key, ignoreCase);
  11597. if (i >= 0)
  11598. return values[i];
  11599. return defaultReturnValue;
  11600. }
  11601. void StringPairArray::set (const String& key, const String& value)
  11602. {
  11603. const int i = keys.indexOf (key, ignoreCase);
  11604. if (i >= 0)
  11605. {
  11606. values.set (i, value);
  11607. }
  11608. else
  11609. {
  11610. keys.add (key);
  11611. values.add (value);
  11612. }
  11613. }
  11614. void StringPairArray::addArray (const StringPairArray& other)
  11615. {
  11616. for (int i = 0; i < other.size(); ++i)
  11617. set (other.keys[i], other.values[i]);
  11618. }
  11619. void StringPairArray::clear()
  11620. {
  11621. keys.clear();
  11622. values.clear();
  11623. }
  11624. void StringPairArray::remove (const String& key)
  11625. {
  11626. remove (keys.indexOf (key, ignoreCase));
  11627. }
  11628. void StringPairArray::remove (const int index)
  11629. {
  11630. keys.remove (index);
  11631. values.remove (index);
  11632. }
  11633. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11634. {
  11635. ignoreCase = shouldIgnoreCase;
  11636. }
  11637. const String StringPairArray::getDescription() const
  11638. {
  11639. String s;
  11640. for (int i = 0; i < keys.size(); ++i)
  11641. {
  11642. s << keys[i] << " = " << values[i];
  11643. if (i < keys.size())
  11644. s << ", ";
  11645. }
  11646. return s;
  11647. }
  11648. void StringPairArray::minimiseStorageOverheads()
  11649. {
  11650. keys.minimiseStorageOverheads();
  11651. values.minimiseStorageOverheads();
  11652. }
  11653. END_JUCE_NAMESPACE
  11654. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11655. /*** Start of inlined file: juce_StringPool.cpp ***/
  11656. BEGIN_JUCE_NAMESPACE
  11657. StringPool::StringPool() throw() {}
  11658. StringPool::~StringPool() {}
  11659. template <class StringType>
  11660. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11661. {
  11662. int start = 0;
  11663. int end = strings.size();
  11664. for (;;)
  11665. {
  11666. if (start >= end)
  11667. {
  11668. jassert (start <= end);
  11669. strings.insert (start, newString);
  11670. return strings.getReference (start);
  11671. }
  11672. else
  11673. {
  11674. const String& startString = strings.getReference (start);
  11675. if (startString == newString)
  11676. return startString;
  11677. const int halfway = (start + end) >> 1;
  11678. if (halfway == start)
  11679. {
  11680. if (startString.compare (newString) < 0)
  11681. ++start;
  11682. strings.insert (start, newString);
  11683. return strings.getReference (start);
  11684. }
  11685. const int comp = strings.getReference (halfway).compare (newString);
  11686. if (comp == 0)
  11687. return strings.getReference (halfway);
  11688. else if (comp < 0)
  11689. start = halfway;
  11690. else
  11691. end = halfway;
  11692. }
  11693. }
  11694. }
  11695. const juce_wchar* StringPool::getPooledString (const String& s)
  11696. {
  11697. if (s.isEmpty())
  11698. return String::empty;
  11699. return getPooledStringFromArray (strings, s);
  11700. }
  11701. const juce_wchar* StringPool::getPooledString (const char* const s)
  11702. {
  11703. if (s == 0 || *s == 0)
  11704. return String::empty;
  11705. return getPooledStringFromArray (strings, s);
  11706. }
  11707. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11708. {
  11709. if (s == 0 || *s == 0)
  11710. return String::empty;
  11711. return getPooledStringFromArray (strings, s);
  11712. }
  11713. int StringPool::size() const throw()
  11714. {
  11715. return strings.size();
  11716. }
  11717. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11718. {
  11719. return strings [index];
  11720. }
  11721. END_JUCE_NAMESPACE
  11722. /*** End of inlined file: juce_StringPool.cpp ***/
  11723. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11724. BEGIN_JUCE_NAMESPACE
  11725. XmlDocument::XmlDocument (const String& documentText)
  11726. : originalText (documentText),
  11727. ignoreEmptyTextElements (true)
  11728. {
  11729. }
  11730. XmlDocument::XmlDocument (const File& file)
  11731. : ignoreEmptyTextElements (true)
  11732. {
  11733. inputSource = new FileInputSource (file);
  11734. }
  11735. XmlDocument::~XmlDocument()
  11736. {
  11737. }
  11738. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11739. {
  11740. inputSource = newSource;
  11741. }
  11742. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11743. {
  11744. ignoreEmptyTextElements = shouldBeIgnored;
  11745. }
  11746. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11747. {
  11748. return CharacterFunctions::isLetterOrDigit (c)
  11749. || c == '_' || c == '-' || c == ':' || c == '.';
  11750. }
  11751. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11752. {
  11753. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11754. : isXmlIdentifierCharSlow (c);
  11755. }
  11756. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11757. {
  11758. String textToParse (originalText);
  11759. if (textToParse.isEmpty() && inputSource != 0)
  11760. {
  11761. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11762. if (in != 0)
  11763. {
  11764. MemoryOutputStream data;
  11765. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11766. textToParse = data.toString();
  11767. if (! onlyReadOuterDocumentElement)
  11768. originalText = textToParse;
  11769. }
  11770. }
  11771. input = textToParse;
  11772. lastError = String::empty;
  11773. errorOccurred = false;
  11774. outOfData = false;
  11775. needToLoadDTD = true;
  11776. for (int i = 0; i < 128; ++i)
  11777. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11778. if (textToParse.isEmpty())
  11779. {
  11780. lastError = "not enough input";
  11781. }
  11782. else
  11783. {
  11784. skipHeader();
  11785. if (input != 0)
  11786. {
  11787. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11788. if (! errorOccurred)
  11789. return result.release();
  11790. }
  11791. else
  11792. {
  11793. lastError = "incorrect xml header";
  11794. }
  11795. }
  11796. return 0;
  11797. }
  11798. const String& XmlDocument::getLastParseError() const throw()
  11799. {
  11800. return lastError;
  11801. }
  11802. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11803. {
  11804. lastError = desc;
  11805. errorOccurred = ! carryOn;
  11806. }
  11807. const String XmlDocument::getFileContents (const String& filename) const
  11808. {
  11809. if (inputSource != 0)
  11810. {
  11811. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11812. if (in != 0)
  11813. return in->readEntireStreamAsString();
  11814. }
  11815. return String::empty;
  11816. }
  11817. juce_wchar XmlDocument::readNextChar() throw()
  11818. {
  11819. if (*input != 0)
  11820. {
  11821. return *input++;
  11822. }
  11823. else
  11824. {
  11825. outOfData = true;
  11826. return 0;
  11827. }
  11828. }
  11829. int XmlDocument::findNextTokenLength() throw()
  11830. {
  11831. int len = 0;
  11832. juce_wchar c = *input;
  11833. while (isXmlIdentifierChar (c))
  11834. c = input [++len];
  11835. return len;
  11836. }
  11837. void XmlDocument::skipHeader()
  11838. {
  11839. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11840. if (found != 0)
  11841. {
  11842. input = found;
  11843. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11844. if (input == 0)
  11845. return;
  11846. input += 2;
  11847. }
  11848. skipNextWhiteSpace();
  11849. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11850. if (docType == 0)
  11851. return;
  11852. input = docType + 9;
  11853. int n = 1;
  11854. while (n > 0)
  11855. {
  11856. const juce_wchar c = readNextChar();
  11857. if (outOfData)
  11858. return;
  11859. if (c == '<')
  11860. ++n;
  11861. else if (c == '>')
  11862. --n;
  11863. }
  11864. docType += 9;
  11865. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11866. }
  11867. void XmlDocument::skipNextWhiteSpace()
  11868. {
  11869. for (;;)
  11870. {
  11871. juce_wchar c = *input;
  11872. while (CharacterFunctions::isWhitespace (c))
  11873. c = *++input;
  11874. if (c == 0)
  11875. {
  11876. outOfData = true;
  11877. break;
  11878. }
  11879. else if (c == '<')
  11880. {
  11881. if (input[1] == '!'
  11882. && input[2] == '-'
  11883. && input[3] == '-')
  11884. {
  11885. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  11886. if (closeComment == 0)
  11887. {
  11888. outOfData = true;
  11889. break;
  11890. }
  11891. input = closeComment + 3;
  11892. continue;
  11893. }
  11894. else if (input[1] == '?')
  11895. {
  11896. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  11897. if (closeBracket == 0)
  11898. {
  11899. outOfData = true;
  11900. break;
  11901. }
  11902. input = closeBracket + 2;
  11903. continue;
  11904. }
  11905. }
  11906. break;
  11907. }
  11908. }
  11909. void XmlDocument::readQuotedString (String& result)
  11910. {
  11911. const juce_wchar quote = readNextChar();
  11912. while (! outOfData)
  11913. {
  11914. const juce_wchar c = readNextChar();
  11915. if (c == quote)
  11916. break;
  11917. if (c == '&')
  11918. {
  11919. --input;
  11920. readEntity (result);
  11921. }
  11922. else
  11923. {
  11924. --input;
  11925. const juce_wchar* const start = input;
  11926. for (;;)
  11927. {
  11928. const juce_wchar character = *input;
  11929. if (character == quote)
  11930. {
  11931. result.append (start, (int) (input - start));
  11932. ++input;
  11933. return;
  11934. }
  11935. else if (character == '&')
  11936. {
  11937. result.append (start, (int) (input - start));
  11938. break;
  11939. }
  11940. else if (character == 0)
  11941. {
  11942. outOfData = true;
  11943. setLastError ("unmatched quotes", false);
  11944. break;
  11945. }
  11946. ++input;
  11947. }
  11948. }
  11949. }
  11950. }
  11951. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11952. {
  11953. XmlElement* node = 0;
  11954. skipNextWhiteSpace();
  11955. if (outOfData)
  11956. return 0;
  11957. input = CharacterFunctions::find (input, JUCE_T("<"));
  11958. if (input != 0)
  11959. {
  11960. ++input;
  11961. int tagLen = findNextTokenLength();
  11962. if (tagLen == 0)
  11963. {
  11964. // no tag name - but allow for a gap after the '<' before giving an error
  11965. skipNextWhiteSpace();
  11966. tagLen = findNextTokenLength();
  11967. if (tagLen == 0)
  11968. {
  11969. setLastError ("tag name missing", false);
  11970. return node;
  11971. }
  11972. }
  11973. node = new XmlElement (String (input, tagLen));
  11974. input += tagLen;
  11975. XmlElement::XmlAttributeNode* lastAttribute = 0;
  11976. // look for attributes
  11977. for (;;)
  11978. {
  11979. skipNextWhiteSpace();
  11980. const juce_wchar c = *input;
  11981. // empty tag..
  11982. if (c == '/' && input[1] == '>')
  11983. {
  11984. input += 2;
  11985. break;
  11986. }
  11987. // parse the guts of the element..
  11988. if (c == '>')
  11989. {
  11990. ++input;
  11991. skipNextWhiteSpace();
  11992. if (alsoParseSubElements)
  11993. readChildElements (node);
  11994. break;
  11995. }
  11996. // get an attribute..
  11997. if (isXmlIdentifierChar (c))
  11998. {
  11999. const int attNameLen = findNextTokenLength();
  12000. if (attNameLen > 0)
  12001. {
  12002. const juce_wchar* attNameStart = input;
  12003. input += attNameLen;
  12004. skipNextWhiteSpace();
  12005. if (readNextChar() == '=')
  12006. {
  12007. skipNextWhiteSpace();
  12008. const juce_wchar nextChar = *input;
  12009. if (nextChar == '"' || nextChar == '\'')
  12010. {
  12011. XmlElement::XmlAttributeNode* const newAtt
  12012. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12013. String::empty);
  12014. readQuotedString (newAtt->value);
  12015. if (lastAttribute == 0)
  12016. node->attributes = newAtt;
  12017. else
  12018. lastAttribute->next = newAtt;
  12019. lastAttribute = newAtt;
  12020. continue;
  12021. }
  12022. }
  12023. }
  12024. }
  12025. else
  12026. {
  12027. if (! outOfData)
  12028. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12029. }
  12030. break;
  12031. }
  12032. }
  12033. return node;
  12034. }
  12035. void XmlDocument::readChildElements (XmlElement* parent)
  12036. {
  12037. XmlElement* lastChildNode = 0;
  12038. for (;;)
  12039. {
  12040. skipNextWhiteSpace();
  12041. if (outOfData)
  12042. {
  12043. setLastError ("unmatched tags", false);
  12044. break;
  12045. }
  12046. if (*input == '<')
  12047. {
  12048. if (input[1] == '/')
  12049. {
  12050. // our close tag..
  12051. input = CharacterFunctions::find (input, JUCE_T(">"));
  12052. ++input;
  12053. break;
  12054. }
  12055. else if (input[1] == '!'
  12056. && input[2] == '['
  12057. && input[3] == 'C'
  12058. && input[4] == 'D'
  12059. && input[5] == 'A'
  12060. && input[6] == 'T'
  12061. && input[7] == 'A'
  12062. && input[8] == '[')
  12063. {
  12064. input += 9;
  12065. const juce_wchar* const inputStart = input;
  12066. int len = 0;
  12067. for (;;)
  12068. {
  12069. if (*input == 0)
  12070. {
  12071. setLastError ("unterminated CDATA section", false);
  12072. outOfData = true;
  12073. break;
  12074. }
  12075. else if (input[0] == ']'
  12076. && input[1] == ']'
  12077. && input[2] == '>')
  12078. {
  12079. input += 3;
  12080. break;
  12081. }
  12082. ++input;
  12083. ++len;
  12084. }
  12085. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12086. if (lastChildNode != 0)
  12087. lastChildNode->nextElement = e;
  12088. else
  12089. parent->addChildElement (e);
  12090. lastChildNode = e;
  12091. }
  12092. else
  12093. {
  12094. // this is some other element, so parse and add it..
  12095. XmlElement* const n = readNextElement (true);
  12096. if (n != 0)
  12097. {
  12098. if (lastChildNode == 0)
  12099. parent->addChildElement (n);
  12100. else
  12101. lastChildNode->nextElement = n;
  12102. lastChildNode = n;
  12103. }
  12104. else
  12105. {
  12106. return;
  12107. }
  12108. }
  12109. }
  12110. else
  12111. {
  12112. // read character block..
  12113. XmlElement* const e = new XmlElement ((int)0);
  12114. if (lastChildNode != 0)
  12115. lastChildNode->nextElement = e;
  12116. else
  12117. parent->addChildElement (e);
  12118. lastChildNode = e;
  12119. String textElementContent;
  12120. for (;;)
  12121. {
  12122. const juce_wchar c = *input;
  12123. if (c == '<')
  12124. break;
  12125. if (c == 0)
  12126. {
  12127. setLastError ("unmatched tags", false);
  12128. outOfData = true;
  12129. return;
  12130. }
  12131. if (c == '&')
  12132. {
  12133. String entity;
  12134. readEntity (entity);
  12135. if (entity.startsWithChar ('<') && entity [1] != 0)
  12136. {
  12137. const juce_wchar* const oldInput = input;
  12138. const bool oldOutOfData = outOfData;
  12139. input = entity;
  12140. outOfData = false;
  12141. for (;;)
  12142. {
  12143. XmlElement* const n = readNextElement (true);
  12144. if (n == 0)
  12145. break;
  12146. if (lastChildNode == 0)
  12147. parent->addChildElement (n);
  12148. else
  12149. lastChildNode->nextElement = n;
  12150. lastChildNode = n;
  12151. }
  12152. input = oldInput;
  12153. outOfData = oldOutOfData;
  12154. }
  12155. else
  12156. {
  12157. textElementContent += entity;
  12158. }
  12159. }
  12160. else
  12161. {
  12162. const juce_wchar* start = input;
  12163. int len = 0;
  12164. for (;;)
  12165. {
  12166. const juce_wchar nextChar = *input;
  12167. if (nextChar == '<' || nextChar == '&')
  12168. {
  12169. break;
  12170. }
  12171. else if (nextChar == 0)
  12172. {
  12173. setLastError ("unmatched tags", false);
  12174. outOfData = true;
  12175. return;
  12176. }
  12177. ++input;
  12178. ++len;
  12179. }
  12180. textElementContent.append (start, len);
  12181. }
  12182. }
  12183. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  12184. : textElementContent.isNotEmpty())
  12185. e->setText (textElementContent);
  12186. }
  12187. }
  12188. }
  12189. void XmlDocument::readEntity (String& result)
  12190. {
  12191. // skip over the ampersand
  12192. ++input;
  12193. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12194. {
  12195. input += 4;
  12196. result += '&';
  12197. }
  12198. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12199. {
  12200. input += 5;
  12201. result += '"';
  12202. }
  12203. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12204. {
  12205. input += 5;
  12206. result += '\'';
  12207. }
  12208. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12209. {
  12210. input += 3;
  12211. result += '<';
  12212. }
  12213. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12214. {
  12215. input += 3;
  12216. result += '>';
  12217. }
  12218. else if (*input == '#')
  12219. {
  12220. int charCode = 0;
  12221. ++input;
  12222. if (*input == 'x' || *input == 'X')
  12223. {
  12224. ++input;
  12225. int numChars = 0;
  12226. while (input[0] != ';')
  12227. {
  12228. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12229. if (hexValue < 0 || ++numChars > 8)
  12230. {
  12231. setLastError ("illegal escape sequence", true);
  12232. break;
  12233. }
  12234. charCode = (charCode << 4) | hexValue;
  12235. ++input;
  12236. }
  12237. ++input;
  12238. }
  12239. else if (input[0] >= '0' && input[0] <= '9')
  12240. {
  12241. int numChars = 0;
  12242. while (input[0] != ';')
  12243. {
  12244. if (++numChars > 12)
  12245. {
  12246. setLastError ("illegal escape sequence", true);
  12247. break;
  12248. }
  12249. charCode = charCode * 10 + (input[0] - '0');
  12250. ++input;
  12251. }
  12252. ++input;
  12253. }
  12254. else
  12255. {
  12256. setLastError ("illegal escape sequence", true);
  12257. result += '&';
  12258. return;
  12259. }
  12260. result << (juce_wchar) charCode;
  12261. }
  12262. else
  12263. {
  12264. const juce_wchar* const entityNameStart = input;
  12265. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12266. if (closingSemiColon == 0)
  12267. {
  12268. outOfData = true;
  12269. result += '&';
  12270. }
  12271. else
  12272. {
  12273. input = closingSemiColon + 1;
  12274. result += expandExternalEntity (String (entityNameStart,
  12275. (int) (closingSemiColon - entityNameStart)));
  12276. }
  12277. }
  12278. }
  12279. const String XmlDocument::expandEntity (const String& ent)
  12280. {
  12281. if (ent.equalsIgnoreCase ("amp"))
  12282. return String::charToString ('&');
  12283. if (ent.equalsIgnoreCase ("quot"))
  12284. return String::charToString ('"');
  12285. if (ent.equalsIgnoreCase ("apos"))
  12286. return String::charToString ('\'');
  12287. if (ent.equalsIgnoreCase ("lt"))
  12288. return String::charToString ('<');
  12289. if (ent.equalsIgnoreCase ("gt"))
  12290. return String::charToString ('>');
  12291. if (ent[0] == '#')
  12292. {
  12293. if (ent[1] == 'x' || ent[1] == 'X')
  12294. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12295. if (ent[1] >= '0' && ent[1] <= '9')
  12296. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12297. setLastError ("illegal escape sequence", false);
  12298. return String::charToString ('&');
  12299. }
  12300. return expandExternalEntity (ent);
  12301. }
  12302. const String XmlDocument::expandExternalEntity (const String& entity)
  12303. {
  12304. if (needToLoadDTD)
  12305. {
  12306. if (dtdText.isNotEmpty())
  12307. {
  12308. dtdText = dtdText.trimCharactersAtEnd (">");
  12309. tokenisedDTD.addTokens (dtdText, true);
  12310. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12311. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12312. {
  12313. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12314. tokenisedDTD.clear();
  12315. tokenisedDTD.addTokens (getFileContents (fn), true);
  12316. }
  12317. else
  12318. {
  12319. tokenisedDTD.clear();
  12320. const int openBracket = dtdText.indexOfChar ('[');
  12321. if (openBracket > 0)
  12322. {
  12323. const int closeBracket = dtdText.lastIndexOfChar (']');
  12324. if (closeBracket > openBracket)
  12325. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12326. closeBracket), true);
  12327. }
  12328. }
  12329. for (int i = tokenisedDTD.size(); --i >= 0;)
  12330. {
  12331. if (tokenisedDTD[i].startsWithChar ('%')
  12332. && tokenisedDTD[i].endsWithChar (';'))
  12333. {
  12334. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12335. StringArray newToks;
  12336. newToks.addTokens (parsed, true);
  12337. tokenisedDTD.remove (i);
  12338. for (int j = newToks.size(); --j >= 0;)
  12339. tokenisedDTD.insert (i, newToks[j]);
  12340. }
  12341. }
  12342. }
  12343. needToLoadDTD = false;
  12344. }
  12345. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12346. {
  12347. if (tokenisedDTD[i] == entity)
  12348. {
  12349. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12350. {
  12351. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12352. // check for sub-entities..
  12353. int ampersand = ent.indexOfChar ('&');
  12354. while (ampersand >= 0)
  12355. {
  12356. const int semiColon = ent.indexOf (i + 1, ";");
  12357. if (semiColon < 0)
  12358. {
  12359. setLastError ("entity without terminating semi-colon", false);
  12360. break;
  12361. }
  12362. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12363. ent = ent.substring (0, ampersand)
  12364. + resolved
  12365. + ent.substring (semiColon + 1);
  12366. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12367. }
  12368. return ent;
  12369. }
  12370. }
  12371. }
  12372. setLastError ("unknown entity", true);
  12373. return entity;
  12374. }
  12375. const String XmlDocument::getParameterEntity (const String& entity)
  12376. {
  12377. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12378. {
  12379. if (tokenisedDTD[i] == entity)
  12380. {
  12381. if (tokenisedDTD [i - 1] == "%"
  12382. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12383. {
  12384. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12385. if (ent.equalsIgnoreCase ("system"))
  12386. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12387. else
  12388. return ent.trim().unquoted();
  12389. }
  12390. }
  12391. }
  12392. return entity;
  12393. }
  12394. END_JUCE_NAMESPACE
  12395. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12396. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12397. BEGIN_JUCE_NAMESPACE
  12398. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12399. : name (other.name),
  12400. value (other.value),
  12401. next (0)
  12402. {
  12403. }
  12404. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12405. : name (name_),
  12406. value (value_),
  12407. next (0)
  12408. {
  12409. }
  12410. XmlElement::XmlElement (const String& tagName_) throw()
  12411. : tagName (tagName_),
  12412. firstChildElement (0),
  12413. nextElement (0),
  12414. attributes (0)
  12415. {
  12416. // the tag name mustn't be empty, or it'll look like a text element!
  12417. jassert (tagName_.containsNonWhitespaceChars())
  12418. // The tag can't contain spaces or other characters that would create invalid XML!
  12419. jassert (! tagName_.containsAnyOf (" <>/&"));
  12420. }
  12421. XmlElement::XmlElement (int /*dummy*/) throw()
  12422. : firstChildElement (0),
  12423. nextElement (0),
  12424. attributes (0)
  12425. {
  12426. }
  12427. XmlElement::XmlElement (const XmlElement& other)
  12428. : tagName (other.tagName),
  12429. firstChildElement (0),
  12430. nextElement (0),
  12431. attributes (0)
  12432. {
  12433. copyChildrenAndAttributesFrom (other);
  12434. }
  12435. XmlElement& XmlElement::operator= (const XmlElement& other)
  12436. {
  12437. if (this != &other)
  12438. {
  12439. removeAllAttributes();
  12440. deleteAllChildElements();
  12441. tagName = other.tagName;
  12442. copyChildrenAndAttributesFrom (other);
  12443. }
  12444. return *this;
  12445. }
  12446. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12447. {
  12448. XmlElement* child = other.firstChildElement;
  12449. XmlElement* lastChild = 0;
  12450. while (child != 0)
  12451. {
  12452. XmlElement* const copiedChild = new XmlElement (*child);
  12453. if (lastChild != 0)
  12454. lastChild->nextElement = copiedChild;
  12455. else
  12456. firstChildElement = copiedChild;
  12457. lastChild = copiedChild;
  12458. child = child->nextElement;
  12459. }
  12460. const XmlAttributeNode* att = other.attributes;
  12461. XmlAttributeNode* lastAtt = 0;
  12462. while (att != 0)
  12463. {
  12464. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12465. if (lastAtt != 0)
  12466. lastAtt->next = newAtt;
  12467. else
  12468. attributes = newAtt;
  12469. lastAtt = newAtt;
  12470. att = att->next;
  12471. }
  12472. }
  12473. XmlElement::~XmlElement() throw()
  12474. {
  12475. XmlElement* child = firstChildElement;
  12476. while (child != 0)
  12477. {
  12478. XmlElement* const nextChild = child->nextElement;
  12479. delete child;
  12480. child = nextChild;
  12481. }
  12482. XmlAttributeNode* att = attributes;
  12483. while (att != 0)
  12484. {
  12485. XmlAttributeNode* const nextAtt = att->next;
  12486. delete att;
  12487. att = nextAtt;
  12488. }
  12489. }
  12490. namespace XmlOutputFunctions
  12491. {
  12492. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12493. {
  12494. if ((character >= 'a' && character <= 'z')
  12495. || (character >= 'A' && character <= 'Z')
  12496. || (character >= '0' && character <= '9'))
  12497. return true;
  12498. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12499. do
  12500. {
  12501. if (((juce_wchar) (uint8) *t) == character)
  12502. return true;
  12503. }
  12504. while (*++t != 0);
  12505. return false;
  12506. }
  12507. static void generateLegalCharConstants()
  12508. {
  12509. uint8 n[32];
  12510. zerostruct (n);
  12511. for (int i = 0; i < 256; ++i)
  12512. if (isLegalXmlCharSlow (i))
  12513. n[i >> 3] |= (1 << (i & 7));
  12514. String s;
  12515. for (int i = 0; i < 32; ++i)
  12516. s << (int) n[i] << ", ";
  12517. DBG (s);
  12518. }*/
  12519. static bool isLegalXmlChar (const uint32 c) throw()
  12520. {
  12521. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12522. return c < sizeof (legalChars) * 8
  12523. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12524. }
  12525. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12526. {
  12527. const juce_wchar* t = text;
  12528. for (;;)
  12529. {
  12530. const juce_wchar character = *t++;
  12531. if (character == 0)
  12532. {
  12533. break;
  12534. }
  12535. else if (isLegalXmlChar ((uint32) character))
  12536. {
  12537. outputStream << (char) character;
  12538. }
  12539. else
  12540. {
  12541. switch (character)
  12542. {
  12543. case '&': outputStream << "&amp;"; break;
  12544. case '"': outputStream << "&quot;"; break;
  12545. case '>': outputStream << "&gt;"; break;
  12546. case '<': outputStream << "&lt;"; break;
  12547. case '\n':
  12548. if (changeNewLines)
  12549. outputStream << "&#10;";
  12550. else
  12551. outputStream << (char) character;
  12552. break;
  12553. case '\r':
  12554. if (changeNewLines)
  12555. outputStream << "&#13;";
  12556. else
  12557. outputStream << (char) character;
  12558. break;
  12559. default:
  12560. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12561. break;
  12562. }
  12563. }
  12564. }
  12565. }
  12566. static void writeSpaces (OutputStream& out, int numSpaces)
  12567. {
  12568. if (numSpaces > 0)
  12569. {
  12570. const char* const blanks = " ";
  12571. const int blankSize = (int) sizeof (blanks) - 1;
  12572. while (numSpaces > blankSize)
  12573. {
  12574. out.write (blanks, blankSize);
  12575. numSpaces -= blankSize;
  12576. }
  12577. out.write (blanks, numSpaces);
  12578. }
  12579. }
  12580. }
  12581. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12582. const int indentationLevel,
  12583. const int lineWrapLength) const
  12584. {
  12585. using namespace XmlOutputFunctions;
  12586. writeSpaces (outputStream, indentationLevel);
  12587. if (! isTextElement())
  12588. {
  12589. outputStream.writeByte ('<');
  12590. outputStream << tagName;
  12591. const int attIndent = indentationLevel + tagName.length() + 1;
  12592. int lineLen = 0;
  12593. const XmlAttributeNode* att = attributes;
  12594. while (att != 0)
  12595. {
  12596. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12597. {
  12598. outputStream.write ("\r\n", 2);
  12599. writeSpaces (outputStream, attIndent);
  12600. lineLen = 0;
  12601. }
  12602. const int64 startPos = outputStream.getPosition();
  12603. outputStream.writeByte (' ');
  12604. outputStream << att->name;
  12605. outputStream.write ("=\"", 2);
  12606. escapeIllegalXmlChars (outputStream, att->value, true);
  12607. outputStream.writeByte ('"');
  12608. lineLen += (int) (outputStream.getPosition() - startPos);
  12609. att = att->next;
  12610. }
  12611. if (firstChildElement != 0)
  12612. {
  12613. XmlElement* child = firstChildElement;
  12614. if (child->nextElement == 0 && child->isTextElement())
  12615. {
  12616. outputStream.writeByte ('>');
  12617. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12618. }
  12619. else
  12620. {
  12621. if (indentationLevel >= 0)
  12622. outputStream.write (">\r\n", 3);
  12623. else
  12624. outputStream.writeByte ('>');
  12625. bool lastWasTextNode = false;
  12626. while (child != 0)
  12627. {
  12628. if (child->isTextElement())
  12629. {
  12630. if ((! lastWasTextNode) && (indentationLevel >= 0))
  12631. writeSpaces (outputStream, indentationLevel + 2);
  12632. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12633. lastWasTextNode = true;
  12634. }
  12635. else
  12636. {
  12637. if (indentationLevel >= 0)
  12638. {
  12639. if (lastWasTextNode)
  12640. outputStream.write ("\r\n", 2);
  12641. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  12642. }
  12643. else
  12644. {
  12645. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  12646. }
  12647. lastWasTextNode = false;
  12648. }
  12649. child = child->nextElement;
  12650. }
  12651. if (indentationLevel >= 0)
  12652. {
  12653. if (lastWasTextNode)
  12654. outputStream.write ("\r\n", 2);
  12655. writeSpaces (outputStream, indentationLevel);
  12656. }
  12657. }
  12658. outputStream.write ("</", 2);
  12659. outputStream << tagName;
  12660. if (indentationLevel >= 0)
  12661. outputStream.write (">\r\n", 3);
  12662. else
  12663. outputStream.writeByte ('>');
  12664. }
  12665. else
  12666. {
  12667. if (indentationLevel >= 0)
  12668. outputStream.write ("/>\r\n", 4);
  12669. else
  12670. outputStream.write ("/>", 2);
  12671. }
  12672. }
  12673. else
  12674. {
  12675. if (indentationLevel >= 0)
  12676. writeSpaces (outputStream, indentationLevel + 2);
  12677. escapeIllegalXmlChars (outputStream, getText(), false);
  12678. }
  12679. }
  12680. const String XmlElement::createDocument (const String& dtdToUse,
  12681. const bool allOnOneLine,
  12682. const bool includeXmlHeader,
  12683. const String& encodingType,
  12684. const int lineWrapLength) const
  12685. {
  12686. MemoryOutputStream mem (2048);
  12687. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12688. return mem.toUTF8();
  12689. }
  12690. void XmlElement::writeToStream (OutputStream& output,
  12691. const String& dtdToUse,
  12692. const bool allOnOneLine,
  12693. const bool includeXmlHeader,
  12694. const String& encodingType,
  12695. const int lineWrapLength) const
  12696. {
  12697. if (includeXmlHeader)
  12698. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  12699. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  12700. if (dtdToUse.isNotEmpty())
  12701. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  12702. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12703. }
  12704. bool XmlElement::writeToFile (const File& file,
  12705. const String& dtdToUse,
  12706. const String& encodingType,
  12707. const int lineWrapLength) const
  12708. {
  12709. if (file.hasWriteAccess())
  12710. {
  12711. TemporaryFile tempFile (file);
  12712. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12713. if (out != 0)
  12714. {
  12715. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12716. out = 0;
  12717. return tempFile.overwriteTargetFileWithTemporary();
  12718. }
  12719. }
  12720. return false;
  12721. }
  12722. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12723. {
  12724. #if JUCE_DEBUG
  12725. // if debugging, check that the case is actually the same, because
  12726. // valid xml is case-sensitive, and although this lets it pass, it's
  12727. // better not to..
  12728. if (tagName.equalsIgnoreCase (tagNameWanted))
  12729. {
  12730. jassert (tagName == tagNameWanted);
  12731. return true;
  12732. }
  12733. else
  12734. {
  12735. return false;
  12736. }
  12737. #else
  12738. return tagName.equalsIgnoreCase (tagNameWanted);
  12739. #endif
  12740. }
  12741. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12742. {
  12743. XmlElement* e = nextElement;
  12744. while (e != 0 && ! e->hasTagName (requiredTagName))
  12745. e = e->nextElement;
  12746. return e;
  12747. }
  12748. int XmlElement::getNumAttributes() const throw()
  12749. {
  12750. const XmlAttributeNode* att = attributes;
  12751. int count = 0;
  12752. while (att != 0)
  12753. {
  12754. att = att->next;
  12755. ++count;
  12756. }
  12757. return count;
  12758. }
  12759. const String& XmlElement::getAttributeName (const int index) const throw()
  12760. {
  12761. const XmlAttributeNode* att = attributes;
  12762. int count = 0;
  12763. while (att != 0)
  12764. {
  12765. if (count == index)
  12766. return att->name;
  12767. att = att->next;
  12768. ++count;
  12769. }
  12770. return String::empty;
  12771. }
  12772. const String& XmlElement::getAttributeValue (const int index) const throw()
  12773. {
  12774. const XmlAttributeNode* att = attributes;
  12775. int count = 0;
  12776. while (att != 0)
  12777. {
  12778. if (count == index)
  12779. return att->value;
  12780. att = att->next;
  12781. ++count;
  12782. }
  12783. return String::empty;
  12784. }
  12785. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12786. {
  12787. const XmlAttributeNode* att = attributes;
  12788. while (att != 0)
  12789. {
  12790. if (att->name.equalsIgnoreCase (attributeName))
  12791. return true;
  12792. att = att->next;
  12793. }
  12794. return false;
  12795. }
  12796. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12797. {
  12798. const XmlAttributeNode* att = attributes;
  12799. while (att != 0)
  12800. {
  12801. if (att->name.equalsIgnoreCase (attributeName))
  12802. return att->value;
  12803. att = att->next;
  12804. }
  12805. return String::empty;
  12806. }
  12807. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12808. {
  12809. const XmlAttributeNode* att = attributes;
  12810. while (att != 0)
  12811. {
  12812. if (att->name.equalsIgnoreCase (attributeName))
  12813. return att->value;
  12814. att = att->next;
  12815. }
  12816. return defaultReturnValue;
  12817. }
  12818. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12819. {
  12820. const XmlAttributeNode* att = attributes;
  12821. while (att != 0)
  12822. {
  12823. if (att->name.equalsIgnoreCase (attributeName))
  12824. return att->value.getIntValue();
  12825. att = att->next;
  12826. }
  12827. return defaultReturnValue;
  12828. }
  12829. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12830. {
  12831. const XmlAttributeNode* att = attributes;
  12832. while (att != 0)
  12833. {
  12834. if (att->name.equalsIgnoreCase (attributeName))
  12835. return att->value.getDoubleValue();
  12836. att = att->next;
  12837. }
  12838. return defaultReturnValue;
  12839. }
  12840. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12841. {
  12842. const XmlAttributeNode* att = attributes;
  12843. while (att != 0)
  12844. {
  12845. if (att->name.equalsIgnoreCase (attributeName))
  12846. {
  12847. juce_wchar firstChar = att->value[0];
  12848. if (CharacterFunctions::isWhitespace (firstChar))
  12849. firstChar = att->value.trimStart() [0];
  12850. return firstChar == '1'
  12851. || firstChar == 't'
  12852. || firstChar == 'y'
  12853. || firstChar == 'T'
  12854. || firstChar == 'Y';
  12855. }
  12856. att = att->next;
  12857. }
  12858. return defaultReturnValue;
  12859. }
  12860. bool XmlElement::compareAttribute (const String& attributeName,
  12861. const String& stringToCompareAgainst,
  12862. const bool ignoreCase) const throw()
  12863. {
  12864. const XmlAttributeNode* att = attributes;
  12865. while (att != 0)
  12866. {
  12867. if (att->name.equalsIgnoreCase (attributeName))
  12868. {
  12869. if (ignoreCase)
  12870. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  12871. else
  12872. return att->value == stringToCompareAgainst;
  12873. }
  12874. att = att->next;
  12875. }
  12876. return false;
  12877. }
  12878. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12879. {
  12880. #if JUCE_DEBUG
  12881. // check the identifier being passed in is legal..
  12882. const juce_wchar* t = attributeName;
  12883. while (*t != 0)
  12884. {
  12885. jassert (CharacterFunctions::isLetterOrDigit (*t)
  12886. || *t == '_'
  12887. || *t == '-'
  12888. || *t == ':');
  12889. ++t;
  12890. }
  12891. #endif
  12892. if (attributes == 0)
  12893. {
  12894. attributes = new XmlAttributeNode (attributeName, value);
  12895. }
  12896. else
  12897. {
  12898. XmlAttributeNode* att = attributes;
  12899. for (;;)
  12900. {
  12901. if (att->name.equalsIgnoreCase (attributeName))
  12902. {
  12903. att->value = value;
  12904. break;
  12905. }
  12906. else if (att->next == 0)
  12907. {
  12908. att->next = new XmlAttributeNode (attributeName, value);
  12909. break;
  12910. }
  12911. att = att->next;
  12912. }
  12913. }
  12914. }
  12915. void XmlElement::setAttribute (const String& attributeName, const int number)
  12916. {
  12917. setAttribute (attributeName, String (number));
  12918. }
  12919. void XmlElement::setAttribute (const String& attributeName, const double number)
  12920. {
  12921. setAttribute (attributeName, String (number));
  12922. }
  12923. void XmlElement::removeAttribute (const String& attributeName) throw()
  12924. {
  12925. XmlAttributeNode* att = attributes;
  12926. XmlAttributeNode* lastAtt = 0;
  12927. while (att != 0)
  12928. {
  12929. if (att->name.equalsIgnoreCase (attributeName))
  12930. {
  12931. if (lastAtt == 0)
  12932. attributes = att->next;
  12933. else
  12934. lastAtt->next = att->next;
  12935. delete att;
  12936. break;
  12937. }
  12938. lastAtt = att;
  12939. att = att->next;
  12940. }
  12941. }
  12942. void XmlElement::removeAllAttributes() throw()
  12943. {
  12944. while (attributes != 0)
  12945. {
  12946. XmlAttributeNode* const nextAtt = attributes->next;
  12947. delete attributes;
  12948. attributes = nextAtt;
  12949. }
  12950. }
  12951. int XmlElement::getNumChildElements() const throw()
  12952. {
  12953. int count = 0;
  12954. const XmlElement* child = firstChildElement;
  12955. while (child != 0)
  12956. {
  12957. ++count;
  12958. child = child->nextElement;
  12959. }
  12960. return count;
  12961. }
  12962. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12963. {
  12964. int count = 0;
  12965. XmlElement* child = firstChildElement;
  12966. while (child != 0 && count < index)
  12967. {
  12968. child = child->nextElement;
  12969. ++count;
  12970. }
  12971. return child;
  12972. }
  12973. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12974. {
  12975. XmlElement* child = firstChildElement;
  12976. while (child != 0)
  12977. {
  12978. if (child->hasTagName (childName))
  12979. break;
  12980. child = child->nextElement;
  12981. }
  12982. return child;
  12983. }
  12984. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12985. {
  12986. if (newNode != 0)
  12987. {
  12988. if (firstChildElement == 0)
  12989. {
  12990. firstChildElement = newNode;
  12991. }
  12992. else
  12993. {
  12994. XmlElement* child = firstChildElement;
  12995. while (child->nextElement != 0)
  12996. child = child->nextElement;
  12997. child->nextElement = newNode;
  12998. // if this is non-zero, then something's probably
  12999. // gone wrong..
  13000. jassert (newNode->nextElement == 0);
  13001. }
  13002. }
  13003. }
  13004. void XmlElement::insertChildElement (XmlElement* const newNode,
  13005. int indexToInsertAt) throw()
  13006. {
  13007. if (newNode != 0)
  13008. {
  13009. removeChildElement (newNode, false);
  13010. if (indexToInsertAt == 0)
  13011. {
  13012. newNode->nextElement = firstChildElement;
  13013. firstChildElement = newNode;
  13014. }
  13015. else
  13016. {
  13017. if (firstChildElement == 0)
  13018. {
  13019. firstChildElement = newNode;
  13020. }
  13021. else
  13022. {
  13023. if (indexToInsertAt < 0)
  13024. indexToInsertAt = std::numeric_limits<int>::max();
  13025. XmlElement* child = firstChildElement;
  13026. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13027. child = child->nextElement;
  13028. newNode->nextElement = child->nextElement;
  13029. child->nextElement = newNode;
  13030. }
  13031. }
  13032. }
  13033. }
  13034. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13035. {
  13036. XmlElement* const newElement = new XmlElement (childTagName);
  13037. addChildElement (newElement);
  13038. return newElement;
  13039. }
  13040. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13041. XmlElement* const newNode) throw()
  13042. {
  13043. if (newNode != 0)
  13044. {
  13045. XmlElement* child = firstChildElement;
  13046. XmlElement* previousNode = 0;
  13047. while (child != 0)
  13048. {
  13049. if (child == currentChildElement)
  13050. {
  13051. if (child != newNode)
  13052. {
  13053. if (previousNode == 0)
  13054. firstChildElement = newNode;
  13055. else
  13056. previousNode->nextElement = newNode;
  13057. newNode->nextElement = child->nextElement;
  13058. delete child;
  13059. }
  13060. return true;
  13061. }
  13062. previousNode = child;
  13063. child = child->nextElement;
  13064. }
  13065. }
  13066. return false;
  13067. }
  13068. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13069. const bool shouldDeleteTheChild) throw()
  13070. {
  13071. if (childToRemove != 0)
  13072. {
  13073. if (firstChildElement == childToRemove)
  13074. {
  13075. firstChildElement = childToRemove->nextElement;
  13076. childToRemove->nextElement = 0;
  13077. }
  13078. else
  13079. {
  13080. XmlElement* child = firstChildElement;
  13081. XmlElement* last = 0;
  13082. while (child != 0)
  13083. {
  13084. if (child == childToRemove)
  13085. {
  13086. if (last == 0)
  13087. firstChildElement = child->nextElement;
  13088. else
  13089. last->nextElement = child->nextElement;
  13090. childToRemove->nextElement = 0;
  13091. break;
  13092. }
  13093. last = child;
  13094. child = child->nextElement;
  13095. }
  13096. }
  13097. if (shouldDeleteTheChild)
  13098. delete childToRemove;
  13099. }
  13100. }
  13101. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13102. const bool ignoreOrderOfAttributes) const throw()
  13103. {
  13104. if (this != other)
  13105. {
  13106. if (other == 0 || tagName != other->tagName)
  13107. {
  13108. return false;
  13109. }
  13110. if (ignoreOrderOfAttributes)
  13111. {
  13112. int totalAtts = 0;
  13113. const XmlAttributeNode* att = attributes;
  13114. while (att != 0)
  13115. {
  13116. if (! other->compareAttribute (att->name, att->value))
  13117. return false;
  13118. att = att->next;
  13119. ++totalAtts;
  13120. }
  13121. if (totalAtts != other->getNumAttributes())
  13122. return false;
  13123. }
  13124. else
  13125. {
  13126. const XmlAttributeNode* thisAtt = attributes;
  13127. const XmlAttributeNode* otherAtt = other->attributes;
  13128. for (;;)
  13129. {
  13130. if (thisAtt == 0 || otherAtt == 0)
  13131. {
  13132. if (thisAtt == otherAtt) // both 0, so it's a match
  13133. break;
  13134. return false;
  13135. }
  13136. if (thisAtt->name != otherAtt->name
  13137. || thisAtt->value != otherAtt->value)
  13138. {
  13139. return false;
  13140. }
  13141. thisAtt = thisAtt->next;
  13142. otherAtt = otherAtt->next;
  13143. }
  13144. }
  13145. const XmlElement* thisChild = firstChildElement;
  13146. const XmlElement* otherChild = other->firstChildElement;
  13147. for (;;)
  13148. {
  13149. if (thisChild == 0 || otherChild == 0)
  13150. {
  13151. if (thisChild == otherChild) // both 0, so it's a match
  13152. break;
  13153. return false;
  13154. }
  13155. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13156. return false;
  13157. thisChild = thisChild->nextElement;
  13158. otherChild = otherChild->nextElement;
  13159. }
  13160. }
  13161. return true;
  13162. }
  13163. void XmlElement::deleteAllChildElements() throw()
  13164. {
  13165. while (firstChildElement != 0)
  13166. {
  13167. XmlElement* const nextChild = firstChildElement->nextElement;
  13168. delete firstChildElement;
  13169. firstChildElement = nextChild;
  13170. }
  13171. }
  13172. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13173. {
  13174. XmlElement* child = firstChildElement;
  13175. while (child != 0)
  13176. {
  13177. if (child->hasTagName (name))
  13178. {
  13179. XmlElement* const nextChild = child->nextElement;
  13180. removeChildElement (child, true);
  13181. child = nextChild;
  13182. }
  13183. else
  13184. {
  13185. child = child->nextElement;
  13186. }
  13187. }
  13188. }
  13189. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13190. {
  13191. const XmlElement* child = firstChildElement;
  13192. while (child != 0)
  13193. {
  13194. if (child == possibleChild)
  13195. return true;
  13196. child = child->nextElement;
  13197. }
  13198. return false;
  13199. }
  13200. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13201. {
  13202. if (this == elementToLookFor || elementToLookFor == 0)
  13203. return 0;
  13204. XmlElement* child = firstChildElement;
  13205. while (child != 0)
  13206. {
  13207. if (elementToLookFor == child)
  13208. return this;
  13209. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13210. if (found != 0)
  13211. return found;
  13212. child = child->nextElement;
  13213. }
  13214. return 0;
  13215. }
  13216. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13217. {
  13218. XmlElement* e = firstChildElement;
  13219. while (e != 0)
  13220. {
  13221. *elems++ = e;
  13222. e = e->nextElement;
  13223. }
  13224. }
  13225. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13226. {
  13227. XmlElement* e = firstChildElement = elems[0];
  13228. for (int i = 1; i < num; ++i)
  13229. {
  13230. e->nextElement = elems[i];
  13231. e = e->nextElement;
  13232. }
  13233. e->nextElement = 0;
  13234. }
  13235. bool XmlElement::isTextElement() const throw()
  13236. {
  13237. return tagName.isEmpty();
  13238. }
  13239. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13240. const String& XmlElement::getText() const throw()
  13241. {
  13242. jassert (isTextElement()); // you're trying to get the text from an element that
  13243. // isn't actually a text element.. If this contains text sub-nodes, you
  13244. // probably want to use getAllSubText instead.
  13245. return getStringAttribute (juce_xmltextContentAttributeName);
  13246. }
  13247. void XmlElement::setText (const String& newText)
  13248. {
  13249. if (isTextElement())
  13250. setAttribute (juce_xmltextContentAttributeName, newText);
  13251. else
  13252. jassertfalse; // you can only change the text in a text element, not a normal one.
  13253. }
  13254. const String XmlElement::getAllSubText() const
  13255. {
  13256. String result;
  13257. String::Concatenator concatenator (result);
  13258. const XmlElement* child = firstChildElement;
  13259. while (child != 0)
  13260. {
  13261. if (child->isTextElement())
  13262. concatenator.append (child->getText());
  13263. child = child->nextElement;
  13264. }
  13265. return result;
  13266. }
  13267. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13268. const String& defaultReturnValue) const
  13269. {
  13270. const XmlElement* const child = getChildByName (childTagName);
  13271. if (child != 0)
  13272. return child->getAllSubText();
  13273. return defaultReturnValue;
  13274. }
  13275. XmlElement* XmlElement::createTextElement (const String& text)
  13276. {
  13277. XmlElement* const e = new XmlElement ((int) 0);
  13278. e->setAttribute (juce_xmltextContentAttributeName, text);
  13279. return e;
  13280. }
  13281. void XmlElement::addTextElement (const String& text)
  13282. {
  13283. addChildElement (createTextElement (text));
  13284. }
  13285. void XmlElement::deleteAllTextElements() throw()
  13286. {
  13287. XmlElement* child = firstChildElement;
  13288. while (child != 0)
  13289. {
  13290. XmlElement* const next = child->nextElement;
  13291. if (child->isTextElement())
  13292. removeChildElement (child, true);
  13293. child = next;
  13294. }
  13295. }
  13296. END_JUCE_NAMESPACE
  13297. /*** End of inlined file: juce_XmlElement.cpp ***/
  13298. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13299. BEGIN_JUCE_NAMESPACE
  13300. ReadWriteLock::ReadWriteLock() throw()
  13301. : numWaitingWriters (0),
  13302. numWriters (0),
  13303. writerThreadId (0)
  13304. {
  13305. }
  13306. ReadWriteLock::~ReadWriteLock() throw()
  13307. {
  13308. jassert (readerThreads.size() == 0);
  13309. jassert (numWriters == 0);
  13310. }
  13311. void ReadWriteLock::enterRead() const throw()
  13312. {
  13313. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13314. const ScopedLock sl (accessLock);
  13315. for (;;)
  13316. {
  13317. jassert (readerThreads.size() % 2 == 0);
  13318. int i;
  13319. for (i = 0; i < readerThreads.size(); i += 2)
  13320. if (readerThreads.getUnchecked(i) == threadId)
  13321. break;
  13322. if (i < readerThreads.size()
  13323. || numWriters + numWaitingWriters == 0
  13324. || (threadId == writerThreadId && numWriters > 0))
  13325. {
  13326. if (i < readerThreads.size())
  13327. {
  13328. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13329. }
  13330. else
  13331. {
  13332. readerThreads.add (threadId);
  13333. readerThreads.add ((Thread::ThreadID) 1);
  13334. }
  13335. return;
  13336. }
  13337. const ScopedUnlock ul (accessLock);
  13338. waitEvent.wait (100);
  13339. }
  13340. }
  13341. void ReadWriteLock::exitRead() const throw()
  13342. {
  13343. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13344. const ScopedLock sl (accessLock);
  13345. for (int i = 0; i < readerThreads.size(); i += 2)
  13346. {
  13347. if (readerThreads.getUnchecked(i) == threadId)
  13348. {
  13349. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13350. if (newCount == 0)
  13351. {
  13352. readerThreads.removeRange (i, 2);
  13353. waitEvent.signal();
  13354. }
  13355. else
  13356. {
  13357. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13358. }
  13359. return;
  13360. }
  13361. }
  13362. jassertfalse; // unlocking a lock that wasn't locked..
  13363. }
  13364. void ReadWriteLock::enterWrite() const throw()
  13365. {
  13366. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13367. const ScopedLock sl (accessLock);
  13368. for (;;)
  13369. {
  13370. if (readerThreads.size() + numWriters == 0
  13371. || threadId == writerThreadId
  13372. || (readerThreads.size() == 2
  13373. && readerThreads.getUnchecked(0) == threadId))
  13374. {
  13375. writerThreadId = threadId;
  13376. ++numWriters;
  13377. break;
  13378. }
  13379. ++numWaitingWriters;
  13380. accessLock.exit();
  13381. waitEvent.wait (100);
  13382. accessLock.enter();
  13383. --numWaitingWriters;
  13384. }
  13385. }
  13386. bool ReadWriteLock::tryEnterWrite() const throw()
  13387. {
  13388. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13389. const ScopedLock sl (accessLock);
  13390. if (readerThreads.size() + numWriters == 0
  13391. || threadId == writerThreadId
  13392. || (readerThreads.size() == 2
  13393. && readerThreads.getUnchecked(0) == threadId))
  13394. {
  13395. writerThreadId = threadId;
  13396. ++numWriters;
  13397. return true;
  13398. }
  13399. return false;
  13400. }
  13401. void ReadWriteLock::exitWrite() const throw()
  13402. {
  13403. const ScopedLock sl (accessLock);
  13404. // check this thread actually had the lock..
  13405. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13406. if (--numWriters == 0)
  13407. {
  13408. writerThreadId = 0;
  13409. waitEvent.signal();
  13410. }
  13411. }
  13412. END_JUCE_NAMESPACE
  13413. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13414. /*** Start of inlined file: juce_Thread.cpp ***/
  13415. BEGIN_JUCE_NAMESPACE
  13416. // these functions are implemented in the platform-specific code.
  13417. void* juce_createThread (void* userData);
  13418. void juce_killThread (void* handle);
  13419. bool juce_setThreadPriority (void* handle, int priority);
  13420. void juce_setCurrentThreadName (const String& name);
  13421. #if JUCE_WINDOWS
  13422. void juce_CloseThreadHandle (void* handle);
  13423. #endif
  13424. void Thread::threadEntryPoint (Thread* const thread)
  13425. {
  13426. {
  13427. const ScopedLock sl (runningThreadsLock);
  13428. runningThreads.add (thread);
  13429. }
  13430. JUCE_TRY
  13431. {
  13432. thread->threadId_ = Thread::getCurrentThreadId();
  13433. if (thread->threadName_.isNotEmpty())
  13434. juce_setCurrentThreadName (thread->threadName_);
  13435. if (thread->startSuspensionEvent_.wait (10000))
  13436. {
  13437. if (thread->affinityMask_ != 0)
  13438. setCurrentThreadAffinityMask (thread->affinityMask_);
  13439. thread->run();
  13440. }
  13441. }
  13442. JUCE_CATCH_ALL_ASSERT
  13443. {
  13444. const ScopedLock sl (runningThreadsLock);
  13445. jassert (runningThreads.contains (thread));
  13446. runningThreads.removeValue (thread);
  13447. }
  13448. #if JUCE_WINDOWS
  13449. juce_CloseThreadHandle (thread->threadHandle_);
  13450. #endif
  13451. thread->threadHandle_ = 0;
  13452. thread->threadId_ = 0;
  13453. }
  13454. // used to wrap the incoming call from the platform-specific code
  13455. void JUCE_API juce_threadEntryPoint (void* userData)
  13456. {
  13457. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13458. }
  13459. Thread::Thread (const String& threadName)
  13460. : threadName_ (threadName),
  13461. threadHandle_ (0),
  13462. threadPriority_ (5),
  13463. threadId_ (0),
  13464. affinityMask_ (0),
  13465. threadShouldExit_ (false)
  13466. {
  13467. }
  13468. Thread::~Thread()
  13469. {
  13470. stopThread (100);
  13471. }
  13472. void Thread::startThread()
  13473. {
  13474. const ScopedLock sl (startStopLock);
  13475. threadShouldExit_ = false;
  13476. if (threadHandle_ == 0)
  13477. {
  13478. threadHandle_ = juce_createThread (this);
  13479. juce_setThreadPriority (threadHandle_, threadPriority_);
  13480. startSuspensionEvent_.signal();
  13481. }
  13482. }
  13483. void Thread::startThread (const int priority)
  13484. {
  13485. const ScopedLock sl (startStopLock);
  13486. if (threadHandle_ == 0)
  13487. {
  13488. threadPriority_ = priority;
  13489. startThread();
  13490. }
  13491. else
  13492. {
  13493. setPriority (priority);
  13494. }
  13495. }
  13496. bool Thread::isThreadRunning() const
  13497. {
  13498. return threadHandle_ != 0;
  13499. }
  13500. void Thread::signalThreadShouldExit()
  13501. {
  13502. threadShouldExit_ = true;
  13503. }
  13504. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13505. {
  13506. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13507. jassert (getThreadId() != getCurrentThreadId());
  13508. const int sleepMsPerIteration = 5;
  13509. int count = timeOutMilliseconds / sleepMsPerIteration;
  13510. while (isThreadRunning())
  13511. {
  13512. if (timeOutMilliseconds > 0 && --count < 0)
  13513. return false;
  13514. sleep (sleepMsPerIteration);
  13515. }
  13516. return true;
  13517. }
  13518. void Thread::stopThread (const int timeOutMilliseconds)
  13519. {
  13520. // agh! You can't stop the thread that's calling this method! How on earth
  13521. // would that work??
  13522. jassert (getCurrentThreadId() != getThreadId());
  13523. const ScopedLock sl (startStopLock);
  13524. if (isThreadRunning())
  13525. {
  13526. signalThreadShouldExit();
  13527. notify();
  13528. if (timeOutMilliseconds != 0)
  13529. waitForThreadToExit (timeOutMilliseconds);
  13530. if (isThreadRunning())
  13531. {
  13532. // very bad karma if this point is reached, as
  13533. // there are bound to be locks and events left in
  13534. // silly states when a thread is killed by force..
  13535. jassertfalse;
  13536. Logger::writeToLog ("!! killing thread by force !!");
  13537. juce_killThread (threadHandle_);
  13538. threadHandle_ = 0;
  13539. threadId_ = 0;
  13540. const ScopedLock sl2 (runningThreadsLock);
  13541. runningThreads.removeValue (this);
  13542. }
  13543. }
  13544. }
  13545. bool Thread::setPriority (const int priority)
  13546. {
  13547. const ScopedLock sl (startStopLock);
  13548. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13549. if (worked)
  13550. threadPriority_ = priority;
  13551. return worked;
  13552. }
  13553. bool Thread::setCurrentThreadPriority (const int priority)
  13554. {
  13555. return juce_setThreadPriority (0, priority);
  13556. }
  13557. void Thread::setAffinityMask (const uint32 affinityMask)
  13558. {
  13559. affinityMask_ = affinityMask;
  13560. }
  13561. bool Thread::wait (const int timeOutMilliseconds) const
  13562. {
  13563. return defaultEvent_.wait (timeOutMilliseconds);
  13564. }
  13565. void Thread::notify() const
  13566. {
  13567. defaultEvent_.signal();
  13568. }
  13569. int Thread::getNumRunningThreads()
  13570. {
  13571. return runningThreads.size();
  13572. }
  13573. Thread* Thread::getCurrentThread()
  13574. {
  13575. const ThreadID thisId = getCurrentThreadId();
  13576. const ScopedLock sl (runningThreadsLock);
  13577. for (int i = runningThreads.size(); --i >= 0;)
  13578. {
  13579. Thread* const t = runningThreads.getUnchecked(i);
  13580. if (t->threadId_ == thisId)
  13581. return t;
  13582. }
  13583. return 0;
  13584. }
  13585. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13586. {
  13587. {
  13588. const ScopedLock sl (runningThreadsLock);
  13589. for (int i = runningThreads.size(); --i >= 0;)
  13590. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13591. }
  13592. for (;;)
  13593. {
  13594. Thread* firstThread;
  13595. {
  13596. const ScopedLock sl (runningThreadsLock);
  13597. firstThread = runningThreads.getFirst();
  13598. }
  13599. if (firstThread == 0)
  13600. break;
  13601. firstThread->stopThread (timeOutMilliseconds);
  13602. }
  13603. }
  13604. Array<Thread*> Thread::runningThreads;
  13605. CriticalSection Thread::runningThreadsLock;
  13606. END_JUCE_NAMESPACE
  13607. /*** End of inlined file: juce_Thread.cpp ***/
  13608. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13609. BEGIN_JUCE_NAMESPACE
  13610. ThreadPoolJob::ThreadPoolJob (const String& name)
  13611. : jobName (name),
  13612. pool (0),
  13613. shouldStop (false),
  13614. isActive (false),
  13615. shouldBeDeleted (false)
  13616. {
  13617. }
  13618. ThreadPoolJob::~ThreadPoolJob()
  13619. {
  13620. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13621. // to remove it first!
  13622. jassert (pool == 0 || ! pool->contains (this));
  13623. }
  13624. const String ThreadPoolJob::getJobName() const
  13625. {
  13626. return jobName;
  13627. }
  13628. void ThreadPoolJob::setJobName (const String& newName)
  13629. {
  13630. jobName = newName;
  13631. }
  13632. void ThreadPoolJob::signalJobShouldExit()
  13633. {
  13634. shouldStop = true;
  13635. }
  13636. class ThreadPool::ThreadPoolThread : public Thread
  13637. {
  13638. public:
  13639. ThreadPoolThread (ThreadPool& pool_)
  13640. : Thread ("Pool"),
  13641. pool (pool_),
  13642. busy (false)
  13643. {
  13644. }
  13645. ~ThreadPoolThread()
  13646. {
  13647. }
  13648. void run()
  13649. {
  13650. while (! threadShouldExit())
  13651. {
  13652. if (! pool.runNextJob())
  13653. wait (500);
  13654. }
  13655. }
  13656. private:
  13657. ThreadPool& pool;
  13658. bool volatile busy;
  13659. ThreadPoolThread (const ThreadPoolThread&);
  13660. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13661. };
  13662. ThreadPool::ThreadPool (const int numThreads,
  13663. const bool startThreadsOnlyWhenNeeded,
  13664. const int stopThreadsWhenNotUsedTimeoutMs)
  13665. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13666. priority (5)
  13667. {
  13668. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13669. for (int i = jmax (1, numThreads); --i >= 0;)
  13670. threads.add (new ThreadPoolThread (*this));
  13671. if (! startThreadsOnlyWhenNeeded)
  13672. for (int i = threads.size(); --i >= 0;)
  13673. threads.getUnchecked(i)->startThread (priority);
  13674. }
  13675. ThreadPool::~ThreadPool()
  13676. {
  13677. removeAllJobs (true, 4000);
  13678. int i;
  13679. for (i = threads.size(); --i >= 0;)
  13680. threads.getUnchecked(i)->signalThreadShouldExit();
  13681. for (i = threads.size(); --i >= 0;)
  13682. threads.getUnchecked(i)->stopThread (500);
  13683. }
  13684. void ThreadPool::addJob (ThreadPoolJob* const job)
  13685. {
  13686. jassert (job != 0);
  13687. jassert (job->pool == 0);
  13688. if (job->pool == 0)
  13689. {
  13690. job->pool = this;
  13691. job->shouldStop = false;
  13692. job->isActive = false;
  13693. {
  13694. const ScopedLock sl (lock);
  13695. jobs.add (job);
  13696. int numRunning = 0;
  13697. for (int i = threads.size(); --i >= 0;)
  13698. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13699. ++numRunning;
  13700. if (numRunning < threads.size())
  13701. {
  13702. bool startedOne = false;
  13703. int n = 1000;
  13704. while (--n >= 0 && ! startedOne)
  13705. {
  13706. for (int i = threads.size(); --i >= 0;)
  13707. {
  13708. if (! threads.getUnchecked(i)->isThreadRunning())
  13709. {
  13710. threads.getUnchecked(i)->startThread (priority);
  13711. startedOne = true;
  13712. break;
  13713. }
  13714. }
  13715. if (! startedOne)
  13716. Thread::sleep (2);
  13717. }
  13718. }
  13719. }
  13720. for (int i = threads.size(); --i >= 0;)
  13721. threads.getUnchecked(i)->notify();
  13722. }
  13723. }
  13724. int ThreadPool::getNumJobs() const
  13725. {
  13726. return jobs.size();
  13727. }
  13728. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13729. {
  13730. const ScopedLock sl (lock);
  13731. return jobs [index];
  13732. }
  13733. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13734. {
  13735. const ScopedLock sl (lock);
  13736. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13737. }
  13738. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13739. {
  13740. const ScopedLock sl (lock);
  13741. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13742. }
  13743. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13744. const int timeOutMs) const
  13745. {
  13746. if (job != 0)
  13747. {
  13748. const uint32 start = Time::getMillisecondCounter();
  13749. while (contains (job))
  13750. {
  13751. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13752. return false;
  13753. jobFinishedSignal.wait (2);
  13754. }
  13755. }
  13756. return true;
  13757. }
  13758. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13759. const bool interruptIfRunning,
  13760. const int timeOutMs)
  13761. {
  13762. bool dontWait = true;
  13763. if (job != 0)
  13764. {
  13765. const ScopedLock sl (lock);
  13766. if (jobs.contains (job))
  13767. {
  13768. if (job->isActive)
  13769. {
  13770. if (interruptIfRunning)
  13771. job->signalJobShouldExit();
  13772. dontWait = false;
  13773. }
  13774. else
  13775. {
  13776. jobs.removeValue (job);
  13777. job->pool = 0;
  13778. }
  13779. }
  13780. }
  13781. return dontWait || waitForJobToFinish (job, timeOutMs);
  13782. }
  13783. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13784. const int timeOutMs,
  13785. const bool deleteInactiveJobs,
  13786. ThreadPool::JobSelector* selectedJobsToRemove)
  13787. {
  13788. Array <ThreadPoolJob*> jobsToWaitFor;
  13789. {
  13790. const ScopedLock sl (lock);
  13791. for (int i = jobs.size(); --i >= 0;)
  13792. {
  13793. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13794. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13795. {
  13796. if (job->isActive)
  13797. {
  13798. jobsToWaitFor.add (job);
  13799. if (interruptRunningJobs)
  13800. job->signalJobShouldExit();
  13801. }
  13802. else
  13803. {
  13804. jobs.remove (i);
  13805. if (deleteInactiveJobs)
  13806. delete job;
  13807. else
  13808. job->pool = 0;
  13809. }
  13810. }
  13811. }
  13812. }
  13813. const uint32 start = Time::getMillisecondCounter();
  13814. for (;;)
  13815. {
  13816. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13817. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13818. jobsToWaitFor.remove (i);
  13819. if (jobsToWaitFor.size() == 0)
  13820. break;
  13821. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13822. return false;
  13823. jobFinishedSignal.wait (20);
  13824. }
  13825. return true;
  13826. }
  13827. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13828. {
  13829. StringArray s;
  13830. const ScopedLock sl (lock);
  13831. for (int i = 0; i < jobs.size(); ++i)
  13832. {
  13833. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13834. if (job->isActive || ! onlyReturnActiveJobs)
  13835. s.add (job->getJobName());
  13836. }
  13837. return s;
  13838. }
  13839. bool ThreadPool::setThreadPriorities (const int newPriority)
  13840. {
  13841. bool ok = true;
  13842. if (priority != newPriority)
  13843. {
  13844. priority = newPriority;
  13845. for (int i = threads.size(); --i >= 0;)
  13846. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13847. ok = false;
  13848. }
  13849. return ok;
  13850. }
  13851. bool ThreadPool::runNextJob()
  13852. {
  13853. ThreadPoolJob* job = 0;
  13854. {
  13855. const ScopedLock sl (lock);
  13856. for (int i = 0; i < jobs.size(); ++i)
  13857. {
  13858. job = jobs[i];
  13859. if (job != 0 && ! (job->isActive || job->shouldStop))
  13860. break;
  13861. job = 0;
  13862. }
  13863. if (job != 0)
  13864. job->isActive = true;
  13865. }
  13866. if (job != 0)
  13867. {
  13868. JUCE_TRY
  13869. {
  13870. ThreadPoolJob::JobStatus result = job->runJob();
  13871. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13872. const ScopedLock sl (lock);
  13873. if (jobs.contains (job))
  13874. {
  13875. job->isActive = false;
  13876. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13877. {
  13878. job->pool = 0;
  13879. job->shouldStop = true;
  13880. jobs.removeValue (job);
  13881. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13882. delete job;
  13883. jobFinishedSignal.signal();
  13884. }
  13885. else
  13886. {
  13887. // move the job to the end of the queue if it wants another go
  13888. jobs.move (jobs.indexOf (job), -1);
  13889. }
  13890. }
  13891. }
  13892. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13893. catch (...)
  13894. {
  13895. const ScopedLock sl (lock);
  13896. jobs.removeValue (job);
  13897. }
  13898. #endif
  13899. }
  13900. else
  13901. {
  13902. if (threadStopTimeout > 0
  13903. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13904. {
  13905. const ScopedLock sl (lock);
  13906. if (jobs.size() == 0)
  13907. for (int i = threads.size(); --i >= 0;)
  13908. threads.getUnchecked(i)->signalThreadShouldExit();
  13909. }
  13910. else
  13911. {
  13912. return false;
  13913. }
  13914. }
  13915. return true;
  13916. }
  13917. END_JUCE_NAMESPACE
  13918. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13919. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13920. BEGIN_JUCE_NAMESPACE
  13921. TimeSliceThread::TimeSliceThread (const String& threadName)
  13922. : Thread (threadName),
  13923. index (0),
  13924. clientBeingCalled (0),
  13925. clientsChanged (false)
  13926. {
  13927. }
  13928. TimeSliceThread::~TimeSliceThread()
  13929. {
  13930. stopThread (2000);
  13931. }
  13932. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  13933. {
  13934. const ScopedLock sl (listLock);
  13935. clients.addIfNotAlreadyThere (client);
  13936. clientsChanged = true;
  13937. notify();
  13938. }
  13939. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13940. {
  13941. const ScopedLock sl1 (listLock);
  13942. clientsChanged = true;
  13943. // if there's a chance we're in the middle of calling this client, we need to
  13944. // also lock the outer lock..
  13945. if (clientBeingCalled == client)
  13946. {
  13947. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13948. const ScopedLock sl2 (callbackLock);
  13949. const ScopedLock sl3 (listLock);
  13950. clients.removeValue (client);
  13951. }
  13952. else
  13953. {
  13954. clients.removeValue (client);
  13955. }
  13956. }
  13957. int TimeSliceThread::getNumClients() const
  13958. {
  13959. return clients.size();
  13960. }
  13961. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13962. {
  13963. const ScopedLock sl (listLock);
  13964. return clients [i];
  13965. }
  13966. void TimeSliceThread::run()
  13967. {
  13968. int numCallsSinceBusy = 0;
  13969. while (! threadShouldExit())
  13970. {
  13971. int timeToWait = 500;
  13972. {
  13973. const ScopedLock sl (callbackLock);
  13974. {
  13975. const ScopedLock sl2 (listLock);
  13976. if (clients.size() > 0)
  13977. {
  13978. index = (index + 1) % clients.size();
  13979. clientBeingCalled = clients [index];
  13980. }
  13981. else
  13982. {
  13983. index = 0;
  13984. clientBeingCalled = 0;
  13985. }
  13986. if (clientsChanged)
  13987. {
  13988. clientsChanged = false;
  13989. numCallsSinceBusy = 0;
  13990. }
  13991. }
  13992. if (clientBeingCalled != 0)
  13993. {
  13994. if (clientBeingCalled->useTimeSlice())
  13995. numCallsSinceBusy = 0;
  13996. else
  13997. ++numCallsSinceBusy;
  13998. if (numCallsSinceBusy >= clients.size())
  13999. timeToWait = 500;
  14000. else if (index == 0)
  14001. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14002. else
  14003. timeToWait = 0;
  14004. }
  14005. }
  14006. if (timeToWait > 0)
  14007. wait (timeToWait);
  14008. }
  14009. }
  14010. END_JUCE_NAMESPACE
  14011. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14012. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14013. BEGIN_JUCE_NAMESPACE
  14014. DeletedAtShutdown::DeletedAtShutdown()
  14015. {
  14016. const ScopedLock sl (getLock());
  14017. getObjects().add (this);
  14018. }
  14019. DeletedAtShutdown::~DeletedAtShutdown()
  14020. {
  14021. const ScopedLock sl (getLock());
  14022. getObjects().removeValue (this);
  14023. }
  14024. void DeletedAtShutdown::deleteAll()
  14025. {
  14026. // make a local copy of the array, so it can't get into a loop if something
  14027. // creates another DeletedAtShutdown object during its destructor.
  14028. Array <DeletedAtShutdown*> localCopy;
  14029. {
  14030. const ScopedLock sl (getLock());
  14031. localCopy = getObjects();
  14032. }
  14033. for (int i = localCopy.size(); --i >= 0;)
  14034. {
  14035. JUCE_TRY
  14036. {
  14037. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14038. // double-check that it's not already been deleted during another object's destructor.
  14039. {
  14040. const ScopedLock sl (getLock());
  14041. if (! getObjects().contains (deletee))
  14042. deletee = 0;
  14043. }
  14044. delete deletee;
  14045. }
  14046. JUCE_CATCH_EXCEPTION
  14047. }
  14048. // if no objects got re-created during shutdown, this should have been emptied by their
  14049. // destructors
  14050. jassert (getObjects().size() == 0);
  14051. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14052. }
  14053. CriticalSection& DeletedAtShutdown::getLock()
  14054. {
  14055. static CriticalSection lock;
  14056. return lock;
  14057. }
  14058. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14059. {
  14060. static Array <DeletedAtShutdown*> objects;
  14061. return objects;
  14062. }
  14063. END_JUCE_NAMESPACE
  14064. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14065. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14066. BEGIN_JUCE_NAMESPACE
  14067. UnitTest::UnitTest (const String& name_)
  14068. : name (name_), runner (0)
  14069. {
  14070. getAllTests().add (this);
  14071. }
  14072. UnitTest::~UnitTest()
  14073. {
  14074. getAllTests().removeValue (this);
  14075. }
  14076. Array<UnitTest*>& UnitTest::getAllTests()
  14077. {
  14078. static Array<UnitTest*> tests;
  14079. return tests;
  14080. }
  14081. void UnitTest::performTest (UnitTestRunner* const runner_)
  14082. {
  14083. jassert (runner_ != 0);
  14084. runner = runner_;
  14085. runTest();
  14086. }
  14087. void UnitTest::logMessage (const String& message)
  14088. {
  14089. runner->logMessage (message);
  14090. }
  14091. void UnitTest::beginTest (const String& testName)
  14092. {
  14093. runner->beginNewTest (this, testName);
  14094. }
  14095. void UnitTest::expect (const bool result, const String& failureMessage)
  14096. {
  14097. if (result)
  14098. runner->addPass();
  14099. else
  14100. runner->addFail (failureMessage);
  14101. }
  14102. UnitTestRunner::UnitTestRunner()
  14103. : currentTest (0), assertOnFailure (false)
  14104. {
  14105. }
  14106. UnitTestRunner::~UnitTestRunner()
  14107. {
  14108. }
  14109. void UnitTestRunner::resultsUpdated()
  14110. {
  14111. }
  14112. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14113. {
  14114. results.clear();
  14115. assertOnFailure = assertOnFailure_;
  14116. resultsUpdated();
  14117. for (int i = 0; i < tests.size(); ++i)
  14118. {
  14119. try
  14120. {
  14121. tests.getUnchecked(i)->performTest (this);
  14122. }
  14123. catch (...)
  14124. {
  14125. addFail ("An unhandled exception was thrown!");
  14126. }
  14127. }
  14128. endTest();
  14129. }
  14130. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14131. {
  14132. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14133. }
  14134. void UnitTestRunner::logMessage (const String& message)
  14135. {
  14136. Logger::writeToLog (message);
  14137. }
  14138. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14139. {
  14140. endTest();
  14141. currentTest = test;
  14142. TestResult* const r = new TestResult();
  14143. r->unitTestName = test->getName();
  14144. r->subcategoryName = subCategory;
  14145. r->passes = 0;
  14146. r->failures = 0;
  14147. results.add (r);
  14148. logMessage ("-----------------------------------------------------------------");
  14149. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14150. resultsUpdated();
  14151. }
  14152. void UnitTestRunner::endTest()
  14153. {
  14154. if (results.size() > 0)
  14155. {
  14156. TestResult* const r = results.getLast();
  14157. if (r->failures > 0)
  14158. {
  14159. String m ("FAILED!!");
  14160. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14161. << " failed, out of a total of " << (r->passes + r->failures);
  14162. logMessage (String::empty);
  14163. logMessage (m);
  14164. logMessage (String::empty);
  14165. }
  14166. else
  14167. {
  14168. logMessage ("All tests completed successfully");
  14169. }
  14170. }
  14171. }
  14172. void UnitTestRunner::addPass()
  14173. {
  14174. {
  14175. const ScopedLock sl (results.getLock());
  14176. TestResult* const r = results.getLast();
  14177. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14178. r->passes++;
  14179. String message ("Test ");
  14180. message << (r->failures + r->passes) << " passed";
  14181. logMessage (message);
  14182. }
  14183. resultsUpdated();
  14184. }
  14185. void UnitTestRunner::addFail (const String& failureMessage)
  14186. {
  14187. {
  14188. const ScopedLock sl (results.getLock());
  14189. TestResult* const r = results.getLast();
  14190. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14191. r->failures++;
  14192. String message ("!!! Test ");
  14193. message << (r->failures + r->passes) << " failed";
  14194. if (failureMessage.isNotEmpty())
  14195. message << ": " << failureMessage;
  14196. r->messages.add (message);
  14197. logMessage (message);
  14198. }
  14199. resultsUpdated();
  14200. if (assertOnFailure) { jassertfalse }
  14201. }
  14202. END_JUCE_NAMESPACE
  14203. /*** End of inlined file: juce_UnitTest.cpp ***/
  14204. #endif
  14205. #if JUCE_BUILD_MISC
  14206. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14207. BEGIN_JUCE_NAMESPACE
  14208. class ValueTree::SetPropertyAction : public UndoableAction
  14209. {
  14210. public:
  14211. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14212. const var& newValue_, const var& oldValue_,
  14213. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14214. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14215. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14216. {
  14217. }
  14218. ~SetPropertyAction() {}
  14219. bool perform()
  14220. {
  14221. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14222. if (isDeletingProperty)
  14223. target->removeProperty (name, 0);
  14224. else
  14225. target->setProperty (name, newValue, 0);
  14226. return true;
  14227. }
  14228. bool undo()
  14229. {
  14230. if (isAddingNewProperty)
  14231. target->removeProperty (name, 0);
  14232. else
  14233. target->setProperty (name, oldValue, 0);
  14234. return true;
  14235. }
  14236. int getSizeInUnits()
  14237. {
  14238. return (int) sizeof (*this); //xxx should be more accurate
  14239. }
  14240. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14241. {
  14242. if (! (isAddingNewProperty || isDeletingProperty))
  14243. {
  14244. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14245. if (next != 0 && next->target == target && next->name == name
  14246. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14247. {
  14248. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14249. }
  14250. }
  14251. return 0;
  14252. }
  14253. private:
  14254. const SharedObjectPtr target;
  14255. const Identifier name;
  14256. const var newValue;
  14257. var oldValue;
  14258. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14259. SetPropertyAction (const SetPropertyAction&);
  14260. SetPropertyAction& operator= (const SetPropertyAction&);
  14261. };
  14262. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14263. {
  14264. public:
  14265. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14266. const SharedObjectPtr& newChild_)
  14267. : target (target_),
  14268. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14269. childIndex (childIndex_),
  14270. isDeleting (newChild_ == 0)
  14271. {
  14272. jassert (child != 0);
  14273. }
  14274. ~AddOrRemoveChildAction() {}
  14275. bool perform()
  14276. {
  14277. if (isDeleting)
  14278. target->removeChild (childIndex, 0);
  14279. else
  14280. target->addChild (child, childIndex, 0);
  14281. return true;
  14282. }
  14283. bool undo()
  14284. {
  14285. if (isDeleting)
  14286. {
  14287. target->addChild (child, childIndex, 0);
  14288. }
  14289. else
  14290. {
  14291. // If you hit this, it seems that your object's state is getting confused - probably
  14292. // because you've interleaved some undoable and non-undoable operations?
  14293. jassert (childIndex < target->children.size());
  14294. target->removeChild (childIndex, 0);
  14295. }
  14296. return true;
  14297. }
  14298. int getSizeInUnits()
  14299. {
  14300. return (int) sizeof (*this); //xxx should be more accurate
  14301. }
  14302. private:
  14303. const SharedObjectPtr target, child;
  14304. const int childIndex;
  14305. const bool isDeleting;
  14306. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14307. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14308. };
  14309. class ValueTree::MoveChildAction : public UndoableAction
  14310. {
  14311. public:
  14312. MoveChildAction (const SharedObjectPtr& parent_,
  14313. const int startIndex_, const int endIndex_)
  14314. : parent (parent_),
  14315. startIndex (startIndex_),
  14316. endIndex (endIndex_)
  14317. {
  14318. }
  14319. ~MoveChildAction() {}
  14320. bool perform()
  14321. {
  14322. parent->moveChild (startIndex, endIndex, 0);
  14323. return true;
  14324. }
  14325. bool undo()
  14326. {
  14327. parent->moveChild (endIndex, startIndex, 0);
  14328. return true;
  14329. }
  14330. int getSizeInUnits()
  14331. {
  14332. return (int) sizeof (*this); //xxx should be more accurate
  14333. }
  14334. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14335. {
  14336. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14337. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14338. return new MoveChildAction (parent, startIndex, next->endIndex);
  14339. return 0;
  14340. }
  14341. private:
  14342. const SharedObjectPtr parent;
  14343. const int startIndex, endIndex;
  14344. MoveChildAction (const MoveChildAction&);
  14345. MoveChildAction& operator= (const MoveChildAction&);
  14346. };
  14347. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14348. : type (type_), parent (0)
  14349. {
  14350. }
  14351. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14352. : type (other.type), properties (other.properties), parent (0)
  14353. {
  14354. for (int i = 0; i < other.children.size(); ++i)
  14355. {
  14356. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14357. child->parent = this;
  14358. children.add (child);
  14359. }
  14360. }
  14361. ValueTree::SharedObject::~SharedObject()
  14362. {
  14363. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14364. for (int i = children.size(); --i >= 0;)
  14365. {
  14366. const SharedObjectPtr c (children.getUnchecked(i));
  14367. c->parent = 0;
  14368. children.remove (i);
  14369. c->sendParentChangeMessage();
  14370. }
  14371. }
  14372. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14373. {
  14374. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14375. {
  14376. ValueTree* const v = valueTreesWithListeners[i];
  14377. if (v != 0)
  14378. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14379. }
  14380. }
  14381. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14382. {
  14383. ValueTree tree (this);
  14384. ValueTree::SharedObject* t = this;
  14385. while (t != 0)
  14386. {
  14387. t->sendPropertyChangeMessage (tree, property);
  14388. t = t->parent;
  14389. }
  14390. }
  14391. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14392. {
  14393. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14394. {
  14395. ValueTree* const v = valueTreesWithListeners[i];
  14396. if (v != 0)
  14397. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14398. }
  14399. }
  14400. void ValueTree::SharedObject::sendChildChangeMessage()
  14401. {
  14402. ValueTree tree (this);
  14403. ValueTree::SharedObject* t = this;
  14404. while (t != 0)
  14405. {
  14406. t->sendChildChangeMessage (tree);
  14407. t = t->parent;
  14408. }
  14409. }
  14410. void ValueTree::SharedObject::sendParentChangeMessage()
  14411. {
  14412. ValueTree tree (this);
  14413. int i;
  14414. for (i = children.size(); --i >= 0;)
  14415. {
  14416. SharedObject* const t = children[i];
  14417. if (t != 0)
  14418. t->sendParentChangeMessage();
  14419. }
  14420. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14421. {
  14422. ValueTree* const v = valueTreesWithListeners[i];
  14423. if (v != 0)
  14424. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14425. }
  14426. }
  14427. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14428. {
  14429. return properties [name];
  14430. }
  14431. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14432. {
  14433. return properties.getWithDefault (name, defaultReturnValue);
  14434. }
  14435. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14436. {
  14437. if (undoManager == 0)
  14438. {
  14439. if (properties.set (name, newValue))
  14440. sendPropertyChangeMessage (name);
  14441. }
  14442. else
  14443. {
  14444. var* const existingValue = properties.getItem (name);
  14445. if (existingValue != 0)
  14446. {
  14447. if (*existingValue != newValue)
  14448. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14449. }
  14450. else
  14451. {
  14452. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14453. }
  14454. }
  14455. }
  14456. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14457. {
  14458. return properties.contains (name);
  14459. }
  14460. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14461. {
  14462. if (undoManager == 0)
  14463. {
  14464. if (properties.remove (name))
  14465. sendPropertyChangeMessage (name);
  14466. }
  14467. else
  14468. {
  14469. if (properties.contains (name))
  14470. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14471. }
  14472. }
  14473. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14474. {
  14475. if (undoManager == 0)
  14476. {
  14477. while (properties.size() > 0)
  14478. {
  14479. const Identifier name (properties.getName (properties.size() - 1));
  14480. properties.remove (name);
  14481. sendPropertyChangeMessage (name);
  14482. }
  14483. }
  14484. else
  14485. {
  14486. for (int i = properties.size(); --i >= 0;)
  14487. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14488. }
  14489. }
  14490. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14491. {
  14492. for (int i = 0; i < children.size(); ++i)
  14493. if (children.getUnchecked(i)->type == typeToMatch)
  14494. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14495. return ValueTree::invalid;
  14496. }
  14497. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14498. {
  14499. for (int i = 0; i < children.size(); ++i)
  14500. if (children.getUnchecked(i)->type == typeToMatch)
  14501. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14502. SharedObject* const newObject = new SharedObject (typeToMatch);
  14503. addChild (newObject, -1, undoManager);
  14504. return ValueTree (newObject);
  14505. }
  14506. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14507. {
  14508. for (int i = 0; i < children.size(); ++i)
  14509. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14510. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14511. return ValueTree::invalid;
  14512. }
  14513. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14514. {
  14515. const SharedObject* p = parent;
  14516. while (p != 0)
  14517. {
  14518. if (p == possibleParent)
  14519. return true;
  14520. p = p->parent;
  14521. }
  14522. return false;
  14523. }
  14524. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14525. {
  14526. return children.indexOf (child.object);
  14527. }
  14528. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14529. {
  14530. if (child != 0 && child->parent != this)
  14531. {
  14532. if (child != this && ! isAChildOf (child))
  14533. {
  14534. // You should always make sure that a child is removed from its previous parent before
  14535. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14536. // undomanager should be used when removing it from its current parent..
  14537. jassert (child->parent == 0);
  14538. if (child->parent != 0)
  14539. {
  14540. jassert (child->parent->children.indexOf (child) >= 0);
  14541. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14542. }
  14543. if (undoManager == 0)
  14544. {
  14545. children.insert (index, child);
  14546. child->parent = this;
  14547. sendChildChangeMessage();
  14548. child->sendParentChangeMessage();
  14549. }
  14550. else
  14551. {
  14552. if (index < 0)
  14553. index = children.size();
  14554. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14555. }
  14556. }
  14557. else
  14558. {
  14559. // You're attempting to create a recursive loop! A node
  14560. // can't be a child of one of its own children!
  14561. jassertfalse;
  14562. }
  14563. }
  14564. }
  14565. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14566. {
  14567. const SharedObjectPtr child (children [childIndex]);
  14568. if (child != 0)
  14569. {
  14570. if (undoManager == 0)
  14571. {
  14572. children.remove (childIndex);
  14573. child->parent = 0;
  14574. sendChildChangeMessage();
  14575. child->sendParentChangeMessage();
  14576. }
  14577. else
  14578. {
  14579. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14580. }
  14581. }
  14582. }
  14583. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14584. {
  14585. while (children.size() > 0)
  14586. removeChild (children.size() - 1, undoManager);
  14587. }
  14588. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14589. {
  14590. // The source index must be a valid index!
  14591. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14592. if (currentIndex != newIndex
  14593. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14594. {
  14595. if (undoManager == 0)
  14596. {
  14597. children.move (currentIndex, newIndex);
  14598. sendChildChangeMessage();
  14599. }
  14600. else
  14601. {
  14602. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14603. newIndex = children.size() - 1;
  14604. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14605. }
  14606. }
  14607. }
  14608. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14609. {
  14610. if (type != other.type
  14611. || properties.size() != other.properties.size()
  14612. || children.size() != other.children.size()
  14613. || properties != other.properties)
  14614. return false;
  14615. for (int i = 0; i < children.size(); ++i)
  14616. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14617. return false;
  14618. return true;
  14619. }
  14620. ValueTree::ValueTree() throw()
  14621. : object (0)
  14622. {
  14623. }
  14624. const ValueTree ValueTree::invalid;
  14625. ValueTree::ValueTree (const Identifier& type_)
  14626. : object (new ValueTree::SharedObject (type_))
  14627. {
  14628. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14629. }
  14630. ValueTree::ValueTree (SharedObject* const object_)
  14631. : object (object_)
  14632. {
  14633. }
  14634. ValueTree::ValueTree (const ValueTree& other)
  14635. : object (other.object)
  14636. {
  14637. }
  14638. ValueTree& ValueTree::operator= (const ValueTree& other)
  14639. {
  14640. if (listeners.size() > 0)
  14641. {
  14642. if (object != 0)
  14643. object->valueTreesWithListeners.removeValue (this);
  14644. if (other.object != 0)
  14645. other.object->valueTreesWithListeners.add (this);
  14646. }
  14647. object = other.object;
  14648. return *this;
  14649. }
  14650. ValueTree::~ValueTree()
  14651. {
  14652. if (listeners.size() > 0 && object != 0)
  14653. object->valueTreesWithListeners.removeValue (this);
  14654. }
  14655. bool ValueTree::operator== (const ValueTree& other) const throw()
  14656. {
  14657. return object == other.object;
  14658. }
  14659. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14660. {
  14661. return object != other.object;
  14662. }
  14663. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14664. {
  14665. return object == other.object
  14666. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14667. }
  14668. ValueTree ValueTree::createCopy() const
  14669. {
  14670. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14671. }
  14672. bool ValueTree::hasType (const Identifier& typeName) const
  14673. {
  14674. return object != 0 && object->type == typeName;
  14675. }
  14676. const Identifier ValueTree::getType() const
  14677. {
  14678. return object != 0 ? object->type : Identifier();
  14679. }
  14680. ValueTree ValueTree::getParent() const
  14681. {
  14682. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14683. }
  14684. ValueTree ValueTree::getSibling (const int delta) const
  14685. {
  14686. if (object == 0 || object->parent == 0)
  14687. return invalid;
  14688. const int index = object->parent->indexOf (*this) + delta;
  14689. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14690. }
  14691. const var& ValueTree::operator[] (const Identifier& name) const
  14692. {
  14693. return object == 0 ? var::null : object->getProperty (name);
  14694. }
  14695. const var& ValueTree::getProperty (const Identifier& name) const
  14696. {
  14697. return object == 0 ? var::null : object->getProperty (name);
  14698. }
  14699. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14700. {
  14701. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14702. }
  14703. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14704. {
  14705. jassert (name.toString().isNotEmpty());
  14706. if (object != 0 && name.toString().isNotEmpty())
  14707. object->setProperty (name, newValue, undoManager);
  14708. }
  14709. bool ValueTree::hasProperty (const Identifier& name) const
  14710. {
  14711. return object != 0 && object->hasProperty (name);
  14712. }
  14713. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14714. {
  14715. if (object != 0)
  14716. object->removeProperty (name, undoManager);
  14717. }
  14718. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14719. {
  14720. if (object != 0)
  14721. object->removeAllProperties (undoManager);
  14722. }
  14723. int ValueTree::getNumProperties() const
  14724. {
  14725. return object == 0 ? 0 : object->properties.size();
  14726. }
  14727. const Identifier ValueTree::getPropertyName (const int index) const
  14728. {
  14729. return object == 0 ? Identifier()
  14730. : object->properties.getName (index);
  14731. }
  14732. class ValueTreePropertyValueSource : public Value::ValueSource,
  14733. public ValueTree::Listener
  14734. {
  14735. public:
  14736. ValueTreePropertyValueSource (const ValueTree& tree_,
  14737. const Identifier& property_,
  14738. UndoManager* const undoManager_)
  14739. : tree (tree_),
  14740. property (property_),
  14741. undoManager (undoManager_)
  14742. {
  14743. tree.addListener (this);
  14744. }
  14745. ~ValueTreePropertyValueSource()
  14746. {
  14747. tree.removeListener (this);
  14748. }
  14749. const var getValue() const
  14750. {
  14751. return tree [property];
  14752. }
  14753. void setValue (const var& newValue)
  14754. {
  14755. tree.setProperty (property, newValue, undoManager);
  14756. }
  14757. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14758. {
  14759. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14760. sendChangeMessage (false);
  14761. }
  14762. void valueTreeChildrenChanged (ValueTree&) {}
  14763. void valueTreeParentChanged (ValueTree&) {}
  14764. private:
  14765. ValueTree tree;
  14766. const Identifier property;
  14767. UndoManager* const undoManager;
  14768. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14769. };
  14770. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14771. {
  14772. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14773. }
  14774. int ValueTree::getNumChildren() const
  14775. {
  14776. return object == 0 ? 0 : object->children.size();
  14777. }
  14778. ValueTree ValueTree::getChild (int index) const
  14779. {
  14780. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14781. }
  14782. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14783. {
  14784. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14785. }
  14786. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14787. {
  14788. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14789. }
  14790. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14791. {
  14792. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14793. }
  14794. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14795. {
  14796. return object != 0 && object->isAChildOf (possibleParent.object);
  14797. }
  14798. int ValueTree::indexOf (const ValueTree& child) const
  14799. {
  14800. return object != 0 ? object->indexOf (child) : -1;
  14801. }
  14802. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14803. {
  14804. if (object != 0)
  14805. object->addChild (child.object, index, undoManager);
  14806. }
  14807. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14808. {
  14809. if (object != 0)
  14810. object->removeChild (childIndex, undoManager);
  14811. }
  14812. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14813. {
  14814. if (object != 0)
  14815. object->removeChild (object->children.indexOf (child.object), undoManager);
  14816. }
  14817. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14818. {
  14819. if (object != 0)
  14820. object->removeAllChildren (undoManager);
  14821. }
  14822. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14823. {
  14824. if (object != 0)
  14825. object->moveChild (currentIndex, newIndex, undoManager);
  14826. }
  14827. void ValueTree::addListener (Listener* listener)
  14828. {
  14829. if (listener != 0)
  14830. {
  14831. if (listeners.size() == 0 && object != 0)
  14832. object->valueTreesWithListeners.add (this);
  14833. listeners.add (listener);
  14834. }
  14835. }
  14836. void ValueTree::removeListener (Listener* listener)
  14837. {
  14838. listeners.remove (listener);
  14839. if (listeners.size() == 0 && object != 0)
  14840. object->valueTreesWithListeners.removeValue (this);
  14841. }
  14842. XmlElement* ValueTree::SharedObject::createXml() const
  14843. {
  14844. XmlElement* xml = new XmlElement (type.toString());
  14845. int i;
  14846. for (i = 0; i < properties.size(); ++i)
  14847. {
  14848. Identifier name (properties.getName(i));
  14849. const var& v = properties [name];
  14850. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14851. xml->setAttribute (name.toString(), v.toString());
  14852. }
  14853. for (i = 0; i < children.size(); ++i)
  14854. xml->addChildElement (children.getUnchecked(i)->createXml());
  14855. return xml;
  14856. }
  14857. XmlElement* ValueTree::createXml() const
  14858. {
  14859. return object != 0 ? object->createXml() : 0;
  14860. }
  14861. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14862. {
  14863. ValueTree v (xml.getTagName());
  14864. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14865. for (int i = 0; i < numAtts; ++i)
  14866. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14867. forEachXmlChildElement (xml, e)
  14868. {
  14869. v.addChild (fromXml (*e), -1, 0);
  14870. }
  14871. return v;
  14872. }
  14873. void ValueTree::writeToStream (OutputStream& output)
  14874. {
  14875. output.writeString (getType().toString());
  14876. const int numProps = getNumProperties();
  14877. output.writeCompressedInt (numProps);
  14878. int i;
  14879. for (i = 0; i < numProps; ++i)
  14880. {
  14881. const Identifier name (getPropertyName(i));
  14882. output.writeString (name.toString());
  14883. getProperty(name).writeToStream (output);
  14884. }
  14885. const int numChildren = getNumChildren();
  14886. output.writeCompressedInt (numChildren);
  14887. for (i = 0; i < numChildren; ++i)
  14888. getChild (i).writeToStream (output);
  14889. }
  14890. ValueTree ValueTree::readFromStream (InputStream& input)
  14891. {
  14892. const String type (input.readString());
  14893. if (type.isEmpty())
  14894. return ValueTree::invalid;
  14895. ValueTree v (type);
  14896. const int numProps = input.readCompressedInt();
  14897. if (numProps < 0)
  14898. {
  14899. jassertfalse; // trying to read corrupted data!
  14900. return v;
  14901. }
  14902. int i;
  14903. for (i = 0; i < numProps; ++i)
  14904. {
  14905. const String name (input.readString());
  14906. jassert (name.isNotEmpty());
  14907. const var value (var::readFromStream (input));
  14908. v.setProperty (name, value, 0);
  14909. }
  14910. const int numChildren = input.readCompressedInt();
  14911. for (i = 0; i < numChildren; ++i)
  14912. v.addChild (readFromStream (input), -1, 0);
  14913. return v;
  14914. }
  14915. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14916. {
  14917. MemoryInputStream in (data, numBytes, false);
  14918. return readFromStream (in);
  14919. }
  14920. END_JUCE_NAMESPACE
  14921. /*** End of inlined file: juce_ValueTree.cpp ***/
  14922. /*** Start of inlined file: juce_Value.cpp ***/
  14923. BEGIN_JUCE_NAMESPACE
  14924. Value::ValueSource::ValueSource()
  14925. {
  14926. }
  14927. Value::ValueSource::~ValueSource()
  14928. {
  14929. }
  14930. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14931. {
  14932. if (synchronous)
  14933. {
  14934. for (int i = valuesWithListeners.size(); --i >= 0;)
  14935. {
  14936. Value* const v = valuesWithListeners[i];
  14937. if (v != 0)
  14938. v->callListeners();
  14939. }
  14940. }
  14941. else
  14942. {
  14943. triggerAsyncUpdate();
  14944. }
  14945. }
  14946. void Value::ValueSource::handleAsyncUpdate()
  14947. {
  14948. sendChangeMessage (true);
  14949. }
  14950. class SimpleValueSource : public Value::ValueSource
  14951. {
  14952. public:
  14953. SimpleValueSource()
  14954. {
  14955. }
  14956. SimpleValueSource (const var& initialValue)
  14957. : value (initialValue)
  14958. {
  14959. }
  14960. ~SimpleValueSource()
  14961. {
  14962. }
  14963. const var getValue() const
  14964. {
  14965. return value;
  14966. }
  14967. void setValue (const var& newValue)
  14968. {
  14969. if (newValue != value)
  14970. {
  14971. value = newValue;
  14972. sendChangeMessage (false);
  14973. }
  14974. }
  14975. private:
  14976. var value;
  14977. SimpleValueSource (const SimpleValueSource&);
  14978. SimpleValueSource& operator= (const SimpleValueSource&);
  14979. };
  14980. Value::Value()
  14981. : value (new SimpleValueSource())
  14982. {
  14983. }
  14984. Value::Value (ValueSource* const value_)
  14985. : value (value_)
  14986. {
  14987. jassert (value_ != 0);
  14988. }
  14989. Value::Value (const var& initialValue)
  14990. : value (new SimpleValueSource (initialValue))
  14991. {
  14992. }
  14993. Value::Value (const Value& other)
  14994. : value (other.value)
  14995. {
  14996. }
  14997. Value& Value::operator= (const Value& other)
  14998. {
  14999. value = other.value;
  15000. return *this;
  15001. }
  15002. Value::~Value()
  15003. {
  15004. if (listeners.size() > 0)
  15005. value->valuesWithListeners.removeValue (this);
  15006. }
  15007. const var Value::getValue() const
  15008. {
  15009. return value->getValue();
  15010. }
  15011. Value::operator const var() const
  15012. {
  15013. return getValue();
  15014. }
  15015. void Value::setValue (const var& newValue)
  15016. {
  15017. value->setValue (newValue);
  15018. }
  15019. const String Value::toString() const
  15020. {
  15021. return value->getValue().toString();
  15022. }
  15023. Value& Value::operator= (const var& newValue)
  15024. {
  15025. value->setValue (newValue);
  15026. return *this;
  15027. }
  15028. void Value::referTo (const Value& valueToReferTo)
  15029. {
  15030. if (valueToReferTo.value != value)
  15031. {
  15032. if (listeners.size() > 0)
  15033. {
  15034. value->valuesWithListeners.removeValue (this);
  15035. valueToReferTo.value->valuesWithListeners.add (this);
  15036. }
  15037. value = valueToReferTo.value;
  15038. callListeners();
  15039. }
  15040. }
  15041. bool Value::refersToSameSourceAs (const Value& other) const
  15042. {
  15043. return value == other.value;
  15044. }
  15045. bool Value::operator== (const Value& other) const
  15046. {
  15047. return value == other.value || value->getValue() == other.getValue();
  15048. }
  15049. bool Value::operator!= (const Value& other) const
  15050. {
  15051. return value != other.value && value->getValue() != other.getValue();
  15052. }
  15053. void Value::addListener (Listener* const listener)
  15054. {
  15055. if (listener != 0)
  15056. {
  15057. if (listeners.size() == 0)
  15058. value->valuesWithListeners.add (this);
  15059. listeners.add (listener);
  15060. }
  15061. }
  15062. void Value::removeListener (Listener* const listener)
  15063. {
  15064. listeners.remove (listener);
  15065. if (listeners.size() == 0)
  15066. value->valuesWithListeners.removeValue (this);
  15067. }
  15068. void Value::callListeners()
  15069. {
  15070. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15071. listeners.call (&Value::Listener::valueChanged, v);
  15072. }
  15073. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15074. {
  15075. return stream << value.toString();
  15076. }
  15077. END_JUCE_NAMESPACE
  15078. /*** End of inlined file: juce_Value.cpp ***/
  15079. /*** Start of inlined file: juce_Application.cpp ***/
  15080. BEGIN_JUCE_NAMESPACE
  15081. #if JUCE_MAC
  15082. extern void juce_initialiseMacMainMenu();
  15083. #endif
  15084. JUCEApplication::JUCEApplication()
  15085. : appReturnValue (0),
  15086. stillInitialising (true)
  15087. {
  15088. jassert (isStandaloneApp() && appInstance == 0);
  15089. appInstance = this;
  15090. }
  15091. JUCEApplication::~JUCEApplication()
  15092. {
  15093. if (appLock != 0)
  15094. {
  15095. appLock->exit();
  15096. appLock = 0;
  15097. }
  15098. jassert (appInstance == this);
  15099. appInstance = 0;
  15100. }
  15101. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15102. JUCEApplication* JUCEApplication::appInstance = 0;
  15103. bool JUCEApplication::moreThanOneInstanceAllowed()
  15104. {
  15105. return true;
  15106. }
  15107. void JUCEApplication::anotherInstanceStarted (const String&)
  15108. {
  15109. }
  15110. void JUCEApplication::systemRequestedQuit()
  15111. {
  15112. quit();
  15113. }
  15114. void JUCEApplication::quit()
  15115. {
  15116. MessageManager::getInstance()->stopDispatchLoop();
  15117. }
  15118. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15119. {
  15120. appReturnValue = newReturnValue;
  15121. }
  15122. void JUCEApplication::actionListenerCallback (const String& message)
  15123. {
  15124. if (message.startsWith (getApplicationName() + "/"))
  15125. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15126. }
  15127. void JUCEApplication::unhandledException (const std::exception*,
  15128. const String&,
  15129. const int)
  15130. {
  15131. jassertfalse;
  15132. }
  15133. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15134. const char* const sourceFile,
  15135. const int lineNumber)
  15136. {
  15137. if (appInstance != 0)
  15138. appInstance->unhandledException (e, sourceFile, lineNumber);
  15139. }
  15140. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15141. {
  15142. return 0;
  15143. }
  15144. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15145. {
  15146. commands.add (StandardApplicationCommandIDs::quit);
  15147. }
  15148. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15149. {
  15150. if (commandID == StandardApplicationCommandIDs::quit)
  15151. {
  15152. result.setInfo (TRANS("Quit"),
  15153. TRANS("Quits the application"),
  15154. "Application",
  15155. 0);
  15156. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15157. }
  15158. }
  15159. bool JUCEApplication::perform (const InvocationInfo& info)
  15160. {
  15161. if (info.commandID == StandardApplicationCommandIDs::quit)
  15162. {
  15163. systemRequestedQuit();
  15164. return true;
  15165. }
  15166. return false;
  15167. }
  15168. bool JUCEApplication::initialiseApp (const String& commandLine)
  15169. {
  15170. commandLineParameters = commandLine.trim();
  15171. #if ! JUCE_IOS
  15172. jassert (appLock == 0); // initialiseApp must only be called once!
  15173. if (! moreThanOneInstanceAllowed())
  15174. {
  15175. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15176. if (! appLock->enter(0))
  15177. {
  15178. appLock = 0;
  15179. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15180. DBG ("Another instance is running - quitting...");
  15181. return false;
  15182. }
  15183. }
  15184. #endif
  15185. // let the app do its setting-up..
  15186. initialise (commandLineParameters);
  15187. #if JUCE_MAC
  15188. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15189. #endif
  15190. // register for broadcast new app messages
  15191. MessageManager::getInstance()->registerBroadcastListener (this);
  15192. stillInitialising = false;
  15193. return true;
  15194. }
  15195. int JUCEApplication::shutdownApp()
  15196. {
  15197. jassert (appInstance == this);
  15198. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15199. JUCE_TRY
  15200. {
  15201. // give the app a chance to clean up..
  15202. shutdown();
  15203. }
  15204. JUCE_CATCH_EXCEPTION
  15205. return getApplicationReturnValue();
  15206. }
  15207. int JUCEApplication::main (const String& commandLine)
  15208. {
  15209. ScopedJuceInitialiser_GUI libraryInitialiser;
  15210. jassert (createInstance != 0);
  15211. const ScopedPointer<JUCEApplication> app (createInstance());
  15212. if (! app->initialiseApp (commandLine))
  15213. return 0;
  15214. JUCE_TRY
  15215. {
  15216. // loop until a quit message is received..
  15217. MessageManager::getInstance()->runDispatchLoop();
  15218. }
  15219. JUCE_CATCH_EXCEPTION
  15220. return app->shutdownApp();
  15221. }
  15222. #if JUCE_IOS
  15223. extern int juce_iOSMain (int argc, const char* argv[]);
  15224. #endif
  15225. #if ! JUCE_WINDOWS
  15226. extern const char* juce_Argv0;
  15227. #endif
  15228. int JUCEApplication::main (int argc, const char* argv[])
  15229. {
  15230. JUCE_AUTORELEASEPOOL
  15231. #if ! JUCE_WINDOWS
  15232. jassert (createInstance != 0);
  15233. juce_Argv0 = argv[0];
  15234. #endif
  15235. #if JUCE_IOS
  15236. return juce_iOSMain (argc, argv);
  15237. #else
  15238. String cmd;
  15239. for (int i = 1; i < argc; ++i)
  15240. cmd << argv[i] << ' ';
  15241. return JUCEApplication::main (cmd);
  15242. #endif
  15243. }
  15244. END_JUCE_NAMESPACE
  15245. /*** End of inlined file: juce_Application.cpp ***/
  15246. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15247. BEGIN_JUCE_NAMESPACE
  15248. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15249. : commandID (commandID_),
  15250. flags (0)
  15251. {
  15252. }
  15253. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15254. const String& description_,
  15255. const String& categoryName_,
  15256. const int flags_) throw()
  15257. {
  15258. shortName = shortName_;
  15259. description = description_;
  15260. categoryName = categoryName_;
  15261. flags = flags_;
  15262. }
  15263. void ApplicationCommandInfo::setActive (const bool b) throw()
  15264. {
  15265. if (b)
  15266. flags &= ~isDisabled;
  15267. else
  15268. flags |= isDisabled;
  15269. }
  15270. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15271. {
  15272. if (b)
  15273. flags |= isTicked;
  15274. else
  15275. flags &= ~isTicked;
  15276. }
  15277. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15278. {
  15279. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15280. }
  15281. END_JUCE_NAMESPACE
  15282. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15283. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15284. BEGIN_JUCE_NAMESPACE
  15285. ApplicationCommandManager::ApplicationCommandManager()
  15286. : firstTarget (0)
  15287. {
  15288. keyMappings = new KeyPressMappingSet (this);
  15289. Desktop::getInstance().addFocusChangeListener (this);
  15290. }
  15291. ApplicationCommandManager::~ApplicationCommandManager()
  15292. {
  15293. Desktop::getInstance().removeFocusChangeListener (this);
  15294. keyMappings = 0;
  15295. }
  15296. void ApplicationCommandManager::clearCommands()
  15297. {
  15298. commands.clear();
  15299. keyMappings->clearAllKeyPresses();
  15300. triggerAsyncUpdate();
  15301. }
  15302. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15303. {
  15304. // zero isn't a valid command ID!
  15305. jassert (newCommand.commandID != 0);
  15306. // the name isn't optional!
  15307. jassert (newCommand.shortName.isNotEmpty());
  15308. if (getCommandForID (newCommand.commandID) == 0)
  15309. {
  15310. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15311. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15312. commands.add (newInfo);
  15313. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15314. triggerAsyncUpdate();
  15315. }
  15316. else
  15317. {
  15318. // trying to re-register the same command with different parameters?
  15319. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15320. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15321. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15322. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15323. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15324. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15325. }
  15326. }
  15327. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15328. {
  15329. if (target != 0)
  15330. {
  15331. Array <CommandID> commandIDs;
  15332. target->getAllCommands (commandIDs);
  15333. for (int i = 0; i < commandIDs.size(); ++i)
  15334. {
  15335. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15336. target->getCommandInfo (info.commandID, info);
  15337. registerCommand (info);
  15338. }
  15339. }
  15340. }
  15341. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15342. {
  15343. for (int i = commands.size(); --i >= 0;)
  15344. {
  15345. if (commands.getUnchecked (i)->commandID == commandID)
  15346. {
  15347. commands.remove (i);
  15348. triggerAsyncUpdate();
  15349. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15350. for (int j = keys.size(); --j >= 0;)
  15351. keyMappings->removeKeyPress (keys.getReference (j));
  15352. }
  15353. }
  15354. }
  15355. void ApplicationCommandManager::commandStatusChanged()
  15356. {
  15357. triggerAsyncUpdate();
  15358. }
  15359. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15360. {
  15361. for (int i = commands.size(); --i >= 0;)
  15362. if (commands.getUnchecked(i)->commandID == commandID)
  15363. return commands.getUnchecked(i);
  15364. return 0;
  15365. }
  15366. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15367. {
  15368. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15369. return (ci != 0) ? ci->shortName : String::empty;
  15370. }
  15371. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15372. {
  15373. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15374. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15375. : String::empty;
  15376. }
  15377. const StringArray ApplicationCommandManager::getCommandCategories() const
  15378. {
  15379. StringArray s;
  15380. for (int i = 0; i < commands.size(); ++i)
  15381. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15382. return s;
  15383. }
  15384. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15385. {
  15386. Array <CommandID> results;
  15387. for (int i = 0; i < commands.size(); ++i)
  15388. if (commands.getUnchecked(i)->categoryName == categoryName)
  15389. results.add (commands.getUnchecked(i)->commandID);
  15390. return results;
  15391. }
  15392. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15393. {
  15394. ApplicationCommandTarget::InvocationInfo info (commandID);
  15395. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15396. return invoke (info, asynchronously);
  15397. }
  15398. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15399. {
  15400. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15401. // manager first..
  15402. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15403. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  15404. if (target == 0)
  15405. return false;
  15406. ApplicationCommandInfo commandInfo (0);
  15407. target->getCommandInfo (info_.commandID, commandInfo);
  15408. ApplicationCommandTarget::InvocationInfo info (info_);
  15409. info.commandFlags = commandInfo.flags;
  15410. sendListenerInvokeCallback (info);
  15411. const bool ok = target->invoke (info, asynchronously);
  15412. commandStatusChanged();
  15413. return ok;
  15414. }
  15415. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15416. {
  15417. return firstTarget != 0 ? firstTarget
  15418. : findDefaultComponentTarget();
  15419. }
  15420. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15421. {
  15422. firstTarget = newTarget;
  15423. }
  15424. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15425. ApplicationCommandInfo& upToDateInfo)
  15426. {
  15427. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15428. if (target == 0)
  15429. target = JUCEApplication::getInstance();
  15430. if (target != 0)
  15431. target = target->getTargetForCommand (commandID);
  15432. if (target != 0)
  15433. target->getCommandInfo (commandID, upToDateInfo);
  15434. return target;
  15435. }
  15436. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15437. {
  15438. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15439. if (target == 0 && c != 0)
  15440. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15441. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15442. return target;
  15443. }
  15444. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15445. {
  15446. Component* c = Component::getCurrentlyFocusedComponent();
  15447. if (c == 0)
  15448. {
  15449. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15450. if (activeWindow != 0)
  15451. {
  15452. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15453. if (c == 0)
  15454. c = activeWindow;
  15455. }
  15456. }
  15457. if (c == 0 && Process::isForegroundProcess())
  15458. {
  15459. // getting a bit desperate now - try all desktop comps..
  15460. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15461. {
  15462. ApplicationCommandTarget* const target
  15463. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15464. ->getPeer()->getLastFocusedSubcomponent());
  15465. if (target != 0)
  15466. return target;
  15467. }
  15468. }
  15469. if (c != 0)
  15470. {
  15471. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15472. // if we're focused on a ResizableWindow, chances are that it's the content
  15473. // component that really should get the event. And if not, the event will
  15474. // still be passed up to the top level window anyway, so let's send it to the
  15475. // content comp.
  15476. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15477. c = resizableWindow->getContentComponent();
  15478. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15479. if (target != 0)
  15480. return target;
  15481. }
  15482. return JUCEApplication::getInstance();
  15483. }
  15484. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15485. {
  15486. listeners.add (listener);
  15487. }
  15488. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15489. {
  15490. listeners.remove (listener);
  15491. }
  15492. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15493. {
  15494. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15495. }
  15496. void ApplicationCommandManager::handleAsyncUpdate()
  15497. {
  15498. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15499. }
  15500. void ApplicationCommandManager::globalFocusChanged (Component*)
  15501. {
  15502. commandStatusChanged();
  15503. }
  15504. END_JUCE_NAMESPACE
  15505. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15506. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15507. BEGIN_JUCE_NAMESPACE
  15508. ApplicationCommandTarget::ApplicationCommandTarget()
  15509. {
  15510. }
  15511. ApplicationCommandTarget::~ApplicationCommandTarget()
  15512. {
  15513. messageInvoker = 0;
  15514. }
  15515. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15516. {
  15517. if (isCommandActive (info.commandID))
  15518. {
  15519. if (async)
  15520. {
  15521. if (messageInvoker == 0)
  15522. messageInvoker = new CommandTargetMessageInvoker (this);
  15523. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15524. return true;
  15525. }
  15526. else
  15527. {
  15528. const bool success = perform (info);
  15529. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15530. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15531. // returns the command's info.
  15532. return success;
  15533. }
  15534. }
  15535. return false;
  15536. }
  15537. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15538. {
  15539. Component* c = dynamic_cast <Component*> (this);
  15540. if (c != 0)
  15541. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15542. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15543. return 0;
  15544. }
  15545. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15546. {
  15547. ApplicationCommandTarget* target = this;
  15548. int depth = 0;
  15549. while (target != 0)
  15550. {
  15551. Array <CommandID> commandIDs;
  15552. target->getAllCommands (commandIDs);
  15553. if (commandIDs.contains (commandID))
  15554. return target;
  15555. target = target->getNextCommandTarget();
  15556. ++depth;
  15557. jassert (depth < 100); // could be a recursive command chain??
  15558. jassert (target != this); // definitely a recursive command chain!
  15559. if (depth > 100 || target == this)
  15560. break;
  15561. }
  15562. if (target == 0)
  15563. {
  15564. target = JUCEApplication::getInstance();
  15565. if (target != 0)
  15566. {
  15567. Array <CommandID> commandIDs;
  15568. target->getAllCommands (commandIDs);
  15569. if (commandIDs.contains (commandID))
  15570. return target;
  15571. }
  15572. }
  15573. return 0;
  15574. }
  15575. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15576. {
  15577. ApplicationCommandInfo info (commandID);
  15578. info.flags = ApplicationCommandInfo::isDisabled;
  15579. getCommandInfo (commandID, info);
  15580. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15581. }
  15582. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15583. {
  15584. ApplicationCommandTarget* target = this;
  15585. int depth = 0;
  15586. while (target != 0)
  15587. {
  15588. if (target->tryToInvoke (info, async))
  15589. return true;
  15590. target = target->getNextCommandTarget();
  15591. ++depth;
  15592. jassert (depth < 100); // could be a recursive command chain??
  15593. jassert (target != this); // definitely a recursive command chain!
  15594. if (depth > 100 || target == this)
  15595. break;
  15596. }
  15597. if (target == 0)
  15598. {
  15599. target = JUCEApplication::getInstance();
  15600. if (target != 0)
  15601. return target->tryToInvoke (info, async);
  15602. }
  15603. return false;
  15604. }
  15605. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15606. {
  15607. ApplicationCommandTarget::InvocationInfo info (commandID);
  15608. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15609. return invoke (info, asynchronously);
  15610. }
  15611. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15612. : commandID (commandID_),
  15613. commandFlags (0),
  15614. invocationMethod (direct),
  15615. originatingComponent (0),
  15616. isKeyDown (false),
  15617. millisecsSinceKeyPressed (0)
  15618. {
  15619. }
  15620. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15621. : owner (owner_)
  15622. {
  15623. }
  15624. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15625. {
  15626. }
  15627. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15628. {
  15629. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15630. owner->tryToInvoke (*info, false);
  15631. }
  15632. END_JUCE_NAMESPACE
  15633. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15634. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15635. BEGIN_JUCE_NAMESPACE
  15636. juce_ImplementSingleton (ApplicationProperties)
  15637. ApplicationProperties::ApplicationProperties()
  15638. : msBeforeSaving (3000),
  15639. options (PropertiesFile::storeAsBinary),
  15640. commonSettingsAreReadOnly (0),
  15641. processLock (0)
  15642. {
  15643. }
  15644. ApplicationProperties::~ApplicationProperties()
  15645. {
  15646. closeFiles();
  15647. clearSingletonInstance();
  15648. }
  15649. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15650. const String& fileNameSuffix,
  15651. const String& folderName_,
  15652. const int millisecondsBeforeSaving,
  15653. const int propertiesFileOptions,
  15654. InterProcessLock* processLock_)
  15655. {
  15656. appName = applicationName;
  15657. fileSuffix = fileNameSuffix;
  15658. folderName = folderName_;
  15659. msBeforeSaving = millisecondsBeforeSaving;
  15660. options = propertiesFileOptions;
  15661. processLock = processLock_;
  15662. }
  15663. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15664. const bool testCommonSettings,
  15665. const bool showWarningDialogOnFailure)
  15666. {
  15667. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15668. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15669. if (! (userOk && commonOk))
  15670. {
  15671. if (showWarningDialogOnFailure)
  15672. {
  15673. String filenames;
  15674. if (userProps != 0 && ! userOk)
  15675. filenames << '\n' << userProps->getFile().getFullPathName();
  15676. if (commonProps != 0 && ! commonOk)
  15677. filenames << '\n' << commonProps->getFile().getFullPathName();
  15678. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15679. appName + TRANS(" - Unable to save settings"),
  15680. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15681. + appName + TRANS(" needs to be able to write to the following files:\n")
  15682. + filenames
  15683. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15684. }
  15685. return false;
  15686. }
  15687. return true;
  15688. }
  15689. void ApplicationProperties::openFiles()
  15690. {
  15691. // You need to call setStorageParameters() before trying to get hold of the
  15692. // properties!
  15693. jassert (appName.isNotEmpty());
  15694. if (appName.isNotEmpty())
  15695. {
  15696. if (userProps == 0)
  15697. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15698. false, msBeforeSaving, options, processLock);
  15699. if (commonProps == 0)
  15700. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15701. true, msBeforeSaving, options, processLock);
  15702. userProps->setFallbackPropertySet (commonProps);
  15703. }
  15704. }
  15705. PropertiesFile* ApplicationProperties::getUserSettings()
  15706. {
  15707. if (userProps == 0)
  15708. openFiles();
  15709. return userProps;
  15710. }
  15711. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15712. {
  15713. if (commonProps == 0)
  15714. openFiles();
  15715. if (returnUserPropsIfReadOnly)
  15716. {
  15717. if (commonSettingsAreReadOnly == 0)
  15718. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15719. if (commonSettingsAreReadOnly > 0)
  15720. return userProps;
  15721. }
  15722. return commonProps;
  15723. }
  15724. bool ApplicationProperties::saveIfNeeded()
  15725. {
  15726. return (userProps == 0 || userProps->saveIfNeeded())
  15727. && (commonProps == 0 || commonProps->saveIfNeeded());
  15728. }
  15729. void ApplicationProperties::closeFiles()
  15730. {
  15731. userProps = 0;
  15732. commonProps = 0;
  15733. }
  15734. END_JUCE_NAMESPACE
  15735. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15736. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15737. BEGIN_JUCE_NAMESPACE
  15738. namespace PropertyFileConstants
  15739. {
  15740. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15741. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15742. static const char* const fileTag = "PROPERTIES";
  15743. static const char* const valueTag = "VALUE";
  15744. static const char* const nameAttribute = "name";
  15745. static const char* const valueAttribute = "val";
  15746. }
  15747. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15748. const int options_, InterProcessLock* const processLock_)
  15749. : PropertySet (ignoreCaseOfKeyNames),
  15750. file (f),
  15751. timerInterval (millisecondsBeforeSaving),
  15752. options (options_),
  15753. loadedOk (false),
  15754. needsWriting (false),
  15755. processLock (processLock_)
  15756. {
  15757. // You need to correctly specify just one storage format for the file
  15758. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15759. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15760. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15761. ProcessScopedLock pl (createProcessLock());
  15762. if (pl != 0 && ! pl->isLocked())
  15763. return; // locking failure..
  15764. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15765. if (fileStream != 0)
  15766. {
  15767. int magicNumber = fileStream->readInt();
  15768. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15769. {
  15770. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15771. magicNumber = PropertyFileConstants::magicNumber;
  15772. }
  15773. if (magicNumber == PropertyFileConstants::magicNumber)
  15774. {
  15775. loadedOk = true;
  15776. BufferedInputStream in (fileStream.release(), 2048, true);
  15777. int numValues = in.readInt();
  15778. while (--numValues >= 0 && ! in.isExhausted())
  15779. {
  15780. const String key (in.readString());
  15781. const String value (in.readString());
  15782. jassert (key.isNotEmpty());
  15783. if (key.isNotEmpty())
  15784. getAllProperties().set (key, value);
  15785. }
  15786. }
  15787. else
  15788. {
  15789. // Not a binary props file - let's see if it's XML..
  15790. fileStream = 0;
  15791. XmlDocument parser (f);
  15792. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15793. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15794. {
  15795. doc = parser.getDocumentElement();
  15796. if (doc != 0)
  15797. {
  15798. loadedOk = true;
  15799. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15800. {
  15801. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15802. if (name.isNotEmpty())
  15803. {
  15804. getAllProperties().set (name,
  15805. e->getFirstChildElement() != 0
  15806. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15807. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15808. }
  15809. }
  15810. }
  15811. else
  15812. {
  15813. // must be a pretty broken XML file we're trying to parse here,
  15814. // or a sign that this object needs an InterProcessLock,
  15815. // or just a failure reading the file. This last reason is why
  15816. // we don't jassertfalse here.
  15817. }
  15818. }
  15819. }
  15820. }
  15821. else
  15822. {
  15823. loadedOk = ! f.exists();
  15824. }
  15825. }
  15826. PropertiesFile::~PropertiesFile()
  15827. {
  15828. if (! saveIfNeeded())
  15829. jassertfalse;
  15830. }
  15831. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15832. {
  15833. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15834. }
  15835. bool PropertiesFile::saveIfNeeded()
  15836. {
  15837. const ScopedLock sl (getLock());
  15838. return (! needsWriting) || save();
  15839. }
  15840. bool PropertiesFile::needsToBeSaved() const
  15841. {
  15842. const ScopedLock sl (getLock());
  15843. return needsWriting;
  15844. }
  15845. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15846. {
  15847. const ScopedLock sl (getLock());
  15848. needsWriting = needsToBeSaved_;
  15849. }
  15850. bool PropertiesFile::save()
  15851. {
  15852. const ScopedLock sl (getLock());
  15853. stopTimer();
  15854. if (file == File::nonexistent
  15855. || file.isDirectory()
  15856. || ! file.getParentDirectory().createDirectory())
  15857. return false;
  15858. if ((options & storeAsXML) != 0)
  15859. {
  15860. XmlElement doc (PropertyFileConstants::fileTag);
  15861. for (int i = 0; i < getAllProperties().size(); ++i)
  15862. {
  15863. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15864. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15865. // if the value seems to contain xml, store it as such..
  15866. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  15867. XmlElement* const childElement = xmlContent.getDocumentElement();
  15868. if (childElement != 0)
  15869. e->addChildElement (childElement);
  15870. else
  15871. e->setAttribute (PropertyFileConstants::valueAttribute,
  15872. getAllProperties().getAllValues() [i]);
  15873. }
  15874. ProcessScopedLock pl (createProcessLock());
  15875. if (pl != 0 && ! pl->isLocked())
  15876. return false; // locking failure..
  15877. if (doc.writeToFile (file, String::empty))
  15878. {
  15879. needsWriting = false;
  15880. return true;
  15881. }
  15882. }
  15883. else
  15884. {
  15885. ProcessScopedLock pl (createProcessLock());
  15886. if (pl != 0 && ! pl->isLocked())
  15887. return false; // locking failure..
  15888. TemporaryFile tempFile (file);
  15889. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15890. if (out != 0)
  15891. {
  15892. if ((options & storeAsCompressedBinary) != 0)
  15893. {
  15894. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15895. out->flush();
  15896. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15897. }
  15898. else
  15899. {
  15900. // have you set up the storage option flags correctly?
  15901. jassert ((options & storeAsBinary) != 0);
  15902. out->writeInt (PropertyFileConstants::magicNumber);
  15903. }
  15904. const int numProperties = getAllProperties().size();
  15905. out->writeInt (numProperties);
  15906. for (int i = 0; i < numProperties; ++i)
  15907. {
  15908. out->writeString (getAllProperties().getAllKeys() [i]);
  15909. out->writeString (getAllProperties().getAllValues() [i]);
  15910. }
  15911. out = 0;
  15912. if (tempFile.overwriteTargetFileWithTemporary())
  15913. {
  15914. needsWriting = false;
  15915. return true;
  15916. }
  15917. }
  15918. }
  15919. return false;
  15920. }
  15921. void PropertiesFile::timerCallback()
  15922. {
  15923. saveIfNeeded();
  15924. }
  15925. void PropertiesFile::propertyChanged()
  15926. {
  15927. sendChangeMessage (this);
  15928. needsWriting = true;
  15929. if (timerInterval > 0)
  15930. startTimer (timerInterval);
  15931. else if (timerInterval == 0)
  15932. saveIfNeeded();
  15933. }
  15934. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15935. const String& fileNameSuffix,
  15936. const String& folderName,
  15937. const bool commonToAllUsers)
  15938. {
  15939. // mustn't have illegal characters in this name..
  15940. jassert (applicationName == File::createLegalFileName (applicationName));
  15941. #if JUCE_MAC || JUCE_IOS
  15942. File dir (commonToAllUsers ? "/Library/Preferences"
  15943. : "~/Library/Preferences");
  15944. if (folderName.isNotEmpty())
  15945. dir = dir.getChildFile (folderName);
  15946. #endif
  15947. #ifdef JUCE_LINUX
  15948. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15949. + (folderName.isNotEmpty() ? folderName
  15950. : ("." + applicationName)));
  15951. #endif
  15952. #if JUCE_WINDOWS
  15953. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15954. : File::userApplicationDataDirectory));
  15955. if (dir == File::nonexistent)
  15956. return File::nonexistent;
  15957. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15958. : applicationName);
  15959. #endif
  15960. return dir.getChildFile (applicationName)
  15961. .withFileExtension (fileNameSuffix);
  15962. }
  15963. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15964. const String& fileNameSuffix,
  15965. const String& folderName,
  15966. const bool commonToAllUsers,
  15967. const int millisecondsBeforeSaving,
  15968. const int propertiesFileOptions,
  15969. InterProcessLock* processLock_)
  15970. {
  15971. const File file (getDefaultAppSettingsFile (applicationName,
  15972. fileNameSuffix,
  15973. folderName,
  15974. commonToAllUsers));
  15975. jassert (file != File::nonexistent);
  15976. if (file == File::nonexistent)
  15977. return 0;
  15978. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15979. }
  15980. END_JUCE_NAMESPACE
  15981. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15982. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15983. BEGIN_JUCE_NAMESPACE
  15984. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15985. const String& fileWildcard_,
  15986. const String& openFileDialogTitle_,
  15987. const String& saveFileDialogTitle_)
  15988. : changedSinceSave (false),
  15989. fileExtension (fileExtension_),
  15990. fileWildcard (fileWildcard_),
  15991. openFileDialogTitle (openFileDialogTitle_),
  15992. saveFileDialogTitle (saveFileDialogTitle_)
  15993. {
  15994. }
  15995. FileBasedDocument::~FileBasedDocument()
  15996. {
  15997. }
  15998. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15999. {
  16000. if (changedSinceSave != hasChanged)
  16001. {
  16002. changedSinceSave = hasChanged;
  16003. sendChangeMessage (this);
  16004. }
  16005. }
  16006. void FileBasedDocument::changed()
  16007. {
  16008. changedSinceSave = true;
  16009. sendChangeMessage (this);
  16010. }
  16011. void FileBasedDocument::setFile (const File& newFile)
  16012. {
  16013. if (documentFile != newFile)
  16014. {
  16015. documentFile = newFile;
  16016. changed();
  16017. }
  16018. }
  16019. bool FileBasedDocument::loadFrom (const File& newFile,
  16020. const bool showMessageOnFailure)
  16021. {
  16022. MouseCursor::showWaitCursor();
  16023. const File oldFile (documentFile);
  16024. documentFile = newFile;
  16025. String error;
  16026. if (newFile.existsAsFile())
  16027. {
  16028. error = loadDocument (newFile);
  16029. if (error.isEmpty())
  16030. {
  16031. setChangedFlag (false);
  16032. MouseCursor::hideWaitCursor();
  16033. setLastDocumentOpened (newFile);
  16034. return true;
  16035. }
  16036. }
  16037. else
  16038. {
  16039. error = "The file doesn't exist";
  16040. }
  16041. documentFile = oldFile;
  16042. MouseCursor::hideWaitCursor();
  16043. if (showMessageOnFailure)
  16044. {
  16045. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16046. TRANS("Failed to open file..."),
  16047. TRANS("There was an error while trying to load the file:\n\n")
  16048. + newFile.getFullPathName()
  16049. + "\n\n"
  16050. + error);
  16051. }
  16052. return false;
  16053. }
  16054. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16055. {
  16056. FileChooser fc (openFileDialogTitle,
  16057. getLastDocumentOpened(),
  16058. fileWildcard);
  16059. if (fc.browseForFileToOpen())
  16060. return loadFrom (fc.getResult(), showMessageOnFailure);
  16061. return false;
  16062. }
  16063. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16064. const bool showMessageOnFailure)
  16065. {
  16066. return saveAs (documentFile,
  16067. false,
  16068. askUserForFileIfNotSpecified,
  16069. showMessageOnFailure);
  16070. }
  16071. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16072. const bool warnAboutOverwritingExistingFiles,
  16073. const bool askUserForFileIfNotSpecified,
  16074. const bool showMessageOnFailure)
  16075. {
  16076. if (newFile == File::nonexistent)
  16077. {
  16078. if (askUserForFileIfNotSpecified)
  16079. {
  16080. return saveAsInteractive (true);
  16081. }
  16082. else
  16083. {
  16084. // can't save to an unspecified file
  16085. jassertfalse;
  16086. return failedToWriteToFile;
  16087. }
  16088. }
  16089. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16090. {
  16091. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16092. TRANS("File already exists"),
  16093. TRANS("There's already a file called:\n\n")
  16094. + newFile.getFullPathName()
  16095. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16096. TRANS("overwrite"),
  16097. TRANS("cancel")))
  16098. {
  16099. return userCancelledSave;
  16100. }
  16101. }
  16102. MouseCursor::showWaitCursor();
  16103. const File oldFile (documentFile);
  16104. documentFile = newFile;
  16105. String error (saveDocument (newFile));
  16106. if (error.isEmpty())
  16107. {
  16108. setChangedFlag (false);
  16109. MouseCursor::hideWaitCursor();
  16110. return savedOk;
  16111. }
  16112. documentFile = oldFile;
  16113. MouseCursor::hideWaitCursor();
  16114. if (showMessageOnFailure)
  16115. {
  16116. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16117. TRANS("Error writing to file..."),
  16118. TRANS("An error occurred while trying to save \"")
  16119. + getDocumentTitle()
  16120. + TRANS("\" to the file:\n\n")
  16121. + newFile.getFullPathName()
  16122. + "\n\n"
  16123. + error);
  16124. }
  16125. return failedToWriteToFile;
  16126. }
  16127. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16128. {
  16129. if (! hasChangedSinceSaved())
  16130. return savedOk;
  16131. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16132. TRANS("Closing document..."),
  16133. TRANS("Do you want to save the changes to \"")
  16134. + getDocumentTitle() + "\"?",
  16135. TRANS("save"),
  16136. TRANS("discard changes"),
  16137. TRANS("cancel"));
  16138. if (r == 1)
  16139. {
  16140. // save changes
  16141. return save (true, true);
  16142. }
  16143. else if (r == 2)
  16144. {
  16145. // discard changes
  16146. return savedOk;
  16147. }
  16148. return userCancelledSave;
  16149. }
  16150. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16151. {
  16152. File f;
  16153. if (documentFile.existsAsFile())
  16154. f = documentFile;
  16155. else
  16156. f = getLastDocumentOpened();
  16157. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16158. if (legalFilename.isEmpty())
  16159. legalFilename = "unnamed";
  16160. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16161. f = f.getSiblingFile (legalFilename);
  16162. else
  16163. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16164. f = f.withFileExtension (fileExtension)
  16165. .getNonexistentSibling (true);
  16166. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16167. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16168. {
  16169. File chosen (fc.getResult());
  16170. if (chosen.getFileExtension().isEmpty())
  16171. {
  16172. chosen = chosen.withFileExtension (fileExtension);
  16173. if (chosen.exists())
  16174. {
  16175. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16176. TRANS("File already exists"),
  16177. TRANS("There's already a file called:")
  16178. + "\n\n" + chosen.getFullPathName()
  16179. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16180. TRANS("overwrite"),
  16181. TRANS("cancel")))
  16182. {
  16183. return userCancelledSave;
  16184. }
  16185. }
  16186. }
  16187. setLastDocumentOpened (chosen);
  16188. return saveAs (chosen, false, false, true);
  16189. }
  16190. return userCancelledSave;
  16191. }
  16192. END_JUCE_NAMESPACE
  16193. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16194. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16195. BEGIN_JUCE_NAMESPACE
  16196. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16197. : maxNumberOfItems (10)
  16198. {
  16199. }
  16200. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16201. {
  16202. }
  16203. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16204. {
  16205. maxNumberOfItems = jmax (1, newMaxNumber);
  16206. while (getNumFiles() > maxNumberOfItems)
  16207. files.remove (getNumFiles() - 1);
  16208. }
  16209. int RecentlyOpenedFilesList::getNumFiles() const
  16210. {
  16211. return files.size();
  16212. }
  16213. const File RecentlyOpenedFilesList::getFile (const int index) const
  16214. {
  16215. return File (files [index]);
  16216. }
  16217. void RecentlyOpenedFilesList::clear()
  16218. {
  16219. files.clear();
  16220. }
  16221. void RecentlyOpenedFilesList::addFile (const File& file)
  16222. {
  16223. const String path (file.getFullPathName());
  16224. files.removeString (path, true);
  16225. files.insert (0, path);
  16226. setMaxNumberOfItems (maxNumberOfItems);
  16227. }
  16228. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16229. {
  16230. for (int i = getNumFiles(); --i >= 0;)
  16231. if (! getFile(i).exists())
  16232. files.remove (i);
  16233. }
  16234. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16235. const int baseItemId,
  16236. const bool showFullPaths,
  16237. const bool dontAddNonExistentFiles,
  16238. const File** filesToAvoid)
  16239. {
  16240. int num = 0;
  16241. for (int i = 0; i < getNumFiles(); ++i)
  16242. {
  16243. const File f (getFile(i));
  16244. if ((! dontAddNonExistentFiles) || f.exists())
  16245. {
  16246. bool needsAvoiding = false;
  16247. if (filesToAvoid != 0)
  16248. {
  16249. const File** avoid = filesToAvoid;
  16250. while (*avoid != 0)
  16251. {
  16252. if (f == **avoid)
  16253. {
  16254. needsAvoiding = true;
  16255. break;
  16256. }
  16257. ++avoid;
  16258. }
  16259. }
  16260. if (! needsAvoiding)
  16261. {
  16262. menuToAddTo.addItem (baseItemId + i,
  16263. showFullPaths ? f.getFullPathName()
  16264. : f.getFileName());
  16265. ++num;
  16266. }
  16267. }
  16268. }
  16269. return num;
  16270. }
  16271. const String RecentlyOpenedFilesList::toString() const
  16272. {
  16273. return files.joinIntoString ("\n");
  16274. }
  16275. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16276. {
  16277. clear();
  16278. files.addLines (stringifiedVersion);
  16279. setMaxNumberOfItems (maxNumberOfItems);
  16280. }
  16281. END_JUCE_NAMESPACE
  16282. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16283. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16284. BEGIN_JUCE_NAMESPACE
  16285. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16286. const int minimumTransactions)
  16287. : totalUnitsStored (0),
  16288. nextIndex (0),
  16289. newTransaction (true),
  16290. reentrancyCheck (false)
  16291. {
  16292. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16293. minimumTransactions);
  16294. }
  16295. UndoManager::~UndoManager()
  16296. {
  16297. clearUndoHistory();
  16298. }
  16299. void UndoManager::clearUndoHistory()
  16300. {
  16301. transactions.clear();
  16302. transactionNames.clear();
  16303. totalUnitsStored = 0;
  16304. nextIndex = 0;
  16305. sendChangeMessage (this);
  16306. }
  16307. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16308. {
  16309. return totalUnitsStored;
  16310. }
  16311. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16312. const int minimumTransactions)
  16313. {
  16314. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16315. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16316. }
  16317. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16318. {
  16319. if (command_ != 0)
  16320. {
  16321. ScopedPointer<UndoableAction> command (command_);
  16322. if (actionName.isNotEmpty())
  16323. currentTransactionName = actionName;
  16324. if (reentrancyCheck)
  16325. {
  16326. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16327. // undo() methods, or else these actions won't actually get done.
  16328. return false;
  16329. }
  16330. else if (command->perform())
  16331. {
  16332. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16333. if (commandSet != 0 && ! newTransaction)
  16334. {
  16335. UndoableAction* lastAction = commandSet->getLast();
  16336. if (lastAction != 0)
  16337. {
  16338. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16339. if (coalescedAction != 0)
  16340. {
  16341. command = coalescedAction;
  16342. totalUnitsStored -= lastAction->getSizeInUnits();
  16343. commandSet->removeLast();
  16344. }
  16345. }
  16346. }
  16347. else
  16348. {
  16349. commandSet = new OwnedArray<UndoableAction>();
  16350. transactions.insert (nextIndex, commandSet);
  16351. transactionNames.insert (nextIndex, currentTransactionName);
  16352. ++nextIndex;
  16353. }
  16354. totalUnitsStored += command->getSizeInUnits();
  16355. commandSet->add (command.release());
  16356. newTransaction = false;
  16357. while (nextIndex < transactions.size())
  16358. {
  16359. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16360. for (int i = lastSet->size(); --i >= 0;)
  16361. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16362. transactions.removeLast();
  16363. transactionNames.remove (transactionNames.size() - 1);
  16364. }
  16365. while (nextIndex > 0
  16366. && totalUnitsStored > maxNumUnitsToKeep
  16367. && transactions.size() > minimumTransactionsToKeep)
  16368. {
  16369. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16370. for (int i = firstSet->size(); --i >= 0;)
  16371. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16372. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16373. transactions.remove (0);
  16374. transactionNames.remove (0);
  16375. --nextIndex;
  16376. }
  16377. sendChangeMessage (this);
  16378. return true;
  16379. }
  16380. }
  16381. return false;
  16382. }
  16383. void UndoManager::beginNewTransaction (const String& actionName)
  16384. {
  16385. newTransaction = true;
  16386. currentTransactionName = actionName;
  16387. }
  16388. void UndoManager::setCurrentTransactionName (const String& newName)
  16389. {
  16390. currentTransactionName = newName;
  16391. }
  16392. bool UndoManager::canUndo() const
  16393. {
  16394. return nextIndex > 0;
  16395. }
  16396. bool UndoManager::canRedo() const
  16397. {
  16398. return nextIndex < transactions.size();
  16399. }
  16400. const String UndoManager::getUndoDescription() const
  16401. {
  16402. return transactionNames [nextIndex - 1];
  16403. }
  16404. const String UndoManager::getRedoDescription() const
  16405. {
  16406. return transactionNames [nextIndex];
  16407. }
  16408. bool UndoManager::undo()
  16409. {
  16410. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16411. if (commandSet == 0)
  16412. return false;
  16413. reentrancyCheck = true;
  16414. bool failed = false;
  16415. for (int i = commandSet->size(); --i >= 0;)
  16416. {
  16417. if (! commandSet->getUnchecked(i)->undo())
  16418. {
  16419. jassertfalse;
  16420. failed = true;
  16421. break;
  16422. }
  16423. }
  16424. reentrancyCheck = false;
  16425. if (failed)
  16426. clearUndoHistory();
  16427. else
  16428. --nextIndex;
  16429. beginNewTransaction();
  16430. sendChangeMessage (this);
  16431. return true;
  16432. }
  16433. bool UndoManager::redo()
  16434. {
  16435. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16436. if (commandSet == 0)
  16437. return false;
  16438. reentrancyCheck = true;
  16439. bool failed = false;
  16440. for (int i = 0; i < commandSet->size(); ++i)
  16441. {
  16442. if (! commandSet->getUnchecked(i)->perform())
  16443. {
  16444. jassertfalse;
  16445. failed = true;
  16446. break;
  16447. }
  16448. }
  16449. reentrancyCheck = false;
  16450. if (failed)
  16451. clearUndoHistory();
  16452. else
  16453. ++nextIndex;
  16454. beginNewTransaction();
  16455. sendChangeMessage (this);
  16456. return true;
  16457. }
  16458. bool UndoManager::undoCurrentTransactionOnly()
  16459. {
  16460. return newTransaction ? false : undo();
  16461. }
  16462. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16463. {
  16464. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16465. if (commandSet != 0 && ! newTransaction)
  16466. {
  16467. for (int i = 0; i < commandSet->size(); ++i)
  16468. actionsFound.add (commandSet->getUnchecked(i));
  16469. }
  16470. }
  16471. int UndoManager::getNumActionsInCurrentTransaction() const
  16472. {
  16473. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16474. if (commandSet != 0 && ! newTransaction)
  16475. return commandSet->size();
  16476. return 0;
  16477. }
  16478. END_JUCE_NAMESPACE
  16479. /*** End of inlined file: juce_UndoManager.cpp ***/
  16480. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16481. BEGIN_JUCE_NAMESPACE
  16482. static const char* const aiffFormatName = "AIFF file";
  16483. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16484. class AiffAudioFormatReader : public AudioFormatReader
  16485. {
  16486. public:
  16487. int bytesPerFrame;
  16488. int64 dataChunkStart;
  16489. bool littleEndian;
  16490. AiffAudioFormatReader (InputStream* in)
  16491. : AudioFormatReader (in, TRANS (aiffFormatName))
  16492. {
  16493. if (input->readInt() == chunkName ("FORM"))
  16494. {
  16495. const int len = input->readIntBigEndian();
  16496. const int64 end = input->getPosition() + len;
  16497. const int nextType = input->readInt();
  16498. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16499. {
  16500. bool hasGotVer = false;
  16501. bool hasGotData = false;
  16502. bool hasGotType = false;
  16503. while (input->getPosition() < end)
  16504. {
  16505. const int type = input->readInt();
  16506. const uint32 length = (uint32) input->readIntBigEndian();
  16507. const int64 chunkEnd = input->getPosition() + length;
  16508. if (type == chunkName ("FVER"))
  16509. {
  16510. hasGotVer = true;
  16511. const int ver = input->readIntBigEndian();
  16512. if (ver != 0 && ver != (int)0xa2805140)
  16513. break;
  16514. }
  16515. else if (type == chunkName ("COMM"))
  16516. {
  16517. hasGotType = true;
  16518. numChannels = (unsigned int)input->readShortBigEndian();
  16519. lengthInSamples = input->readIntBigEndian();
  16520. bitsPerSample = input->readShortBigEndian();
  16521. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16522. unsigned char sampleRateBytes[10];
  16523. input->read (sampleRateBytes, 10);
  16524. const int byte0 = sampleRateBytes[0];
  16525. if ((byte0 & 0x80) != 0
  16526. || byte0 <= 0x3F || byte0 > 0x40
  16527. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16528. break;
  16529. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16530. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16531. sampleRate = (int) sampRate;
  16532. if (length <= 18)
  16533. {
  16534. // some types don't have a chunk large enough to include a compression
  16535. // type, so assume it's just big-endian pcm
  16536. littleEndian = false;
  16537. }
  16538. else
  16539. {
  16540. const int compType = input->readInt();
  16541. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16542. {
  16543. littleEndian = false;
  16544. }
  16545. else if (compType == chunkName ("sowt"))
  16546. {
  16547. littleEndian = true;
  16548. }
  16549. else
  16550. {
  16551. sampleRate = 0;
  16552. break;
  16553. }
  16554. }
  16555. }
  16556. else if (type == chunkName ("SSND"))
  16557. {
  16558. hasGotData = true;
  16559. const int offset = input->readIntBigEndian();
  16560. dataChunkStart = input->getPosition() + 4 + offset;
  16561. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16562. }
  16563. else if ((hasGotVer && hasGotData && hasGotType)
  16564. || chunkEnd < input->getPosition()
  16565. || input->isExhausted())
  16566. {
  16567. break;
  16568. }
  16569. input->setPosition (chunkEnd);
  16570. }
  16571. }
  16572. }
  16573. }
  16574. ~AiffAudioFormatReader()
  16575. {
  16576. }
  16577. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16578. int64 startSampleInFile, int numSamples)
  16579. {
  16580. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16581. if (samplesAvailable < numSamples)
  16582. {
  16583. for (int i = numDestChannels; --i >= 0;)
  16584. if (destSamples[i] != 0)
  16585. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16586. numSamples = (int) samplesAvailable;
  16587. }
  16588. if (numSamples <= 0)
  16589. return true;
  16590. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16591. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16592. char tempBuffer [tempBufSize];
  16593. while (numSamples > 0)
  16594. {
  16595. int* left = destSamples[0];
  16596. if (left != 0)
  16597. left += startOffsetInDestBuffer;
  16598. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  16599. if (right != 0)
  16600. right += startOffsetInDestBuffer;
  16601. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16602. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16603. if (bytesRead < numThisTime * bytesPerFrame)
  16604. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16605. if (bitsPerSample == 16)
  16606. {
  16607. if (littleEndian)
  16608. {
  16609. const short* src = reinterpret_cast <const short*> (tempBuffer);
  16610. if (numChannels > 1)
  16611. {
  16612. if (left == 0)
  16613. {
  16614. for (int i = numThisTime; --i >= 0;)
  16615. {
  16616. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16617. ++src;
  16618. }
  16619. }
  16620. else if (right == 0)
  16621. {
  16622. for (int i = numThisTime; --i >= 0;)
  16623. {
  16624. ++src;
  16625. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16626. }
  16627. }
  16628. else
  16629. {
  16630. for (int i = numThisTime; --i >= 0;)
  16631. {
  16632. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16633. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16634. }
  16635. }
  16636. }
  16637. else
  16638. {
  16639. for (int i = numThisTime; --i >= 0;)
  16640. {
  16641. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  16642. }
  16643. }
  16644. }
  16645. else
  16646. {
  16647. const char* src = tempBuffer;
  16648. if (numChannels > 1)
  16649. {
  16650. if (left == 0)
  16651. {
  16652. for (int i = numThisTime; --i >= 0;)
  16653. {
  16654. *right++ = ByteOrder::bigEndianShort (src) << 16;
  16655. src += 4;
  16656. }
  16657. }
  16658. else if (right == 0)
  16659. {
  16660. for (int i = numThisTime; --i >= 0;)
  16661. {
  16662. src += 2;
  16663. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16664. src += 2;
  16665. }
  16666. }
  16667. else
  16668. {
  16669. for (int i = numThisTime; --i >= 0;)
  16670. {
  16671. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16672. src += 2;
  16673. *right++ = ByteOrder::bigEndianShort (src) << 16;
  16674. src += 2;
  16675. }
  16676. }
  16677. }
  16678. else
  16679. {
  16680. for (int i = numThisTime; --i >= 0;)
  16681. {
  16682. *left++ = ByteOrder::bigEndianShort (src) << 16;
  16683. src += 2;
  16684. }
  16685. }
  16686. }
  16687. }
  16688. else if (bitsPerSample == 24)
  16689. {
  16690. const char* src = tempBuffer;
  16691. if (littleEndian)
  16692. {
  16693. if (numChannels > 1)
  16694. {
  16695. if (left == 0)
  16696. {
  16697. for (int i = numThisTime; --i >= 0;)
  16698. {
  16699. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  16700. src += 6;
  16701. }
  16702. }
  16703. else if (right == 0)
  16704. {
  16705. for (int i = numThisTime; --i >= 0;)
  16706. {
  16707. src += 3;
  16708. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16709. src += 3;
  16710. }
  16711. }
  16712. else
  16713. {
  16714. for (int i = numThisTime; --i >= 0;)
  16715. {
  16716. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16717. src += 3;
  16718. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  16719. src += 3;
  16720. }
  16721. }
  16722. }
  16723. else
  16724. {
  16725. for (int i = numThisTime; --i >= 0;)
  16726. {
  16727. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  16728. src += 3;
  16729. }
  16730. }
  16731. }
  16732. else
  16733. {
  16734. if (numChannels > 1)
  16735. {
  16736. if (left == 0)
  16737. {
  16738. for (int i = numThisTime; --i >= 0;)
  16739. {
  16740. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  16741. src += 6;
  16742. }
  16743. }
  16744. else if (right == 0)
  16745. {
  16746. for (int i = numThisTime; --i >= 0;)
  16747. {
  16748. src += 3;
  16749. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16750. src += 3;
  16751. }
  16752. }
  16753. else
  16754. {
  16755. for (int i = numThisTime; --i >= 0;)
  16756. {
  16757. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16758. src += 3;
  16759. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  16760. src += 3;
  16761. }
  16762. }
  16763. }
  16764. else
  16765. {
  16766. for (int i = numThisTime; --i >= 0;)
  16767. {
  16768. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  16769. src += 3;
  16770. }
  16771. }
  16772. }
  16773. }
  16774. else if (bitsPerSample == 32)
  16775. {
  16776. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  16777. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  16778. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  16779. if (littleEndian)
  16780. {
  16781. if (numChannels > 1)
  16782. {
  16783. if (l == 0)
  16784. {
  16785. for (int i = numThisTime; --i >= 0;)
  16786. {
  16787. ++src;
  16788. *r++ = ByteOrder::swapIfBigEndian (*src++);
  16789. }
  16790. }
  16791. else if (r == 0)
  16792. {
  16793. for (int i = numThisTime; --i >= 0;)
  16794. {
  16795. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16796. ++src;
  16797. }
  16798. }
  16799. else
  16800. {
  16801. for (int i = numThisTime; --i >= 0;)
  16802. {
  16803. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16804. *r++ = ByteOrder::swapIfBigEndian (*src++);
  16805. }
  16806. }
  16807. }
  16808. else
  16809. {
  16810. for (int i = numThisTime; --i >= 0;)
  16811. {
  16812. *l++ = ByteOrder::swapIfBigEndian (*src++);
  16813. }
  16814. }
  16815. }
  16816. else
  16817. {
  16818. if (numChannels > 1)
  16819. {
  16820. if (l == 0)
  16821. {
  16822. for (int i = numThisTime; --i >= 0;)
  16823. {
  16824. ++src;
  16825. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  16826. }
  16827. }
  16828. else if (r == 0)
  16829. {
  16830. for (int i = numThisTime; --i >= 0;)
  16831. {
  16832. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16833. ++src;
  16834. }
  16835. }
  16836. else
  16837. {
  16838. for (int i = numThisTime; --i >= 0;)
  16839. {
  16840. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16841. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  16842. }
  16843. }
  16844. }
  16845. else
  16846. {
  16847. for (int i = numThisTime; --i >= 0;)
  16848. {
  16849. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  16850. }
  16851. }
  16852. }
  16853. left = reinterpret_cast <int*> (l);
  16854. right = reinterpret_cast <int*> (r);
  16855. }
  16856. else if (bitsPerSample == 8)
  16857. {
  16858. const char* src = tempBuffer;
  16859. if (numChannels > 1)
  16860. {
  16861. if (left == 0)
  16862. {
  16863. for (int i = numThisTime; --i >= 0;)
  16864. {
  16865. *right++ = ((int) *src++) << 24;
  16866. ++src;
  16867. }
  16868. }
  16869. else if (right == 0)
  16870. {
  16871. for (int i = numThisTime; --i >= 0;)
  16872. {
  16873. ++src;
  16874. *left++ = ((int) *src++) << 24;
  16875. }
  16876. }
  16877. else
  16878. {
  16879. for (int i = numThisTime; --i >= 0;)
  16880. {
  16881. *left++ = ((int) *src++) << 24;
  16882. *right++ = ((int) *src++) << 24;
  16883. }
  16884. }
  16885. }
  16886. else
  16887. {
  16888. for (int i = numThisTime; --i >= 0;)
  16889. {
  16890. *left++ = ((int) *src++) << 24;
  16891. }
  16892. }
  16893. }
  16894. startOffsetInDestBuffer += numThisTime;
  16895. numSamples -= numThisTime;
  16896. }
  16897. if (numSamples > 0)
  16898. {
  16899. for (int i = numDestChannels; --i >= 0;)
  16900. if (destSamples[i] != 0)
  16901. zeromem (destSamples[i] + startOffsetInDestBuffer,
  16902. sizeof (int) * numSamples);
  16903. }
  16904. return true;
  16905. }
  16906. juce_UseDebuggingNewOperator
  16907. private:
  16908. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16909. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16910. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16911. };
  16912. class AiffAudioFormatWriter : public AudioFormatWriter
  16913. {
  16914. MemoryBlock tempBlock;
  16915. uint32 lengthInSamples, bytesWritten;
  16916. int64 headerPosition;
  16917. bool writeFailed;
  16918. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16919. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16920. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16921. void writeHeader()
  16922. {
  16923. const bool couldSeekOk = output->setPosition (headerPosition);
  16924. (void) couldSeekOk;
  16925. // if this fails, you've given it an output stream that can't seek! It needs
  16926. // to be able to seek back to write the header
  16927. jassert (couldSeekOk);
  16928. const int headerLen = 54;
  16929. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16930. audioBytes += (audioBytes & 1);
  16931. output->writeInt (chunkName ("FORM"));
  16932. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16933. output->writeInt (chunkName ("AIFF"));
  16934. output->writeInt (chunkName ("COMM"));
  16935. output->writeIntBigEndian (18);
  16936. output->writeShortBigEndian ((short) numChannels);
  16937. output->writeIntBigEndian (lengthInSamples);
  16938. output->writeShortBigEndian ((short) bitsPerSample);
  16939. uint8 sampleRateBytes[10];
  16940. zeromem (sampleRateBytes, 10);
  16941. if (sampleRate <= 1)
  16942. {
  16943. sampleRateBytes[0] = 0x3f;
  16944. sampleRateBytes[1] = 0xff;
  16945. sampleRateBytes[2] = 0x80;
  16946. }
  16947. else
  16948. {
  16949. int mask = 0x40000000;
  16950. sampleRateBytes[0] = 0x40;
  16951. if (sampleRate >= mask)
  16952. {
  16953. jassertfalse;
  16954. sampleRateBytes[1] = 0x1d;
  16955. }
  16956. else
  16957. {
  16958. int n = (int) sampleRate;
  16959. int i;
  16960. for (i = 0; i <= 32 ; ++i)
  16961. {
  16962. if ((n & mask) != 0)
  16963. break;
  16964. mask >>= 1;
  16965. }
  16966. n = n << (i + 1);
  16967. sampleRateBytes[1] = (uint8) (29 - i);
  16968. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16969. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16970. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16971. sampleRateBytes[5] = (uint8) (n & 0xff);
  16972. }
  16973. }
  16974. output->write (sampleRateBytes, 10);
  16975. output->writeInt (chunkName ("SSND"));
  16976. output->writeIntBigEndian (audioBytes + 8);
  16977. output->writeInt (0);
  16978. output->writeInt (0);
  16979. jassert (output->getPosition() == headerLen);
  16980. }
  16981. public:
  16982. AiffAudioFormatWriter (OutputStream* out,
  16983. const double sampleRate_,
  16984. const unsigned int chans,
  16985. const int bits)
  16986. : AudioFormatWriter (out,
  16987. TRANS (aiffFormatName),
  16988. sampleRate_,
  16989. chans,
  16990. bits),
  16991. lengthInSamples (0),
  16992. bytesWritten (0),
  16993. writeFailed (false)
  16994. {
  16995. headerPosition = out->getPosition();
  16996. writeHeader();
  16997. }
  16998. ~AiffAudioFormatWriter()
  16999. {
  17000. if ((bytesWritten & 1) != 0)
  17001. output->writeByte (0);
  17002. writeHeader();
  17003. }
  17004. bool write (const int** data, int numSamples)
  17005. {
  17006. if (writeFailed)
  17007. return false;
  17008. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17009. tempBlock.ensureSize (bytes, false);
  17010. char* buffer = static_cast <char*> (tempBlock.getData());
  17011. const int* left = data[0];
  17012. const int* right = data[1];
  17013. if (right == 0)
  17014. right = left;
  17015. if (bitsPerSample == 16)
  17016. {
  17017. short* b = reinterpret_cast <short*> (buffer);
  17018. if (numChannels > 1)
  17019. {
  17020. for (int i = numSamples; --i >= 0;)
  17021. {
  17022. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  17023. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  17024. }
  17025. }
  17026. else
  17027. {
  17028. for (int i = numSamples; --i >= 0;)
  17029. {
  17030. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  17031. }
  17032. }
  17033. }
  17034. else if (bitsPerSample == 24)
  17035. {
  17036. char* b = buffer;
  17037. if (numChannels > 1)
  17038. {
  17039. for (int i = numSamples; --i >= 0;)
  17040. {
  17041. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  17042. b += 3;
  17043. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  17044. b += 3;
  17045. }
  17046. }
  17047. else
  17048. {
  17049. for (int i = numSamples; --i >= 0;)
  17050. {
  17051. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  17052. b += 3;
  17053. }
  17054. }
  17055. }
  17056. else if (bitsPerSample == 32)
  17057. {
  17058. uint32* b = reinterpret_cast <uint32*> (buffer);
  17059. if (numChannels > 1)
  17060. {
  17061. for (int i = numSamples; --i >= 0;)
  17062. {
  17063. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  17064. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  17065. }
  17066. }
  17067. else
  17068. {
  17069. for (int i = numSamples; --i >= 0;)
  17070. {
  17071. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  17072. }
  17073. }
  17074. }
  17075. else if (bitsPerSample == 8)
  17076. {
  17077. char* b = buffer;
  17078. if (numChannels > 1)
  17079. {
  17080. for (int i = numSamples; --i >= 0;)
  17081. {
  17082. *b++ = (char) (*left++ >> 24);
  17083. *b++ = (char) (*right++ >> 24);
  17084. }
  17085. }
  17086. else
  17087. {
  17088. for (int i = numSamples; --i >= 0;)
  17089. {
  17090. *b++ = (char) (*left++ >> 24);
  17091. }
  17092. }
  17093. }
  17094. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17095. || ! output->write (buffer, bytes))
  17096. {
  17097. // failed to write to disk, so let's try writing the header.
  17098. // If it's just run out of disk space, then if it does manage
  17099. // to write the header, we'll still have a useable file..
  17100. writeHeader();
  17101. writeFailed = true;
  17102. return false;
  17103. }
  17104. else
  17105. {
  17106. bytesWritten += bytes;
  17107. lengthInSamples += numSamples;
  17108. return true;
  17109. }
  17110. }
  17111. juce_UseDebuggingNewOperator
  17112. };
  17113. AiffAudioFormat::AiffAudioFormat()
  17114. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  17115. {
  17116. }
  17117. AiffAudioFormat::~AiffAudioFormat()
  17118. {
  17119. }
  17120. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  17121. {
  17122. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17123. return Array <int> (rates);
  17124. }
  17125. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  17126. {
  17127. const int depths[] = { 8, 16, 24, 0 };
  17128. return Array <int> (depths);
  17129. }
  17130. bool AiffAudioFormat::canDoStereo()
  17131. {
  17132. return true;
  17133. }
  17134. bool AiffAudioFormat::canDoMono()
  17135. {
  17136. return true;
  17137. }
  17138. #if JUCE_MAC
  17139. bool AiffAudioFormat::canHandleFile (const File& f)
  17140. {
  17141. if (AudioFormat::canHandleFile (f))
  17142. return true;
  17143. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  17144. return type == 'AIFF' || type == 'AIFC'
  17145. || type == 'aiff' || type == 'aifc';
  17146. }
  17147. #endif
  17148. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  17149. const bool deleteStreamIfOpeningFails)
  17150. {
  17151. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  17152. if (w->sampleRate != 0)
  17153. return w.release();
  17154. if (! deleteStreamIfOpeningFails)
  17155. w->input = 0;
  17156. return 0;
  17157. }
  17158. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  17159. double sampleRate,
  17160. unsigned int chans,
  17161. int bitsPerSample,
  17162. const StringPairArray& /*metadataValues*/,
  17163. int /*qualityOptionIndex*/)
  17164. {
  17165. if (getPossibleBitDepths().contains (bitsPerSample))
  17166. {
  17167. return new AiffAudioFormatWriter (out,
  17168. sampleRate,
  17169. chans,
  17170. bitsPerSample);
  17171. }
  17172. return 0;
  17173. }
  17174. END_JUCE_NAMESPACE
  17175. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  17176. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  17177. BEGIN_JUCE_NAMESPACE
  17178. AudioFormatReader::AudioFormatReader (InputStream* const in,
  17179. const String& formatName_)
  17180. : sampleRate (0),
  17181. bitsPerSample (0),
  17182. lengthInSamples (0),
  17183. numChannels (0),
  17184. usesFloatingPointData (false),
  17185. input (in),
  17186. formatName (formatName_)
  17187. {
  17188. }
  17189. AudioFormatReader::~AudioFormatReader()
  17190. {
  17191. delete input;
  17192. }
  17193. bool AudioFormatReader::read (int* const* destSamples,
  17194. int numDestChannels,
  17195. int64 startSampleInSource,
  17196. int numSamplesToRead,
  17197. const bool fillLeftoverChannelsWithCopies)
  17198. {
  17199. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  17200. int startOffsetInDestBuffer = 0;
  17201. if (startSampleInSource < 0)
  17202. {
  17203. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  17204. for (int i = numDestChannels; --i >= 0;)
  17205. if (destSamples[i] != 0)
  17206. zeromem (destSamples[i], sizeof (int) * silence);
  17207. startOffsetInDestBuffer += silence;
  17208. numSamplesToRead -= silence;
  17209. startSampleInSource = 0;
  17210. }
  17211. if (numSamplesToRead <= 0)
  17212. return true;
  17213. if (! readSamples (const_cast<int**> (destSamples),
  17214. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17215. startSampleInSource, numSamplesToRead))
  17216. return false;
  17217. if (numDestChannels > (int) numChannels)
  17218. {
  17219. if (fillLeftoverChannelsWithCopies)
  17220. {
  17221. int* lastFullChannel = destSamples[0];
  17222. for (int i = (int) numChannels; --i > 0;)
  17223. {
  17224. if (destSamples[i] != 0)
  17225. {
  17226. lastFullChannel = destSamples[i];
  17227. break;
  17228. }
  17229. }
  17230. if (lastFullChannel != 0)
  17231. for (int i = numChannels; i < numDestChannels; ++i)
  17232. if (destSamples[i] != 0)
  17233. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17234. }
  17235. else
  17236. {
  17237. for (int i = numChannels; i < numDestChannels; ++i)
  17238. if (destSamples[i] != 0)
  17239. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17240. }
  17241. }
  17242. return true;
  17243. }
  17244. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17245. {
  17246. float mn = buffer[0];
  17247. float mx = mn;
  17248. for (int i = 1; i < num; ++i)
  17249. {
  17250. const float s = buffer[i];
  17251. if (s > mx) mx = s;
  17252. if (s < mn) mn = s;
  17253. }
  17254. maxVal = mx;
  17255. minVal = mn;
  17256. }
  17257. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17258. int64 numSamples,
  17259. float& lowestLeft, float& highestLeft,
  17260. float& lowestRight, float& highestRight)
  17261. {
  17262. if (numSamples <= 0)
  17263. {
  17264. lowestLeft = 0;
  17265. lowestRight = 0;
  17266. highestLeft = 0;
  17267. highestRight = 0;
  17268. return;
  17269. }
  17270. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17271. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17272. int* tempBuffer[3];
  17273. tempBuffer[0] = tempSpace.getData();
  17274. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17275. tempBuffer[2] = 0;
  17276. if (usesFloatingPointData)
  17277. {
  17278. float lmin = 1.0e6f;
  17279. float lmax = -lmin;
  17280. float rmin = lmin;
  17281. float rmax = lmax;
  17282. while (numSamples > 0)
  17283. {
  17284. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17285. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17286. numSamples -= numToDo;
  17287. startSampleInFile += numToDo;
  17288. float bufmin, bufmax;
  17289. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17290. lmin = jmin (lmin, bufmin);
  17291. lmax = jmax (lmax, bufmax);
  17292. if (numChannels > 1)
  17293. {
  17294. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17295. rmin = jmin (rmin, bufmin);
  17296. rmax = jmax (rmax, bufmax);
  17297. }
  17298. }
  17299. if (numChannels <= 1)
  17300. {
  17301. rmax = lmax;
  17302. rmin = lmin;
  17303. }
  17304. lowestLeft = lmin;
  17305. highestLeft = lmax;
  17306. lowestRight = rmin;
  17307. highestRight = rmax;
  17308. }
  17309. else
  17310. {
  17311. int lmax = std::numeric_limits<int>::min();
  17312. int lmin = std::numeric_limits<int>::max();
  17313. int rmax = std::numeric_limits<int>::min();
  17314. int rmin = std::numeric_limits<int>::max();
  17315. while (numSamples > 0)
  17316. {
  17317. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17318. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17319. numSamples -= numToDo;
  17320. startSampleInFile += numToDo;
  17321. for (int j = numChannels; --j >= 0;)
  17322. {
  17323. int bufMax = std::numeric_limits<int>::min();
  17324. int bufMin = std::numeric_limits<int>::max();
  17325. const int* const b = tempBuffer[j];
  17326. for (int i = 0; i < numToDo; ++i)
  17327. {
  17328. const int samp = b[i];
  17329. if (samp < bufMin)
  17330. bufMin = samp;
  17331. if (samp > bufMax)
  17332. bufMax = samp;
  17333. }
  17334. if (j == 0)
  17335. {
  17336. lmax = jmax (lmax, bufMax);
  17337. lmin = jmin (lmin, bufMin);
  17338. }
  17339. else
  17340. {
  17341. rmax = jmax (rmax, bufMax);
  17342. rmin = jmin (rmin, bufMin);
  17343. }
  17344. }
  17345. }
  17346. if (numChannels <= 1)
  17347. {
  17348. rmax = lmax;
  17349. rmin = lmin;
  17350. }
  17351. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17352. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17353. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17354. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17355. }
  17356. }
  17357. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17358. int64 numSamplesToSearch,
  17359. const double magnitudeRangeMinimum,
  17360. const double magnitudeRangeMaximum,
  17361. const int minimumConsecutiveSamples)
  17362. {
  17363. if (numSamplesToSearch == 0)
  17364. return -1;
  17365. const int bufferSize = 4096;
  17366. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17367. int* tempBuffer[3];
  17368. tempBuffer[0] = tempSpace.getData();
  17369. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17370. tempBuffer[2] = 0;
  17371. int consecutive = 0;
  17372. int64 firstMatchPos = -1;
  17373. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17374. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17375. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17376. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17377. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17378. while (numSamplesToSearch != 0)
  17379. {
  17380. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17381. int64 bufferStart = startSample;
  17382. if (numSamplesToSearch < 0)
  17383. bufferStart -= numThisTime;
  17384. if (bufferStart >= (int) lengthInSamples)
  17385. break;
  17386. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17387. int num = numThisTime;
  17388. while (--num >= 0)
  17389. {
  17390. if (numSamplesToSearch < 0)
  17391. --startSample;
  17392. bool matches = false;
  17393. const int index = (int) (startSample - bufferStart);
  17394. if (usesFloatingPointData)
  17395. {
  17396. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17397. if (sample1 >= magnitudeRangeMinimum
  17398. && sample1 <= magnitudeRangeMaximum)
  17399. {
  17400. matches = true;
  17401. }
  17402. else if (numChannels > 1)
  17403. {
  17404. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17405. matches = (sample2 >= magnitudeRangeMinimum
  17406. && sample2 <= magnitudeRangeMaximum);
  17407. }
  17408. }
  17409. else
  17410. {
  17411. const int sample1 = abs (tempBuffer[0] [index]);
  17412. if (sample1 >= intMagnitudeRangeMinimum
  17413. && sample1 <= intMagnitudeRangeMaximum)
  17414. {
  17415. matches = true;
  17416. }
  17417. else if (numChannels > 1)
  17418. {
  17419. const int sample2 = abs (tempBuffer[1][index]);
  17420. matches = (sample2 >= intMagnitudeRangeMinimum
  17421. && sample2 <= intMagnitudeRangeMaximum);
  17422. }
  17423. }
  17424. if (matches)
  17425. {
  17426. if (firstMatchPos < 0)
  17427. firstMatchPos = startSample;
  17428. if (++consecutive >= minimumConsecutiveSamples)
  17429. {
  17430. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17431. return -1;
  17432. return firstMatchPos;
  17433. }
  17434. }
  17435. else
  17436. {
  17437. consecutive = 0;
  17438. firstMatchPos = -1;
  17439. }
  17440. if (numSamplesToSearch > 0)
  17441. ++startSample;
  17442. }
  17443. if (numSamplesToSearch > 0)
  17444. numSamplesToSearch -= numThisTime;
  17445. else
  17446. numSamplesToSearch += numThisTime;
  17447. }
  17448. return -1;
  17449. }
  17450. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17451. const String& formatName_,
  17452. const double rate,
  17453. const unsigned int numChannels_,
  17454. const unsigned int bitsPerSample_)
  17455. : sampleRate (rate),
  17456. numChannels (numChannels_),
  17457. bitsPerSample (bitsPerSample_),
  17458. usesFloatingPointData (false),
  17459. output (out),
  17460. formatName (formatName_)
  17461. {
  17462. }
  17463. AudioFormatWriter::~AudioFormatWriter()
  17464. {
  17465. delete output;
  17466. }
  17467. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17468. int64 startSample,
  17469. int64 numSamplesToRead)
  17470. {
  17471. const int bufferSize = 16384;
  17472. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17473. int* buffers [128];
  17474. zerostruct (buffers);
  17475. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17476. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17477. if (numSamplesToRead < 0)
  17478. numSamplesToRead = reader.lengthInSamples;
  17479. while (numSamplesToRead > 0)
  17480. {
  17481. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17482. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17483. return false;
  17484. if (reader.usesFloatingPointData != isFloatingPoint())
  17485. {
  17486. int** bufferChan = buffers;
  17487. while (*bufferChan != 0)
  17488. {
  17489. int* b = *bufferChan++;
  17490. if (isFloatingPoint())
  17491. {
  17492. // int -> float
  17493. const double factor = 1.0 / std::numeric_limits<int>::max();
  17494. for (int i = 0; i < numToDo; ++i)
  17495. ((float*) b)[i] = (float) (factor * b[i]);
  17496. }
  17497. else
  17498. {
  17499. // float -> int
  17500. for (int i = 0; i < numToDo; ++i)
  17501. {
  17502. const double samp = *(const float*) b;
  17503. if (samp <= -1.0)
  17504. *b++ = std::numeric_limits<int>::min();
  17505. else if (samp >= 1.0)
  17506. *b++ = std::numeric_limits<int>::max();
  17507. else
  17508. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17509. }
  17510. }
  17511. }
  17512. }
  17513. if (! write (const_cast<const int**> (buffers), numToDo))
  17514. return false;
  17515. numSamplesToRead -= numToDo;
  17516. startSample += numToDo;
  17517. }
  17518. return true;
  17519. }
  17520. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  17521. int numSamplesToRead,
  17522. const int samplesPerBlock)
  17523. {
  17524. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17525. int* buffers [128];
  17526. zerostruct (buffers);
  17527. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17528. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17529. while (numSamplesToRead > 0)
  17530. {
  17531. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17532. AudioSourceChannelInfo info;
  17533. info.buffer = &tempBuffer;
  17534. info.startSample = 0;
  17535. info.numSamples = numToDo;
  17536. info.clearActiveBufferRegion();
  17537. source.getNextAudioBlock (info);
  17538. if (! isFloatingPoint())
  17539. {
  17540. int** bufferChan = buffers;
  17541. while (*bufferChan != 0)
  17542. {
  17543. int* b = *bufferChan++;
  17544. // float -> int
  17545. for (int j = numToDo; --j >= 0;)
  17546. {
  17547. const double samp = *(const float*) b;
  17548. if (samp <= -1.0)
  17549. *b++ = std::numeric_limits<int>::min();
  17550. else if (samp >= 1.0)
  17551. *b++ = std::numeric_limits<int>::max();
  17552. else
  17553. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17554. }
  17555. }
  17556. }
  17557. if (! write ((const int**) buffers, numToDo))
  17558. return false;
  17559. numSamplesToRead -= numToDo;
  17560. }
  17561. return true;
  17562. }
  17563. AudioFormat::AudioFormat (const String& name,
  17564. const StringArray& extensions)
  17565. : formatName (name),
  17566. fileExtensions (extensions)
  17567. {
  17568. }
  17569. AudioFormat::~AudioFormat()
  17570. {
  17571. }
  17572. const String& AudioFormat::getFormatName() const
  17573. {
  17574. return formatName;
  17575. }
  17576. const StringArray& AudioFormat::getFileExtensions() const
  17577. {
  17578. return fileExtensions;
  17579. }
  17580. bool AudioFormat::canHandleFile (const File& f)
  17581. {
  17582. for (int i = 0; i < fileExtensions.size(); ++i)
  17583. if (f.hasFileExtension (fileExtensions[i]))
  17584. return true;
  17585. return false;
  17586. }
  17587. bool AudioFormat::isCompressed()
  17588. {
  17589. return false;
  17590. }
  17591. const StringArray AudioFormat::getQualityOptions()
  17592. {
  17593. return StringArray();
  17594. }
  17595. END_JUCE_NAMESPACE
  17596. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17597. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17598. BEGIN_JUCE_NAMESPACE
  17599. AudioFormatManager::AudioFormatManager()
  17600. : defaultFormatIndex (0)
  17601. {
  17602. }
  17603. AudioFormatManager::~AudioFormatManager()
  17604. {
  17605. clearFormats();
  17606. clearSingletonInstance();
  17607. }
  17608. juce_ImplementSingleton (AudioFormatManager);
  17609. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17610. const bool makeThisTheDefaultFormat)
  17611. {
  17612. jassert (newFormat != 0);
  17613. if (newFormat != 0)
  17614. {
  17615. #if JUCE_DEBUG
  17616. for (int i = getNumKnownFormats(); --i >= 0;)
  17617. {
  17618. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17619. {
  17620. jassertfalse; // trying to add the same format twice!
  17621. }
  17622. }
  17623. #endif
  17624. if (makeThisTheDefaultFormat)
  17625. defaultFormatIndex = getNumKnownFormats();
  17626. knownFormats.add (newFormat);
  17627. }
  17628. }
  17629. void AudioFormatManager::registerBasicFormats()
  17630. {
  17631. #if JUCE_MAC
  17632. registerFormat (new AiffAudioFormat(), true);
  17633. registerFormat (new WavAudioFormat(), false);
  17634. #else
  17635. registerFormat (new WavAudioFormat(), true);
  17636. registerFormat (new AiffAudioFormat(), false);
  17637. #endif
  17638. #if JUCE_USE_FLAC
  17639. registerFormat (new FlacAudioFormat(), false);
  17640. #endif
  17641. #if JUCE_USE_OGGVORBIS
  17642. registerFormat (new OggVorbisAudioFormat(), false);
  17643. #endif
  17644. }
  17645. void AudioFormatManager::clearFormats()
  17646. {
  17647. knownFormats.clear();
  17648. defaultFormatIndex = 0;
  17649. }
  17650. int AudioFormatManager::getNumKnownFormats() const
  17651. {
  17652. return knownFormats.size();
  17653. }
  17654. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17655. {
  17656. return knownFormats [index];
  17657. }
  17658. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17659. {
  17660. return getKnownFormat (defaultFormatIndex);
  17661. }
  17662. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17663. {
  17664. String e (fileExtension);
  17665. if (! e.startsWithChar ('.'))
  17666. e = "." + e;
  17667. for (int i = 0; i < getNumKnownFormats(); ++i)
  17668. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17669. return getKnownFormat(i);
  17670. return 0;
  17671. }
  17672. const String AudioFormatManager::getWildcardForAllFormats() const
  17673. {
  17674. StringArray allExtensions;
  17675. int i;
  17676. for (i = 0; i < getNumKnownFormats(); ++i)
  17677. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17678. allExtensions.trim();
  17679. allExtensions.removeEmptyStrings();
  17680. String s;
  17681. for (i = 0; i < allExtensions.size(); ++i)
  17682. {
  17683. s << '*';
  17684. if (! allExtensions[i].startsWithChar ('.'))
  17685. s << '.';
  17686. s << allExtensions[i];
  17687. if (i < allExtensions.size() - 1)
  17688. s << ';';
  17689. }
  17690. return s;
  17691. }
  17692. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17693. {
  17694. // you need to actually register some formats before the manager can
  17695. // use them to open a file!
  17696. jassert (getNumKnownFormats() > 0);
  17697. for (int i = 0; i < getNumKnownFormats(); ++i)
  17698. {
  17699. AudioFormat* const af = getKnownFormat(i);
  17700. if (af->canHandleFile (file))
  17701. {
  17702. InputStream* const in = file.createInputStream();
  17703. if (in != 0)
  17704. {
  17705. AudioFormatReader* const r = af->createReaderFor (in, true);
  17706. if (r != 0)
  17707. return r;
  17708. }
  17709. }
  17710. }
  17711. return 0;
  17712. }
  17713. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17714. {
  17715. // you need to actually register some formats before the manager can
  17716. // use them to open a file!
  17717. jassert (getNumKnownFormats() > 0);
  17718. ScopedPointer <InputStream> in (audioFileStream);
  17719. if (in != 0)
  17720. {
  17721. const int64 originalStreamPos = in->getPosition();
  17722. for (int i = 0; i < getNumKnownFormats(); ++i)
  17723. {
  17724. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17725. if (r != 0)
  17726. {
  17727. in.release();
  17728. return r;
  17729. }
  17730. in->setPosition (originalStreamPos);
  17731. // the stream that is passed-in must be capable of being repositioned so
  17732. // that all the formats can have a go at opening it.
  17733. jassert (in->getPosition() == originalStreamPos);
  17734. }
  17735. }
  17736. return 0;
  17737. }
  17738. END_JUCE_NAMESPACE
  17739. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17740. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17741. BEGIN_JUCE_NAMESPACE
  17742. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17743. const int64 startSample_,
  17744. const int64 length_,
  17745. const bool deleteSourceWhenDeleted_)
  17746. : AudioFormatReader (0, source_->getFormatName()),
  17747. source (source_),
  17748. startSample (startSample_),
  17749. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17750. {
  17751. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17752. sampleRate = source->sampleRate;
  17753. bitsPerSample = source->bitsPerSample;
  17754. lengthInSamples = length;
  17755. numChannels = source->numChannels;
  17756. usesFloatingPointData = source->usesFloatingPointData;
  17757. }
  17758. AudioSubsectionReader::~AudioSubsectionReader()
  17759. {
  17760. if (deleteSourceWhenDeleted)
  17761. delete source;
  17762. }
  17763. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17764. int64 startSampleInFile, int numSamples)
  17765. {
  17766. if (startSampleInFile + numSamples > length)
  17767. {
  17768. for (int i = numDestChannels; --i >= 0;)
  17769. if (destSamples[i] != 0)
  17770. zeromem (destSamples[i], sizeof (int) * numSamples);
  17771. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17772. if (numSamples <= 0)
  17773. return true;
  17774. }
  17775. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17776. startSampleInFile + startSample, numSamples);
  17777. }
  17778. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17779. int64 numSamples,
  17780. float& lowestLeft,
  17781. float& highestLeft,
  17782. float& lowestRight,
  17783. float& highestRight)
  17784. {
  17785. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17786. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17787. source->readMaxLevels (startSampleInFile + startSample,
  17788. numSamples,
  17789. lowestLeft,
  17790. highestLeft,
  17791. lowestRight,
  17792. highestRight);
  17793. }
  17794. END_JUCE_NAMESPACE
  17795. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17796. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17797. BEGIN_JUCE_NAMESPACE
  17798. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17799. AudioFormatManager& formatManagerToUse_,
  17800. AudioThumbnailCache& cacheToUse)
  17801. : formatManagerToUse (formatManagerToUse_),
  17802. cache (cacheToUse),
  17803. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17804. timeBeforeDeletingReader (2000)
  17805. {
  17806. clear();
  17807. }
  17808. AudioThumbnail::~AudioThumbnail()
  17809. {
  17810. cache.removeThumbnail (this);
  17811. const ScopedLock sl (readerLock);
  17812. reader = 0;
  17813. }
  17814. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17815. {
  17816. jassert (data.getData() != 0);
  17817. return static_cast <DataFormat*> (data.getData());
  17818. }
  17819. void AudioThumbnail::setSource (InputSource* const newSource)
  17820. {
  17821. cache.removeThumbnail (this);
  17822. timerCallback(); // stops the timer and deletes the reader
  17823. source = newSource;
  17824. clear();
  17825. if (newSource != 0
  17826. && ! (cache.loadThumb (*this, newSource->hashCode())
  17827. && isFullyLoaded()))
  17828. {
  17829. {
  17830. const ScopedLock sl (readerLock);
  17831. reader = createReader();
  17832. }
  17833. if (reader != 0)
  17834. {
  17835. initialiseFromAudioFile (*reader);
  17836. cache.addThumbnail (this);
  17837. }
  17838. }
  17839. sendChangeMessage (this);
  17840. }
  17841. bool AudioThumbnail::useTimeSlice()
  17842. {
  17843. const ScopedLock sl (readerLock);
  17844. if (isFullyLoaded())
  17845. {
  17846. if (reader != 0)
  17847. startTimer (timeBeforeDeletingReader);
  17848. cache.removeThumbnail (this);
  17849. return false;
  17850. }
  17851. if (reader == 0)
  17852. reader = createReader();
  17853. if (reader != 0)
  17854. {
  17855. readNextBlockFromAudioFile (*reader);
  17856. stopTimer();
  17857. sendChangeMessage (this);
  17858. const bool justFinished = isFullyLoaded();
  17859. if (justFinished)
  17860. cache.storeThumb (*this, source->hashCode());
  17861. return ! justFinished;
  17862. }
  17863. return false;
  17864. }
  17865. AudioFormatReader* AudioThumbnail::createReader() const
  17866. {
  17867. if (source != 0)
  17868. {
  17869. InputStream* const audioFileStream = source->createInputStream();
  17870. if (audioFileStream != 0)
  17871. return formatManagerToUse.createReaderFor (audioFileStream);
  17872. }
  17873. return 0;
  17874. }
  17875. void AudioThumbnail::timerCallback()
  17876. {
  17877. stopTimer();
  17878. const ScopedLock sl (readerLock);
  17879. reader = 0;
  17880. }
  17881. void AudioThumbnail::clear()
  17882. {
  17883. data.setSize (sizeof (DataFormat) + 3);
  17884. DataFormat* const d = getData();
  17885. d->thumbnailMagic[0] = 'j';
  17886. d->thumbnailMagic[1] = 'a';
  17887. d->thumbnailMagic[2] = 't';
  17888. d->thumbnailMagic[3] = 'm';
  17889. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17890. d->totalSamples = 0;
  17891. d->numFinishedSamples = 0;
  17892. d->numThumbnailSamples = 0;
  17893. d->numChannels = 0;
  17894. d->sampleRate = 0;
  17895. numSamplesCached = 0;
  17896. cacheNeedsRefilling = true;
  17897. }
  17898. void AudioThumbnail::loadFrom (InputStream& input)
  17899. {
  17900. const ScopedLock sl (readerLock);
  17901. data.setSize (0);
  17902. input.readIntoMemoryBlock (data);
  17903. DataFormat* const d = getData();
  17904. d->flipEndiannessIfBigEndian();
  17905. if (! (d->thumbnailMagic[0] == 'j'
  17906. && d->thumbnailMagic[1] == 'a'
  17907. && d->thumbnailMagic[2] == 't'
  17908. && d->thumbnailMagic[3] == 'm'))
  17909. {
  17910. clear();
  17911. }
  17912. numSamplesCached = 0;
  17913. cacheNeedsRefilling = true;
  17914. }
  17915. void AudioThumbnail::saveTo (OutputStream& output) const
  17916. {
  17917. const ScopedLock sl (readerLock);
  17918. DataFormat* const d = getData();
  17919. d->flipEndiannessIfBigEndian();
  17920. output.write (d, (int) data.getSize());
  17921. d->flipEndiannessIfBigEndian();
  17922. }
  17923. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17924. {
  17925. DataFormat* d = getData();
  17926. d->totalSamples = fileReader.lengthInSamples;
  17927. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17928. d->numFinishedSamples = 0;
  17929. d->sampleRate = roundToInt (fileReader.sampleRate);
  17930. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17931. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17932. d = getData();
  17933. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17934. return d->totalSamples > 0;
  17935. }
  17936. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17937. {
  17938. DataFormat* const d = getData();
  17939. if (d->numFinishedSamples < d->totalSamples)
  17940. {
  17941. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17942. generateSection (fileReader,
  17943. d->numFinishedSamples,
  17944. numToDo);
  17945. d->numFinishedSamples += numToDo;
  17946. }
  17947. cacheNeedsRefilling = true;
  17948. return d->numFinishedSamples < d->totalSamples;
  17949. }
  17950. int AudioThumbnail::getNumChannels() const throw()
  17951. {
  17952. return getData()->numChannels;
  17953. }
  17954. double AudioThumbnail::getTotalLength() const throw()
  17955. {
  17956. const DataFormat* const d = getData();
  17957. if (d->sampleRate > 0)
  17958. return d->totalSamples / (double) d->sampleRate;
  17959. else
  17960. return 0.0;
  17961. }
  17962. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17963. int64 startSample,
  17964. int numSamples)
  17965. {
  17966. DataFormat* const d = getData();
  17967. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17968. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17969. char* const l = getChannelData (0);
  17970. char* const r = getChannelData (1);
  17971. for (int i = firstDataPos; i < lastDataPos; ++i)
  17972. {
  17973. const int sourceStart = i * d->samplesPerThumbSample;
  17974. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17975. float lowestLeft, highestLeft, lowestRight, highestRight;
  17976. fileReader.readMaxLevels (sourceStart,
  17977. sourceEnd - sourceStart,
  17978. lowestLeft,
  17979. highestLeft,
  17980. lowestRight,
  17981. highestRight);
  17982. int n = i * 2;
  17983. if (r != 0)
  17984. {
  17985. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17986. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17987. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17988. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17989. }
  17990. else
  17991. {
  17992. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17993. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17994. }
  17995. }
  17996. }
  17997. char* AudioThumbnail::getChannelData (int channel) const
  17998. {
  17999. DataFormat* const d = getData();
  18000. if (channel >= 0 && channel < d->numChannels)
  18001. return d->data + (channel * 2 * d->numThumbnailSamples);
  18002. return 0;
  18003. }
  18004. bool AudioThumbnail::isFullyLoaded() const throw()
  18005. {
  18006. const DataFormat* const d = getData();
  18007. return d->numFinishedSamples >= d->totalSamples;
  18008. }
  18009. void AudioThumbnail::refillCache (const int numSamples,
  18010. double startTime,
  18011. const double timePerPixel)
  18012. {
  18013. const DataFormat* const d = getData();
  18014. if (numSamples <= 0
  18015. || timePerPixel <= 0.0
  18016. || d->sampleRate <= 0)
  18017. {
  18018. numSamplesCached = 0;
  18019. cacheNeedsRefilling = true;
  18020. return;
  18021. }
  18022. if (numSamples == numSamplesCached
  18023. && numChannelsCached == d->numChannels
  18024. && startTime == cachedStart
  18025. && timePerPixel == cachedTimePerPixel
  18026. && ! cacheNeedsRefilling)
  18027. {
  18028. return;
  18029. }
  18030. numSamplesCached = numSamples;
  18031. numChannelsCached = d->numChannels;
  18032. cachedStart = startTime;
  18033. cachedTimePerPixel = timePerPixel;
  18034. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  18035. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  18036. const ScopedLock sl (readerLock);
  18037. cacheNeedsRefilling = false;
  18038. if (needExtraDetail && reader == 0)
  18039. reader = createReader();
  18040. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  18041. {
  18042. startTimer (timeBeforeDeletingReader);
  18043. char* cacheData = static_cast <char*> (cachedLevels.getData());
  18044. int sample = roundToInt (startTime * d->sampleRate);
  18045. for (int i = numSamples; --i >= 0;)
  18046. {
  18047. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  18048. if (sample >= 0)
  18049. {
  18050. if (sample >= reader->lengthInSamples)
  18051. break;
  18052. float lmin, lmax, rmin, rmax;
  18053. reader->readMaxLevels (sample,
  18054. jmax (1, nextSample - sample),
  18055. lmin, lmax, rmin, rmax);
  18056. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  18057. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  18058. if (numChannelsCached > 1)
  18059. {
  18060. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  18061. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  18062. }
  18063. cacheData += 2 * numChannelsCached;
  18064. }
  18065. startTime += timePerPixel;
  18066. sample = nextSample;
  18067. }
  18068. }
  18069. else
  18070. {
  18071. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  18072. {
  18073. char* const channelData = getChannelData (channelNum);
  18074. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  18075. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  18076. startTime = cachedStart;
  18077. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  18078. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  18079. for (int i = numSamples; --i >= 0;)
  18080. {
  18081. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  18082. if (sample >= 0 && channelData != 0)
  18083. {
  18084. char mx = -128;
  18085. char mn = 127;
  18086. while (sample <= nextSample)
  18087. {
  18088. if (sample >= numFinished)
  18089. break;
  18090. const int n = sample << 1;
  18091. const char sampMin = channelData [n];
  18092. const char sampMax = channelData [n + 1];
  18093. if (sampMin < mn)
  18094. mn = sampMin;
  18095. if (sampMax > mx)
  18096. mx = sampMax;
  18097. ++sample;
  18098. }
  18099. if (mn <= mx)
  18100. {
  18101. cacheData[0] = mn;
  18102. cacheData[1] = mx;
  18103. }
  18104. else
  18105. {
  18106. cacheData[0] = 1;
  18107. cacheData[1] = 0;
  18108. }
  18109. }
  18110. else
  18111. {
  18112. cacheData[0] = 1;
  18113. cacheData[1] = 0;
  18114. }
  18115. cacheData += numChannelsCached * 2;
  18116. startTime += timePerPixel;
  18117. sample = nextSample;
  18118. }
  18119. }
  18120. }
  18121. }
  18122. void AudioThumbnail::drawChannel (Graphics& g,
  18123. int x, int y, int w, int h,
  18124. double startTime,
  18125. double endTime,
  18126. int channelNum,
  18127. const float verticalZoomFactor)
  18128. {
  18129. refillCache (w, startTime, (endTime - startTime) / w);
  18130. if (numSamplesCached >= w
  18131. && channelNum >= 0
  18132. && channelNum < numChannelsCached)
  18133. {
  18134. const float topY = (float) y;
  18135. const float bottomY = topY + h;
  18136. const float midY = topY + h * 0.5f;
  18137. const float vscale = verticalZoomFactor * h / 256.0f;
  18138. const Rectangle<int> clip (g.getClipBounds());
  18139. const int skipLeft = jlimit (0, w, clip.getX() - x);
  18140. w -= skipLeft;
  18141. x += skipLeft;
  18142. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  18143. + (channelNum << 1)
  18144. + skipLeft * (numChannelsCached << 1);
  18145. while (--w >= 0)
  18146. {
  18147. const char mn = cacheData[0];
  18148. const char mx = cacheData[1];
  18149. cacheData += numChannelsCached << 1;
  18150. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  18151. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  18152. jmin (midY - mn * vscale + 0.3f, bottomY));
  18153. if (++x >= clip.getRight())
  18154. break;
  18155. }
  18156. }
  18157. }
  18158. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  18159. {
  18160. #if JUCE_BIG_ENDIAN
  18161. struct Flipper
  18162. {
  18163. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18164. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18165. };
  18166. Flipper::flip (samplesPerThumbSample);
  18167. Flipper::flip (totalSamples);
  18168. Flipper::flip (numFinishedSamples);
  18169. Flipper::flip (numThumbnailSamples);
  18170. Flipper::flip (numChannels);
  18171. Flipper::flip (sampleRate);
  18172. #endif
  18173. }
  18174. END_JUCE_NAMESPACE
  18175. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18176. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18177. BEGIN_JUCE_NAMESPACE
  18178. struct ThumbnailCacheEntry
  18179. {
  18180. int64 hash;
  18181. uint32 lastUsed;
  18182. MemoryBlock data;
  18183. juce_UseDebuggingNewOperator
  18184. };
  18185. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18186. : TimeSliceThread ("thumb cache"),
  18187. maxNumThumbsToStore (maxNumThumbsToStore_)
  18188. {
  18189. startThread (2);
  18190. }
  18191. AudioThumbnailCache::~AudioThumbnailCache()
  18192. {
  18193. }
  18194. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18195. {
  18196. for (int i = thumbs.size(); --i >= 0;)
  18197. {
  18198. if (thumbs[i]->hash == hashCode)
  18199. {
  18200. MemoryInputStream in (thumbs[i]->data, false);
  18201. thumb.loadFrom (in);
  18202. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18203. return true;
  18204. }
  18205. }
  18206. return false;
  18207. }
  18208. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18209. const int64 hashCode)
  18210. {
  18211. MemoryOutputStream out;
  18212. thumb.saveTo (out);
  18213. ThumbnailCacheEntry* te = 0;
  18214. for (int i = thumbs.size(); --i >= 0;)
  18215. {
  18216. if (thumbs[i]->hash == hashCode)
  18217. {
  18218. te = thumbs[i];
  18219. break;
  18220. }
  18221. }
  18222. if (te == 0)
  18223. {
  18224. te = new ThumbnailCacheEntry();
  18225. te->hash = hashCode;
  18226. if (thumbs.size() < maxNumThumbsToStore)
  18227. {
  18228. thumbs.add (te);
  18229. }
  18230. else
  18231. {
  18232. int oldest = 0;
  18233. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18234. int i;
  18235. for (i = thumbs.size(); --i >= 0;)
  18236. if (thumbs[i]->lastUsed < oldestTime)
  18237. oldest = i;
  18238. thumbs.set (i, te);
  18239. }
  18240. }
  18241. te->lastUsed = Time::getMillisecondCounter();
  18242. te->data.setSize (0);
  18243. te->data.append (out.getData(), out.getDataSize());
  18244. }
  18245. void AudioThumbnailCache::clear()
  18246. {
  18247. thumbs.clear();
  18248. }
  18249. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18250. {
  18251. addTimeSliceClient (thumb);
  18252. }
  18253. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18254. {
  18255. removeTimeSliceClient (thumb);
  18256. }
  18257. END_JUCE_NAMESPACE
  18258. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18259. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18260. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18261. #if ! JUCE_WINDOWS
  18262. #include <QuickTime/Movies.h>
  18263. #include <QuickTime/QTML.h>
  18264. #include <QuickTime/QuickTimeComponents.h>
  18265. #include <QuickTime/MediaHandlers.h>
  18266. #include <QuickTime/ImageCodec.h>
  18267. #else
  18268. #if JUCE_MSVC
  18269. #pragma warning (push)
  18270. #pragma warning (disable : 4100)
  18271. #endif
  18272. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18273. add its header directory to your include path.
  18274. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  18275. flag in juce_Config.h
  18276. */
  18277. #include <Movies.h>
  18278. #include <QTML.h>
  18279. #include <QuickTimeComponents.h>
  18280. #include <MediaHandlers.h>
  18281. #include <ImageCodec.h>
  18282. #if JUCE_MSVC
  18283. #pragma warning (pop)
  18284. #endif
  18285. #endif
  18286. BEGIN_JUCE_NAMESPACE
  18287. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18288. static const char* const quickTimeFormatName = "QuickTime file";
  18289. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  18290. class QTAudioReader : public AudioFormatReader
  18291. {
  18292. public:
  18293. QTAudioReader (InputStream* const input_, const int trackNum_)
  18294. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18295. ok (false),
  18296. movie (0),
  18297. trackNum (trackNum_),
  18298. lastSampleRead (0),
  18299. lastThreadId (0),
  18300. extractor (0),
  18301. dataHandle (0)
  18302. {
  18303. bufferList.calloc (256, 1);
  18304. #if JUCE_WINDOWS
  18305. if (InitializeQTML (0) != noErr)
  18306. return;
  18307. #endif
  18308. if (EnterMovies() != noErr)
  18309. return;
  18310. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18311. if (! opened)
  18312. return;
  18313. {
  18314. const int numTracks = GetMovieTrackCount (movie);
  18315. int trackCount = 0;
  18316. for (int i = 1; i <= numTracks; ++i)
  18317. {
  18318. track = GetMovieIndTrack (movie, i);
  18319. media = GetTrackMedia (track);
  18320. OSType mediaType;
  18321. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18322. if (mediaType == SoundMediaType
  18323. && trackCount++ == trackNum_)
  18324. {
  18325. ok = true;
  18326. break;
  18327. }
  18328. }
  18329. }
  18330. if (! ok)
  18331. return;
  18332. ok = false;
  18333. lengthInSamples = GetMediaDecodeDuration (media);
  18334. usesFloatingPointData = false;
  18335. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18336. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18337. / GetMediaTimeScale (media);
  18338. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18339. unsigned long output_layout_size;
  18340. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18341. kQTPropertyClass_MovieAudioExtraction_Audio,
  18342. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18343. 0, &output_layout_size, 0);
  18344. if (err != noErr)
  18345. return;
  18346. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18347. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18348. err = MovieAudioExtractionGetProperty (extractor,
  18349. kQTPropertyClass_MovieAudioExtraction_Audio,
  18350. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18351. output_layout_size, qt_audio_channel_layout, 0);
  18352. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18353. err = MovieAudioExtractionSetProperty (extractor,
  18354. kQTPropertyClass_MovieAudioExtraction_Audio,
  18355. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18356. output_layout_size,
  18357. qt_audio_channel_layout);
  18358. err = MovieAudioExtractionGetProperty (extractor,
  18359. kQTPropertyClass_MovieAudioExtraction_Audio,
  18360. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18361. sizeof (inputStreamDesc),
  18362. &inputStreamDesc, 0);
  18363. if (err != noErr)
  18364. return;
  18365. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18366. | kAudioFormatFlagIsPacked
  18367. | kAudioFormatFlagsNativeEndian;
  18368. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18369. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18370. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18371. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18372. err = MovieAudioExtractionSetProperty (extractor,
  18373. kQTPropertyClass_MovieAudioExtraction_Audio,
  18374. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18375. sizeof (inputStreamDesc),
  18376. &inputStreamDesc);
  18377. if (err != noErr)
  18378. return;
  18379. Boolean allChannelsDiscrete = false;
  18380. err = MovieAudioExtractionSetProperty (extractor,
  18381. kQTPropertyClass_MovieAudioExtraction_Movie,
  18382. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18383. sizeof (allChannelsDiscrete),
  18384. &allChannelsDiscrete);
  18385. if (err != noErr)
  18386. return;
  18387. bufferList->mNumberBuffers = 1;
  18388. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18389. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  18390. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18391. bufferList->mBuffers[0].mData = dataBuffer;
  18392. sampleRate = inputStreamDesc.mSampleRate;
  18393. bitsPerSample = 16;
  18394. numChannels = inputStreamDesc.mChannelsPerFrame;
  18395. detachThread();
  18396. ok = true;
  18397. }
  18398. ~QTAudioReader()
  18399. {
  18400. if (dataHandle != 0)
  18401. DisposeHandle (dataHandle);
  18402. if (extractor != 0)
  18403. {
  18404. MovieAudioExtractionEnd (extractor);
  18405. extractor = 0;
  18406. }
  18407. checkThreadIsAttached();
  18408. DisposeMovie (movie);
  18409. #if JUCE_MAC
  18410. ExitMoviesOnThread ();
  18411. #endif
  18412. }
  18413. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18414. int64 startSampleInFile, int numSamples)
  18415. {
  18416. checkThreadIsAttached();
  18417. while (numSamples > 0)
  18418. {
  18419. if (! loadFrame ((int) startSampleInFile))
  18420. return false;
  18421. const int numToDo = jmin (numSamples, samplesPerFrame);
  18422. for (int j = numDestChannels; --j >= 0;)
  18423. {
  18424. if (destSamples[j] != 0)
  18425. {
  18426. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18427. for (int i = 0; i < numToDo; ++i)
  18428. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18429. }
  18430. }
  18431. startOffsetInDestBuffer += numToDo;
  18432. startSampleInFile += numToDo;
  18433. numSamples -= numToDo;
  18434. }
  18435. detachThread();
  18436. return true;
  18437. }
  18438. bool loadFrame (const int sampleNum)
  18439. {
  18440. if (lastSampleRead != sampleNum)
  18441. {
  18442. TimeRecord time;
  18443. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18444. time.base = 0;
  18445. time.value.hi = 0;
  18446. time.value.lo = (UInt32) sampleNum;
  18447. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18448. kQTPropertyClass_MovieAudioExtraction_Movie,
  18449. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18450. sizeof (time), &time);
  18451. if (err != noErr)
  18452. return false;
  18453. }
  18454. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  18455. UInt32 outFlags = 0;
  18456. UInt32 actualNumSamples = samplesPerFrame;
  18457. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  18458. bufferList, &outFlags);
  18459. lastSampleRead = sampleNum + samplesPerFrame;
  18460. return err == noErr;
  18461. }
  18462. juce_UseDebuggingNewOperator
  18463. bool ok;
  18464. private:
  18465. Movie movie;
  18466. Media media;
  18467. Track track;
  18468. const int trackNum;
  18469. double trackUnitsPerFrame;
  18470. int samplesPerFrame;
  18471. int lastSampleRead;
  18472. Thread::ThreadID lastThreadId;
  18473. MovieAudioExtractionRef extractor;
  18474. AudioStreamBasicDescription inputStreamDesc;
  18475. HeapBlock <AudioBufferList> bufferList;
  18476. HeapBlock <char> dataBuffer;
  18477. Handle dataHandle;
  18478. void checkThreadIsAttached()
  18479. {
  18480. #if JUCE_MAC
  18481. if (Thread::getCurrentThreadId() != lastThreadId)
  18482. EnterMoviesOnThread (0);
  18483. AttachMovieToCurrentThread (movie);
  18484. #endif
  18485. }
  18486. void detachThread()
  18487. {
  18488. #if JUCE_MAC
  18489. DetachMovieFromCurrentThread (movie);
  18490. #endif
  18491. }
  18492. QTAudioReader (const QTAudioReader&);
  18493. QTAudioReader& operator= (const QTAudioReader&);
  18494. };
  18495. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18496. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18497. {
  18498. }
  18499. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18500. {
  18501. }
  18502. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  18503. {
  18504. return Array<int>();
  18505. }
  18506. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  18507. {
  18508. return Array<int>();
  18509. }
  18510. bool QuickTimeAudioFormat::canDoStereo()
  18511. {
  18512. return true;
  18513. }
  18514. bool QuickTimeAudioFormat::canDoMono()
  18515. {
  18516. return true;
  18517. }
  18518. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18519. const bool deleteStreamIfOpeningFails)
  18520. {
  18521. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18522. if (r->ok)
  18523. return r.release();
  18524. if (! deleteStreamIfOpeningFails)
  18525. r->input = 0;
  18526. return 0;
  18527. }
  18528. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18529. double /*sampleRateToUse*/,
  18530. unsigned int /*numberOfChannels*/,
  18531. int /*bitsPerSample*/,
  18532. const StringPairArray& /*metadataValues*/,
  18533. int /*qualityOptionIndex*/)
  18534. {
  18535. jassertfalse; // not yet implemented!
  18536. return 0;
  18537. }
  18538. END_JUCE_NAMESPACE
  18539. #endif
  18540. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18541. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18542. BEGIN_JUCE_NAMESPACE
  18543. static const char* const wavFormatName = "WAV file";
  18544. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18545. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18546. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18547. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18548. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18549. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18550. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18551. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18552. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18553. const String& originator,
  18554. const String& originatorRef,
  18555. const Time& date,
  18556. const int64 timeReferenceSamples,
  18557. const String& codingHistory)
  18558. {
  18559. StringPairArray m;
  18560. m.set (bwavDescription, description);
  18561. m.set (bwavOriginator, originator);
  18562. m.set (bwavOriginatorRef, originatorRef);
  18563. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18564. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18565. m.set (bwavTimeReference, String (timeReferenceSamples));
  18566. m.set (bwavCodingHistory, codingHistory);
  18567. return m;
  18568. }
  18569. #if JUCE_MSVC
  18570. #pragma pack (push, 1)
  18571. #define PACKED
  18572. #elif JUCE_GCC
  18573. #define PACKED __attribute__((packed))
  18574. #else
  18575. #define PACKED
  18576. #endif
  18577. struct BWAVChunk
  18578. {
  18579. char description [256];
  18580. char originator [32];
  18581. char originatorRef [32];
  18582. char originationDate [10];
  18583. char originationTime [8];
  18584. uint32 timeRefLow;
  18585. uint32 timeRefHigh;
  18586. uint16 version;
  18587. uint8 umid[64];
  18588. uint8 reserved[190];
  18589. char codingHistory[1];
  18590. void copyTo (StringPairArray& values) const
  18591. {
  18592. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18593. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18594. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18595. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18596. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18597. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18598. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18599. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18600. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18601. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18602. }
  18603. static MemoryBlock createFrom (const StringPairArray& values)
  18604. {
  18605. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18606. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18607. data.fillWith (0);
  18608. BWAVChunk* b = (BWAVChunk*) data.getData();
  18609. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18610. // as they get called in the right order..
  18611. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18612. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18613. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18614. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18615. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18616. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18617. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18618. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18619. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18620. if (b->description[0] != 0
  18621. || b->originator[0] != 0
  18622. || b->originationDate[0] != 0
  18623. || b->originationTime[0] != 0
  18624. || b->codingHistory[0] != 0
  18625. || time != 0)
  18626. {
  18627. return data;
  18628. }
  18629. return MemoryBlock();
  18630. }
  18631. } PACKED;
  18632. struct SMPLChunk
  18633. {
  18634. struct SampleLoop
  18635. {
  18636. uint32 identifier;
  18637. uint32 type;
  18638. uint32 start;
  18639. uint32 end;
  18640. uint32 fraction;
  18641. uint32 playCount;
  18642. } PACKED;
  18643. uint32 manufacturer;
  18644. uint32 product;
  18645. uint32 samplePeriod;
  18646. uint32 midiUnityNote;
  18647. uint32 midiPitchFraction;
  18648. uint32 smpteFormat;
  18649. uint32 smpteOffset;
  18650. uint32 numSampleLoops;
  18651. uint32 samplerData;
  18652. SampleLoop loops[1];
  18653. void copyTo (StringPairArray& values, const int totalSize) const
  18654. {
  18655. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18656. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18657. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18658. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18659. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18660. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18661. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18662. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18663. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18664. for (uint32 i = 0; i < numSampleLoops; ++i)
  18665. {
  18666. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18667. break;
  18668. const String prefix ("Loop" + String(i));
  18669. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18670. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18671. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18672. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18673. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18674. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18675. }
  18676. }
  18677. static MemoryBlock createFrom (const StringPairArray& values)
  18678. {
  18679. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18680. if (numLoops <= 0)
  18681. return MemoryBlock();
  18682. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18683. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18684. data.fillWith (0);
  18685. SMPLChunk* s = (SMPLChunk*) data.getData();
  18686. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18687. // as they get called in the right order..
  18688. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18689. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18690. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18691. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18692. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18693. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18694. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18695. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18696. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18697. for (int i = 0; i < numLoops; ++i)
  18698. {
  18699. const String prefix ("Loop" + String(i));
  18700. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18701. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18702. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18703. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18704. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18705. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18706. }
  18707. return data;
  18708. }
  18709. } PACKED;
  18710. struct ExtensibleWavSubFormat
  18711. {
  18712. uint32 data1;
  18713. uint16 data2;
  18714. uint16 data3;
  18715. uint8 data4[8];
  18716. } PACKED;
  18717. #if JUCE_MSVC
  18718. #pragma pack (pop)
  18719. #endif
  18720. #undef PACKED
  18721. class WavAudioFormatReader : public AudioFormatReader
  18722. {
  18723. int bytesPerFrame;
  18724. int64 dataChunkStart, dataLength;
  18725. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18726. WavAudioFormatReader (const WavAudioFormatReader&);
  18727. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18728. public:
  18729. int64 bwavChunkStart, bwavSize;
  18730. WavAudioFormatReader (InputStream* const in)
  18731. : AudioFormatReader (in, TRANS (wavFormatName)),
  18732. dataLength (0),
  18733. bwavChunkStart (0),
  18734. bwavSize (0)
  18735. {
  18736. if (input->readInt() == chunkName ("RIFF"))
  18737. {
  18738. const uint32 len = (uint32) input->readInt();
  18739. const int64 end = input->getPosition() + len;
  18740. bool hasGotType = false;
  18741. bool hasGotData = false;
  18742. if (input->readInt() == chunkName ("WAVE"))
  18743. {
  18744. while (input->getPosition() < end
  18745. && ! input->isExhausted())
  18746. {
  18747. const int chunkType = input->readInt();
  18748. uint32 length = (uint32) input->readInt();
  18749. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18750. if (chunkType == chunkName ("fmt "))
  18751. {
  18752. // read the format chunk
  18753. const unsigned short format = input->readShort();
  18754. const short numChans = input->readShort();
  18755. sampleRate = input->readInt();
  18756. const int bytesPerSec = input->readInt();
  18757. numChannels = numChans;
  18758. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18759. bitsPerSample = 8 * bytesPerFrame / numChans;
  18760. if (format == 3)
  18761. {
  18762. usesFloatingPointData = true;
  18763. }
  18764. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18765. {
  18766. if (length < 40) // too short
  18767. {
  18768. bytesPerFrame = 0;
  18769. }
  18770. else
  18771. {
  18772. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18773. ExtensibleWavSubFormat subFormat;
  18774. subFormat.data1 = input->readInt();
  18775. subFormat.data2 = input->readShort();
  18776. subFormat.data3 = input->readShort();
  18777. input->read (subFormat.data4, sizeof (subFormat.data4));
  18778. const ExtensibleWavSubFormat pcmFormat
  18779. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18780. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18781. {
  18782. const ExtensibleWavSubFormat ambisonicFormat
  18783. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18784. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18785. bytesPerFrame = 0;
  18786. }
  18787. }
  18788. }
  18789. else if (format != 1)
  18790. {
  18791. bytesPerFrame = 0;
  18792. }
  18793. hasGotType = true;
  18794. }
  18795. else if (chunkType == chunkName ("data"))
  18796. {
  18797. // get the data chunk's position
  18798. dataLength = length;
  18799. dataChunkStart = input->getPosition();
  18800. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18801. hasGotData = true;
  18802. }
  18803. else if (chunkType == chunkName ("bext"))
  18804. {
  18805. bwavChunkStart = input->getPosition();
  18806. bwavSize = length;
  18807. // Broadcast-wav extension chunk..
  18808. HeapBlock <BWAVChunk> bwav;
  18809. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18810. input->read (bwav, length);
  18811. bwav->copyTo (metadataValues);
  18812. }
  18813. else if (chunkType == chunkName ("smpl"))
  18814. {
  18815. HeapBlock <SMPLChunk> smpl;
  18816. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18817. input->read (smpl, length);
  18818. smpl->copyTo (metadataValues, length);
  18819. }
  18820. else if (chunkEnd <= input->getPosition())
  18821. {
  18822. break;
  18823. }
  18824. input->setPosition (chunkEnd);
  18825. }
  18826. }
  18827. }
  18828. }
  18829. ~WavAudioFormatReader()
  18830. {
  18831. }
  18832. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18833. int64 startSampleInFile, int numSamples)
  18834. {
  18835. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18836. if (samplesAvailable < numSamples)
  18837. {
  18838. for (int i = numDestChannels; --i >= 0;)
  18839. if (destSamples[i] != 0)
  18840. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18841. numSamples = (int) samplesAvailable;
  18842. }
  18843. if (numSamples <= 0)
  18844. return true;
  18845. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18846. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18847. char tempBuffer [tempBufSize];
  18848. while (numSamples > 0)
  18849. {
  18850. int* left = destSamples[0];
  18851. if (left != 0)
  18852. left += startOffsetInDestBuffer;
  18853. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  18854. if (right != 0)
  18855. right += startOffsetInDestBuffer;
  18856. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18857. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18858. if (bytesRead < numThisTime * bytesPerFrame)
  18859. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18860. if (bitsPerSample == 16)
  18861. {
  18862. const short* src = reinterpret_cast <const short*> (tempBuffer);
  18863. if (numChannels > 1)
  18864. {
  18865. if (left == 0)
  18866. {
  18867. for (int i = numThisTime; --i >= 0;)
  18868. {
  18869. ++src;
  18870. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18871. }
  18872. }
  18873. else if (right == 0)
  18874. {
  18875. for (int i = numThisTime; --i >= 0;)
  18876. {
  18877. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18878. ++src;
  18879. }
  18880. }
  18881. else
  18882. {
  18883. for (int i = numThisTime; --i >= 0;)
  18884. {
  18885. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18886. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18887. }
  18888. }
  18889. }
  18890. else
  18891. {
  18892. for (int i = numThisTime; --i >= 0;)
  18893. {
  18894. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  18895. }
  18896. }
  18897. }
  18898. else if (bitsPerSample == 24)
  18899. {
  18900. const char* src = tempBuffer;
  18901. if (numChannels > 1)
  18902. {
  18903. if (left == 0)
  18904. {
  18905. for (int i = numThisTime; --i >= 0;)
  18906. {
  18907. src += 3;
  18908. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  18909. src += 3;
  18910. }
  18911. }
  18912. else if (right == 0)
  18913. {
  18914. for (int i = numThisTime; --i >= 0;)
  18915. {
  18916. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18917. src += 6;
  18918. }
  18919. }
  18920. else
  18921. {
  18922. for (int i = 0; i < numThisTime; ++i)
  18923. {
  18924. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18925. src += 3;
  18926. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  18927. src += 3;
  18928. }
  18929. }
  18930. }
  18931. else
  18932. {
  18933. for (int i = 0; i < numThisTime; ++i)
  18934. {
  18935. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  18936. src += 3;
  18937. }
  18938. }
  18939. }
  18940. else if (bitsPerSample == 32)
  18941. {
  18942. const unsigned int* src = (const unsigned int*) tempBuffer;
  18943. unsigned int* l = reinterpret_cast<unsigned int*> (left);
  18944. unsigned int* r = reinterpret_cast<unsigned int*> (right);
  18945. if (numChannels > 1)
  18946. {
  18947. if (l == 0)
  18948. {
  18949. for (int i = numThisTime; --i >= 0;)
  18950. {
  18951. ++src;
  18952. *r++ = ByteOrder::swapIfBigEndian (*src++);
  18953. }
  18954. }
  18955. else if (r == 0)
  18956. {
  18957. for (int i = numThisTime; --i >= 0;)
  18958. {
  18959. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18960. ++src;
  18961. }
  18962. }
  18963. else
  18964. {
  18965. for (int i = numThisTime; --i >= 0;)
  18966. {
  18967. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18968. *r++ = ByteOrder::swapIfBigEndian (*src++);
  18969. }
  18970. }
  18971. }
  18972. else
  18973. {
  18974. for (int i = numThisTime; --i >= 0;)
  18975. {
  18976. *l++ = ByteOrder::swapIfBigEndian (*src++);
  18977. }
  18978. }
  18979. left = reinterpret_cast<int*> (l);
  18980. right = reinterpret_cast<int*> (r);
  18981. }
  18982. else if (bitsPerSample == 8)
  18983. {
  18984. const unsigned char* src = reinterpret_cast<const unsigned char*> (tempBuffer);
  18985. if (numChannels > 1)
  18986. {
  18987. if (left == 0)
  18988. {
  18989. for (int i = numThisTime; --i >= 0;)
  18990. {
  18991. ++src;
  18992. *right++ = ((int) *src++ - 128) << 24;
  18993. }
  18994. }
  18995. else if (right == 0)
  18996. {
  18997. for (int i = numThisTime; --i >= 0;)
  18998. {
  18999. *left++ = ((int) *src++ - 128) << 24;
  19000. ++src;
  19001. }
  19002. }
  19003. else
  19004. {
  19005. for (int i = numThisTime; --i >= 0;)
  19006. {
  19007. *left++ = ((int) *src++ - 128) << 24;
  19008. *right++ = ((int) *src++ - 128) << 24;
  19009. }
  19010. }
  19011. }
  19012. else
  19013. {
  19014. for (int i = numThisTime; --i >= 0;)
  19015. {
  19016. *left++ = ((int)*src++ - 128) << 24;
  19017. }
  19018. }
  19019. }
  19020. startOffsetInDestBuffer += numThisTime;
  19021. numSamples -= numThisTime;
  19022. }
  19023. if (numSamples > 0)
  19024. {
  19025. for (int i = numDestChannels; --i >= 0;)
  19026. if (destSamples[i] != 0)
  19027. zeromem (destSamples[i] + startOffsetInDestBuffer,
  19028. sizeof (int) * numSamples);
  19029. }
  19030. return true;
  19031. }
  19032. juce_UseDebuggingNewOperator
  19033. };
  19034. class WavAudioFormatWriter : public AudioFormatWriter
  19035. {
  19036. MemoryBlock tempBlock, bwavChunk, smplChunk;
  19037. uint32 lengthInSamples, bytesWritten;
  19038. int64 headerPosition;
  19039. bool writeFailed;
  19040. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  19041. WavAudioFormatWriter (const WavAudioFormatWriter&);
  19042. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  19043. void writeHeader()
  19044. {
  19045. const bool seekedOk = output->setPosition (headerPosition);
  19046. (void) seekedOk;
  19047. // if this fails, you've given it an output stream that can't seek! It needs
  19048. // to be able to seek back to write the header
  19049. jassert (seekedOk);
  19050. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  19051. output->writeInt (chunkName ("RIFF"));
  19052. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  19053. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  19054. output->writeInt (chunkName ("WAVE"));
  19055. output->writeInt (chunkName ("fmt "));
  19056. output->writeInt (16);
  19057. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  19058. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  19059. output->writeShort ((short) numChannels);
  19060. output->writeInt ((int) sampleRate);
  19061. output->writeInt (bytesPerFrame * (int) sampleRate);
  19062. output->writeShort ((short) bytesPerFrame);
  19063. output->writeShort ((short) bitsPerSample);
  19064. if (bwavChunk.getSize() > 0)
  19065. {
  19066. output->writeInt (chunkName ("bext"));
  19067. output->writeInt ((int) bwavChunk.getSize());
  19068. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  19069. }
  19070. if (smplChunk.getSize() > 0)
  19071. {
  19072. output->writeInt (chunkName ("smpl"));
  19073. output->writeInt ((int) smplChunk.getSize());
  19074. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  19075. }
  19076. output->writeInt (chunkName ("data"));
  19077. output->writeInt (lengthInSamples * bytesPerFrame);
  19078. usesFloatingPointData = (bitsPerSample == 32);
  19079. }
  19080. public:
  19081. WavAudioFormatWriter (OutputStream* const out,
  19082. const double sampleRate_,
  19083. const unsigned int numChannels_,
  19084. const int bits,
  19085. const StringPairArray& metadataValues)
  19086. : AudioFormatWriter (out,
  19087. TRANS (wavFormatName),
  19088. sampleRate_,
  19089. numChannels_,
  19090. bits),
  19091. lengthInSamples (0),
  19092. bytesWritten (0),
  19093. writeFailed (false)
  19094. {
  19095. if (metadataValues.size() > 0)
  19096. {
  19097. bwavChunk = BWAVChunk::createFrom (metadataValues);
  19098. smplChunk = SMPLChunk::createFrom (metadataValues);
  19099. }
  19100. headerPosition = out->getPosition();
  19101. writeHeader();
  19102. }
  19103. ~WavAudioFormatWriter()
  19104. {
  19105. writeHeader();
  19106. }
  19107. bool write (const int** data, int numSamples)
  19108. {
  19109. if (writeFailed)
  19110. return false;
  19111. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  19112. tempBlock.ensureSize (bytes, false);
  19113. char* buffer = static_cast <char*> (tempBlock.getData());
  19114. const int* left = data[0];
  19115. const int* right = data[1];
  19116. if (right == 0)
  19117. right = left;
  19118. if (bitsPerSample == 16)
  19119. {
  19120. short* b = (short*) buffer;
  19121. if (numChannels > 1)
  19122. {
  19123. for (int i = numSamples; --i >= 0;)
  19124. {
  19125. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  19126. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  19127. }
  19128. }
  19129. else
  19130. {
  19131. for (int i = numSamples; --i >= 0;)
  19132. {
  19133. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  19134. }
  19135. }
  19136. }
  19137. else if (bitsPerSample == 24)
  19138. {
  19139. char* b = buffer;
  19140. if (numChannels > 1)
  19141. {
  19142. for (int i = numSamples; --i >= 0;)
  19143. {
  19144. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  19145. b += 3;
  19146. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  19147. b += 3;
  19148. }
  19149. }
  19150. else
  19151. {
  19152. for (int i = numSamples; --i >= 0;)
  19153. {
  19154. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  19155. b += 3;
  19156. }
  19157. }
  19158. }
  19159. else if (bitsPerSample == 32)
  19160. {
  19161. unsigned int* b = (unsigned int*) buffer;
  19162. if (numChannels > 1)
  19163. {
  19164. for (int i = numSamples; --i >= 0;)
  19165. {
  19166. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  19167. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  19168. }
  19169. }
  19170. else
  19171. {
  19172. for (int i = numSamples; --i >= 0;)
  19173. {
  19174. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  19175. }
  19176. }
  19177. }
  19178. else if (bitsPerSample == 8)
  19179. {
  19180. unsigned char* b = (unsigned char*) buffer;
  19181. if (numChannels > 1)
  19182. {
  19183. for (int i = numSamples; --i >= 0;)
  19184. {
  19185. *b++ = (unsigned char) (128 + (*left++ >> 24));
  19186. *b++ = (unsigned char) (128 + (*right++ >> 24));
  19187. }
  19188. }
  19189. else
  19190. {
  19191. for (int i = numSamples; --i >= 0;)
  19192. {
  19193. *b++ = (unsigned char) (128 + (*left++ >> 24));
  19194. }
  19195. }
  19196. }
  19197. if (bytesWritten + bytes >= (uint32) 0xfff00000
  19198. || ! output->write (buffer, bytes))
  19199. {
  19200. // failed to write to disk, so let's try writing the header.
  19201. // If it's just run out of disk space, then if it does manage
  19202. // to write the header, we'll still have a useable file..
  19203. writeHeader();
  19204. writeFailed = true;
  19205. return false;
  19206. }
  19207. else
  19208. {
  19209. bytesWritten += bytes;
  19210. lengthInSamples += numSamples;
  19211. return true;
  19212. }
  19213. }
  19214. juce_UseDebuggingNewOperator
  19215. };
  19216. WavAudioFormat::WavAudioFormat()
  19217. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  19218. {
  19219. }
  19220. WavAudioFormat::~WavAudioFormat()
  19221. {
  19222. }
  19223. const Array <int> WavAudioFormat::getPossibleSampleRates()
  19224. {
  19225. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  19226. return Array <int> (rates);
  19227. }
  19228. const Array <int> WavAudioFormat::getPossibleBitDepths()
  19229. {
  19230. const int depths[] = { 8, 16, 24, 32, 0 };
  19231. return Array <int> (depths);
  19232. }
  19233. bool WavAudioFormat::canDoStereo()
  19234. {
  19235. return true;
  19236. }
  19237. bool WavAudioFormat::canDoMono()
  19238. {
  19239. return true;
  19240. }
  19241. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  19242. const bool deleteStreamIfOpeningFails)
  19243. {
  19244. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  19245. if (r->sampleRate != 0)
  19246. return r.release();
  19247. if (! deleteStreamIfOpeningFails)
  19248. r->input = 0;
  19249. return 0;
  19250. }
  19251. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  19252. double sampleRate,
  19253. unsigned int numChannels,
  19254. int bitsPerSample,
  19255. const StringPairArray& metadataValues,
  19256. int /*qualityOptionIndex*/)
  19257. {
  19258. if (getPossibleBitDepths().contains (bitsPerSample))
  19259. {
  19260. return new WavAudioFormatWriter (out,
  19261. sampleRate,
  19262. numChannels,
  19263. bitsPerSample,
  19264. metadataValues);
  19265. }
  19266. return 0;
  19267. }
  19268. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  19269. {
  19270. TemporaryFile tempFile (file);
  19271. WavAudioFormat wav;
  19272. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  19273. if (reader != 0)
  19274. {
  19275. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  19276. if (outStream != 0)
  19277. {
  19278. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  19279. reader->numChannels, reader->bitsPerSample,
  19280. metadata, 0));
  19281. if (writer != 0)
  19282. {
  19283. outStream.release();
  19284. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  19285. writer = 0;
  19286. reader = 0;
  19287. return ok && tempFile.overwriteTargetFileWithTemporary();
  19288. }
  19289. }
  19290. }
  19291. return false;
  19292. }
  19293. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  19294. {
  19295. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  19296. if (reader != 0)
  19297. {
  19298. const int64 bwavPos = reader->bwavChunkStart;
  19299. const int64 bwavSize = reader->bwavSize;
  19300. reader = 0;
  19301. if (bwavSize > 0)
  19302. {
  19303. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  19304. if (chunk.getSize() <= (size_t) bwavSize)
  19305. {
  19306. // the new one will fit in the space available, so write it directly..
  19307. const int64 oldSize = wavFile.getSize();
  19308. {
  19309. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  19310. out->setPosition (bwavPos);
  19311. out->write (chunk.getData(), (int) chunk.getSize());
  19312. out->setPosition (oldSize);
  19313. }
  19314. jassert (wavFile.getSize() == oldSize);
  19315. return true;
  19316. }
  19317. }
  19318. }
  19319. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  19320. }
  19321. END_JUCE_NAMESPACE
  19322. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  19323. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  19324. #if JUCE_USE_CDREADER
  19325. BEGIN_JUCE_NAMESPACE
  19326. int AudioCDReader::getNumTracks() const
  19327. {
  19328. return trackStartSamples.size() - 1;
  19329. }
  19330. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  19331. {
  19332. return trackStartSamples [trackNum];
  19333. }
  19334. const Array<int>& AudioCDReader::getTrackOffsets() const
  19335. {
  19336. return trackStartSamples;
  19337. }
  19338. int AudioCDReader::getCDDBId()
  19339. {
  19340. int checksum = 0;
  19341. const int numTracks = getNumTracks();
  19342. for (int i = 0; i < numTracks; ++i)
  19343. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  19344. checksum += offset % 10;
  19345. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  19346. // CCLLLLTT: checksum, length, tracks
  19347. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  19348. }
  19349. END_JUCE_NAMESPACE
  19350. #endif
  19351. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  19352. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19353. BEGIN_JUCE_NAMESPACE
  19354. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  19355. const bool deleteReaderWhenThisIsDeleted)
  19356. : reader (reader_),
  19357. deleteReader (deleteReaderWhenThisIsDeleted),
  19358. nextPlayPos (0),
  19359. looping (false)
  19360. {
  19361. jassert (reader != 0);
  19362. }
  19363. AudioFormatReaderSource::~AudioFormatReaderSource()
  19364. {
  19365. releaseResources();
  19366. if (deleteReader)
  19367. delete reader;
  19368. }
  19369. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19370. {
  19371. nextPlayPos = newPosition;
  19372. }
  19373. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19374. {
  19375. looping = shouldLoop;
  19376. }
  19377. int AudioFormatReaderSource::getNextReadPosition() const
  19378. {
  19379. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19380. : nextPlayPos;
  19381. }
  19382. int AudioFormatReaderSource::getTotalLength() const
  19383. {
  19384. return (int) reader->lengthInSamples;
  19385. }
  19386. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19387. double /*sampleRate*/)
  19388. {
  19389. }
  19390. void AudioFormatReaderSource::releaseResources()
  19391. {
  19392. }
  19393. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19394. {
  19395. if (info.numSamples > 0)
  19396. {
  19397. const int start = nextPlayPos;
  19398. if (looping)
  19399. {
  19400. const int newStart = start % (int) reader->lengthInSamples;
  19401. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19402. if (newEnd > newStart)
  19403. {
  19404. info.buffer->readFromAudioReader (reader,
  19405. info.startSample,
  19406. newEnd - newStart,
  19407. newStart,
  19408. true, true);
  19409. }
  19410. else
  19411. {
  19412. const int endSamps = (int) reader->lengthInSamples - newStart;
  19413. info.buffer->readFromAudioReader (reader,
  19414. info.startSample,
  19415. endSamps,
  19416. newStart,
  19417. true, true);
  19418. info.buffer->readFromAudioReader (reader,
  19419. info.startSample + endSamps,
  19420. newEnd,
  19421. 0,
  19422. true, true);
  19423. }
  19424. nextPlayPos = newEnd;
  19425. }
  19426. else
  19427. {
  19428. info.buffer->readFromAudioReader (reader,
  19429. info.startSample,
  19430. info.numSamples,
  19431. start,
  19432. true, true);
  19433. nextPlayPos += info.numSamples;
  19434. }
  19435. }
  19436. }
  19437. END_JUCE_NAMESPACE
  19438. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19439. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19440. BEGIN_JUCE_NAMESPACE
  19441. AudioSourcePlayer::AudioSourcePlayer()
  19442. : source (0),
  19443. sampleRate (0),
  19444. bufferSize (0),
  19445. tempBuffer (2, 8),
  19446. lastGain (1.0f),
  19447. gain (1.0f)
  19448. {
  19449. }
  19450. AudioSourcePlayer::~AudioSourcePlayer()
  19451. {
  19452. setSource (0);
  19453. }
  19454. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19455. {
  19456. if (source != newSource)
  19457. {
  19458. AudioSource* const oldSource = source;
  19459. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19460. newSource->prepareToPlay (bufferSize, sampleRate);
  19461. {
  19462. const ScopedLock sl (readLock);
  19463. source = newSource;
  19464. }
  19465. if (oldSource != 0)
  19466. oldSource->releaseResources();
  19467. }
  19468. }
  19469. void AudioSourcePlayer::setGain (const float newGain) throw()
  19470. {
  19471. gain = newGain;
  19472. }
  19473. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19474. int totalNumInputChannels,
  19475. float** outputChannelData,
  19476. int totalNumOutputChannels,
  19477. int numSamples)
  19478. {
  19479. // these should have been prepared by audioDeviceAboutToStart()...
  19480. jassert (sampleRate > 0 && bufferSize > 0);
  19481. const ScopedLock sl (readLock);
  19482. if (source != 0)
  19483. {
  19484. AudioSourceChannelInfo info;
  19485. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19486. // messy stuff needed to compact the channels down into an array
  19487. // of non-zero pointers..
  19488. for (i = 0; i < totalNumInputChannels; ++i)
  19489. {
  19490. if (inputChannelData[i] != 0)
  19491. {
  19492. inputChans [numInputs++] = inputChannelData[i];
  19493. if (numInputs >= numElementsInArray (inputChans))
  19494. break;
  19495. }
  19496. }
  19497. for (i = 0; i < totalNumOutputChannels; ++i)
  19498. {
  19499. if (outputChannelData[i] != 0)
  19500. {
  19501. outputChans [numOutputs++] = outputChannelData[i];
  19502. if (numOutputs >= numElementsInArray (outputChans))
  19503. break;
  19504. }
  19505. }
  19506. if (numInputs > numOutputs)
  19507. {
  19508. // if there aren't enough output channels for the number of
  19509. // inputs, we need to create some temporary extra ones (can't
  19510. // use the input data in case it gets written to)
  19511. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19512. false, false, true);
  19513. for (i = 0; i < numOutputs; ++i)
  19514. {
  19515. channels[numActiveChans] = outputChans[i];
  19516. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19517. ++numActiveChans;
  19518. }
  19519. for (i = numOutputs; i < numInputs; ++i)
  19520. {
  19521. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19522. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19523. ++numActiveChans;
  19524. }
  19525. }
  19526. else
  19527. {
  19528. for (i = 0; i < numInputs; ++i)
  19529. {
  19530. channels[numActiveChans] = outputChans[i];
  19531. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19532. ++numActiveChans;
  19533. }
  19534. for (i = numInputs; i < numOutputs; ++i)
  19535. {
  19536. channels[numActiveChans] = outputChans[i];
  19537. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19538. ++numActiveChans;
  19539. }
  19540. }
  19541. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19542. info.buffer = &buffer;
  19543. info.startSample = 0;
  19544. info.numSamples = numSamples;
  19545. source->getNextAudioBlock (info);
  19546. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19547. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19548. lastGain = gain;
  19549. }
  19550. else
  19551. {
  19552. for (int i = 0; i < totalNumOutputChannels; ++i)
  19553. if (outputChannelData[i] != 0)
  19554. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19555. }
  19556. }
  19557. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19558. {
  19559. sampleRate = device->getCurrentSampleRate();
  19560. bufferSize = device->getCurrentBufferSizeSamples();
  19561. zeromem (channels, sizeof (channels));
  19562. if (source != 0)
  19563. source->prepareToPlay (bufferSize, sampleRate);
  19564. }
  19565. void AudioSourcePlayer::audioDeviceStopped()
  19566. {
  19567. if (source != 0)
  19568. source->releaseResources();
  19569. sampleRate = 0.0;
  19570. bufferSize = 0;
  19571. tempBuffer.setSize (2, 8);
  19572. }
  19573. END_JUCE_NAMESPACE
  19574. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19575. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19576. BEGIN_JUCE_NAMESPACE
  19577. AudioTransportSource::AudioTransportSource()
  19578. : source (0),
  19579. resamplerSource (0),
  19580. bufferingSource (0),
  19581. positionableSource (0),
  19582. masterSource (0),
  19583. gain (1.0f),
  19584. lastGain (1.0f),
  19585. playing (false),
  19586. stopped (true),
  19587. sampleRate (44100.0),
  19588. sourceSampleRate (0.0),
  19589. blockSize (128),
  19590. readAheadBufferSize (0),
  19591. isPrepared (false),
  19592. inputStreamEOF (false)
  19593. {
  19594. }
  19595. AudioTransportSource::~AudioTransportSource()
  19596. {
  19597. setSource (0);
  19598. releaseResources();
  19599. }
  19600. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19601. int readAheadBufferSize_,
  19602. double sourceSampleRateToCorrectFor)
  19603. {
  19604. if (source == newSource)
  19605. {
  19606. if (source == 0)
  19607. return;
  19608. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19609. }
  19610. readAheadBufferSize = readAheadBufferSize_;
  19611. sourceSampleRate = sourceSampleRateToCorrectFor;
  19612. ResamplingAudioSource* newResamplerSource = 0;
  19613. BufferingAudioSource* newBufferingSource = 0;
  19614. PositionableAudioSource* newPositionableSource = 0;
  19615. AudioSource* newMasterSource = 0;
  19616. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19617. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19618. AudioSource* oldMasterSource = masterSource;
  19619. if (newSource != 0)
  19620. {
  19621. newPositionableSource = newSource;
  19622. if (readAheadBufferSize_ > 0)
  19623. newPositionableSource = newBufferingSource
  19624. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19625. newPositionableSource->setNextReadPosition (0);
  19626. if (sourceSampleRateToCorrectFor != 0)
  19627. newMasterSource = newResamplerSource
  19628. = new ResamplingAudioSource (newPositionableSource, false);
  19629. else
  19630. newMasterSource = newPositionableSource;
  19631. if (isPrepared)
  19632. {
  19633. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19634. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19635. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19636. }
  19637. }
  19638. {
  19639. const ScopedLock sl (callbackLock);
  19640. source = newSource;
  19641. resamplerSource = newResamplerSource;
  19642. bufferingSource = newBufferingSource;
  19643. masterSource = newMasterSource;
  19644. positionableSource = newPositionableSource;
  19645. playing = false;
  19646. }
  19647. if (oldMasterSource != 0)
  19648. oldMasterSource->releaseResources();
  19649. }
  19650. void AudioTransportSource::start()
  19651. {
  19652. if ((! playing) && masterSource != 0)
  19653. {
  19654. {
  19655. const ScopedLock sl (callbackLock);
  19656. playing = true;
  19657. stopped = false;
  19658. inputStreamEOF = false;
  19659. }
  19660. sendChangeMessage (this);
  19661. }
  19662. }
  19663. void AudioTransportSource::stop()
  19664. {
  19665. if (playing)
  19666. {
  19667. {
  19668. const ScopedLock sl (callbackLock);
  19669. playing = false;
  19670. }
  19671. int n = 500;
  19672. while (--n >= 0 && ! stopped)
  19673. Thread::sleep (2);
  19674. sendChangeMessage (this);
  19675. }
  19676. }
  19677. void AudioTransportSource::setPosition (double newPosition)
  19678. {
  19679. if (sampleRate > 0.0)
  19680. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19681. }
  19682. double AudioTransportSource::getCurrentPosition() const
  19683. {
  19684. if (sampleRate > 0.0)
  19685. return getNextReadPosition() / sampleRate;
  19686. else
  19687. return 0.0;
  19688. }
  19689. void AudioTransportSource::setNextReadPosition (int newPosition)
  19690. {
  19691. if (positionableSource != 0)
  19692. {
  19693. if (sampleRate > 0 && sourceSampleRate > 0)
  19694. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19695. positionableSource->setNextReadPosition (newPosition);
  19696. }
  19697. }
  19698. int AudioTransportSource::getNextReadPosition() const
  19699. {
  19700. if (positionableSource != 0)
  19701. {
  19702. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19703. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19704. }
  19705. return 0;
  19706. }
  19707. int AudioTransportSource::getTotalLength() const
  19708. {
  19709. const ScopedLock sl (callbackLock);
  19710. if (positionableSource != 0)
  19711. {
  19712. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19713. return roundToInt (positionableSource->getTotalLength() * ratio);
  19714. }
  19715. return 0;
  19716. }
  19717. bool AudioTransportSource::isLooping() const
  19718. {
  19719. const ScopedLock sl (callbackLock);
  19720. return positionableSource != 0
  19721. && positionableSource->isLooping();
  19722. }
  19723. void AudioTransportSource::setGain (const float newGain) throw()
  19724. {
  19725. gain = newGain;
  19726. }
  19727. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19728. double sampleRate_)
  19729. {
  19730. const ScopedLock sl (callbackLock);
  19731. sampleRate = sampleRate_;
  19732. blockSize = samplesPerBlockExpected;
  19733. if (masterSource != 0)
  19734. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19735. if (resamplerSource != 0 && sourceSampleRate != 0)
  19736. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19737. isPrepared = true;
  19738. }
  19739. void AudioTransportSource::releaseResources()
  19740. {
  19741. const ScopedLock sl (callbackLock);
  19742. if (masterSource != 0)
  19743. masterSource->releaseResources();
  19744. isPrepared = false;
  19745. }
  19746. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19747. {
  19748. const ScopedLock sl (callbackLock);
  19749. inputStreamEOF = false;
  19750. if (masterSource != 0 && ! stopped)
  19751. {
  19752. masterSource->getNextAudioBlock (info);
  19753. if (! playing)
  19754. {
  19755. // just stopped playing, so fade out the last block..
  19756. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19757. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19758. if (info.numSamples > 256)
  19759. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19760. }
  19761. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19762. && ! positionableSource->isLooping())
  19763. {
  19764. playing = false;
  19765. inputStreamEOF = true;
  19766. sendChangeMessage (this);
  19767. }
  19768. stopped = ! playing;
  19769. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19770. {
  19771. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19772. lastGain, gain);
  19773. }
  19774. }
  19775. else
  19776. {
  19777. info.clearActiveBufferRegion();
  19778. stopped = true;
  19779. }
  19780. lastGain = gain;
  19781. }
  19782. END_JUCE_NAMESPACE
  19783. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19784. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19785. BEGIN_JUCE_NAMESPACE
  19786. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19787. public Thread,
  19788. private Timer
  19789. {
  19790. public:
  19791. SharedBufferingAudioSourceThread()
  19792. : Thread ("Audio Buffer")
  19793. {
  19794. }
  19795. ~SharedBufferingAudioSourceThread()
  19796. {
  19797. stopThread (10000);
  19798. clearSingletonInstance();
  19799. }
  19800. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19801. void addSource (BufferingAudioSource* source)
  19802. {
  19803. const ScopedLock sl (lock);
  19804. if (! sources.contains (source))
  19805. {
  19806. sources.add (source);
  19807. startThread();
  19808. stopTimer();
  19809. }
  19810. notify();
  19811. }
  19812. void removeSource (BufferingAudioSource* source)
  19813. {
  19814. const ScopedLock sl (lock);
  19815. sources.removeValue (source);
  19816. if (sources.size() == 0)
  19817. startTimer (5000);
  19818. }
  19819. private:
  19820. Array <BufferingAudioSource*> sources;
  19821. CriticalSection lock;
  19822. void run()
  19823. {
  19824. while (! threadShouldExit())
  19825. {
  19826. bool busy = false;
  19827. for (int i = sources.size(); --i >= 0;)
  19828. {
  19829. if (threadShouldExit())
  19830. return;
  19831. const ScopedLock sl (lock);
  19832. BufferingAudioSource* const b = sources[i];
  19833. if (b != 0 && b->readNextBufferChunk())
  19834. busy = true;
  19835. }
  19836. if (! busy)
  19837. wait (500);
  19838. }
  19839. }
  19840. void timerCallback()
  19841. {
  19842. stopTimer();
  19843. if (sources.size() == 0)
  19844. deleteInstance();
  19845. }
  19846. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19847. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19848. };
  19849. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19850. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19851. const bool deleteSourceWhenDeleted_,
  19852. int numberOfSamplesToBuffer_)
  19853. : source (source_),
  19854. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19855. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19856. buffer (2, 0),
  19857. bufferValidStart (0),
  19858. bufferValidEnd (0),
  19859. nextPlayPos (0),
  19860. wasSourceLooping (false)
  19861. {
  19862. jassert (source_ != 0);
  19863. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19864. // not using a larger buffer..
  19865. }
  19866. BufferingAudioSource::~BufferingAudioSource()
  19867. {
  19868. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19869. if (thread != 0)
  19870. thread->removeSource (this);
  19871. if (deleteSourceWhenDeleted)
  19872. delete source;
  19873. }
  19874. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19875. {
  19876. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19877. sampleRate = sampleRate_;
  19878. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19879. buffer.clear();
  19880. bufferValidStart = 0;
  19881. bufferValidEnd = 0;
  19882. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19883. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19884. buffer.getNumSamples() / 2))
  19885. {
  19886. SharedBufferingAudioSourceThread::getInstance()->notify();
  19887. Thread::sleep (5);
  19888. }
  19889. }
  19890. void BufferingAudioSource::releaseResources()
  19891. {
  19892. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19893. if (thread != 0)
  19894. thread->removeSource (this);
  19895. buffer.setSize (2, 0);
  19896. source->releaseResources();
  19897. }
  19898. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19899. {
  19900. const ScopedLock sl (bufferStartPosLock);
  19901. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19902. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19903. if (validStart == validEnd)
  19904. {
  19905. // total cache miss
  19906. info.clearActiveBufferRegion();
  19907. }
  19908. else
  19909. {
  19910. if (validStart > 0)
  19911. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19912. if (validEnd < info.numSamples)
  19913. info.buffer->clear (info.startSample + validEnd,
  19914. info.numSamples - validEnd); // partial cache miss at end
  19915. if (validStart < validEnd)
  19916. {
  19917. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19918. {
  19919. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19920. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19921. if (startBufferIndex < endBufferIndex)
  19922. {
  19923. info.buffer->copyFrom (chan, info.startSample + validStart,
  19924. buffer,
  19925. chan, startBufferIndex,
  19926. validEnd - validStart);
  19927. }
  19928. else
  19929. {
  19930. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19931. info.buffer->copyFrom (chan, info.startSample + validStart,
  19932. buffer,
  19933. chan, startBufferIndex,
  19934. initialSize);
  19935. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19936. buffer,
  19937. chan, 0,
  19938. (validEnd - validStart) - initialSize);
  19939. }
  19940. }
  19941. }
  19942. nextPlayPos += info.numSamples;
  19943. if (source->isLooping() && nextPlayPos > 0)
  19944. nextPlayPos %= source->getTotalLength();
  19945. }
  19946. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19947. if (thread != 0)
  19948. thread->notify();
  19949. }
  19950. int BufferingAudioSource::getNextReadPosition() const
  19951. {
  19952. return (source->isLooping() && nextPlayPos > 0)
  19953. ? nextPlayPos % source->getTotalLength()
  19954. : nextPlayPos;
  19955. }
  19956. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19957. {
  19958. const ScopedLock sl (bufferStartPosLock);
  19959. nextPlayPos = newPosition;
  19960. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19961. if (thread != 0)
  19962. thread->notify();
  19963. }
  19964. bool BufferingAudioSource::readNextBufferChunk()
  19965. {
  19966. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19967. {
  19968. const ScopedLock sl (bufferStartPosLock);
  19969. if (wasSourceLooping != isLooping())
  19970. {
  19971. wasSourceLooping = isLooping();
  19972. bufferValidStart = 0;
  19973. bufferValidEnd = 0;
  19974. }
  19975. newBVS = jmax (0, nextPlayPos);
  19976. newBVE = newBVS + buffer.getNumSamples() - 4;
  19977. sectionToReadStart = 0;
  19978. sectionToReadEnd = 0;
  19979. const int maxChunkSize = 2048;
  19980. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19981. {
  19982. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19983. sectionToReadStart = newBVS;
  19984. sectionToReadEnd = newBVE;
  19985. bufferValidStart = 0;
  19986. bufferValidEnd = 0;
  19987. }
  19988. else if (abs (newBVS - bufferValidStart) > 512
  19989. || abs (newBVE - bufferValidEnd) > 512)
  19990. {
  19991. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19992. sectionToReadStart = bufferValidEnd;
  19993. sectionToReadEnd = newBVE;
  19994. bufferValidStart = newBVS;
  19995. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19996. }
  19997. }
  19998. if (sectionToReadStart != sectionToReadEnd)
  19999. {
  20000. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  20001. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  20002. if (bufferIndexStart < bufferIndexEnd)
  20003. {
  20004. readBufferSection (sectionToReadStart,
  20005. sectionToReadEnd - sectionToReadStart,
  20006. bufferIndexStart);
  20007. }
  20008. else
  20009. {
  20010. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  20011. readBufferSection (sectionToReadStart,
  20012. initialSize,
  20013. bufferIndexStart);
  20014. readBufferSection (sectionToReadStart + initialSize,
  20015. (sectionToReadEnd - sectionToReadStart) - initialSize,
  20016. 0);
  20017. }
  20018. const ScopedLock sl2 (bufferStartPosLock);
  20019. bufferValidStart = newBVS;
  20020. bufferValidEnd = newBVE;
  20021. return true;
  20022. }
  20023. else
  20024. {
  20025. return false;
  20026. }
  20027. }
  20028. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  20029. {
  20030. if (source->getNextReadPosition() != start)
  20031. source->setNextReadPosition (start);
  20032. AudioSourceChannelInfo info;
  20033. info.buffer = &buffer;
  20034. info.startSample = bufferOffset;
  20035. info.numSamples = length;
  20036. source->getNextAudioBlock (info);
  20037. }
  20038. END_JUCE_NAMESPACE
  20039. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  20040. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  20041. BEGIN_JUCE_NAMESPACE
  20042. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  20043. const bool deleteSourceWhenDeleted_)
  20044. : requiredNumberOfChannels (2),
  20045. source (source_),
  20046. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  20047. buffer (2, 16)
  20048. {
  20049. remappedInfo.buffer = &buffer;
  20050. remappedInfo.startSample = 0;
  20051. }
  20052. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  20053. {
  20054. if (deleteSourceWhenDeleted)
  20055. delete source;
  20056. }
  20057. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  20058. {
  20059. const ScopedLock sl (lock);
  20060. requiredNumberOfChannels = requiredNumberOfChannels_;
  20061. }
  20062. void ChannelRemappingAudioSource::clearAllMappings()
  20063. {
  20064. const ScopedLock sl (lock);
  20065. remappedInputs.clear();
  20066. remappedOutputs.clear();
  20067. }
  20068. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  20069. {
  20070. const ScopedLock sl (lock);
  20071. while (remappedInputs.size() < destIndex)
  20072. remappedInputs.add (-1);
  20073. remappedInputs.set (destIndex, sourceIndex);
  20074. }
  20075. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  20076. {
  20077. const ScopedLock sl (lock);
  20078. while (remappedOutputs.size() < sourceIndex)
  20079. remappedOutputs.add (-1);
  20080. remappedOutputs.set (sourceIndex, destIndex);
  20081. }
  20082. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  20083. {
  20084. const ScopedLock sl (lock);
  20085. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  20086. return remappedInputs.getUnchecked (inputChannelIndex);
  20087. return -1;
  20088. }
  20089. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  20090. {
  20091. const ScopedLock sl (lock);
  20092. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  20093. return remappedOutputs .getUnchecked (outputChannelIndex);
  20094. return -1;
  20095. }
  20096. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  20097. {
  20098. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20099. }
  20100. void ChannelRemappingAudioSource::releaseResources()
  20101. {
  20102. source->releaseResources();
  20103. }
  20104. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  20105. {
  20106. const ScopedLock sl (lock);
  20107. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  20108. const int numChans = bufferToFill.buffer->getNumChannels();
  20109. int i;
  20110. for (i = 0; i < buffer.getNumChannels(); ++i)
  20111. {
  20112. const int remappedChan = getRemappedInputChannel (i);
  20113. if (remappedChan >= 0 && remappedChan < numChans)
  20114. {
  20115. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  20116. remappedChan,
  20117. bufferToFill.startSample,
  20118. bufferToFill.numSamples);
  20119. }
  20120. else
  20121. {
  20122. buffer.clear (i, 0, bufferToFill.numSamples);
  20123. }
  20124. }
  20125. remappedInfo.numSamples = bufferToFill.numSamples;
  20126. source->getNextAudioBlock (remappedInfo);
  20127. bufferToFill.clearActiveBufferRegion();
  20128. for (i = 0; i < requiredNumberOfChannels; ++i)
  20129. {
  20130. const int remappedChan = getRemappedOutputChannel (i);
  20131. if (remappedChan >= 0 && remappedChan < numChans)
  20132. {
  20133. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  20134. buffer, i, 0, bufferToFill.numSamples);
  20135. }
  20136. }
  20137. }
  20138. XmlElement* ChannelRemappingAudioSource::createXml() const
  20139. {
  20140. XmlElement* e = new XmlElement ("MAPPINGS");
  20141. String ins, outs;
  20142. int i;
  20143. const ScopedLock sl (lock);
  20144. for (i = 0; i < remappedInputs.size(); ++i)
  20145. ins << remappedInputs.getUnchecked(i) << ' ';
  20146. for (i = 0; i < remappedOutputs.size(); ++i)
  20147. outs << remappedOutputs.getUnchecked(i) << ' ';
  20148. e->setAttribute ("inputs", ins.trimEnd());
  20149. e->setAttribute ("outputs", outs.trimEnd());
  20150. return e;
  20151. }
  20152. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  20153. {
  20154. if (e.hasTagName ("MAPPINGS"))
  20155. {
  20156. const ScopedLock sl (lock);
  20157. clearAllMappings();
  20158. StringArray ins, outs;
  20159. ins.addTokens (e.getStringAttribute ("inputs"), false);
  20160. outs.addTokens (e.getStringAttribute ("outputs"), false);
  20161. int i;
  20162. for (i = 0; i < ins.size(); ++i)
  20163. remappedInputs.add (ins[i].getIntValue());
  20164. for (i = 0; i < outs.size(); ++i)
  20165. remappedOutputs.add (outs[i].getIntValue());
  20166. }
  20167. }
  20168. END_JUCE_NAMESPACE
  20169. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  20170. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  20171. BEGIN_JUCE_NAMESPACE
  20172. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  20173. const bool deleteInputWhenDeleted_)
  20174. : input (inputSource),
  20175. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  20176. {
  20177. jassert (inputSource != 0);
  20178. for (int i = 2; --i >= 0;)
  20179. iirFilters.add (new IIRFilter());
  20180. }
  20181. IIRFilterAudioSource::~IIRFilterAudioSource()
  20182. {
  20183. if (deleteInputWhenDeleted)
  20184. delete input;
  20185. }
  20186. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  20187. {
  20188. for (int i = iirFilters.size(); --i >= 0;)
  20189. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  20190. }
  20191. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  20192. {
  20193. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20194. for (int i = iirFilters.size(); --i >= 0;)
  20195. iirFilters.getUnchecked(i)->reset();
  20196. }
  20197. void IIRFilterAudioSource::releaseResources()
  20198. {
  20199. input->releaseResources();
  20200. }
  20201. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  20202. {
  20203. input->getNextAudioBlock (bufferToFill);
  20204. const int numChannels = bufferToFill.buffer->getNumChannels();
  20205. while (numChannels > iirFilters.size())
  20206. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  20207. for (int i = 0; i < numChannels; ++i)
  20208. iirFilters.getUnchecked(i)
  20209. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  20210. bufferToFill.numSamples);
  20211. }
  20212. END_JUCE_NAMESPACE
  20213. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  20214. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  20215. BEGIN_JUCE_NAMESPACE
  20216. MixerAudioSource::MixerAudioSource()
  20217. : tempBuffer (2, 0),
  20218. currentSampleRate (0.0),
  20219. bufferSizeExpected (0)
  20220. {
  20221. }
  20222. MixerAudioSource::~MixerAudioSource()
  20223. {
  20224. removeAllInputs();
  20225. }
  20226. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  20227. {
  20228. if (input != 0 && ! inputs.contains (input))
  20229. {
  20230. double localRate;
  20231. int localBufferSize;
  20232. {
  20233. const ScopedLock sl (lock);
  20234. localRate = currentSampleRate;
  20235. localBufferSize = bufferSizeExpected;
  20236. }
  20237. if (localRate != 0.0)
  20238. input->prepareToPlay (localBufferSize, localRate);
  20239. const ScopedLock sl (lock);
  20240. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  20241. inputs.add (input);
  20242. }
  20243. }
  20244. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  20245. {
  20246. if (input != 0)
  20247. {
  20248. int index;
  20249. {
  20250. const ScopedLock sl (lock);
  20251. index = inputs.indexOf (input);
  20252. if (index >= 0)
  20253. {
  20254. inputsToDelete.shiftBits (index, 1);
  20255. inputs.remove (index);
  20256. }
  20257. }
  20258. if (index >= 0)
  20259. {
  20260. input->releaseResources();
  20261. if (deleteInput)
  20262. delete input;
  20263. }
  20264. }
  20265. }
  20266. void MixerAudioSource::removeAllInputs()
  20267. {
  20268. OwnedArray<AudioSource> toDelete;
  20269. {
  20270. const ScopedLock sl (lock);
  20271. for (int i = inputs.size(); --i >= 0;)
  20272. if (inputsToDelete[i])
  20273. toDelete.add (inputs.getUnchecked(i));
  20274. }
  20275. }
  20276. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  20277. {
  20278. tempBuffer.setSize (2, samplesPerBlockExpected);
  20279. const ScopedLock sl (lock);
  20280. currentSampleRate = sampleRate;
  20281. bufferSizeExpected = samplesPerBlockExpected;
  20282. for (int i = inputs.size(); --i >= 0;)
  20283. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20284. }
  20285. void MixerAudioSource::releaseResources()
  20286. {
  20287. const ScopedLock sl (lock);
  20288. for (int i = inputs.size(); --i >= 0;)
  20289. inputs.getUnchecked(i)->releaseResources();
  20290. tempBuffer.setSize (2, 0);
  20291. currentSampleRate = 0;
  20292. bufferSizeExpected = 0;
  20293. }
  20294. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20295. {
  20296. const ScopedLock sl (lock);
  20297. if (inputs.size() > 0)
  20298. {
  20299. inputs.getUnchecked(0)->getNextAudioBlock (info);
  20300. if (inputs.size() > 1)
  20301. {
  20302. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  20303. info.buffer->getNumSamples());
  20304. AudioSourceChannelInfo info2;
  20305. info2.buffer = &tempBuffer;
  20306. info2.numSamples = info.numSamples;
  20307. info2.startSample = 0;
  20308. for (int i = 1; i < inputs.size(); ++i)
  20309. {
  20310. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  20311. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  20312. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  20313. }
  20314. }
  20315. }
  20316. else
  20317. {
  20318. info.clearActiveBufferRegion();
  20319. }
  20320. }
  20321. END_JUCE_NAMESPACE
  20322. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  20323. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  20324. BEGIN_JUCE_NAMESPACE
  20325. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  20326. const bool deleteInputWhenDeleted_,
  20327. const int numChannels_)
  20328. : input (inputSource),
  20329. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  20330. ratio (1.0),
  20331. lastRatio (1.0),
  20332. buffer (numChannels_, 0),
  20333. sampsInBuffer (0),
  20334. numChannels (numChannels_)
  20335. {
  20336. jassert (input != 0);
  20337. }
  20338. ResamplingAudioSource::~ResamplingAudioSource()
  20339. {
  20340. if (deleteInputWhenDeleted)
  20341. delete input;
  20342. }
  20343. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  20344. {
  20345. jassert (samplesInPerOutputSample > 0);
  20346. const ScopedLock sl (ratioLock);
  20347. ratio = jmax (0.0, samplesInPerOutputSample);
  20348. }
  20349. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  20350. double sampleRate)
  20351. {
  20352. const ScopedLock sl (ratioLock);
  20353. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20354. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  20355. buffer.clear();
  20356. sampsInBuffer = 0;
  20357. bufferPos = 0;
  20358. subSampleOffset = 0.0;
  20359. filterStates.calloc (numChannels);
  20360. srcBuffers.calloc (numChannels);
  20361. destBuffers.calloc (numChannels);
  20362. createLowPass (ratio);
  20363. resetFilters();
  20364. }
  20365. void ResamplingAudioSource::releaseResources()
  20366. {
  20367. input->releaseResources();
  20368. buffer.setSize (numChannels, 0);
  20369. }
  20370. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20371. {
  20372. const ScopedLock sl (ratioLock);
  20373. if (lastRatio != ratio)
  20374. {
  20375. createLowPass (ratio);
  20376. lastRatio = ratio;
  20377. }
  20378. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20379. int bufferSize = buffer.getNumSamples();
  20380. if (bufferSize < sampsNeeded + 8)
  20381. {
  20382. bufferPos %= bufferSize;
  20383. bufferSize = sampsNeeded + 32;
  20384. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20385. }
  20386. bufferPos %= bufferSize;
  20387. int endOfBufferPos = bufferPos + sampsInBuffer;
  20388. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20389. while (sampsNeeded > sampsInBuffer)
  20390. {
  20391. endOfBufferPos %= bufferSize;
  20392. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20393. bufferSize - endOfBufferPos);
  20394. AudioSourceChannelInfo readInfo;
  20395. readInfo.buffer = &buffer;
  20396. readInfo.numSamples = numToDo;
  20397. readInfo.startSample = endOfBufferPos;
  20398. input->getNextAudioBlock (readInfo);
  20399. if (ratio > 1.0001)
  20400. {
  20401. // for down-sampling, pre-apply the filter..
  20402. for (int i = channelsToProcess; --i >= 0;)
  20403. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20404. }
  20405. sampsInBuffer += numToDo;
  20406. endOfBufferPos += numToDo;
  20407. }
  20408. for (int channel = 0; channel < channelsToProcess; ++channel)
  20409. {
  20410. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20411. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20412. }
  20413. int nextPos = (bufferPos + 1) % bufferSize;
  20414. for (int m = info.numSamples; --m >= 0;)
  20415. {
  20416. const float alpha = (float) subSampleOffset;
  20417. const float invAlpha = 1.0f - alpha;
  20418. for (int channel = 0; channel < channelsToProcess; ++channel)
  20419. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20420. subSampleOffset += ratio;
  20421. jassert (sampsInBuffer > 0);
  20422. while (subSampleOffset >= 1.0)
  20423. {
  20424. if (++bufferPos >= bufferSize)
  20425. bufferPos = 0;
  20426. --sampsInBuffer;
  20427. nextPos = (bufferPos + 1) % bufferSize;
  20428. subSampleOffset -= 1.0;
  20429. }
  20430. }
  20431. if (ratio < 0.9999)
  20432. {
  20433. // for up-sampling, apply the filter after transposing..
  20434. for (int i = channelsToProcess; --i >= 0;)
  20435. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20436. }
  20437. else if (ratio <= 1.0001)
  20438. {
  20439. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20440. for (int i = channelsToProcess; --i >= 0;)
  20441. {
  20442. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20443. FilterState& fs = filterStates[i];
  20444. if (info.numSamples > 1)
  20445. {
  20446. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20447. }
  20448. else
  20449. {
  20450. fs.y2 = fs.y1;
  20451. fs.x2 = fs.x1;
  20452. }
  20453. fs.y1 = fs.x1 = *endOfBuffer;
  20454. }
  20455. }
  20456. jassert (sampsInBuffer >= 0);
  20457. }
  20458. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20459. {
  20460. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20461. : 0.5 * frequencyRatio;
  20462. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20463. const double nSquared = n * n;
  20464. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20465. setFilterCoefficients (c1,
  20466. c1 * 2.0f,
  20467. c1,
  20468. 1.0,
  20469. c1 * 2.0 * (1.0 - nSquared),
  20470. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20471. }
  20472. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20473. {
  20474. const double a = 1.0 / c4;
  20475. c1 *= a;
  20476. c2 *= a;
  20477. c3 *= a;
  20478. c5 *= a;
  20479. c6 *= a;
  20480. coefficients[0] = c1;
  20481. coefficients[1] = c2;
  20482. coefficients[2] = c3;
  20483. coefficients[3] = c4;
  20484. coefficients[4] = c5;
  20485. coefficients[5] = c6;
  20486. }
  20487. void ResamplingAudioSource::resetFilters()
  20488. {
  20489. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20490. }
  20491. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20492. {
  20493. while (--num >= 0)
  20494. {
  20495. const double in = *samples;
  20496. double out = coefficients[0] * in
  20497. + coefficients[1] * fs.x1
  20498. + coefficients[2] * fs.x2
  20499. - coefficients[4] * fs.y1
  20500. - coefficients[5] * fs.y2;
  20501. #if JUCE_INTEL
  20502. if (! (out < -1.0e-8 || out > 1.0e-8))
  20503. out = 0;
  20504. #endif
  20505. fs.x2 = fs.x1;
  20506. fs.x1 = in;
  20507. fs.y2 = fs.y1;
  20508. fs.y1 = out;
  20509. *samples++ = (float) out;
  20510. }
  20511. }
  20512. END_JUCE_NAMESPACE
  20513. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20514. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20515. BEGIN_JUCE_NAMESPACE
  20516. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20517. : frequency (1000.0),
  20518. sampleRate (44100.0),
  20519. currentPhase (0.0),
  20520. phasePerSample (0.0),
  20521. amplitude (0.5f)
  20522. {
  20523. }
  20524. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20525. {
  20526. }
  20527. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20528. {
  20529. amplitude = newAmplitude;
  20530. }
  20531. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20532. {
  20533. frequency = newFrequencyHz;
  20534. phasePerSample = 0.0;
  20535. }
  20536. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20537. double sampleRate_)
  20538. {
  20539. currentPhase = 0.0;
  20540. phasePerSample = 0.0;
  20541. sampleRate = sampleRate_;
  20542. }
  20543. void ToneGeneratorAudioSource::releaseResources()
  20544. {
  20545. }
  20546. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20547. {
  20548. if (phasePerSample == 0.0)
  20549. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20550. for (int i = 0; i < info.numSamples; ++i)
  20551. {
  20552. const float sample = amplitude * (float) std::sin (currentPhase);
  20553. currentPhase += phasePerSample;
  20554. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20555. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20556. }
  20557. }
  20558. END_JUCE_NAMESPACE
  20559. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20560. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20561. BEGIN_JUCE_NAMESPACE
  20562. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20563. : sampleRate (0),
  20564. bufferSize (0),
  20565. useDefaultInputChannels (true),
  20566. useDefaultOutputChannels (true)
  20567. {
  20568. }
  20569. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20570. {
  20571. return outputDeviceName == other.outputDeviceName
  20572. && inputDeviceName == other.inputDeviceName
  20573. && sampleRate == other.sampleRate
  20574. && bufferSize == other.bufferSize
  20575. && inputChannels == other.inputChannels
  20576. && useDefaultInputChannels == other.useDefaultInputChannels
  20577. && outputChannels == other.outputChannels
  20578. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20579. }
  20580. AudioDeviceManager::AudioDeviceManager()
  20581. : currentAudioDevice (0),
  20582. numInputChansNeeded (0),
  20583. numOutputChansNeeded (2),
  20584. listNeedsScanning (true),
  20585. useInputNames (false),
  20586. inputLevelMeasurementEnabledCount (0),
  20587. inputLevel (0),
  20588. tempBuffer (2, 2),
  20589. defaultMidiOutput (0),
  20590. cpuUsageMs (0),
  20591. timeToCpuScale (0)
  20592. {
  20593. callbackHandler.owner = this;
  20594. }
  20595. AudioDeviceManager::~AudioDeviceManager()
  20596. {
  20597. currentAudioDevice = 0;
  20598. defaultMidiOutput = 0;
  20599. }
  20600. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20601. {
  20602. if (availableDeviceTypes.size() == 0)
  20603. {
  20604. createAudioDeviceTypes (availableDeviceTypes);
  20605. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20606. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20607. if (availableDeviceTypes.size() > 0)
  20608. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20609. }
  20610. }
  20611. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20612. {
  20613. scanDevicesIfNeeded();
  20614. return availableDeviceTypes;
  20615. }
  20616. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20617. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20618. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20619. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20620. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20621. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20622. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20623. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20624. {
  20625. (void) list; // (to avoid 'unused param' warnings)
  20626. #if JUCE_WINDOWS
  20627. #if JUCE_WASAPI
  20628. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20629. list.add (juce_createAudioIODeviceType_WASAPI());
  20630. #endif
  20631. #if JUCE_DIRECTSOUND
  20632. list.add (juce_createAudioIODeviceType_DirectSound());
  20633. #endif
  20634. #if JUCE_ASIO
  20635. list.add (juce_createAudioIODeviceType_ASIO());
  20636. #endif
  20637. #endif
  20638. #if JUCE_MAC
  20639. list.add (juce_createAudioIODeviceType_CoreAudio());
  20640. #endif
  20641. #if JUCE_IOS
  20642. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20643. #endif
  20644. #if JUCE_LINUX && JUCE_ALSA
  20645. list.add (juce_createAudioIODeviceType_ALSA());
  20646. #endif
  20647. #if JUCE_LINUX && JUCE_JACK
  20648. list.add (juce_createAudioIODeviceType_JACK());
  20649. #endif
  20650. }
  20651. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20652. const int numOutputChannelsNeeded,
  20653. const XmlElement* const e,
  20654. const bool selectDefaultDeviceOnFailure,
  20655. const String& preferredDefaultDeviceName,
  20656. const AudioDeviceSetup* preferredSetupOptions)
  20657. {
  20658. scanDevicesIfNeeded();
  20659. numInputChansNeeded = numInputChannelsNeeded;
  20660. numOutputChansNeeded = numOutputChannelsNeeded;
  20661. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20662. {
  20663. lastExplicitSettings = new XmlElement (*e);
  20664. String error;
  20665. AudioDeviceSetup setup;
  20666. if (preferredSetupOptions != 0)
  20667. setup = *preferredSetupOptions;
  20668. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20669. {
  20670. setup.inputDeviceName = setup.outputDeviceName
  20671. = e->getStringAttribute ("audioDeviceName");
  20672. }
  20673. else
  20674. {
  20675. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20676. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20677. }
  20678. currentDeviceType = e->getStringAttribute ("deviceType");
  20679. if (currentDeviceType.isEmpty())
  20680. {
  20681. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20682. if (type != 0)
  20683. currentDeviceType = type->getTypeName();
  20684. else if (availableDeviceTypes.size() > 0)
  20685. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20686. }
  20687. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20688. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20689. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20690. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20691. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20692. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20693. error = setAudioDeviceSetup (setup, true);
  20694. midiInsFromXml.clear();
  20695. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20696. midiInsFromXml.add (c->getStringAttribute ("name"));
  20697. const StringArray allMidiIns (MidiInput::getDevices());
  20698. for (int i = allMidiIns.size(); --i >= 0;)
  20699. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20700. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20701. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20702. false, preferredDefaultDeviceName);
  20703. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20704. return error;
  20705. }
  20706. else
  20707. {
  20708. AudioDeviceSetup setup;
  20709. if (preferredSetupOptions != 0)
  20710. {
  20711. setup = *preferredSetupOptions;
  20712. }
  20713. else if (preferredDefaultDeviceName.isNotEmpty())
  20714. {
  20715. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20716. {
  20717. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20718. StringArray outs (type->getDeviceNames (false));
  20719. int i;
  20720. for (i = 0; i < outs.size(); ++i)
  20721. {
  20722. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20723. {
  20724. setup.outputDeviceName = outs[i];
  20725. break;
  20726. }
  20727. }
  20728. StringArray ins (type->getDeviceNames (true));
  20729. for (i = 0; i < ins.size(); ++i)
  20730. {
  20731. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20732. {
  20733. setup.inputDeviceName = ins[i];
  20734. break;
  20735. }
  20736. }
  20737. }
  20738. }
  20739. insertDefaultDeviceNames (setup);
  20740. return setAudioDeviceSetup (setup, false);
  20741. }
  20742. }
  20743. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20744. {
  20745. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20746. if (type != 0)
  20747. {
  20748. if (setup.outputDeviceName.isEmpty())
  20749. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20750. if (setup.inputDeviceName.isEmpty())
  20751. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20752. }
  20753. }
  20754. XmlElement* AudioDeviceManager::createStateXml() const
  20755. {
  20756. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20757. }
  20758. void AudioDeviceManager::scanDevicesIfNeeded()
  20759. {
  20760. if (listNeedsScanning)
  20761. {
  20762. listNeedsScanning = false;
  20763. createDeviceTypesIfNeeded();
  20764. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20765. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20766. }
  20767. }
  20768. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20769. {
  20770. scanDevicesIfNeeded();
  20771. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20772. {
  20773. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20774. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20775. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20776. {
  20777. return type;
  20778. }
  20779. }
  20780. return 0;
  20781. }
  20782. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20783. {
  20784. setup = currentSetup;
  20785. }
  20786. void AudioDeviceManager::deleteCurrentDevice()
  20787. {
  20788. currentAudioDevice = 0;
  20789. currentSetup.inputDeviceName = String::empty;
  20790. currentSetup.outputDeviceName = String::empty;
  20791. }
  20792. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20793. const bool treatAsChosenDevice)
  20794. {
  20795. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20796. {
  20797. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20798. && currentDeviceType != type)
  20799. {
  20800. currentDeviceType = type;
  20801. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20802. insertDefaultDeviceNames (s);
  20803. setAudioDeviceSetup (s, treatAsChosenDevice);
  20804. sendChangeMessage (this);
  20805. break;
  20806. }
  20807. }
  20808. }
  20809. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20810. {
  20811. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20812. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20813. return availableDeviceTypes[i];
  20814. return availableDeviceTypes[0];
  20815. }
  20816. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20817. const bool treatAsChosenDevice)
  20818. {
  20819. jassert (&newSetup != &currentSetup); // this will have no effect
  20820. if (newSetup == currentSetup && currentAudioDevice != 0)
  20821. return String::empty;
  20822. if (! (newSetup == currentSetup))
  20823. sendChangeMessage (this);
  20824. stopDevice();
  20825. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20826. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20827. String error;
  20828. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20829. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20830. {
  20831. deleteCurrentDevice();
  20832. if (treatAsChosenDevice)
  20833. updateXml();
  20834. return String::empty;
  20835. }
  20836. if (currentSetup.inputDeviceName != newInputDeviceName
  20837. || currentSetup.outputDeviceName != newOutputDeviceName
  20838. || currentAudioDevice == 0)
  20839. {
  20840. deleteCurrentDevice();
  20841. scanDevicesIfNeeded();
  20842. if (newOutputDeviceName.isNotEmpty()
  20843. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20844. {
  20845. return "No such device: " + newOutputDeviceName;
  20846. }
  20847. if (newInputDeviceName.isNotEmpty()
  20848. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20849. {
  20850. return "No such device: " + newInputDeviceName;
  20851. }
  20852. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20853. if (currentAudioDevice == 0)
  20854. 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!";
  20855. else
  20856. error = currentAudioDevice->getLastError();
  20857. if (error.isNotEmpty())
  20858. {
  20859. deleteCurrentDevice();
  20860. return error;
  20861. }
  20862. if (newSetup.useDefaultInputChannels)
  20863. {
  20864. inputChannels.clear();
  20865. inputChannels.setRange (0, numInputChansNeeded, true);
  20866. }
  20867. if (newSetup.useDefaultOutputChannels)
  20868. {
  20869. outputChannels.clear();
  20870. outputChannels.setRange (0, numOutputChansNeeded, true);
  20871. }
  20872. if (newInputDeviceName.isEmpty())
  20873. inputChannels.clear();
  20874. if (newOutputDeviceName.isEmpty())
  20875. outputChannels.clear();
  20876. }
  20877. if (! newSetup.useDefaultInputChannels)
  20878. inputChannels = newSetup.inputChannels;
  20879. if (! newSetup.useDefaultOutputChannels)
  20880. outputChannels = newSetup.outputChannels;
  20881. currentSetup = newSetup;
  20882. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20883. error = currentAudioDevice->open (inputChannels,
  20884. outputChannels,
  20885. currentSetup.sampleRate,
  20886. currentSetup.bufferSize);
  20887. if (error.isEmpty())
  20888. {
  20889. currentDeviceType = currentAudioDevice->getTypeName();
  20890. currentAudioDevice->start (&callbackHandler);
  20891. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20892. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20893. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20894. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20895. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20896. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20897. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20898. if (treatAsChosenDevice)
  20899. updateXml();
  20900. }
  20901. else
  20902. {
  20903. deleteCurrentDevice();
  20904. }
  20905. return error;
  20906. }
  20907. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20908. {
  20909. jassert (currentAudioDevice != 0);
  20910. if (rate > 0)
  20911. {
  20912. bool ok = false;
  20913. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20914. {
  20915. const double sr = currentAudioDevice->getSampleRate (i);
  20916. if (sr == rate)
  20917. ok = true;
  20918. }
  20919. if (! ok)
  20920. rate = 0;
  20921. }
  20922. if (rate == 0)
  20923. {
  20924. double lowestAbove44 = 0.0;
  20925. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20926. {
  20927. const double sr = currentAudioDevice->getSampleRate (i);
  20928. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20929. lowestAbove44 = sr;
  20930. }
  20931. if (lowestAbove44 == 0.0)
  20932. rate = currentAudioDevice->getSampleRate (0);
  20933. else
  20934. rate = lowestAbove44;
  20935. }
  20936. return rate;
  20937. }
  20938. void AudioDeviceManager::stopDevice()
  20939. {
  20940. if (currentAudioDevice != 0)
  20941. currentAudioDevice->stop();
  20942. testSound = 0;
  20943. }
  20944. void AudioDeviceManager::closeAudioDevice()
  20945. {
  20946. stopDevice();
  20947. currentAudioDevice = 0;
  20948. }
  20949. void AudioDeviceManager::restartLastAudioDevice()
  20950. {
  20951. if (currentAudioDevice == 0)
  20952. {
  20953. if (currentSetup.inputDeviceName.isEmpty()
  20954. && currentSetup.outputDeviceName.isEmpty())
  20955. {
  20956. // This method will only reload the last device that was running
  20957. // before closeAudioDevice() was called - you need to actually open
  20958. // one first, with setAudioDevice().
  20959. jassertfalse;
  20960. return;
  20961. }
  20962. AudioDeviceSetup s (currentSetup);
  20963. setAudioDeviceSetup (s, false);
  20964. }
  20965. }
  20966. void AudioDeviceManager::updateXml()
  20967. {
  20968. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20969. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20970. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20971. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20972. if (currentAudioDevice != 0)
  20973. {
  20974. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20975. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20976. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20977. if (! currentSetup.useDefaultInputChannels)
  20978. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20979. if (! currentSetup.useDefaultOutputChannels)
  20980. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20981. }
  20982. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20983. {
  20984. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20985. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20986. }
  20987. if (midiInsFromXml.size() > 0)
  20988. {
  20989. // Add any midi devices that have been enabled before, but which aren't currently
  20990. // open because the device has been disconnected.
  20991. const StringArray availableMidiDevices (MidiInput::getDevices());
  20992. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20993. {
  20994. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20995. {
  20996. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20997. m->setAttribute ("name", midiInsFromXml[i]);
  20998. }
  20999. }
  21000. }
  21001. if (defaultMidiOutputName.isNotEmpty())
  21002. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  21003. }
  21004. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  21005. {
  21006. {
  21007. const ScopedLock sl (audioCallbackLock);
  21008. if (callbacks.contains (newCallback))
  21009. return;
  21010. }
  21011. if (currentAudioDevice != 0 && newCallback != 0)
  21012. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  21013. const ScopedLock sl (audioCallbackLock);
  21014. callbacks.add (newCallback);
  21015. }
  21016. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  21017. {
  21018. if (callback != 0)
  21019. {
  21020. bool needsDeinitialising = currentAudioDevice != 0;
  21021. {
  21022. const ScopedLock sl (audioCallbackLock);
  21023. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  21024. callbacks.removeValue (callback);
  21025. }
  21026. if (needsDeinitialising)
  21027. callback->audioDeviceStopped();
  21028. }
  21029. }
  21030. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  21031. int numInputChannels,
  21032. float** outputChannelData,
  21033. int numOutputChannels,
  21034. int numSamples)
  21035. {
  21036. const ScopedLock sl (audioCallbackLock);
  21037. if (inputLevelMeasurementEnabledCount > 0)
  21038. {
  21039. for (int j = 0; j < numSamples; ++j)
  21040. {
  21041. float s = 0;
  21042. for (int i = 0; i < numInputChannels; ++i)
  21043. s += std::abs (inputChannelData[i][j]);
  21044. s /= numInputChannels;
  21045. const double decayFactor = 0.99992;
  21046. if (s > inputLevel)
  21047. inputLevel = s;
  21048. else if (inputLevel > 0.001f)
  21049. inputLevel *= decayFactor;
  21050. else
  21051. inputLevel = 0;
  21052. }
  21053. }
  21054. if (callbacks.size() > 0)
  21055. {
  21056. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  21057. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  21058. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  21059. outputChannelData, numOutputChannels, numSamples);
  21060. float** const tempChans = tempBuffer.getArrayOfChannels();
  21061. for (int i = callbacks.size(); --i > 0;)
  21062. {
  21063. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  21064. tempChans, numOutputChannels, numSamples);
  21065. for (int chan = 0; chan < numOutputChannels; ++chan)
  21066. {
  21067. const float* const src = tempChans [chan];
  21068. float* const dst = outputChannelData [chan];
  21069. if (src != 0 && dst != 0)
  21070. for (int j = 0; j < numSamples; ++j)
  21071. dst[j] += src[j];
  21072. }
  21073. }
  21074. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  21075. const double filterAmount = 0.2;
  21076. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  21077. }
  21078. else
  21079. {
  21080. for (int i = 0; i < numOutputChannels; ++i)
  21081. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  21082. }
  21083. if (testSound != 0)
  21084. {
  21085. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  21086. const float* const src = testSound->getSampleData (0, testSoundPosition);
  21087. for (int i = 0; i < numOutputChannels; ++i)
  21088. for (int j = 0; j < numSamps; ++j)
  21089. outputChannelData [i][j] += src[j];
  21090. testSoundPosition += numSamps;
  21091. if (testSoundPosition >= testSound->getNumSamples())
  21092. testSound = 0;
  21093. }
  21094. }
  21095. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  21096. {
  21097. cpuUsageMs = 0;
  21098. const double sampleRate = device->getCurrentSampleRate();
  21099. const int blockSize = device->getCurrentBufferSizeSamples();
  21100. if (sampleRate > 0.0 && blockSize > 0)
  21101. {
  21102. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  21103. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  21104. }
  21105. {
  21106. const ScopedLock sl (audioCallbackLock);
  21107. for (int i = callbacks.size(); --i >= 0;)
  21108. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  21109. }
  21110. sendChangeMessage (this);
  21111. }
  21112. void AudioDeviceManager::audioDeviceStoppedInt()
  21113. {
  21114. cpuUsageMs = 0;
  21115. timeToCpuScale = 0;
  21116. sendChangeMessage (this);
  21117. const ScopedLock sl (audioCallbackLock);
  21118. for (int i = callbacks.size(); --i >= 0;)
  21119. callbacks.getUnchecked(i)->audioDeviceStopped();
  21120. }
  21121. double AudioDeviceManager::getCpuUsage() const
  21122. {
  21123. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  21124. }
  21125. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  21126. const bool enabled)
  21127. {
  21128. if (enabled != isMidiInputEnabled (name))
  21129. {
  21130. if (enabled)
  21131. {
  21132. const int index = MidiInput::getDevices().indexOf (name);
  21133. if (index >= 0)
  21134. {
  21135. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  21136. if (min != 0)
  21137. {
  21138. enabledMidiInputs.add (min);
  21139. min->start();
  21140. }
  21141. }
  21142. }
  21143. else
  21144. {
  21145. for (int i = enabledMidiInputs.size(); --i >= 0;)
  21146. if (enabledMidiInputs[i]->getName() == name)
  21147. enabledMidiInputs.remove (i);
  21148. }
  21149. updateXml();
  21150. sendChangeMessage (this);
  21151. }
  21152. }
  21153. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  21154. {
  21155. for (int i = enabledMidiInputs.size(); --i >= 0;)
  21156. if (enabledMidiInputs[i]->getName() == name)
  21157. return true;
  21158. return false;
  21159. }
  21160. void AudioDeviceManager::addMidiInputCallback (const String& name,
  21161. MidiInputCallback* callback)
  21162. {
  21163. removeMidiInputCallback (name, callback);
  21164. if (name.isEmpty())
  21165. {
  21166. midiCallbacks.add (callback);
  21167. midiCallbackDevices.add (0);
  21168. }
  21169. else
  21170. {
  21171. for (int i = enabledMidiInputs.size(); --i >= 0;)
  21172. {
  21173. if (enabledMidiInputs[i]->getName() == name)
  21174. {
  21175. const ScopedLock sl (midiCallbackLock);
  21176. midiCallbacks.add (callback);
  21177. midiCallbackDevices.add (enabledMidiInputs[i]);
  21178. break;
  21179. }
  21180. }
  21181. }
  21182. }
  21183. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  21184. MidiInputCallback* /*callback*/)
  21185. {
  21186. const ScopedLock sl (midiCallbackLock);
  21187. for (int i = midiCallbacks.size(); --i >= 0;)
  21188. {
  21189. String devName;
  21190. if (midiCallbackDevices.getUnchecked(i) != 0)
  21191. devName = midiCallbackDevices.getUnchecked(i)->getName();
  21192. if (devName == name)
  21193. {
  21194. midiCallbacks.remove (i);
  21195. midiCallbackDevices.remove (i);
  21196. }
  21197. }
  21198. }
  21199. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  21200. const MidiMessage& message)
  21201. {
  21202. if (! message.isActiveSense())
  21203. {
  21204. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  21205. const ScopedLock sl (midiCallbackLock);
  21206. for (int i = midiCallbackDevices.size(); --i >= 0;)
  21207. {
  21208. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  21209. if (md == source || (md == 0 && isDefaultSource))
  21210. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  21211. }
  21212. }
  21213. }
  21214. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  21215. {
  21216. if (defaultMidiOutputName != deviceName)
  21217. {
  21218. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  21219. {
  21220. const ScopedLock sl (audioCallbackLock);
  21221. oldCallbacks = callbacks;
  21222. callbacks.clear();
  21223. }
  21224. if (currentAudioDevice != 0)
  21225. for (int i = oldCallbacks.size(); --i >= 0;)
  21226. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  21227. defaultMidiOutput = 0;
  21228. defaultMidiOutputName = deviceName;
  21229. if (deviceName.isNotEmpty())
  21230. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  21231. if (currentAudioDevice != 0)
  21232. for (int i = oldCallbacks.size(); --i >= 0;)
  21233. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  21234. {
  21235. const ScopedLock sl (audioCallbackLock);
  21236. callbacks = oldCallbacks;
  21237. }
  21238. updateXml();
  21239. sendChangeMessage (this);
  21240. }
  21241. }
  21242. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  21243. int numInputChannels,
  21244. float** outputChannelData,
  21245. int numOutputChannels,
  21246. int numSamples)
  21247. {
  21248. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  21249. }
  21250. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  21251. {
  21252. owner->audioDeviceAboutToStartInt (device);
  21253. }
  21254. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  21255. {
  21256. owner->audioDeviceStoppedInt();
  21257. }
  21258. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  21259. {
  21260. owner->handleIncomingMidiMessageInt (source, message);
  21261. }
  21262. void AudioDeviceManager::playTestSound()
  21263. {
  21264. { // cunningly nested to swap, unlock and delete in that order.
  21265. ScopedPointer <AudioSampleBuffer> oldSound;
  21266. {
  21267. const ScopedLock sl (audioCallbackLock);
  21268. oldSound = testSound;
  21269. }
  21270. }
  21271. testSoundPosition = 0;
  21272. if (currentAudioDevice != 0)
  21273. {
  21274. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  21275. const int soundLength = (int) sampleRate;
  21276. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  21277. float* samples = newSound->getSampleData (0);
  21278. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  21279. const float amplitude = 0.5f;
  21280. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  21281. for (int i = 0; i < soundLength; ++i)
  21282. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  21283. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  21284. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  21285. const ScopedLock sl (audioCallbackLock);
  21286. testSound = newSound;
  21287. }
  21288. }
  21289. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  21290. {
  21291. const ScopedLock sl (audioCallbackLock);
  21292. if (enableMeasurement)
  21293. ++inputLevelMeasurementEnabledCount;
  21294. else
  21295. --inputLevelMeasurementEnabledCount;
  21296. inputLevel = 0;
  21297. }
  21298. double AudioDeviceManager::getCurrentInputLevel() const
  21299. {
  21300. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  21301. return inputLevel;
  21302. }
  21303. END_JUCE_NAMESPACE
  21304. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  21305. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  21306. BEGIN_JUCE_NAMESPACE
  21307. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  21308. : name (deviceName),
  21309. typeName (typeName_)
  21310. {
  21311. }
  21312. AudioIODevice::~AudioIODevice()
  21313. {
  21314. }
  21315. bool AudioIODevice::hasControlPanel() const
  21316. {
  21317. return false;
  21318. }
  21319. bool AudioIODevice::showControlPanel()
  21320. {
  21321. jassertfalse; // this should only be called for devices which return true from
  21322. // their hasControlPanel() method.
  21323. return false;
  21324. }
  21325. END_JUCE_NAMESPACE
  21326. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  21327. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  21328. BEGIN_JUCE_NAMESPACE
  21329. AudioIODeviceType::AudioIODeviceType (const String& name)
  21330. : typeName (name)
  21331. {
  21332. }
  21333. AudioIODeviceType::~AudioIODeviceType()
  21334. {
  21335. }
  21336. END_JUCE_NAMESPACE
  21337. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  21338. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  21339. BEGIN_JUCE_NAMESPACE
  21340. MidiOutput::MidiOutput()
  21341. : Thread ("midi out"),
  21342. internal (0),
  21343. firstMessage (0)
  21344. {
  21345. }
  21346. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  21347. const double sampleNumber)
  21348. : message (data, len, sampleNumber)
  21349. {
  21350. }
  21351. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  21352. const double millisecondCounterToStartAt,
  21353. double samplesPerSecondForBuffer)
  21354. {
  21355. // You've got to call startBackgroundThread() for this to actually work..
  21356. jassert (isThreadRunning());
  21357. // this needs to be a value in the future - RTFM for this method!
  21358. jassert (millisecondCounterToStartAt > 0);
  21359. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  21360. MidiBuffer::Iterator i (buffer);
  21361. const uint8* data;
  21362. int len, time;
  21363. while (i.getNextEvent (data, len, time))
  21364. {
  21365. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  21366. PendingMessage* const m
  21367. = new PendingMessage (data, len, eventTime);
  21368. const ScopedLock sl (lock);
  21369. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21370. {
  21371. m->next = firstMessage;
  21372. firstMessage = m;
  21373. }
  21374. else
  21375. {
  21376. PendingMessage* mm = firstMessage;
  21377. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21378. mm = mm->next;
  21379. m->next = mm->next;
  21380. mm->next = m;
  21381. }
  21382. }
  21383. notify();
  21384. }
  21385. void MidiOutput::clearAllPendingMessages()
  21386. {
  21387. const ScopedLock sl (lock);
  21388. while (firstMessage != 0)
  21389. {
  21390. PendingMessage* const m = firstMessage;
  21391. firstMessage = firstMessage->next;
  21392. delete m;
  21393. }
  21394. }
  21395. void MidiOutput::startBackgroundThread()
  21396. {
  21397. startThread (9);
  21398. }
  21399. void MidiOutput::stopBackgroundThread()
  21400. {
  21401. stopThread (5000);
  21402. }
  21403. void MidiOutput::run()
  21404. {
  21405. while (! threadShouldExit())
  21406. {
  21407. uint32 now = Time::getMillisecondCounter();
  21408. uint32 eventTime = 0;
  21409. uint32 timeToWait = 500;
  21410. PendingMessage* message;
  21411. {
  21412. const ScopedLock sl (lock);
  21413. message = firstMessage;
  21414. if (message != 0)
  21415. {
  21416. eventTime = roundToInt (message->message.getTimeStamp());
  21417. if (eventTime > now + 20)
  21418. {
  21419. timeToWait = eventTime - (now + 20);
  21420. message = 0;
  21421. }
  21422. else
  21423. {
  21424. firstMessage = message->next;
  21425. }
  21426. }
  21427. }
  21428. if (message != 0)
  21429. {
  21430. if (eventTime > now)
  21431. {
  21432. Time::waitForMillisecondCounter (eventTime);
  21433. if (threadShouldExit())
  21434. break;
  21435. }
  21436. if (eventTime > now - 200)
  21437. sendMessageNow (message->message);
  21438. delete message;
  21439. }
  21440. else
  21441. {
  21442. jassert (timeToWait < 1000 * 30);
  21443. wait (timeToWait);
  21444. }
  21445. }
  21446. clearAllPendingMessages();
  21447. }
  21448. END_JUCE_NAMESPACE
  21449. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21450. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21451. BEGIN_JUCE_NAMESPACE
  21452. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21453. {
  21454. const double maxVal = (double) 0x7fff;
  21455. char* intData = static_cast <char*> (dest);
  21456. if (dest != (void*) source || destBytesPerSample <= 4)
  21457. {
  21458. for (int i = 0; i < numSamples; ++i)
  21459. {
  21460. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21461. intData += destBytesPerSample;
  21462. }
  21463. }
  21464. else
  21465. {
  21466. intData += destBytesPerSample * numSamples;
  21467. for (int i = numSamples; --i >= 0;)
  21468. {
  21469. intData -= destBytesPerSample;
  21470. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21471. }
  21472. }
  21473. }
  21474. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21475. {
  21476. const double maxVal = (double) 0x7fff;
  21477. char* intData = static_cast <char*> (dest);
  21478. if (dest != (void*) source || destBytesPerSample <= 4)
  21479. {
  21480. for (int i = 0; i < numSamples; ++i)
  21481. {
  21482. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21483. intData += destBytesPerSample;
  21484. }
  21485. }
  21486. else
  21487. {
  21488. intData += destBytesPerSample * numSamples;
  21489. for (int i = numSamples; --i >= 0;)
  21490. {
  21491. intData -= destBytesPerSample;
  21492. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21493. }
  21494. }
  21495. }
  21496. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21497. {
  21498. const double maxVal = (double) 0x7fffff;
  21499. char* intData = static_cast <char*> (dest);
  21500. if (dest != (void*) source || destBytesPerSample <= 4)
  21501. {
  21502. for (int i = 0; i < numSamples; ++i)
  21503. {
  21504. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21505. intData += destBytesPerSample;
  21506. }
  21507. }
  21508. else
  21509. {
  21510. intData += destBytesPerSample * numSamples;
  21511. for (int i = numSamples; --i >= 0;)
  21512. {
  21513. intData -= destBytesPerSample;
  21514. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21515. }
  21516. }
  21517. }
  21518. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21519. {
  21520. const double maxVal = (double) 0x7fffff;
  21521. char* intData = static_cast <char*> (dest);
  21522. if (dest != (void*) source || destBytesPerSample <= 4)
  21523. {
  21524. for (int i = 0; i < numSamples; ++i)
  21525. {
  21526. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21527. intData += destBytesPerSample;
  21528. }
  21529. }
  21530. else
  21531. {
  21532. intData += destBytesPerSample * numSamples;
  21533. for (int i = numSamples; --i >= 0;)
  21534. {
  21535. intData -= destBytesPerSample;
  21536. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21537. }
  21538. }
  21539. }
  21540. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21541. {
  21542. const double maxVal = (double) 0x7fffffff;
  21543. char* intData = static_cast <char*> (dest);
  21544. if (dest != (void*) source || destBytesPerSample <= 4)
  21545. {
  21546. for (int i = 0; i < numSamples; ++i)
  21547. {
  21548. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21549. intData += destBytesPerSample;
  21550. }
  21551. }
  21552. else
  21553. {
  21554. intData += destBytesPerSample * numSamples;
  21555. for (int i = numSamples; --i >= 0;)
  21556. {
  21557. intData -= destBytesPerSample;
  21558. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21559. }
  21560. }
  21561. }
  21562. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21563. {
  21564. const double maxVal = (double) 0x7fffffff;
  21565. char* intData = static_cast <char*> (dest);
  21566. if (dest != (void*) source || destBytesPerSample <= 4)
  21567. {
  21568. for (int i = 0; i < numSamples; ++i)
  21569. {
  21570. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21571. intData += destBytesPerSample;
  21572. }
  21573. }
  21574. else
  21575. {
  21576. intData += destBytesPerSample * numSamples;
  21577. for (int i = numSamples; --i >= 0;)
  21578. {
  21579. intData -= destBytesPerSample;
  21580. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21581. }
  21582. }
  21583. }
  21584. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21585. {
  21586. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21587. char* d = static_cast <char*> (dest);
  21588. for (int i = 0; i < numSamples; ++i)
  21589. {
  21590. *(float*) d = source[i];
  21591. #if JUCE_BIG_ENDIAN
  21592. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21593. #endif
  21594. d += destBytesPerSample;
  21595. }
  21596. }
  21597. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21598. {
  21599. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21600. char* d = static_cast <char*> (dest);
  21601. for (int i = 0; i < numSamples; ++i)
  21602. {
  21603. *(float*) d = source[i];
  21604. #if JUCE_LITTLE_ENDIAN
  21605. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21606. #endif
  21607. d += destBytesPerSample;
  21608. }
  21609. }
  21610. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21611. {
  21612. const float scale = 1.0f / 0x7fff;
  21613. const char* intData = static_cast <const char*> (source);
  21614. if (source != (void*) dest || srcBytesPerSample >= 4)
  21615. {
  21616. for (int i = 0; i < numSamples; ++i)
  21617. {
  21618. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21619. intData += srcBytesPerSample;
  21620. }
  21621. }
  21622. else
  21623. {
  21624. intData += srcBytesPerSample * numSamples;
  21625. for (int i = numSamples; --i >= 0;)
  21626. {
  21627. intData -= srcBytesPerSample;
  21628. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21629. }
  21630. }
  21631. }
  21632. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21633. {
  21634. const float scale = 1.0f / 0x7fff;
  21635. const char* intData = static_cast <const char*> (source);
  21636. if (source != (void*) dest || srcBytesPerSample >= 4)
  21637. {
  21638. for (int i = 0; i < numSamples; ++i)
  21639. {
  21640. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21641. intData += srcBytesPerSample;
  21642. }
  21643. }
  21644. else
  21645. {
  21646. intData += srcBytesPerSample * numSamples;
  21647. for (int i = numSamples; --i >= 0;)
  21648. {
  21649. intData -= srcBytesPerSample;
  21650. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21651. }
  21652. }
  21653. }
  21654. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21655. {
  21656. const float scale = 1.0f / 0x7fffff;
  21657. const char* intData = static_cast <const char*> (source);
  21658. if (source != (void*) dest || srcBytesPerSample >= 4)
  21659. {
  21660. for (int i = 0; i < numSamples; ++i)
  21661. {
  21662. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21663. intData += srcBytesPerSample;
  21664. }
  21665. }
  21666. else
  21667. {
  21668. intData += srcBytesPerSample * numSamples;
  21669. for (int i = numSamples; --i >= 0;)
  21670. {
  21671. intData -= srcBytesPerSample;
  21672. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21673. }
  21674. }
  21675. }
  21676. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21677. {
  21678. const float scale = 1.0f / 0x7fffff;
  21679. const char* intData = static_cast <const char*> (source);
  21680. if (source != (void*) dest || srcBytesPerSample >= 4)
  21681. {
  21682. for (int i = 0; i < numSamples; ++i)
  21683. {
  21684. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21685. intData += srcBytesPerSample;
  21686. }
  21687. }
  21688. else
  21689. {
  21690. intData += srcBytesPerSample * numSamples;
  21691. for (int i = numSamples; --i >= 0;)
  21692. {
  21693. intData -= srcBytesPerSample;
  21694. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21695. }
  21696. }
  21697. }
  21698. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21699. {
  21700. const float scale = 1.0f / 0x7fffffff;
  21701. const char* intData = static_cast <const char*> (source);
  21702. if (source != (void*) dest || srcBytesPerSample >= 4)
  21703. {
  21704. for (int i = 0; i < numSamples; ++i)
  21705. {
  21706. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21707. intData += srcBytesPerSample;
  21708. }
  21709. }
  21710. else
  21711. {
  21712. intData += srcBytesPerSample * numSamples;
  21713. for (int i = numSamples; --i >= 0;)
  21714. {
  21715. intData -= srcBytesPerSample;
  21716. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21717. }
  21718. }
  21719. }
  21720. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21721. {
  21722. const float scale = 1.0f / 0x7fffffff;
  21723. const char* intData = static_cast <const char*> (source);
  21724. if (source != (void*) dest || srcBytesPerSample >= 4)
  21725. {
  21726. for (int i = 0; i < numSamples; ++i)
  21727. {
  21728. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21729. intData += srcBytesPerSample;
  21730. }
  21731. }
  21732. else
  21733. {
  21734. intData += srcBytesPerSample * numSamples;
  21735. for (int i = numSamples; --i >= 0;)
  21736. {
  21737. intData -= srcBytesPerSample;
  21738. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21739. }
  21740. }
  21741. }
  21742. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21743. {
  21744. const char* s = static_cast <const char*> (source);
  21745. for (int i = 0; i < numSamples; ++i)
  21746. {
  21747. dest[i] = *(float*)s;
  21748. #if JUCE_BIG_ENDIAN
  21749. uint32* const d = (uint32*) (dest + i);
  21750. *d = ByteOrder::swap (*d);
  21751. #endif
  21752. s += srcBytesPerSample;
  21753. }
  21754. }
  21755. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21756. {
  21757. const char* s = static_cast <const char*> (source);
  21758. for (int i = 0; i < numSamples; ++i)
  21759. {
  21760. dest[i] = *(float*)s;
  21761. #if JUCE_LITTLE_ENDIAN
  21762. uint32* const d = (uint32*) (dest + i);
  21763. *d = ByteOrder::swap (*d);
  21764. #endif
  21765. s += srcBytesPerSample;
  21766. }
  21767. }
  21768. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21769. const float* const source,
  21770. void* const dest,
  21771. const int numSamples)
  21772. {
  21773. switch (destFormat)
  21774. {
  21775. case int16LE:
  21776. convertFloatToInt16LE (source, dest, numSamples);
  21777. break;
  21778. case int16BE:
  21779. convertFloatToInt16BE (source, dest, numSamples);
  21780. break;
  21781. case int24LE:
  21782. convertFloatToInt24LE (source, dest, numSamples);
  21783. break;
  21784. case int24BE:
  21785. convertFloatToInt24BE (source, dest, numSamples);
  21786. break;
  21787. case int32LE:
  21788. convertFloatToInt32LE (source, dest, numSamples);
  21789. break;
  21790. case int32BE:
  21791. convertFloatToInt32BE (source, dest, numSamples);
  21792. break;
  21793. case float32LE:
  21794. convertFloatToFloat32LE (source, dest, numSamples);
  21795. break;
  21796. case float32BE:
  21797. convertFloatToFloat32BE (source, dest, numSamples);
  21798. break;
  21799. default:
  21800. jassertfalse;
  21801. break;
  21802. }
  21803. }
  21804. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21805. const void* const source,
  21806. float* const dest,
  21807. const int numSamples)
  21808. {
  21809. switch (sourceFormat)
  21810. {
  21811. case int16LE:
  21812. convertInt16LEToFloat (source, dest, numSamples);
  21813. break;
  21814. case int16BE:
  21815. convertInt16BEToFloat (source, dest, numSamples);
  21816. break;
  21817. case int24LE:
  21818. convertInt24LEToFloat (source, dest, numSamples);
  21819. break;
  21820. case int24BE:
  21821. convertInt24BEToFloat (source, dest, numSamples);
  21822. break;
  21823. case int32LE:
  21824. convertInt32LEToFloat (source, dest, numSamples);
  21825. break;
  21826. case int32BE:
  21827. convertInt32BEToFloat (source, dest, numSamples);
  21828. break;
  21829. case float32LE:
  21830. convertFloat32LEToFloat (source, dest, numSamples);
  21831. break;
  21832. case float32BE:
  21833. convertFloat32BEToFloat (source, dest, numSamples);
  21834. break;
  21835. default:
  21836. jassertfalse;
  21837. break;
  21838. }
  21839. }
  21840. void AudioDataConverters::interleaveSamples (const float** const source,
  21841. float* const dest,
  21842. const int numSamples,
  21843. const int numChannels)
  21844. {
  21845. for (int chan = 0; chan < numChannels; ++chan)
  21846. {
  21847. int i = chan;
  21848. const float* src = source [chan];
  21849. for (int j = 0; j < numSamples; ++j)
  21850. {
  21851. dest [i] = src [j];
  21852. i += numChannels;
  21853. }
  21854. }
  21855. }
  21856. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21857. float** const dest,
  21858. const int numSamples,
  21859. const int numChannels)
  21860. {
  21861. for (int chan = 0; chan < numChannels; ++chan)
  21862. {
  21863. int i = chan;
  21864. float* dst = dest [chan];
  21865. for (int j = 0; j < numSamples; ++j)
  21866. {
  21867. dst [j] = source [i];
  21868. i += numChannels;
  21869. }
  21870. }
  21871. }
  21872. END_JUCE_NAMESPACE
  21873. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21874. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21875. BEGIN_JUCE_NAMESPACE
  21876. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21877. const int numSamples) throw()
  21878. : numChannels (numChannels_),
  21879. size (numSamples)
  21880. {
  21881. jassert (numSamples >= 0);
  21882. jassert (numChannels_ > 0);
  21883. allocateData();
  21884. }
  21885. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21886. : numChannels (other.numChannels),
  21887. size (other.size)
  21888. {
  21889. allocateData();
  21890. const size_t numBytes = size * sizeof (float);
  21891. for (int i = 0; i < numChannels; ++i)
  21892. memcpy (channels[i], other.channels[i], numBytes);
  21893. }
  21894. void AudioSampleBuffer::allocateData()
  21895. {
  21896. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21897. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21898. allocatedData.malloc (allocatedBytes);
  21899. channels = reinterpret_cast <float**> (allocatedData.getData());
  21900. float* chan = (float*) (allocatedData + channelListSize);
  21901. for (int i = 0; i < numChannels; ++i)
  21902. {
  21903. channels[i] = chan;
  21904. chan += size;
  21905. }
  21906. channels [numChannels] = 0;
  21907. }
  21908. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21909. const int numChannels_,
  21910. const int numSamples) throw()
  21911. : numChannels (numChannels_),
  21912. size (numSamples),
  21913. allocatedBytes (0)
  21914. {
  21915. jassert (numChannels_ > 0);
  21916. allocateChannels (dataToReferTo);
  21917. }
  21918. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21919. const int newNumChannels,
  21920. const int newNumSamples) throw()
  21921. {
  21922. jassert (newNumChannels > 0);
  21923. allocatedBytes = 0;
  21924. allocatedData.free();
  21925. numChannels = newNumChannels;
  21926. size = newNumSamples;
  21927. allocateChannels (dataToReferTo);
  21928. }
  21929. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21930. {
  21931. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21932. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21933. {
  21934. channels = static_cast <float**> (preallocatedChannelSpace);
  21935. }
  21936. else
  21937. {
  21938. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21939. channels = reinterpret_cast <float**> (allocatedData.getData());
  21940. }
  21941. for (int i = 0; i < numChannels; ++i)
  21942. {
  21943. // you have to pass in the same number of valid pointers as numChannels
  21944. jassert (dataToReferTo[i] != 0);
  21945. channels[i] = dataToReferTo[i];
  21946. }
  21947. channels [numChannels] = 0;
  21948. }
  21949. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21950. {
  21951. if (this != &other)
  21952. {
  21953. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21954. const size_t numBytes = size * sizeof (float);
  21955. for (int i = 0; i < numChannels; ++i)
  21956. memcpy (channels[i], other.channels[i], numBytes);
  21957. }
  21958. return *this;
  21959. }
  21960. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21961. {
  21962. }
  21963. void AudioSampleBuffer::setSize (const int newNumChannels,
  21964. const int newNumSamples,
  21965. const bool keepExistingContent,
  21966. const bool clearExtraSpace,
  21967. const bool avoidReallocating) throw()
  21968. {
  21969. jassert (newNumChannels > 0);
  21970. if (newNumSamples != size || newNumChannels != numChannels)
  21971. {
  21972. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21973. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21974. if (keepExistingContent)
  21975. {
  21976. HeapBlock <char> newData;
  21977. newData.allocate (newTotalBytes, clearExtraSpace);
  21978. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21979. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21980. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21981. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21982. for (int i = 0; i < numChansToCopy; ++i)
  21983. {
  21984. memcpy (newChan, channels[i], numBytesToCopy);
  21985. newChannels[i] = newChan;
  21986. newChan += newNumSamples;
  21987. }
  21988. allocatedData.swapWith (newData);
  21989. allocatedBytes = (int) newTotalBytes;
  21990. channels = newChannels;
  21991. }
  21992. else
  21993. {
  21994. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21995. {
  21996. if (clearExtraSpace)
  21997. zeromem (allocatedData, newTotalBytes);
  21998. }
  21999. else
  22000. {
  22001. allocatedBytes = newTotalBytes;
  22002. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  22003. channels = reinterpret_cast <float**> (allocatedData.getData());
  22004. }
  22005. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  22006. for (int i = 0; i < newNumChannels; ++i)
  22007. {
  22008. channels[i] = chan;
  22009. chan += newNumSamples;
  22010. }
  22011. }
  22012. channels [newNumChannels] = 0;
  22013. size = newNumSamples;
  22014. numChannels = newNumChannels;
  22015. }
  22016. }
  22017. void AudioSampleBuffer::clear() throw()
  22018. {
  22019. for (int i = 0; i < numChannels; ++i)
  22020. zeromem (channels[i], size * sizeof (float));
  22021. }
  22022. void AudioSampleBuffer::clear (const int startSample,
  22023. const int numSamples) throw()
  22024. {
  22025. jassert (startSample >= 0 && startSample + numSamples <= size);
  22026. for (int i = 0; i < numChannels; ++i)
  22027. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  22028. }
  22029. void AudioSampleBuffer::clear (const int channel,
  22030. const int startSample,
  22031. const int numSamples) throw()
  22032. {
  22033. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22034. jassert (startSample >= 0 && startSample + numSamples <= size);
  22035. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  22036. }
  22037. void AudioSampleBuffer::applyGain (const int channel,
  22038. const int startSample,
  22039. int numSamples,
  22040. const float gain) throw()
  22041. {
  22042. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22043. jassert (startSample >= 0 && startSample + numSamples <= size);
  22044. if (gain != 1.0f)
  22045. {
  22046. float* d = channels [channel] + startSample;
  22047. if (gain == 0.0f)
  22048. {
  22049. zeromem (d, sizeof (float) * numSamples);
  22050. }
  22051. else
  22052. {
  22053. while (--numSamples >= 0)
  22054. *d++ *= gain;
  22055. }
  22056. }
  22057. }
  22058. void AudioSampleBuffer::applyGainRamp (const int channel,
  22059. const int startSample,
  22060. int numSamples,
  22061. float startGain,
  22062. float endGain) throw()
  22063. {
  22064. if (startGain == endGain)
  22065. {
  22066. applyGain (channel, startSample, numSamples, startGain);
  22067. }
  22068. else
  22069. {
  22070. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22071. jassert (startSample >= 0 && startSample + numSamples <= size);
  22072. const float increment = (endGain - startGain) / numSamples;
  22073. float* d = channels [channel] + startSample;
  22074. while (--numSamples >= 0)
  22075. {
  22076. *d++ *= startGain;
  22077. startGain += increment;
  22078. }
  22079. }
  22080. }
  22081. void AudioSampleBuffer::applyGain (const int startSample,
  22082. const int numSamples,
  22083. const float gain) throw()
  22084. {
  22085. for (int i = 0; i < numChannels; ++i)
  22086. applyGain (i, startSample, numSamples, gain);
  22087. }
  22088. void AudioSampleBuffer::addFrom (const int destChannel,
  22089. const int destStartSample,
  22090. const AudioSampleBuffer& source,
  22091. const int sourceChannel,
  22092. const int sourceStartSample,
  22093. int numSamples,
  22094. const float gain) throw()
  22095. {
  22096. jassert (&source != this || sourceChannel != destChannel);
  22097. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22098. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22099. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  22100. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  22101. if (gain != 0.0f && numSamples > 0)
  22102. {
  22103. float* d = channels [destChannel] + destStartSample;
  22104. const float* s = source.channels [sourceChannel] + sourceStartSample;
  22105. if (gain != 1.0f)
  22106. {
  22107. while (--numSamples >= 0)
  22108. *d++ += gain * *s++;
  22109. }
  22110. else
  22111. {
  22112. while (--numSamples >= 0)
  22113. *d++ += *s++;
  22114. }
  22115. }
  22116. }
  22117. void AudioSampleBuffer::addFrom (const int destChannel,
  22118. const int destStartSample,
  22119. const float* source,
  22120. int numSamples,
  22121. const float gain) throw()
  22122. {
  22123. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22124. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22125. jassert (source != 0);
  22126. if (gain != 0.0f && numSamples > 0)
  22127. {
  22128. float* d = channels [destChannel] + destStartSample;
  22129. if (gain != 1.0f)
  22130. {
  22131. while (--numSamples >= 0)
  22132. *d++ += gain * *source++;
  22133. }
  22134. else
  22135. {
  22136. while (--numSamples >= 0)
  22137. *d++ += *source++;
  22138. }
  22139. }
  22140. }
  22141. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  22142. const int destStartSample,
  22143. const float* source,
  22144. int numSamples,
  22145. float startGain,
  22146. const float endGain) throw()
  22147. {
  22148. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22149. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22150. jassert (source != 0);
  22151. if (startGain == endGain)
  22152. {
  22153. addFrom (destChannel,
  22154. destStartSample,
  22155. source,
  22156. numSamples,
  22157. startGain);
  22158. }
  22159. else
  22160. {
  22161. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22162. {
  22163. const float increment = (endGain - startGain) / numSamples;
  22164. float* d = channels [destChannel] + destStartSample;
  22165. while (--numSamples >= 0)
  22166. {
  22167. *d++ += startGain * *source++;
  22168. startGain += increment;
  22169. }
  22170. }
  22171. }
  22172. }
  22173. void AudioSampleBuffer::copyFrom (const int destChannel,
  22174. const int destStartSample,
  22175. const AudioSampleBuffer& source,
  22176. const int sourceChannel,
  22177. const int sourceStartSample,
  22178. int numSamples) throw()
  22179. {
  22180. jassert (&source != this || sourceChannel != destChannel);
  22181. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22182. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22183. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  22184. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  22185. if (numSamples > 0)
  22186. {
  22187. memcpy (channels [destChannel] + destStartSample,
  22188. source.channels [sourceChannel] + sourceStartSample,
  22189. sizeof (float) * numSamples);
  22190. }
  22191. }
  22192. void AudioSampleBuffer::copyFrom (const int destChannel,
  22193. const int destStartSample,
  22194. const float* source,
  22195. int numSamples) throw()
  22196. {
  22197. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22198. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22199. jassert (source != 0);
  22200. if (numSamples > 0)
  22201. {
  22202. memcpy (channels [destChannel] + destStartSample,
  22203. source,
  22204. sizeof (float) * numSamples);
  22205. }
  22206. }
  22207. void AudioSampleBuffer::copyFrom (const int destChannel,
  22208. const int destStartSample,
  22209. const float* source,
  22210. int numSamples,
  22211. const float gain) throw()
  22212. {
  22213. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22214. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22215. jassert (source != 0);
  22216. if (numSamples > 0)
  22217. {
  22218. float* d = channels [destChannel] + destStartSample;
  22219. if (gain != 1.0f)
  22220. {
  22221. if (gain == 0)
  22222. {
  22223. zeromem (d, sizeof (float) * numSamples);
  22224. }
  22225. else
  22226. {
  22227. while (--numSamples >= 0)
  22228. *d++ = gain * *source++;
  22229. }
  22230. }
  22231. else
  22232. {
  22233. memcpy (d, source, sizeof (float) * numSamples);
  22234. }
  22235. }
  22236. }
  22237. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  22238. const int destStartSample,
  22239. const float* source,
  22240. int numSamples,
  22241. float startGain,
  22242. float endGain) throw()
  22243. {
  22244. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22245. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22246. jassert (source != 0);
  22247. if (startGain == endGain)
  22248. {
  22249. copyFrom (destChannel,
  22250. destStartSample,
  22251. source,
  22252. numSamples,
  22253. startGain);
  22254. }
  22255. else
  22256. {
  22257. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22258. {
  22259. const float increment = (endGain - startGain) / numSamples;
  22260. float* d = channels [destChannel] + destStartSample;
  22261. while (--numSamples >= 0)
  22262. {
  22263. *d++ = startGain * *source++;
  22264. startGain += increment;
  22265. }
  22266. }
  22267. }
  22268. }
  22269. void AudioSampleBuffer::findMinMax (const int channel,
  22270. const int startSample,
  22271. int numSamples,
  22272. float& minVal,
  22273. float& maxVal) const throw()
  22274. {
  22275. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22276. jassert (startSample >= 0 && startSample + numSamples <= size);
  22277. if (numSamples <= 0)
  22278. {
  22279. minVal = 0.0f;
  22280. maxVal = 0.0f;
  22281. }
  22282. else
  22283. {
  22284. const float* d = channels [channel] + startSample;
  22285. float mn = *d++;
  22286. float mx = mn;
  22287. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  22288. {
  22289. const float samp = *d++;
  22290. if (samp > mx)
  22291. mx = samp;
  22292. if (samp < mn)
  22293. mn = samp;
  22294. }
  22295. maxVal = mx;
  22296. minVal = mn;
  22297. }
  22298. }
  22299. float AudioSampleBuffer::getMagnitude (const int channel,
  22300. const int startSample,
  22301. const int numSamples) const throw()
  22302. {
  22303. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22304. jassert (startSample >= 0 && startSample + numSamples <= size);
  22305. float mn, mx;
  22306. findMinMax (channel, startSample, numSamples, mn, mx);
  22307. return jmax (mn, -mn, mx, -mx);
  22308. }
  22309. float AudioSampleBuffer::getMagnitude (const int startSample,
  22310. const int numSamples) const throw()
  22311. {
  22312. float mag = 0.0f;
  22313. for (int i = 0; i < numChannels; ++i)
  22314. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22315. return mag;
  22316. }
  22317. float AudioSampleBuffer::getRMSLevel (const int channel,
  22318. const int startSample,
  22319. const int numSamples) const throw()
  22320. {
  22321. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22322. jassert (startSample >= 0 && startSample + numSamples <= size);
  22323. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22324. return 0.0f;
  22325. const float* const data = channels [channel] + startSample;
  22326. double sum = 0.0;
  22327. for (int i = 0; i < numSamples; ++i)
  22328. {
  22329. const float sample = data [i];
  22330. sum += sample * sample;
  22331. }
  22332. return (float) std::sqrt (sum / numSamples);
  22333. }
  22334. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22335. const int startSample,
  22336. const int numSamples,
  22337. const int readerStartSample,
  22338. const bool useLeftChan,
  22339. const bool useRightChan)
  22340. {
  22341. jassert (reader != 0);
  22342. jassert (startSample >= 0 && startSample + numSamples <= size);
  22343. if (numSamples > 0)
  22344. {
  22345. int* chans[3];
  22346. if (useLeftChan == useRightChan)
  22347. {
  22348. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22349. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22350. }
  22351. else if (useLeftChan || (reader->numChannels == 1))
  22352. {
  22353. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22354. chans[1] = 0;
  22355. }
  22356. else if (useRightChan)
  22357. {
  22358. chans[0] = 0;
  22359. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22360. }
  22361. chans[2] = 0;
  22362. reader->read (chans, 2, readerStartSample, numSamples, true);
  22363. if (! reader->usesFloatingPointData)
  22364. {
  22365. for (int j = 0; j < 2; ++j)
  22366. {
  22367. float* const d = reinterpret_cast <float*> (chans[j]);
  22368. if (d != 0)
  22369. {
  22370. const float multiplier = 1.0f / 0x7fffffff;
  22371. for (int i = 0; i < numSamples; ++i)
  22372. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22373. }
  22374. }
  22375. }
  22376. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22377. {
  22378. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22379. memcpy (getSampleData (1, startSample),
  22380. getSampleData (0, startSample),
  22381. sizeof (float) * numSamples);
  22382. }
  22383. }
  22384. }
  22385. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22386. const int startSample,
  22387. const int numSamples) const
  22388. {
  22389. jassert (startSample >= 0 && startSample + numSamples <= size && numChannels > 0);
  22390. if (numSamples > 0)
  22391. {
  22392. HeapBlock<int> tempBuffer;
  22393. HeapBlock<int*> chans (numChannels + 1);
  22394. chans [numChannels] = 0;
  22395. if (writer->isFloatingPoint())
  22396. {
  22397. for (int i = numChannels; --i >= 0;)
  22398. chans[i] = reinterpret_cast<int*> (channels[i] + startSample);
  22399. }
  22400. else
  22401. {
  22402. tempBuffer.malloc (numSamples * numChannels);
  22403. for (int j = 0; j < numChannels; ++j)
  22404. {
  22405. int* const dest = tempBuffer + j * numSamples;
  22406. const float* const src = channels[j] + startSample;
  22407. chans[j] = dest;
  22408. for (int i = 0; i < numSamples; ++i)
  22409. {
  22410. const double samp = src[i];
  22411. if (samp <= -1.0)
  22412. dest[i] = std::numeric_limits<int>::min();
  22413. else if (samp >= 1.0)
  22414. dest[i] = std::numeric_limits<int>::max();
  22415. else
  22416. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  22417. }
  22418. }
  22419. }
  22420. writer->write ((const int**) chans.getData(), numSamples);
  22421. }
  22422. }
  22423. END_JUCE_NAMESPACE
  22424. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22425. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22426. BEGIN_JUCE_NAMESPACE
  22427. IIRFilter::IIRFilter()
  22428. : active (false)
  22429. {
  22430. reset();
  22431. }
  22432. IIRFilter::IIRFilter (const IIRFilter& other)
  22433. : active (other.active)
  22434. {
  22435. const ScopedLock sl (other.processLock);
  22436. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22437. reset();
  22438. }
  22439. IIRFilter::~IIRFilter()
  22440. {
  22441. }
  22442. void IIRFilter::reset() throw()
  22443. {
  22444. const ScopedLock sl (processLock);
  22445. x1 = 0;
  22446. x2 = 0;
  22447. y1 = 0;
  22448. y2 = 0;
  22449. }
  22450. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22451. {
  22452. float out = coefficients[0] * in
  22453. + coefficients[1] * x1
  22454. + coefficients[2] * x2
  22455. - coefficients[4] * y1
  22456. - coefficients[5] * y2;
  22457. #if JUCE_INTEL
  22458. if (! (out < -1.0e-8 || out > 1.0e-8))
  22459. out = 0;
  22460. #endif
  22461. x2 = x1;
  22462. x1 = in;
  22463. y2 = y1;
  22464. y1 = out;
  22465. return out;
  22466. }
  22467. void IIRFilter::processSamples (float* const samples,
  22468. const int numSamples) throw()
  22469. {
  22470. const ScopedLock sl (processLock);
  22471. if (active)
  22472. {
  22473. for (int i = 0; i < numSamples; ++i)
  22474. {
  22475. const float in = samples[i];
  22476. float out = coefficients[0] * in
  22477. + coefficients[1] * x1
  22478. + coefficients[2] * x2
  22479. - coefficients[4] * y1
  22480. - coefficients[5] * y2;
  22481. #if JUCE_INTEL
  22482. if (! (out < -1.0e-8 || out > 1.0e-8))
  22483. out = 0;
  22484. #endif
  22485. x2 = x1;
  22486. x1 = in;
  22487. y2 = y1;
  22488. y1 = out;
  22489. samples[i] = out;
  22490. }
  22491. }
  22492. }
  22493. void IIRFilter::makeLowPass (const double sampleRate,
  22494. const double frequency) throw()
  22495. {
  22496. jassert (sampleRate > 0);
  22497. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22498. const double nSquared = n * n;
  22499. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22500. setCoefficients (c1,
  22501. c1 * 2.0f,
  22502. c1,
  22503. 1.0,
  22504. c1 * 2.0 * (1.0 - nSquared),
  22505. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22506. }
  22507. void IIRFilter::makeHighPass (const double sampleRate,
  22508. const double frequency) throw()
  22509. {
  22510. const double n = tan (double_Pi * frequency / sampleRate);
  22511. const double nSquared = n * n;
  22512. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22513. setCoefficients (c1,
  22514. c1 * -2.0f,
  22515. c1,
  22516. 1.0,
  22517. c1 * 2.0 * (nSquared - 1.0),
  22518. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22519. }
  22520. void IIRFilter::makeLowShelf (const double sampleRate,
  22521. const double cutOffFrequency,
  22522. const double Q,
  22523. const float gainFactor) throw()
  22524. {
  22525. jassert (sampleRate > 0);
  22526. jassert (Q > 0);
  22527. const double A = jmax (0.0f, gainFactor);
  22528. const double aminus1 = A - 1.0;
  22529. const double aplus1 = A + 1.0;
  22530. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22531. const double coso = std::cos (omega);
  22532. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22533. const double aminus1TimesCoso = aminus1 * coso;
  22534. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22535. A * 2.0 * (aminus1 - aplus1 * coso),
  22536. A * (aplus1 - aminus1TimesCoso - beta),
  22537. aplus1 + aminus1TimesCoso + beta,
  22538. -2.0 * (aminus1 + aplus1 * coso),
  22539. aplus1 + aminus1TimesCoso - beta);
  22540. }
  22541. void IIRFilter::makeHighShelf (const double sampleRate,
  22542. const double cutOffFrequency,
  22543. const double Q,
  22544. const float gainFactor) throw()
  22545. {
  22546. jassert (sampleRate > 0);
  22547. jassert (Q > 0);
  22548. const double A = jmax (0.0f, gainFactor);
  22549. const double aminus1 = A - 1.0;
  22550. const double aplus1 = A + 1.0;
  22551. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22552. const double coso = std::cos (omega);
  22553. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22554. const double aminus1TimesCoso = aminus1 * coso;
  22555. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22556. A * -2.0 * (aminus1 + aplus1 * coso),
  22557. A * (aplus1 + aminus1TimesCoso - beta),
  22558. aplus1 - aminus1TimesCoso + beta,
  22559. 2.0 * (aminus1 - aplus1 * coso),
  22560. aplus1 - aminus1TimesCoso - beta);
  22561. }
  22562. void IIRFilter::makeBandPass (const double sampleRate,
  22563. const double centreFrequency,
  22564. const double Q,
  22565. const float gainFactor) throw()
  22566. {
  22567. jassert (sampleRate > 0);
  22568. jassert (Q > 0);
  22569. const double A = jmax (0.0f, gainFactor);
  22570. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22571. const double alpha = 0.5 * std::sin (omega) / Q;
  22572. const double c2 = -2.0 * std::cos (omega);
  22573. const double alphaTimesA = alpha * A;
  22574. const double alphaOverA = alpha / A;
  22575. setCoefficients (1.0 + alphaTimesA,
  22576. c2,
  22577. 1.0 - alphaTimesA,
  22578. 1.0 + alphaOverA,
  22579. c2,
  22580. 1.0 - alphaOverA);
  22581. }
  22582. void IIRFilter::makeInactive() throw()
  22583. {
  22584. const ScopedLock sl (processLock);
  22585. active = false;
  22586. }
  22587. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22588. {
  22589. const ScopedLock sl (processLock);
  22590. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22591. active = other.active;
  22592. }
  22593. void IIRFilter::setCoefficients (double c1,
  22594. double c2,
  22595. double c3,
  22596. double c4,
  22597. double c5,
  22598. double c6) throw()
  22599. {
  22600. const double a = 1.0 / c4;
  22601. c1 *= a;
  22602. c2 *= a;
  22603. c3 *= a;
  22604. c5 *= a;
  22605. c6 *= a;
  22606. const ScopedLock sl (processLock);
  22607. coefficients[0] = (float) c1;
  22608. coefficients[1] = (float) c2;
  22609. coefficients[2] = (float) c3;
  22610. coefficients[3] = (float) c4;
  22611. coefficients[4] = (float) c5;
  22612. coefficients[5] = (float) c6;
  22613. active = true;
  22614. }
  22615. END_JUCE_NAMESPACE
  22616. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22617. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22618. BEGIN_JUCE_NAMESPACE
  22619. MidiBuffer::MidiBuffer() throw()
  22620. : bytesUsed (0)
  22621. {
  22622. }
  22623. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22624. : bytesUsed (0)
  22625. {
  22626. addEvent (message, 0);
  22627. }
  22628. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22629. : data (other.data),
  22630. bytesUsed (other.bytesUsed)
  22631. {
  22632. }
  22633. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22634. {
  22635. bytesUsed = other.bytesUsed;
  22636. data = other.data;
  22637. return *this;
  22638. }
  22639. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22640. {
  22641. data.swapWith (other.data);
  22642. swapVariables <int> (bytesUsed, other.bytesUsed);
  22643. }
  22644. MidiBuffer::~MidiBuffer()
  22645. {
  22646. }
  22647. inline uint8* MidiBuffer::getData() const throw()
  22648. {
  22649. return static_cast <uint8*> (data.getData());
  22650. }
  22651. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22652. {
  22653. return *static_cast <const int*> (d);
  22654. }
  22655. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22656. {
  22657. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22658. }
  22659. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22660. {
  22661. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22662. }
  22663. void MidiBuffer::clear() throw()
  22664. {
  22665. bytesUsed = 0;
  22666. }
  22667. void MidiBuffer::clear (const int startSample, const int numSamples)
  22668. {
  22669. uint8* const start = findEventAfter (getData(), startSample - 1);
  22670. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22671. if (end > start)
  22672. {
  22673. const int bytesToMove = bytesUsed - (int) (end - getData());
  22674. if (bytesToMove > 0)
  22675. memmove (start, end, bytesToMove);
  22676. bytesUsed -= (int) (end - start);
  22677. }
  22678. }
  22679. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22680. {
  22681. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22682. }
  22683. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22684. {
  22685. unsigned int byte = (unsigned int) *data;
  22686. int size = 0;
  22687. if (byte == 0xf0 || byte == 0xf7)
  22688. {
  22689. const uint8* d = data + 1;
  22690. while (d < data + maxBytes)
  22691. if (*d++ == 0xf7)
  22692. break;
  22693. size = (int) (d - data);
  22694. }
  22695. else if (byte == 0xff)
  22696. {
  22697. int n;
  22698. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22699. size = jmin (maxBytes, n + 2 + bytesLeft);
  22700. }
  22701. else if (byte >= 0x80)
  22702. {
  22703. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22704. }
  22705. return size;
  22706. }
  22707. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22708. {
  22709. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22710. if (numBytes > 0)
  22711. {
  22712. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22713. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22714. uint8* d = findEventAfter (getData(), sampleNumber);
  22715. const int bytesToMove = bytesUsed - (int) (d - getData());
  22716. if (bytesToMove > 0)
  22717. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22718. *reinterpret_cast <int*> (d) = sampleNumber;
  22719. d += sizeof (int);
  22720. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22721. d += sizeof (uint16);
  22722. memcpy (d, newData, numBytes);
  22723. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22724. }
  22725. }
  22726. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22727. const int startSample,
  22728. const int numSamples,
  22729. const int sampleDeltaToAdd)
  22730. {
  22731. Iterator i (otherBuffer);
  22732. i.setNextSamplePosition (startSample);
  22733. const uint8* eventData;
  22734. int eventSize, position;
  22735. while (i.getNextEvent (eventData, eventSize, position)
  22736. && (position < startSample + numSamples || numSamples < 0))
  22737. {
  22738. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22739. }
  22740. }
  22741. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22742. {
  22743. data.ensureSize (minimumNumBytes);
  22744. }
  22745. bool MidiBuffer::isEmpty() const throw()
  22746. {
  22747. return bytesUsed == 0;
  22748. }
  22749. int MidiBuffer::getNumEvents() const throw()
  22750. {
  22751. int n = 0;
  22752. const uint8* d = getData();
  22753. const uint8* const end = d + bytesUsed;
  22754. while (d < end)
  22755. {
  22756. d += getEventTotalSize (d);
  22757. ++n;
  22758. }
  22759. return n;
  22760. }
  22761. int MidiBuffer::getFirstEventTime() const throw()
  22762. {
  22763. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22764. }
  22765. int MidiBuffer::getLastEventTime() const throw()
  22766. {
  22767. if (bytesUsed == 0)
  22768. return 0;
  22769. const uint8* d = getData();
  22770. const uint8* const endData = d + bytesUsed;
  22771. for (;;)
  22772. {
  22773. const uint8* const nextOne = d + getEventTotalSize (d);
  22774. if (nextOne >= endData)
  22775. return getEventTime (d);
  22776. d = nextOne;
  22777. }
  22778. }
  22779. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22780. {
  22781. const uint8* const endData = getData() + bytesUsed;
  22782. while (d < endData && getEventTime (d) <= samplePosition)
  22783. d += getEventTotalSize (d);
  22784. return d;
  22785. }
  22786. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22787. : buffer (buffer_),
  22788. data (buffer_.getData())
  22789. {
  22790. }
  22791. MidiBuffer::Iterator::~Iterator() throw()
  22792. {
  22793. }
  22794. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22795. {
  22796. data = buffer.getData();
  22797. const uint8* dataEnd = data + buffer.bytesUsed;
  22798. while (data < dataEnd && getEventTime (data) < samplePosition)
  22799. data += getEventTotalSize (data);
  22800. }
  22801. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22802. {
  22803. if (data >= buffer.getData() + buffer.bytesUsed)
  22804. return false;
  22805. samplePosition = getEventTime (data);
  22806. numBytes = getEventDataSize (data);
  22807. data += sizeof (int) + sizeof (uint16);
  22808. midiData = data;
  22809. data += numBytes;
  22810. return true;
  22811. }
  22812. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22813. {
  22814. if (data >= buffer.getData() + buffer.bytesUsed)
  22815. return false;
  22816. samplePosition = getEventTime (data);
  22817. const int numBytes = getEventDataSize (data);
  22818. data += sizeof (int) + sizeof (uint16);
  22819. result = MidiMessage (data, numBytes, samplePosition);
  22820. data += numBytes;
  22821. return true;
  22822. }
  22823. END_JUCE_NAMESPACE
  22824. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22825. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22826. BEGIN_JUCE_NAMESPACE
  22827. namespace MidiFileHelpers
  22828. {
  22829. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22830. {
  22831. unsigned int buffer = v & 0x7F;
  22832. while ((v >>= 7) != 0)
  22833. {
  22834. buffer <<= 8;
  22835. buffer |= ((v & 0x7F) | 0x80);
  22836. }
  22837. for (;;)
  22838. {
  22839. out.writeByte ((char) buffer);
  22840. if (buffer & 0x80)
  22841. buffer >>= 8;
  22842. else
  22843. break;
  22844. }
  22845. }
  22846. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22847. {
  22848. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22849. data += 4;
  22850. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22851. {
  22852. bool ok = false;
  22853. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22854. {
  22855. for (int i = 0; i < 8; ++i)
  22856. {
  22857. ch = ByteOrder::bigEndianInt (data);
  22858. data += 4;
  22859. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22860. {
  22861. ok = true;
  22862. break;
  22863. }
  22864. }
  22865. }
  22866. if (! ok)
  22867. return false;
  22868. }
  22869. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22870. data += 4;
  22871. fileType = (short) ByteOrder::bigEndianShort (data);
  22872. data += 2;
  22873. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22874. data += 2;
  22875. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22876. data += 2;
  22877. bytesRemaining -= 6;
  22878. data += bytesRemaining;
  22879. return true;
  22880. }
  22881. static double convertTicksToSeconds (const double time,
  22882. const MidiMessageSequence& tempoEvents,
  22883. const int timeFormat)
  22884. {
  22885. if (timeFormat > 0)
  22886. {
  22887. int numer = 4, denom = 4;
  22888. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22889. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22890. double secsPerTick = 0.5 * tickLen;
  22891. const int numEvents = tempoEvents.getNumEvents();
  22892. for (int i = 0; i < numEvents; ++i)
  22893. {
  22894. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22895. if (time <= m.getTimeStamp())
  22896. break;
  22897. if (timeFormat > 0)
  22898. {
  22899. correctedTempoTime = correctedTempoTime
  22900. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22901. }
  22902. else
  22903. {
  22904. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22905. }
  22906. tempoTime = m.getTimeStamp();
  22907. if (m.isTempoMetaEvent())
  22908. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22909. else if (m.isTimeSignatureMetaEvent())
  22910. m.getTimeSignatureInfo (numer, denom);
  22911. while (i + 1 < numEvents)
  22912. {
  22913. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22914. if (m2.getTimeStamp() == tempoTime)
  22915. {
  22916. ++i;
  22917. if (m2.isTempoMetaEvent())
  22918. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22919. else if (m2.isTimeSignatureMetaEvent())
  22920. m2.getTimeSignatureInfo (numer, denom);
  22921. }
  22922. else
  22923. {
  22924. break;
  22925. }
  22926. }
  22927. }
  22928. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22929. }
  22930. else
  22931. {
  22932. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22933. }
  22934. }
  22935. // a comparator that puts all the note-offs before note-ons that have the same time
  22936. struct Sorter
  22937. {
  22938. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22939. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22940. {
  22941. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22942. if (diff == 0)
  22943. {
  22944. if (first->message.isNoteOff() && second->message.isNoteOn())
  22945. return -1;
  22946. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22947. return 1;
  22948. else
  22949. return 0;
  22950. }
  22951. else
  22952. {
  22953. return (diff > 0) ? 1 : -1;
  22954. }
  22955. }
  22956. };
  22957. }
  22958. MidiFile::MidiFile()
  22959. : timeFormat ((short) (unsigned short) 0xe728)
  22960. {
  22961. }
  22962. MidiFile::~MidiFile()
  22963. {
  22964. clear();
  22965. }
  22966. void MidiFile::clear()
  22967. {
  22968. tracks.clear();
  22969. }
  22970. int MidiFile::getNumTracks() const throw()
  22971. {
  22972. return tracks.size();
  22973. }
  22974. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22975. {
  22976. return tracks [index];
  22977. }
  22978. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22979. {
  22980. tracks.add (new MidiMessageSequence (trackSequence));
  22981. }
  22982. short MidiFile::getTimeFormat() const throw()
  22983. {
  22984. return timeFormat;
  22985. }
  22986. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22987. {
  22988. timeFormat = (short) ticks;
  22989. }
  22990. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22991. const int subframeResolution) throw()
  22992. {
  22993. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22994. }
  22995. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22996. {
  22997. for (int i = tracks.size(); --i >= 0;)
  22998. {
  22999. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  23000. for (int j = 0; j < numEvents; ++j)
  23001. {
  23002. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  23003. if (m.isTempoMetaEvent())
  23004. tempoChangeEvents.addEvent (m);
  23005. }
  23006. }
  23007. }
  23008. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  23009. {
  23010. for (int i = tracks.size(); --i >= 0;)
  23011. {
  23012. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  23013. for (int j = 0; j < numEvents; ++j)
  23014. {
  23015. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  23016. if (m.isTimeSignatureMetaEvent())
  23017. timeSigEvents.addEvent (m);
  23018. }
  23019. }
  23020. }
  23021. double MidiFile::getLastTimestamp() const
  23022. {
  23023. double t = 0.0;
  23024. for (int i = tracks.size(); --i >= 0;)
  23025. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  23026. return t;
  23027. }
  23028. bool MidiFile::readFrom (InputStream& sourceStream)
  23029. {
  23030. clear();
  23031. MemoryBlock data;
  23032. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  23033. // (put a sanity-check on the file size, as midi files are generally small)
  23034. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  23035. {
  23036. size_t size = data.getSize();
  23037. const uint8* d = static_cast <const uint8*> (data.getData());
  23038. short fileType, expectedTracks;
  23039. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  23040. {
  23041. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  23042. int track = 0;
  23043. while (size > 0 && track < expectedTracks)
  23044. {
  23045. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  23046. d += 4;
  23047. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  23048. d += 4;
  23049. if (chunkSize <= 0)
  23050. break;
  23051. if (size < 0)
  23052. return false;
  23053. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  23054. {
  23055. readNextTrack (d, chunkSize);
  23056. }
  23057. size -= chunkSize + 8;
  23058. d += chunkSize;
  23059. ++track;
  23060. }
  23061. return true;
  23062. }
  23063. }
  23064. return false;
  23065. }
  23066. void MidiFile::readNextTrack (const uint8* data, int size)
  23067. {
  23068. double time = 0;
  23069. char lastStatusByte = 0;
  23070. MidiMessageSequence result;
  23071. while (size > 0)
  23072. {
  23073. int bytesUsed;
  23074. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  23075. data += bytesUsed;
  23076. size -= bytesUsed;
  23077. time += delay;
  23078. int messSize = 0;
  23079. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  23080. if (messSize <= 0)
  23081. break;
  23082. size -= messSize;
  23083. data += messSize;
  23084. result.addEvent (mm);
  23085. const char firstByte = *(mm.getRawData());
  23086. if ((firstByte & 0xf0) != 0xf0)
  23087. lastStatusByte = firstByte;
  23088. }
  23089. // use a sort that puts all the note-offs before note-ons that have the same time
  23090. MidiFileHelpers::Sorter sorter;
  23091. result.list.sort (sorter, true);
  23092. result.updateMatchedPairs();
  23093. addTrack (result);
  23094. }
  23095. void MidiFile::convertTimestampTicksToSeconds()
  23096. {
  23097. MidiMessageSequence tempoEvents;
  23098. findAllTempoEvents (tempoEvents);
  23099. findAllTimeSigEvents (tempoEvents);
  23100. for (int i = 0; i < tracks.size(); ++i)
  23101. {
  23102. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  23103. for (int j = ms.getNumEvents(); --j >= 0;)
  23104. {
  23105. MidiMessage& m = ms.getEventPointer(j)->message;
  23106. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  23107. tempoEvents,
  23108. timeFormat));
  23109. }
  23110. }
  23111. }
  23112. bool MidiFile::writeTo (OutputStream& out)
  23113. {
  23114. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  23115. out.writeIntBigEndian (6);
  23116. out.writeShortBigEndian (1); // type
  23117. out.writeShortBigEndian ((short) tracks.size());
  23118. out.writeShortBigEndian (timeFormat);
  23119. for (int i = 0; i < tracks.size(); ++i)
  23120. writeTrack (out, i);
  23121. out.flush();
  23122. return true;
  23123. }
  23124. void MidiFile::writeTrack (OutputStream& mainOut,
  23125. const int trackNum)
  23126. {
  23127. MemoryOutputStream out;
  23128. const MidiMessageSequence& ms = *tracks[trackNum];
  23129. int lastTick = 0;
  23130. char lastStatusByte = 0;
  23131. for (int i = 0; i < ms.getNumEvents(); ++i)
  23132. {
  23133. const MidiMessage& mm = ms.getEventPointer(i)->message;
  23134. const int tick = roundToInt (mm.getTimeStamp());
  23135. const int delta = jmax (0, tick - lastTick);
  23136. MidiFileHelpers::writeVariableLengthInt (out, delta);
  23137. lastTick = tick;
  23138. const char statusByte = *(mm.getRawData());
  23139. if ((statusByte == lastStatusByte)
  23140. && ((statusByte & 0xf0) != 0xf0)
  23141. && i > 0
  23142. && mm.getRawDataSize() > 1)
  23143. {
  23144. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  23145. }
  23146. else
  23147. {
  23148. out.write (mm.getRawData(), mm.getRawDataSize());
  23149. }
  23150. lastStatusByte = statusByte;
  23151. }
  23152. out.writeByte (0);
  23153. const MidiMessage m (MidiMessage::endOfTrack());
  23154. out.write (m.getRawData(),
  23155. m.getRawDataSize());
  23156. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  23157. mainOut.writeIntBigEndian ((int) out.getDataSize());
  23158. mainOut.write (out.getData(), (int) out.getDataSize());
  23159. }
  23160. END_JUCE_NAMESPACE
  23161. /*** End of inlined file: juce_MidiFile.cpp ***/
  23162. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  23163. BEGIN_JUCE_NAMESPACE
  23164. MidiKeyboardState::MidiKeyboardState()
  23165. {
  23166. zerostruct (noteStates);
  23167. }
  23168. MidiKeyboardState::~MidiKeyboardState()
  23169. {
  23170. }
  23171. void MidiKeyboardState::reset()
  23172. {
  23173. const ScopedLock sl (lock);
  23174. zerostruct (noteStates);
  23175. eventsToAdd.clear();
  23176. }
  23177. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  23178. {
  23179. jassert (midiChannel >= 0 && midiChannel <= 16);
  23180. return ((unsigned int) n) < 128
  23181. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  23182. }
  23183. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  23184. {
  23185. return ((unsigned int) n) < 128
  23186. && (noteStates[n] & midiChannelMask) != 0;
  23187. }
  23188. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  23189. {
  23190. jassert (midiChannel >= 0 && midiChannel <= 16);
  23191. jassert (((unsigned int) midiNoteNumber) < 128);
  23192. const ScopedLock sl (lock);
  23193. if (((unsigned int) midiNoteNumber) < 128)
  23194. {
  23195. const int timeNow = (int) Time::getMillisecondCounter();
  23196. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  23197. eventsToAdd.clear (0, timeNow - 500);
  23198. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  23199. }
  23200. }
  23201. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  23202. {
  23203. if (((unsigned int) midiNoteNumber) < 128)
  23204. {
  23205. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  23206. for (int i = listeners.size(); --i >= 0;)
  23207. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  23208. }
  23209. }
  23210. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  23211. {
  23212. const ScopedLock sl (lock);
  23213. if (isNoteOn (midiChannel, midiNoteNumber))
  23214. {
  23215. const int timeNow = (int) Time::getMillisecondCounter();
  23216. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  23217. eventsToAdd.clear (0, timeNow - 500);
  23218. noteOffInternal (midiChannel, midiNoteNumber);
  23219. }
  23220. }
  23221. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  23222. {
  23223. if (isNoteOn (midiChannel, midiNoteNumber))
  23224. {
  23225. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  23226. for (int i = listeners.size(); --i >= 0;)
  23227. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  23228. }
  23229. }
  23230. void MidiKeyboardState::allNotesOff (const int midiChannel)
  23231. {
  23232. const ScopedLock sl (lock);
  23233. if (midiChannel <= 0)
  23234. {
  23235. for (int i = 1; i <= 16; ++i)
  23236. allNotesOff (i);
  23237. }
  23238. else
  23239. {
  23240. for (int i = 0; i < 128; ++i)
  23241. noteOff (midiChannel, i);
  23242. }
  23243. }
  23244. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  23245. {
  23246. if (message.isNoteOn())
  23247. {
  23248. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  23249. }
  23250. else if (message.isNoteOff())
  23251. {
  23252. noteOffInternal (message.getChannel(), message.getNoteNumber());
  23253. }
  23254. else if (message.isAllNotesOff())
  23255. {
  23256. for (int i = 0; i < 128; ++i)
  23257. noteOffInternal (message.getChannel(), i);
  23258. }
  23259. }
  23260. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  23261. const int startSample,
  23262. const int numSamples,
  23263. const bool injectIndirectEvents)
  23264. {
  23265. MidiBuffer::Iterator i (buffer);
  23266. MidiMessage message (0xf4, 0.0);
  23267. int time;
  23268. const ScopedLock sl (lock);
  23269. while (i.getNextEvent (message, time))
  23270. processNextMidiEvent (message);
  23271. if (injectIndirectEvents)
  23272. {
  23273. MidiBuffer::Iterator i2 (eventsToAdd);
  23274. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  23275. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  23276. while (i2.getNextEvent (message, time))
  23277. {
  23278. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  23279. buffer.addEvent (message, startSample + pos);
  23280. }
  23281. }
  23282. eventsToAdd.clear();
  23283. }
  23284. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  23285. {
  23286. const ScopedLock sl (lock);
  23287. listeners.addIfNotAlreadyThere (listener);
  23288. }
  23289. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  23290. {
  23291. const ScopedLock sl (lock);
  23292. listeners.removeValue (listener);
  23293. }
  23294. END_JUCE_NAMESPACE
  23295. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  23296. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  23297. BEGIN_JUCE_NAMESPACE
  23298. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23299. {
  23300. numBytesUsed = 0;
  23301. int v = 0;
  23302. int i;
  23303. do
  23304. {
  23305. i = (int) *data++;
  23306. if (++numBytesUsed > 6)
  23307. break;
  23308. v = (v << 7) + (i & 0x7f);
  23309. } while (i & 0x80);
  23310. return v;
  23311. }
  23312. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23313. {
  23314. // this method only works for valid starting bytes of a short midi message
  23315. jassert (firstByte >= 0x80
  23316. && firstByte != 0xf0
  23317. && firstByte != 0xf7);
  23318. static const char messageLengths[] =
  23319. {
  23320. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23321. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23322. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23323. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23324. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23325. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23326. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23327. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23328. };
  23329. return messageLengths [firstByte & 0x7f];
  23330. }
  23331. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23332. : timeStamp (t),
  23333. size (dataSize)
  23334. {
  23335. jassert (dataSize > 0);
  23336. if (dataSize <= 4)
  23337. data = static_cast<uint8*> (preallocatedData.asBytes);
  23338. else
  23339. data = new uint8 [dataSize];
  23340. memcpy (data, d, dataSize);
  23341. // check that the length matches the data..
  23342. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23343. }
  23344. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23345. : timeStamp (t),
  23346. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23347. size (1)
  23348. {
  23349. data[0] = (uint8) byte1;
  23350. // check that the length matches the data..
  23351. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23352. }
  23353. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23354. : timeStamp (t),
  23355. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23356. size (2)
  23357. {
  23358. data[0] = (uint8) byte1;
  23359. data[1] = (uint8) byte2;
  23360. // check that the length matches the data..
  23361. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23362. }
  23363. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23364. : timeStamp (t),
  23365. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23366. size (3)
  23367. {
  23368. data[0] = (uint8) byte1;
  23369. data[1] = (uint8) byte2;
  23370. data[2] = (uint8) byte3;
  23371. // check that the length matches the data..
  23372. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23373. }
  23374. MidiMessage::MidiMessage (const MidiMessage& other)
  23375. : timeStamp (other.timeStamp),
  23376. size (other.size)
  23377. {
  23378. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23379. {
  23380. data = new uint8 [size];
  23381. memcpy (data, other.data, size);
  23382. }
  23383. else
  23384. {
  23385. data = static_cast<uint8*> (preallocatedData.asBytes);
  23386. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23387. }
  23388. }
  23389. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23390. : timeStamp (newTimeStamp),
  23391. size (other.size)
  23392. {
  23393. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23394. {
  23395. data = new uint8 [size];
  23396. memcpy (data, other.data, size);
  23397. }
  23398. else
  23399. {
  23400. data = static_cast<uint8*> (preallocatedData.asBytes);
  23401. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23402. }
  23403. }
  23404. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23405. : timeStamp (t),
  23406. data (static_cast<uint8*> (preallocatedData.asBytes))
  23407. {
  23408. const uint8* src = static_cast <const uint8*> (src_);
  23409. unsigned int byte = (unsigned int) *src;
  23410. if (byte < 0x80)
  23411. {
  23412. byte = (unsigned int) (uint8) lastStatusByte;
  23413. numBytesUsed = -1;
  23414. }
  23415. else
  23416. {
  23417. numBytesUsed = 0;
  23418. --sz;
  23419. ++src;
  23420. }
  23421. if (byte >= 0x80)
  23422. {
  23423. if (byte == 0xf0)
  23424. {
  23425. const uint8* d = src;
  23426. while (d < src + sz)
  23427. {
  23428. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23429. {
  23430. if (*d == 0xf7) // include an 0xf7 if we hit one
  23431. ++d;
  23432. break;
  23433. }
  23434. ++d;
  23435. }
  23436. size = 1 + (int) (d - src);
  23437. data = new uint8 [size];
  23438. *data = (uint8) byte;
  23439. memcpy (data + 1, src, size - 1);
  23440. }
  23441. else if (byte == 0xff)
  23442. {
  23443. int n;
  23444. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23445. size = jmin (sz + 1, n + 2 + bytesLeft);
  23446. data = new uint8 [size];
  23447. *data = (uint8) byte;
  23448. memcpy (data + 1, src, size - 1);
  23449. }
  23450. else
  23451. {
  23452. preallocatedData.asInt32 = 0;
  23453. size = getMessageLengthFromFirstByte ((uint8) byte);
  23454. data[0] = (uint8) byte;
  23455. if (size > 1)
  23456. {
  23457. data[1] = src[0];
  23458. if (size > 2)
  23459. data[2] = src[1];
  23460. }
  23461. }
  23462. numBytesUsed += size;
  23463. }
  23464. else
  23465. {
  23466. preallocatedData.asInt32 = 0;
  23467. size = 0;
  23468. }
  23469. }
  23470. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23471. {
  23472. if (this != &other)
  23473. {
  23474. timeStamp = other.timeStamp;
  23475. size = other.size;
  23476. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23477. delete[] data;
  23478. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23479. {
  23480. data = new uint8 [size];
  23481. memcpy (data, other.data, size);
  23482. }
  23483. else
  23484. {
  23485. data = static_cast<uint8*> (preallocatedData.asBytes);
  23486. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23487. }
  23488. }
  23489. return *this;
  23490. }
  23491. MidiMessage::~MidiMessage()
  23492. {
  23493. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23494. delete[] data;
  23495. }
  23496. int MidiMessage::getChannel() const throw()
  23497. {
  23498. if ((data[0] & 0xf0) != 0xf0)
  23499. return (data[0] & 0xf) + 1;
  23500. else
  23501. return 0;
  23502. }
  23503. bool MidiMessage::isForChannel (const int channel) const throw()
  23504. {
  23505. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23506. return ((data[0] & 0xf) == channel - 1)
  23507. && ((data[0] & 0xf0) != 0xf0);
  23508. }
  23509. void MidiMessage::setChannel (const int channel) throw()
  23510. {
  23511. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23512. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23513. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23514. | (uint8)(channel - 1));
  23515. }
  23516. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23517. {
  23518. return ((data[0] & 0xf0) == 0x90)
  23519. && (returnTrueForVelocity0 || data[2] != 0);
  23520. }
  23521. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23522. {
  23523. return ((data[0] & 0xf0) == 0x80)
  23524. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23525. }
  23526. bool MidiMessage::isNoteOnOrOff() const throw()
  23527. {
  23528. const int d = data[0] & 0xf0;
  23529. return (d == 0x90) || (d == 0x80);
  23530. }
  23531. int MidiMessage::getNoteNumber() const throw()
  23532. {
  23533. return data[1];
  23534. }
  23535. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23536. {
  23537. if (isNoteOnOrOff())
  23538. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23539. }
  23540. uint8 MidiMessage::getVelocity() const throw()
  23541. {
  23542. if (isNoteOnOrOff())
  23543. return data[2];
  23544. else
  23545. return 0;
  23546. }
  23547. float MidiMessage::getFloatVelocity() const throw()
  23548. {
  23549. return getVelocity() * (1.0f / 127.0f);
  23550. }
  23551. void MidiMessage::setVelocity (const float newVelocity) throw()
  23552. {
  23553. if (isNoteOnOrOff())
  23554. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23555. }
  23556. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23557. {
  23558. if (isNoteOnOrOff())
  23559. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23560. }
  23561. bool MidiMessage::isAftertouch() const throw()
  23562. {
  23563. return (data[0] & 0xf0) == 0xa0;
  23564. }
  23565. int MidiMessage::getAfterTouchValue() const throw()
  23566. {
  23567. return data[2];
  23568. }
  23569. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23570. const int noteNum,
  23571. const int aftertouchValue) throw()
  23572. {
  23573. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23574. jassert (((unsigned int) noteNum) <= 127);
  23575. jassert (((unsigned int) aftertouchValue) <= 127);
  23576. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23577. noteNum & 0x7f,
  23578. aftertouchValue & 0x7f);
  23579. }
  23580. bool MidiMessage::isChannelPressure() const throw()
  23581. {
  23582. return (data[0] & 0xf0) == 0xd0;
  23583. }
  23584. int MidiMessage::getChannelPressureValue() const throw()
  23585. {
  23586. jassert (isChannelPressure());
  23587. return data[1];
  23588. }
  23589. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23590. const int pressure) throw()
  23591. {
  23592. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23593. jassert (((unsigned int) pressure) <= 127);
  23594. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23595. pressure & 0x7f);
  23596. }
  23597. bool MidiMessage::isProgramChange() const throw()
  23598. {
  23599. return (data[0] & 0xf0) == 0xc0;
  23600. }
  23601. int MidiMessage::getProgramChangeNumber() const throw()
  23602. {
  23603. return data[1];
  23604. }
  23605. const MidiMessage MidiMessage::programChange (const int channel,
  23606. const int programNumber) throw()
  23607. {
  23608. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23609. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23610. programNumber & 0x7f);
  23611. }
  23612. bool MidiMessage::isPitchWheel() const throw()
  23613. {
  23614. return (data[0] & 0xf0) == 0xe0;
  23615. }
  23616. int MidiMessage::getPitchWheelValue() const throw()
  23617. {
  23618. return data[1] | (data[2] << 7);
  23619. }
  23620. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23621. const int position) throw()
  23622. {
  23623. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23624. jassert (((unsigned int) position) <= 0x3fff);
  23625. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23626. position & 127,
  23627. (position >> 7) & 127);
  23628. }
  23629. bool MidiMessage::isController() const throw()
  23630. {
  23631. return (data[0] & 0xf0) == 0xb0;
  23632. }
  23633. int MidiMessage::getControllerNumber() const throw()
  23634. {
  23635. jassert (isController());
  23636. return data[1];
  23637. }
  23638. int MidiMessage::getControllerValue() const throw()
  23639. {
  23640. jassert (isController());
  23641. return data[2];
  23642. }
  23643. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23644. const int controllerType,
  23645. const int value) throw()
  23646. {
  23647. // the channel must be between 1 and 16 inclusive
  23648. jassert (channel > 0 && channel <= 16);
  23649. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23650. controllerType & 127,
  23651. value & 127);
  23652. }
  23653. const MidiMessage MidiMessage::noteOn (const int channel,
  23654. const int noteNumber,
  23655. const float velocity) throw()
  23656. {
  23657. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23658. }
  23659. const MidiMessage MidiMessage::noteOn (const int channel,
  23660. const int noteNumber,
  23661. const uint8 velocity) throw()
  23662. {
  23663. jassert (channel > 0 && channel <= 16);
  23664. jassert (((unsigned int) noteNumber) <= 127);
  23665. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23666. noteNumber & 127,
  23667. jlimit (0, 127, roundToInt (velocity)));
  23668. }
  23669. const MidiMessage MidiMessage::noteOff (const int channel,
  23670. const int noteNumber) throw()
  23671. {
  23672. jassert (channel > 0 && channel <= 16);
  23673. jassert (((unsigned int) noteNumber) <= 127);
  23674. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23675. }
  23676. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23677. {
  23678. return controllerEvent (channel, 123, 0);
  23679. }
  23680. bool MidiMessage::isAllNotesOff() const throw()
  23681. {
  23682. return (data[0] & 0xf0) == 0xb0
  23683. && data[1] == 123;
  23684. }
  23685. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23686. {
  23687. return controllerEvent (channel, 120, 0);
  23688. }
  23689. bool MidiMessage::isAllSoundOff() const throw()
  23690. {
  23691. return (data[0] & 0xf0) == 0xb0
  23692. && data[1] == 120;
  23693. }
  23694. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23695. {
  23696. return controllerEvent (channel, 121, 0);
  23697. }
  23698. const MidiMessage MidiMessage::masterVolume (const float volume)
  23699. {
  23700. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23701. uint8 buf[8];
  23702. buf[0] = 0xf0;
  23703. buf[1] = 0x7f;
  23704. buf[2] = 0x7f;
  23705. buf[3] = 0x04;
  23706. buf[4] = 0x01;
  23707. buf[5] = (uint8) (vol & 0x7f);
  23708. buf[6] = (uint8) (vol >> 7);
  23709. buf[7] = 0xf7;
  23710. return MidiMessage (buf, 8);
  23711. }
  23712. bool MidiMessage::isSysEx() const throw()
  23713. {
  23714. return *data == 0xf0;
  23715. }
  23716. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23717. {
  23718. MemoryBlock mm (dataSize + 2);
  23719. uint8* const m = static_cast <uint8*> (mm.getData());
  23720. m[0] = 0xf0;
  23721. memcpy (m + 1, sysexData, dataSize);
  23722. m[dataSize + 1] = 0xf7;
  23723. return MidiMessage (m, dataSize + 2);
  23724. }
  23725. const uint8* MidiMessage::getSysExData() const throw()
  23726. {
  23727. return (isSysEx()) ? getRawData() + 1 : 0;
  23728. }
  23729. int MidiMessage::getSysExDataSize() const throw()
  23730. {
  23731. return (isSysEx()) ? size - 2 : 0;
  23732. }
  23733. bool MidiMessage::isMetaEvent() const throw()
  23734. {
  23735. return *data == 0xff;
  23736. }
  23737. bool MidiMessage::isActiveSense() const throw()
  23738. {
  23739. return *data == 0xfe;
  23740. }
  23741. int MidiMessage::getMetaEventType() const throw()
  23742. {
  23743. if (*data != 0xff)
  23744. return -1;
  23745. else
  23746. return data[1];
  23747. }
  23748. int MidiMessage::getMetaEventLength() const throw()
  23749. {
  23750. if (*data == 0xff)
  23751. {
  23752. int n;
  23753. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23754. }
  23755. return 0;
  23756. }
  23757. const uint8* MidiMessage::getMetaEventData() const throw()
  23758. {
  23759. int n;
  23760. const uint8* d = data + 2;
  23761. readVariableLengthVal (d, n);
  23762. return d + n;
  23763. }
  23764. bool MidiMessage::isTrackMetaEvent() const throw()
  23765. {
  23766. return getMetaEventType() == 0;
  23767. }
  23768. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23769. {
  23770. return getMetaEventType() == 47;
  23771. }
  23772. bool MidiMessage::isTextMetaEvent() const throw()
  23773. {
  23774. const int t = getMetaEventType();
  23775. return t > 0 && t < 16;
  23776. }
  23777. const String MidiMessage::getTextFromTextMetaEvent() const
  23778. {
  23779. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23780. }
  23781. bool MidiMessage::isTrackNameEvent() const throw()
  23782. {
  23783. return (data[1] == 3)
  23784. && (*data == 0xff);
  23785. }
  23786. bool MidiMessage::isTempoMetaEvent() const throw()
  23787. {
  23788. return (data[1] == 81)
  23789. && (*data == 0xff);
  23790. }
  23791. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23792. {
  23793. return (data[1] == 0x20)
  23794. && (*data == 0xff)
  23795. && (data[2] == 1);
  23796. }
  23797. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23798. {
  23799. return data[3] + 1;
  23800. }
  23801. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23802. {
  23803. if (! isTempoMetaEvent())
  23804. return 0.0;
  23805. const uint8* const d = getMetaEventData();
  23806. return (((unsigned int) d[0] << 16)
  23807. | ((unsigned int) d[1] << 8)
  23808. | d[2])
  23809. / 1000000.0;
  23810. }
  23811. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23812. {
  23813. if (timeFormat > 0)
  23814. {
  23815. if (! isTempoMetaEvent())
  23816. return 0.5 / timeFormat;
  23817. return getTempoSecondsPerQuarterNote() / timeFormat;
  23818. }
  23819. else
  23820. {
  23821. const int frameCode = (-timeFormat) >> 8;
  23822. double framesPerSecond;
  23823. switch (frameCode)
  23824. {
  23825. case 24: framesPerSecond = 24.0; break;
  23826. case 25: framesPerSecond = 25.0; break;
  23827. case 29: framesPerSecond = 29.97; break;
  23828. case 30: framesPerSecond = 30.0; break;
  23829. default: framesPerSecond = 30.0; break;
  23830. }
  23831. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23832. }
  23833. }
  23834. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23835. {
  23836. uint8 d[8];
  23837. d[0] = 0xff;
  23838. d[1] = 81;
  23839. d[2] = 3;
  23840. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23841. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23842. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23843. return MidiMessage (d, 6, 0.0);
  23844. }
  23845. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23846. {
  23847. return (data[1] == 0x58)
  23848. && (*data == (uint8) 0xff);
  23849. }
  23850. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23851. {
  23852. if (isTimeSignatureMetaEvent())
  23853. {
  23854. const uint8* const d = getMetaEventData();
  23855. numerator = d[0];
  23856. denominator = 1 << d[1];
  23857. }
  23858. else
  23859. {
  23860. numerator = 4;
  23861. denominator = 4;
  23862. }
  23863. }
  23864. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23865. {
  23866. uint8 d[8];
  23867. d[0] = 0xff;
  23868. d[1] = 0x58;
  23869. d[2] = 0x04;
  23870. d[3] = (uint8) numerator;
  23871. int n = 1;
  23872. int powerOfTwo = 0;
  23873. while (n < denominator)
  23874. {
  23875. n <<= 1;
  23876. ++powerOfTwo;
  23877. }
  23878. d[4] = (uint8) powerOfTwo;
  23879. d[5] = 0x01;
  23880. d[6] = 96;
  23881. return MidiMessage (d, 7, 0.0);
  23882. }
  23883. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23884. {
  23885. uint8 d[8];
  23886. d[0] = 0xff;
  23887. d[1] = 0x20;
  23888. d[2] = 0x01;
  23889. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23890. return MidiMessage (d, 4, 0.0);
  23891. }
  23892. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23893. {
  23894. return getMetaEventType() == 89;
  23895. }
  23896. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23897. {
  23898. return (int) *getMetaEventData();
  23899. }
  23900. const MidiMessage MidiMessage::endOfTrack() throw()
  23901. {
  23902. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23903. }
  23904. bool MidiMessage::isSongPositionPointer() const throw()
  23905. {
  23906. return *data == 0xf2;
  23907. }
  23908. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23909. {
  23910. return data[1] | (data[2] << 7);
  23911. }
  23912. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23913. {
  23914. return MidiMessage (0xf2,
  23915. positionInMidiBeats & 127,
  23916. (positionInMidiBeats >> 7) & 127);
  23917. }
  23918. bool MidiMessage::isMidiStart() const throw()
  23919. {
  23920. return *data == 0xfa;
  23921. }
  23922. const MidiMessage MidiMessage::midiStart() throw()
  23923. {
  23924. return MidiMessage (0xfa);
  23925. }
  23926. bool MidiMessage::isMidiContinue() const throw()
  23927. {
  23928. return *data == 0xfb;
  23929. }
  23930. const MidiMessage MidiMessage::midiContinue() throw()
  23931. {
  23932. return MidiMessage (0xfb);
  23933. }
  23934. bool MidiMessage::isMidiStop() const throw()
  23935. {
  23936. return *data == 0xfc;
  23937. }
  23938. const MidiMessage MidiMessage::midiStop() throw()
  23939. {
  23940. return MidiMessage (0xfc);
  23941. }
  23942. bool MidiMessage::isMidiClock() const throw()
  23943. {
  23944. return *data == 0xf8;
  23945. }
  23946. const MidiMessage MidiMessage::midiClock() throw()
  23947. {
  23948. return MidiMessage (0xf8);
  23949. }
  23950. bool MidiMessage::isQuarterFrame() const throw()
  23951. {
  23952. return *data == 0xf1;
  23953. }
  23954. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23955. {
  23956. return ((int) data[1]) >> 4;
  23957. }
  23958. int MidiMessage::getQuarterFrameValue() const throw()
  23959. {
  23960. return ((int) data[1]) & 0x0f;
  23961. }
  23962. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23963. const int value) throw()
  23964. {
  23965. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23966. }
  23967. bool MidiMessage::isFullFrame() const throw()
  23968. {
  23969. return data[0] == 0xf0
  23970. && data[1] == 0x7f
  23971. && size >= 10
  23972. && data[3] == 0x01
  23973. && data[4] == 0x01;
  23974. }
  23975. void MidiMessage::getFullFrameParameters (int& hours,
  23976. int& minutes,
  23977. int& seconds,
  23978. int& frames,
  23979. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23980. {
  23981. jassert (isFullFrame());
  23982. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23983. hours = data[5] & 0x1f;
  23984. minutes = data[6];
  23985. seconds = data[7];
  23986. frames = data[8];
  23987. }
  23988. const MidiMessage MidiMessage::fullFrame (const int hours,
  23989. const int minutes,
  23990. const int seconds,
  23991. const int frames,
  23992. MidiMessage::SmpteTimecodeType timecodeType)
  23993. {
  23994. uint8 d[10];
  23995. d[0] = 0xf0;
  23996. d[1] = 0x7f;
  23997. d[2] = 0x7f;
  23998. d[3] = 0x01;
  23999. d[4] = 0x01;
  24000. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  24001. d[6] = (uint8) minutes;
  24002. d[7] = (uint8) seconds;
  24003. d[8] = (uint8) frames;
  24004. d[9] = 0xf7;
  24005. return MidiMessage (d, 10, 0.0);
  24006. }
  24007. bool MidiMessage::isMidiMachineControlMessage() const throw()
  24008. {
  24009. return data[0] == 0xf0
  24010. && data[1] == 0x7f
  24011. && data[3] == 0x06
  24012. && size > 5;
  24013. }
  24014. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  24015. {
  24016. jassert (isMidiMachineControlMessage());
  24017. return (MidiMachineControlCommand) data[4];
  24018. }
  24019. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  24020. {
  24021. uint8 d[6];
  24022. d[0] = 0xf0;
  24023. d[1] = 0x7f;
  24024. d[2] = 0x00;
  24025. d[3] = 0x06;
  24026. d[4] = (uint8) command;
  24027. d[5] = 0xf7;
  24028. return MidiMessage (d, 6, 0.0);
  24029. }
  24030. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  24031. int& minutes,
  24032. int& seconds,
  24033. int& frames) const throw()
  24034. {
  24035. if (size >= 12
  24036. && data[0] == 0xf0
  24037. && data[1] == 0x7f
  24038. && data[3] == 0x06
  24039. && data[4] == 0x44
  24040. && data[5] == 0x06
  24041. && data[6] == 0x01)
  24042. {
  24043. hours = data[7] % 24; // (that some machines send out hours > 24)
  24044. minutes = data[8];
  24045. seconds = data[9];
  24046. frames = data[10];
  24047. return true;
  24048. }
  24049. return false;
  24050. }
  24051. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  24052. int minutes,
  24053. int seconds,
  24054. int frames)
  24055. {
  24056. uint8 d[12];
  24057. d[0] = 0xf0;
  24058. d[1] = 0x7f;
  24059. d[2] = 0x00;
  24060. d[3] = 0x06;
  24061. d[4] = 0x44;
  24062. d[5] = 0x06;
  24063. d[6] = 0x01;
  24064. d[7] = (uint8) hours;
  24065. d[8] = (uint8) minutes;
  24066. d[9] = (uint8) seconds;
  24067. d[10] = (uint8) frames;
  24068. d[11] = 0xf7;
  24069. return MidiMessage (d, 12, 0.0);
  24070. }
  24071. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  24072. {
  24073. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  24074. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  24075. if (((unsigned int) note) < 128)
  24076. {
  24077. String s (useSharps ? sharpNoteNames [note % 12]
  24078. : flatNoteNames [note % 12]);
  24079. if (includeOctaveNumber)
  24080. s << (note / 12 + (octaveNumForMiddleC - 5));
  24081. return s;
  24082. }
  24083. return String::empty;
  24084. }
  24085. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  24086. {
  24087. noteNumber -= 12 * 6 + 9; // now 0 = A
  24088. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  24089. }
  24090. const String MidiMessage::getGMInstrumentName (const int n)
  24091. {
  24092. const char* names[] =
  24093. {
  24094. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  24095. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  24096. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  24097. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  24098. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  24099. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  24100. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  24101. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  24102. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  24103. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  24104. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  24105. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  24106. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  24107. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  24108. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  24109. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  24110. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  24111. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  24112. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  24113. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  24114. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  24115. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  24116. "Applause", "Gunshot"
  24117. };
  24118. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  24119. }
  24120. const String MidiMessage::getGMInstrumentBankName (const int n)
  24121. {
  24122. const char* names[] =
  24123. {
  24124. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  24125. "Bass", "Strings", "Ensemble", "Brass",
  24126. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  24127. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  24128. };
  24129. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  24130. }
  24131. const String MidiMessage::getRhythmInstrumentName (const int n)
  24132. {
  24133. const char* names[] =
  24134. {
  24135. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  24136. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  24137. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  24138. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  24139. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  24140. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  24141. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  24142. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  24143. "Mute Triangle", "Open Triangle"
  24144. };
  24145. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  24146. }
  24147. const String MidiMessage::getControllerName (const int n)
  24148. {
  24149. const char* names[] =
  24150. {
  24151. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  24152. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  24153. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  24154. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  24155. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  24156. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  24157. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  24158. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  24159. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  24160. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  24161. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  24162. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  24163. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  24164. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  24165. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  24166. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  24167. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  24168. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  24169. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  24170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  24171. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  24172. "Poly Operation"
  24173. };
  24174. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  24175. }
  24176. END_JUCE_NAMESPACE
  24177. /*** End of inlined file: juce_MidiMessage.cpp ***/
  24178. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  24179. BEGIN_JUCE_NAMESPACE
  24180. MidiMessageCollector::MidiMessageCollector()
  24181. : lastCallbackTime (0),
  24182. sampleRate (44100.0001)
  24183. {
  24184. }
  24185. MidiMessageCollector::~MidiMessageCollector()
  24186. {
  24187. }
  24188. void MidiMessageCollector::reset (const double sampleRate_)
  24189. {
  24190. jassert (sampleRate_ > 0);
  24191. const ScopedLock sl (midiCallbackLock);
  24192. sampleRate = sampleRate_;
  24193. incomingMessages.clear();
  24194. lastCallbackTime = Time::getMillisecondCounterHiRes();
  24195. }
  24196. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  24197. {
  24198. // you need to call reset() to set the correct sample rate before using this object
  24199. jassert (sampleRate != 44100.0001);
  24200. // the messages that come in here need to be time-stamped correctly - see MidiInput
  24201. // for details of what the number should be.
  24202. jassert (message.getTimeStamp() != 0);
  24203. const ScopedLock sl (midiCallbackLock);
  24204. const int sampleNumber
  24205. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  24206. incomingMessages.addEvent (message, sampleNumber);
  24207. // if the messages don't get used for over a second, we'd better
  24208. // get rid of any old ones to avoid the queue getting too big
  24209. if (sampleNumber > sampleRate)
  24210. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  24211. }
  24212. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  24213. const int numSamples)
  24214. {
  24215. // you need to call reset() to set the correct sample rate before using this object
  24216. jassert (sampleRate != 44100.0001);
  24217. const double timeNow = Time::getMillisecondCounterHiRes();
  24218. const double msElapsed = timeNow - lastCallbackTime;
  24219. const ScopedLock sl (midiCallbackLock);
  24220. lastCallbackTime = timeNow;
  24221. if (! incomingMessages.isEmpty())
  24222. {
  24223. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  24224. int startSample = 0;
  24225. int scale = 1 << 16;
  24226. const uint8* midiData;
  24227. int numBytes, samplePosition;
  24228. MidiBuffer::Iterator iter (incomingMessages);
  24229. if (numSourceSamples > numSamples)
  24230. {
  24231. // if our list of events is longer than the buffer we're being
  24232. // asked for, scale them down to squeeze them all in..
  24233. const int maxBlockLengthToUse = numSamples << 5;
  24234. if (numSourceSamples > maxBlockLengthToUse)
  24235. {
  24236. startSample = numSourceSamples - maxBlockLengthToUse;
  24237. numSourceSamples = maxBlockLengthToUse;
  24238. iter.setNextSamplePosition (startSample);
  24239. }
  24240. scale = (numSamples << 10) / numSourceSamples;
  24241. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24242. {
  24243. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  24244. destBuffer.addEvent (midiData, numBytes,
  24245. jlimit (0, numSamples - 1, samplePosition));
  24246. }
  24247. }
  24248. else
  24249. {
  24250. // if our event list is shorter than the number we need, put them
  24251. // towards the end of the buffer
  24252. startSample = numSamples - numSourceSamples;
  24253. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  24254. {
  24255. destBuffer.addEvent (midiData, numBytes,
  24256. jlimit (0, numSamples - 1, samplePosition + startSample));
  24257. }
  24258. }
  24259. incomingMessages.clear();
  24260. }
  24261. }
  24262. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  24263. {
  24264. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  24265. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24266. addMessageToQueue (m);
  24267. }
  24268. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  24269. {
  24270. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  24271. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24272. addMessageToQueue (m);
  24273. }
  24274. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  24275. {
  24276. addMessageToQueue (message);
  24277. }
  24278. END_JUCE_NAMESPACE
  24279. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  24280. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  24281. BEGIN_JUCE_NAMESPACE
  24282. MidiMessageSequence::MidiMessageSequence()
  24283. {
  24284. }
  24285. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  24286. {
  24287. list.ensureStorageAllocated (other.list.size());
  24288. for (int i = 0; i < other.list.size(); ++i)
  24289. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  24290. }
  24291. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  24292. {
  24293. MidiMessageSequence otherCopy (other);
  24294. swapWith (otherCopy);
  24295. return *this;
  24296. }
  24297. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  24298. {
  24299. list.swapWithArray (other.list);
  24300. }
  24301. MidiMessageSequence::~MidiMessageSequence()
  24302. {
  24303. }
  24304. void MidiMessageSequence::clear()
  24305. {
  24306. list.clear();
  24307. }
  24308. int MidiMessageSequence::getNumEvents() const
  24309. {
  24310. return list.size();
  24311. }
  24312. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24313. {
  24314. return list [index];
  24315. }
  24316. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24317. {
  24318. const MidiEventHolder* const meh = list [index];
  24319. if (meh != 0 && meh->noteOffObject != 0)
  24320. return meh->noteOffObject->message.getTimeStamp();
  24321. else
  24322. return 0.0;
  24323. }
  24324. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24325. {
  24326. const MidiEventHolder* const meh = list [index];
  24327. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24328. }
  24329. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24330. {
  24331. return list.indexOf (event);
  24332. }
  24333. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24334. {
  24335. const int numEvents = list.size();
  24336. int i;
  24337. for (i = 0; i < numEvents; ++i)
  24338. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24339. break;
  24340. return i;
  24341. }
  24342. double MidiMessageSequence::getStartTime() const
  24343. {
  24344. if (list.size() > 0)
  24345. return list.getUnchecked(0)->message.getTimeStamp();
  24346. else
  24347. return 0;
  24348. }
  24349. double MidiMessageSequence::getEndTime() const
  24350. {
  24351. if (list.size() > 0)
  24352. return list.getLast()->message.getTimeStamp();
  24353. else
  24354. return 0;
  24355. }
  24356. double MidiMessageSequence::getEventTime (const int index) const
  24357. {
  24358. if (((unsigned int) index) < (unsigned int) list.size())
  24359. return list.getUnchecked (index)->message.getTimeStamp();
  24360. return 0.0;
  24361. }
  24362. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24363. double timeAdjustment)
  24364. {
  24365. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24366. timeAdjustment += newMessage.getTimeStamp();
  24367. newOne->message.setTimeStamp (timeAdjustment);
  24368. int i;
  24369. for (i = list.size(); --i >= 0;)
  24370. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24371. break;
  24372. list.insert (i + 1, newOne);
  24373. }
  24374. void MidiMessageSequence::deleteEvent (const int index,
  24375. const bool deleteMatchingNoteUp)
  24376. {
  24377. if (((unsigned int) index) < (unsigned int) list.size())
  24378. {
  24379. if (deleteMatchingNoteUp)
  24380. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24381. list.remove (index);
  24382. }
  24383. }
  24384. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24385. double timeAdjustment,
  24386. double firstAllowableTime,
  24387. double endOfAllowableDestTimes)
  24388. {
  24389. firstAllowableTime -= timeAdjustment;
  24390. endOfAllowableDestTimes -= timeAdjustment;
  24391. for (int i = 0; i < other.list.size(); ++i)
  24392. {
  24393. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24394. const double t = m.getTimeStamp();
  24395. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24396. {
  24397. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24398. newOne->message.setTimeStamp (timeAdjustment + t);
  24399. list.add (newOne);
  24400. }
  24401. }
  24402. sort();
  24403. }
  24404. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24405. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24406. {
  24407. const double diff = first->message.getTimeStamp()
  24408. - second->message.getTimeStamp();
  24409. return (diff > 0) - (diff < 0);
  24410. }
  24411. void MidiMessageSequence::sort()
  24412. {
  24413. list.sort (*this, true);
  24414. }
  24415. void MidiMessageSequence::updateMatchedPairs()
  24416. {
  24417. for (int i = 0; i < list.size(); ++i)
  24418. {
  24419. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24420. if (m1.isNoteOn())
  24421. {
  24422. list.getUnchecked(i)->noteOffObject = 0;
  24423. const int note = m1.getNoteNumber();
  24424. const int chan = m1.getChannel();
  24425. const int len = list.size();
  24426. for (int j = i + 1; j < len; ++j)
  24427. {
  24428. const MidiMessage& m = list.getUnchecked(j)->message;
  24429. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24430. {
  24431. if (m.isNoteOff())
  24432. {
  24433. list.getUnchecked(i)->noteOffObject = list[j];
  24434. break;
  24435. }
  24436. else if (m.isNoteOn())
  24437. {
  24438. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24439. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24440. list.getUnchecked(i)->noteOffObject = list[j];
  24441. break;
  24442. }
  24443. }
  24444. }
  24445. }
  24446. }
  24447. }
  24448. void MidiMessageSequence::addTimeToMessages (const double delta)
  24449. {
  24450. for (int i = list.size(); --i >= 0;)
  24451. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24452. + delta);
  24453. }
  24454. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24455. MidiMessageSequence& destSequence,
  24456. const bool alsoIncludeMetaEvents) const
  24457. {
  24458. for (int i = 0; i < list.size(); ++i)
  24459. {
  24460. const MidiMessage& mm = list.getUnchecked(i)->message;
  24461. if (mm.isForChannel (channelNumberToExtract)
  24462. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24463. {
  24464. destSequence.addEvent (mm);
  24465. }
  24466. }
  24467. }
  24468. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24469. {
  24470. for (int i = 0; i < list.size(); ++i)
  24471. {
  24472. const MidiMessage& mm = list.getUnchecked(i)->message;
  24473. if (mm.isSysEx())
  24474. destSequence.addEvent (mm);
  24475. }
  24476. }
  24477. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24478. {
  24479. for (int i = list.size(); --i >= 0;)
  24480. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24481. list.remove(i);
  24482. }
  24483. void MidiMessageSequence::deleteSysExMessages()
  24484. {
  24485. for (int i = list.size(); --i >= 0;)
  24486. if (list.getUnchecked(i)->message.isSysEx())
  24487. list.remove(i);
  24488. }
  24489. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24490. const double time,
  24491. OwnedArray<MidiMessage>& dest)
  24492. {
  24493. bool doneProg = false;
  24494. bool donePitchWheel = false;
  24495. Array <int> doneControllers;
  24496. doneControllers.ensureStorageAllocated (32);
  24497. for (int i = list.size(); --i >= 0;)
  24498. {
  24499. const MidiMessage& mm = list.getUnchecked(i)->message;
  24500. if (mm.isForChannel (channelNumber)
  24501. && mm.getTimeStamp() <= time)
  24502. {
  24503. if (mm.isProgramChange())
  24504. {
  24505. if (! doneProg)
  24506. {
  24507. dest.add (new MidiMessage (mm, 0.0));
  24508. doneProg = true;
  24509. }
  24510. }
  24511. else if (mm.isController())
  24512. {
  24513. if (! doneControllers.contains (mm.getControllerNumber()))
  24514. {
  24515. dest.add (new MidiMessage (mm, 0.0));
  24516. doneControllers.add (mm.getControllerNumber());
  24517. }
  24518. }
  24519. else if (mm.isPitchWheel())
  24520. {
  24521. if (! donePitchWheel)
  24522. {
  24523. dest.add (new MidiMessage (mm, 0.0));
  24524. donePitchWheel = true;
  24525. }
  24526. }
  24527. }
  24528. }
  24529. }
  24530. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24531. : message (message_),
  24532. noteOffObject (0)
  24533. {
  24534. }
  24535. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24536. {
  24537. }
  24538. END_JUCE_NAMESPACE
  24539. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24540. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24541. BEGIN_JUCE_NAMESPACE
  24542. AudioPluginFormat::AudioPluginFormat() throw()
  24543. {
  24544. }
  24545. AudioPluginFormat::~AudioPluginFormat()
  24546. {
  24547. }
  24548. END_JUCE_NAMESPACE
  24549. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24550. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24551. BEGIN_JUCE_NAMESPACE
  24552. AudioPluginFormatManager::AudioPluginFormatManager()
  24553. {
  24554. }
  24555. AudioPluginFormatManager::~AudioPluginFormatManager()
  24556. {
  24557. clearSingletonInstance();
  24558. }
  24559. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24560. void AudioPluginFormatManager::addDefaultFormats()
  24561. {
  24562. #if JUCE_DEBUG
  24563. // you should only call this method once!
  24564. for (int i = formats.size(); --i >= 0;)
  24565. {
  24566. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24567. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24568. #endif
  24569. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24570. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24571. #endif
  24572. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24573. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24574. #endif
  24575. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24576. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24577. #endif
  24578. }
  24579. #endif
  24580. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24581. formats.add (new AudioUnitPluginFormat());
  24582. #endif
  24583. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24584. formats.add (new VSTPluginFormat());
  24585. #endif
  24586. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24587. formats.add (new DirectXPluginFormat());
  24588. #endif
  24589. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24590. formats.add (new LADSPAPluginFormat());
  24591. #endif
  24592. }
  24593. int AudioPluginFormatManager::getNumFormats()
  24594. {
  24595. return formats.size();
  24596. }
  24597. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24598. {
  24599. return formats [index];
  24600. }
  24601. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24602. {
  24603. formats.add (format);
  24604. }
  24605. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24606. String& errorMessage) const
  24607. {
  24608. AudioPluginInstance* result = 0;
  24609. for (int i = 0; i < formats.size(); ++i)
  24610. {
  24611. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24612. if (result != 0)
  24613. break;
  24614. }
  24615. if (result == 0)
  24616. {
  24617. if (! doesPluginStillExist (description))
  24618. errorMessage = TRANS ("This plug-in file no longer exists");
  24619. else
  24620. errorMessage = TRANS ("This plug-in failed to load correctly");
  24621. }
  24622. return result;
  24623. }
  24624. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24625. {
  24626. for (int i = 0; i < formats.size(); ++i)
  24627. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24628. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24629. return false;
  24630. }
  24631. END_JUCE_NAMESPACE
  24632. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24633. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24634. #define JUCE_PLUGIN_HOST 1
  24635. BEGIN_JUCE_NAMESPACE
  24636. AudioPluginInstance::AudioPluginInstance()
  24637. {
  24638. }
  24639. AudioPluginInstance::~AudioPluginInstance()
  24640. {
  24641. }
  24642. END_JUCE_NAMESPACE
  24643. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24644. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24645. BEGIN_JUCE_NAMESPACE
  24646. KnownPluginList::KnownPluginList()
  24647. {
  24648. }
  24649. KnownPluginList::~KnownPluginList()
  24650. {
  24651. }
  24652. void KnownPluginList::clear()
  24653. {
  24654. if (types.size() > 0)
  24655. {
  24656. types.clear();
  24657. sendChangeMessage (this);
  24658. }
  24659. }
  24660. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24661. {
  24662. for (int i = 0; i < types.size(); ++i)
  24663. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24664. return types.getUnchecked(i);
  24665. return 0;
  24666. }
  24667. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24668. {
  24669. for (int i = 0; i < types.size(); ++i)
  24670. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24671. return types.getUnchecked(i);
  24672. return 0;
  24673. }
  24674. bool KnownPluginList::addType (const PluginDescription& type)
  24675. {
  24676. for (int i = types.size(); --i >= 0;)
  24677. {
  24678. if (types.getUnchecked(i)->isDuplicateOf (type))
  24679. {
  24680. // strange - found a duplicate plugin with different info..
  24681. jassert (types.getUnchecked(i)->name == type.name);
  24682. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24683. *types.getUnchecked(i) = type;
  24684. return false;
  24685. }
  24686. }
  24687. types.add (new PluginDescription (type));
  24688. sendChangeMessage (this);
  24689. return true;
  24690. }
  24691. void KnownPluginList::removeType (const int index)
  24692. {
  24693. types.remove (index);
  24694. sendChangeMessage (this);
  24695. }
  24696. static const Time getPluginFileModTime (const String& fileOrIdentifier)
  24697. {
  24698. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24699. return File (fileOrIdentifier).getLastModificationTime();
  24700. return Time (0);
  24701. }
  24702. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24703. {
  24704. return t1 != t2 || t1 == Time (0);
  24705. }
  24706. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24707. {
  24708. if (getTypeForFile (fileOrIdentifier) == 0)
  24709. return false;
  24710. for (int i = types.size(); --i >= 0;)
  24711. {
  24712. const PluginDescription* const d = types.getUnchecked(i);
  24713. if (d->fileOrIdentifier == fileOrIdentifier
  24714. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24715. {
  24716. return false;
  24717. }
  24718. }
  24719. return true;
  24720. }
  24721. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24722. const bool dontRescanIfAlreadyInList,
  24723. OwnedArray <PluginDescription>& typesFound,
  24724. AudioPluginFormat& format)
  24725. {
  24726. bool addedOne = false;
  24727. if (dontRescanIfAlreadyInList
  24728. && getTypeForFile (fileOrIdentifier) != 0)
  24729. {
  24730. bool needsRescanning = false;
  24731. for (int i = types.size(); --i >= 0;)
  24732. {
  24733. const PluginDescription* const d = types.getUnchecked(i);
  24734. if (d->fileOrIdentifier == fileOrIdentifier)
  24735. {
  24736. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24737. needsRescanning = true;
  24738. else
  24739. typesFound.add (new PluginDescription (*d));
  24740. }
  24741. }
  24742. if (! needsRescanning)
  24743. return false;
  24744. }
  24745. OwnedArray <PluginDescription> found;
  24746. format.findAllTypesForFile (found, fileOrIdentifier);
  24747. for (int i = 0; i < found.size(); ++i)
  24748. {
  24749. PluginDescription* const desc = found.getUnchecked(i);
  24750. jassert (desc != 0);
  24751. if (addType (*desc))
  24752. addedOne = true;
  24753. typesFound.add (new PluginDescription (*desc));
  24754. }
  24755. return addedOne;
  24756. }
  24757. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24758. OwnedArray <PluginDescription>& typesFound)
  24759. {
  24760. for (int i = 0; i < files.size(); ++i)
  24761. {
  24762. bool loaded = false;
  24763. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24764. {
  24765. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24766. if (scanAndAddFile (files[i], true, typesFound, *format))
  24767. loaded = true;
  24768. }
  24769. if (! loaded)
  24770. {
  24771. const File f (files[i]);
  24772. if (f.isDirectory())
  24773. {
  24774. StringArray s;
  24775. {
  24776. Array<File> subFiles;
  24777. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24778. for (int j = 0; j < subFiles.size(); ++j)
  24779. s.add (subFiles.getReference(j).getFullPathName());
  24780. }
  24781. scanAndAddDragAndDroppedFiles (s, typesFound);
  24782. }
  24783. }
  24784. }
  24785. }
  24786. class PluginSorter
  24787. {
  24788. public:
  24789. KnownPluginList::SortMethod method;
  24790. PluginSorter() throw() {}
  24791. int compareElements (const PluginDescription* const first,
  24792. const PluginDescription* const second) const
  24793. {
  24794. int diff = 0;
  24795. if (method == KnownPluginList::sortByCategory)
  24796. diff = first->category.compareLexicographically (second->category);
  24797. else if (method == KnownPluginList::sortByManufacturer)
  24798. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24799. else if (method == KnownPluginList::sortByFileSystemLocation)
  24800. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24801. .upToLastOccurrenceOf ("/", false, false)
  24802. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24803. .upToLastOccurrenceOf ("/", false, false));
  24804. if (diff == 0)
  24805. diff = first->name.compareLexicographically (second->name);
  24806. return diff;
  24807. }
  24808. };
  24809. void KnownPluginList::sort (const SortMethod method)
  24810. {
  24811. if (method != defaultOrder)
  24812. {
  24813. PluginSorter sorter;
  24814. sorter.method = method;
  24815. types.sort (sorter, true);
  24816. sendChangeMessage (this);
  24817. }
  24818. }
  24819. XmlElement* KnownPluginList::createXml() const
  24820. {
  24821. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24822. for (int i = 0; i < types.size(); ++i)
  24823. e->addChildElement (types.getUnchecked(i)->createXml());
  24824. return e;
  24825. }
  24826. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24827. {
  24828. clear();
  24829. if (xml.hasTagName ("KNOWNPLUGINS"))
  24830. {
  24831. forEachXmlChildElement (xml, e)
  24832. {
  24833. PluginDescription info;
  24834. if (info.loadFromXml (*e))
  24835. addType (info);
  24836. }
  24837. }
  24838. }
  24839. const int menuIdBase = 0x324503f4;
  24840. // This is used to turn a bunch of paths into a nested menu structure.
  24841. struct PluginFilesystemTree
  24842. {
  24843. private:
  24844. String folder;
  24845. OwnedArray <PluginFilesystemTree> subFolders;
  24846. Array <PluginDescription*> plugins;
  24847. void addPlugin (PluginDescription* const pd, const String& path)
  24848. {
  24849. if (path.isEmpty())
  24850. {
  24851. plugins.add (pd);
  24852. }
  24853. else
  24854. {
  24855. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24856. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24857. for (int i = subFolders.size(); --i >= 0;)
  24858. {
  24859. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24860. {
  24861. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24862. return;
  24863. }
  24864. }
  24865. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24866. newFolder->folder = firstSubFolder;
  24867. subFolders.add (newFolder);
  24868. newFolder->addPlugin (pd, remainingPath);
  24869. }
  24870. }
  24871. // removes any deeply nested folders that don't contain any actual plugins
  24872. void optimise()
  24873. {
  24874. for (int i = subFolders.size(); --i >= 0;)
  24875. {
  24876. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24877. sub->optimise();
  24878. if (sub->plugins.size() == 0)
  24879. {
  24880. for (int j = 0; j < sub->subFolders.size(); ++j)
  24881. subFolders.add (sub->subFolders.getUnchecked(j));
  24882. sub->subFolders.clear (false);
  24883. subFolders.remove (i);
  24884. }
  24885. }
  24886. }
  24887. public:
  24888. void buildTree (const Array <PluginDescription*>& allPlugins)
  24889. {
  24890. for (int i = 0; i < allPlugins.size(); ++i)
  24891. {
  24892. String path (allPlugins.getUnchecked(i)
  24893. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24894. .upToLastOccurrenceOf ("/", false, false));
  24895. if (path.substring (1, 2) == ":")
  24896. path = path.substring (2);
  24897. addPlugin (allPlugins.getUnchecked(i), path);
  24898. }
  24899. optimise();
  24900. }
  24901. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24902. {
  24903. int i;
  24904. for (i = 0; i < subFolders.size(); ++i)
  24905. {
  24906. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24907. PopupMenu subMenu;
  24908. sub->addToMenu (subMenu, allPlugins);
  24909. #if JUCE_MAC
  24910. // avoid the special AU formatting nonsense on Mac..
  24911. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24912. #else
  24913. m.addSubMenu (sub->folder, subMenu);
  24914. #endif
  24915. }
  24916. for (i = 0; i < plugins.size(); ++i)
  24917. {
  24918. PluginDescription* const plugin = plugins.getUnchecked(i);
  24919. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24920. plugin->name, true, false);
  24921. }
  24922. }
  24923. };
  24924. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24925. {
  24926. Array <PluginDescription*> sorted;
  24927. {
  24928. PluginSorter sorter;
  24929. sorter.method = sortMethod;
  24930. for (int i = 0; i < types.size(); ++i)
  24931. sorted.addSorted (sorter, types.getUnchecked(i));
  24932. }
  24933. if (sortMethod == sortByCategory
  24934. || sortMethod == sortByManufacturer)
  24935. {
  24936. String lastSubMenuName;
  24937. PopupMenu sub;
  24938. for (int i = 0; i < sorted.size(); ++i)
  24939. {
  24940. const PluginDescription* const pd = sorted.getUnchecked(i);
  24941. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24942. : pd->manufacturerName);
  24943. if (! thisSubMenuName.containsNonWhitespaceChars())
  24944. thisSubMenuName = "Other";
  24945. if (thisSubMenuName != lastSubMenuName)
  24946. {
  24947. if (sub.getNumItems() > 0)
  24948. {
  24949. menu.addSubMenu (lastSubMenuName, sub);
  24950. sub.clear();
  24951. }
  24952. lastSubMenuName = thisSubMenuName;
  24953. }
  24954. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24955. }
  24956. if (sub.getNumItems() > 0)
  24957. menu.addSubMenu (lastSubMenuName, sub);
  24958. }
  24959. else if (sortMethod == sortByFileSystemLocation)
  24960. {
  24961. PluginFilesystemTree root;
  24962. root.buildTree (sorted);
  24963. root.addToMenu (menu, types);
  24964. }
  24965. else
  24966. {
  24967. for (int i = 0; i < sorted.size(); ++i)
  24968. {
  24969. const PluginDescription* const pd = sorted.getUnchecked(i);
  24970. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24971. }
  24972. }
  24973. }
  24974. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24975. {
  24976. const int i = menuResultCode - menuIdBase;
  24977. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24978. }
  24979. END_JUCE_NAMESPACE
  24980. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24981. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24982. BEGIN_JUCE_NAMESPACE
  24983. PluginDescription::PluginDescription()
  24984. : uid (0),
  24985. isInstrument (false),
  24986. numInputChannels (0),
  24987. numOutputChannels (0)
  24988. {
  24989. }
  24990. PluginDescription::~PluginDescription()
  24991. {
  24992. }
  24993. PluginDescription::PluginDescription (const PluginDescription& other)
  24994. : name (other.name),
  24995. pluginFormatName (other.pluginFormatName),
  24996. category (other.category),
  24997. manufacturerName (other.manufacturerName),
  24998. version (other.version),
  24999. fileOrIdentifier (other.fileOrIdentifier),
  25000. lastFileModTime (other.lastFileModTime),
  25001. uid (other.uid),
  25002. isInstrument (other.isInstrument),
  25003. numInputChannels (other.numInputChannels),
  25004. numOutputChannels (other.numOutputChannels)
  25005. {
  25006. }
  25007. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  25008. {
  25009. name = other.name;
  25010. pluginFormatName = other.pluginFormatName;
  25011. category = other.category;
  25012. manufacturerName = other.manufacturerName;
  25013. version = other.version;
  25014. fileOrIdentifier = other.fileOrIdentifier;
  25015. uid = other.uid;
  25016. isInstrument = other.isInstrument;
  25017. lastFileModTime = other.lastFileModTime;
  25018. numInputChannels = other.numInputChannels;
  25019. numOutputChannels = other.numOutputChannels;
  25020. return *this;
  25021. }
  25022. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  25023. {
  25024. return fileOrIdentifier == other.fileOrIdentifier
  25025. && uid == other.uid;
  25026. }
  25027. const String PluginDescription::createIdentifierString() const
  25028. {
  25029. return pluginFormatName
  25030. + "-" + name
  25031. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  25032. + "-" + String::toHexString (uid);
  25033. }
  25034. XmlElement* PluginDescription::createXml() const
  25035. {
  25036. XmlElement* const e = new XmlElement ("PLUGIN");
  25037. e->setAttribute ("name", name);
  25038. e->setAttribute ("format", pluginFormatName);
  25039. e->setAttribute ("category", category);
  25040. e->setAttribute ("manufacturer", manufacturerName);
  25041. e->setAttribute ("version", version);
  25042. e->setAttribute ("file", fileOrIdentifier);
  25043. e->setAttribute ("uid", String::toHexString (uid));
  25044. e->setAttribute ("isInstrument", isInstrument);
  25045. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  25046. e->setAttribute ("numInputs", numInputChannels);
  25047. e->setAttribute ("numOutputs", numOutputChannels);
  25048. return e;
  25049. }
  25050. bool PluginDescription::loadFromXml (const XmlElement& xml)
  25051. {
  25052. if (xml.hasTagName ("PLUGIN"))
  25053. {
  25054. name = xml.getStringAttribute ("name");
  25055. pluginFormatName = xml.getStringAttribute ("format");
  25056. category = xml.getStringAttribute ("category");
  25057. manufacturerName = xml.getStringAttribute ("manufacturer");
  25058. version = xml.getStringAttribute ("version");
  25059. fileOrIdentifier = xml.getStringAttribute ("file");
  25060. uid = xml.getStringAttribute ("uid").getHexValue32();
  25061. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  25062. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  25063. numInputChannels = xml.getIntAttribute ("numInputs");
  25064. numOutputChannels = xml.getIntAttribute ("numOutputs");
  25065. return true;
  25066. }
  25067. return false;
  25068. }
  25069. END_JUCE_NAMESPACE
  25070. /*** End of inlined file: juce_PluginDescription.cpp ***/
  25071. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  25072. BEGIN_JUCE_NAMESPACE
  25073. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  25074. AudioPluginFormat& formatToLookFor,
  25075. FileSearchPath directoriesToSearch,
  25076. const bool recursive,
  25077. const File& deadMansPedalFile_)
  25078. : list (listToAddTo),
  25079. format (formatToLookFor),
  25080. deadMansPedalFile (deadMansPedalFile_),
  25081. nextIndex (0),
  25082. progress (0)
  25083. {
  25084. directoriesToSearch.removeRedundantPaths();
  25085. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  25086. // If any plugins have crashed recently when being loaded, move them to the
  25087. // end of the list to give the others a chance to load correctly..
  25088. const StringArray crashedPlugins (getDeadMansPedalFile());
  25089. for (int i = 0; i < crashedPlugins.size(); ++i)
  25090. {
  25091. const String f = crashedPlugins[i];
  25092. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  25093. if (f == filesOrIdentifiersToScan[j])
  25094. filesOrIdentifiersToScan.move (j, -1);
  25095. }
  25096. }
  25097. PluginDirectoryScanner::~PluginDirectoryScanner()
  25098. {
  25099. }
  25100. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  25101. {
  25102. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  25103. }
  25104. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  25105. {
  25106. String file (filesOrIdentifiersToScan [nextIndex]);
  25107. if (file.isNotEmpty())
  25108. {
  25109. if (! list.isListingUpToDate (file))
  25110. {
  25111. OwnedArray <PluginDescription> typesFound;
  25112. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  25113. StringArray crashedPlugins (getDeadMansPedalFile());
  25114. crashedPlugins.removeString (file);
  25115. crashedPlugins.add (file);
  25116. setDeadMansPedalFile (crashedPlugins);
  25117. list.scanAndAddFile (file,
  25118. dontRescanIfAlreadyInList,
  25119. typesFound,
  25120. format);
  25121. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  25122. crashedPlugins.removeString (file);
  25123. setDeadMansPedalFile (crashedPlugins);
  25124. if (typesFound.size() == 0)
  25125. failedFiles.add (file);
  25126. }
  25127. ++nextIndex;
  25128. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  25129. }
  25130. return nextIndex < filesOrIdentifiersToScan.size();
  25131. }
  25132. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  25133. {
  25134. StringArray lines;
  25135. if (deadMansPedalFile != File::nonexistent)
  25136. {
  25137. lines.addLines (deadMansPedalFile.loadFileAsString());
  25138. lines.removeEmptyStrings();
  25139. }
  25140. return lines;
  25141. }
  25142. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  25143. {
  25144. if (deadMansPedalFile != File::nonexistent)
  25145. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  25146. }
  25147. END_JUCE_NAMESPACE
  25148. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  25149. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  25150. BEGIN_JUCE_NAMESPACE
  25151. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  25152. const File& deadMansPedalFile_,
  25153. PropertiesFile* const propertiesToUse_)
  25154. : list (listToEdit),
  25155. deadMansPedalFile (deadMansPedalFile_),
  25156. propertiesToUse (propertiesToUse_)
  25157. {
  25158. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  25159. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  25160. optionsButton->addButtonListener (this);
  25161. optionsButton->setTriggeredOnMouseDown (true);
  25162. setSize (400, 600);
  25163. list.addChangeListener (this);
  25164. changeListenerCallback (0);
  25165. }
  25166. PluginListComponent::~PluginListComponent()
  25167. {
  25168. list.removeChangeListener (this);
  25169. deleteAllChildren();
  25170. }
  25171. void PluginListComponent::resized()
  25172. {
  25173. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  25174. optionsButton->changeWidthToFitText (24);
  25175. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  25176. }
  25177. void PluginListComponent::changeListenerCallback (void*)
  25178. {
  25179. listBox->updateContent();
  25180. listBox->repaint();
  25181. }
  25182. int PluginListComponent::getNumRows()
  25183. {
  25184. return list.getNumTypes();
  25185. }
  25186. void PluginListComponent::paintListBoxItem (int row,
  25187. Graphics& g,
  25188. int width, int height,
  25189. bool rowIsSelected)
  25190. {
  25191. if (rowIsSelected)
  25192. g.fillAll (findColour (TextEditor::highlightColourId));
  25193. const PluginDescription* const pd = list.getType (row);
  25194. if (pd != 0)
  25195. {
  25196. GlyphArrangement ga;
  25197. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  25198. g.setColour (Colours::black);
  25199. ga.draw (g);
  25200. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  25201. String desc;
  25202. desc << pd->pluginFormatName
  25203. << (pd->isInstrument ? " instrument" : " effect")
  25204. << " - "
  25205. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  25206. << " / "
  25207. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  25208. if (pd->manufacturerName.isNotEmpty())
  25209. desc << " - " << pd->manufacturerName;
  25210. if (pd->version.isNotEmpty())
  25211. desc << " - " << pd->version;
  25212. if (pd->category.isNotEmpty())
  25213. desc << " - category: '" << pd->category << '\'';
  25214. g.setColour (Colours::grey);
  25215. ga.clear();
  25216. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  25217. ga.draw (g);
  25218. }
  25219. }
  25220. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  25221. {
  25222. list.removeType (lastRowSelected);
  25223. }
  25224. void PluginListComponent::buttonClicked (Button* b)
  25225. {
  25226. if (optionsButton == b)
  25227. {
  25228. PopupMenu menu;
  25229. menu.addItem (1, TRANS("Clear list"));
  25230. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  25231. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  25232. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  25233. menu.addSeparator();
  25234. menu.addItem (2, TRANS("Sort alphabetically"));
  25235. menu.addItem (3, TRANS("Sort by category"));
  25236. menu.addItem (4, TRANS("Sort by manufacturer"));
  25237. menu.addSeparator();
  25238. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  25239. {
  25240. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  25241. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  25242. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  25243. }
  25244. const int r = menu.showAt (optionsButton);
  25245. if (r == 1)
  25246. {
  25247. list.clear();
  25248. }
  25249. else if (r == 2)
  25250. {
  25251. list.sort (KnownPluginList::sortAlphabetically);
  25252. }
  25253. else if (r == 3)
  25254. {
  25255. list.sort (KnownPluginList::sortByCategory);
  25256. }
  25257. else if (r == 4)
  25258. {
  25259. list.sort (KnownPluginList::sortByManufacturer);
  25260. }
  25261. else if (r == 5)
  25262. {
  25263. const SparseSet <int> selected (listBox->getSelectedRows());
  25264. for (int i = list.getNumTypes(); --i >= 0;)
  25265. if (selected.contains (i))
  25266. list.removeType (i);
  25267. }
  25268. else if (r == 6)
  25269. {
  25270. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  25271. if (desc != 0)
  25272. {
  25273. if (File (desc->fileOrIdentifier).existsAsFile())
  25274. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  25275. }
  25276. }
  25277. else if (r == 7)
  25278. {
  25279. for (int i = list.getNumTypes(); --i >= 0;)
  25280. {
  25281. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  25282. {
  25283. list.removeType (i);
  25284. }
  25285. }
  25286. }
  25287. else if (r != 0)
  25288. {
  25289. typeToScan = r - 10;
  25290. startTimer (1);
  25291. }
  25292. }
  25293. }
  25294. void PluginListComponent::timerCallback()
  25295. {
  25296. stopTimer();
  25297. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25298. }
  25299. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25300. {
  25301. return true;
  25302. }
  25303. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25304. {
  25305. OwnedArray <PluginDescription> typesFound;
  25306. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25307. }
  25308. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25309. {
  25310. if (format == 0)
  25311. return;
  25312. FileSearchPath path (format->getDefaultLocationsToSearch());
  25313. if (propertiesToUse != 0)
  25314. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25315. {
  25316. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25317. FileSearchPathListComponent pathList;
  25318. pathList.setSize (500, 300);
  25319. pathList.setPath (path);
  25320. aw.addCustomComponent (&pathList);
  25321. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25322. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25323. if (aw.runModalLoop() == 0)
  25324. return;
  25325. path = pathList.getPath();
  25326. }
  25327. if (propertiesToUse != 0)
  25328. {
  25329. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25330. propertiesToUse->saveIfNeeded();
  25331. }
  25332. double progress = 0.0;
  25333. AlertWindow aw (TRANS("Scanning for plugins..."),
  25334. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25335. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25336. aw.addProgressBarComponent (progress);
  25337. aw.enterModalState();
  25338. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25339. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25340. for (;;)
  25341. {
  25342. aw.setMessage (TRANS("Testing:\n\n")
  25343. + scanner.getNextPluginFileThatWillBeScanned());
  25344. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25345. if (! scanner.scanNextFile (true))
  25346. break;
  25347. if (! aw.isCurrentlyModal())
  25348. break;
  25349. progress = scanner.getProgress();
  25350. }
  25351. if (scanner.getFailedFiles().size() > 0)
  25352. {
  25353. StringArray shortNames;
  25354. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25355. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25356. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25357. TRANS("Scan complete"),
  25358. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25359. + shortNames.joinIntoString (", "));
  25360. }
  25361. }
  25362. END_JUCE_NAMESPACE
  25363. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25364. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25365. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25366. #include <AudioUnit/AudioUnit.h>
  25367. #include <AudioUnit/AUCocoaUIView.h>
  25368. #include <CoreAudioKit/AUGenericView.h>
  25369. #if JUCE_SUPPORT_CARBON
  25370. #include <AudioToolbox/AudioUnitUtilities.h>
  25371. #include <AudioUnit/AudioUnitCarbonView.h>
  25372. #endif
  25373. BEGIN_JUCE_NAMESPACE
  25374. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25375. #endif
  25376. #if JUCE_MAC
  25377. // Change this to disable logging of various activities
  25378. #ifndef AU_LOGGING
  25379. #define AU_LOGGING 1
  25380. #endif
  25381. #if AU_LOGGING
  25382. #define log(a) Logger::writeToLog(a);
  25383. #else
  25384. #define log(a)
  25385. #endif
  25386. namespace AudioUnitFormatHelpers
  25387. {
  25388. static int insideCallback = 0;
  25389. static const String osTypeToString (OSType type)
  25390. {
  25391. char s[4];
  25392. s[0] = (char) (((uint32) type) >> 24);
  25393. s[1] = (char) (((uint32) type) >> 16);
  25394. s[2] = (char) (((uint32) type) >> 8);
  25395. s[3] = (char) ((uint32) type);
  25396. return String (s, 4);
  25397. }
  25398. static OSType stringToOSType (const String& s1)
  25399. {
  25400. const String s (s1 + " ");
  25401. return (((OSType) (unsigned char) s[0]) << 24)
  25402. | (((OSType) (unsigned char) s[1]) << 16)
  25403. | (((OSType) (unsigned char) s[2]) << 8)
  25404. | ((OSType) (unsigned char) s[3]);
  25405. }
  25406. static const char* auIdentifierPrefix = "AudioUnit:";
  25407. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25408. {
  25409. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25410. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25411. String s (auIdentifierPrefix);
  25412. if (desc.componentType == kAudioUnitType_MusicDevice)
  25413. s << "Synths/";
  25414. else if (desc.componentType == kAudioUnitType_MusicEffect
  25415. || desc.componentType == kAudioUnitType_Effect)
  25416. s << "Effects/";
  25417. else if (desc.componentType == kAudioUnitType_Generator)
  25418. s << "Generators/";
  25419. else if (desc.componentType == kAudioUnitType_Panner)
  25420. s << "Panners/";
  25421. s << osTypeToString (desc.componentType) << ","
  25422. << osTypeToString (desc.componentSubType) << ","
  25423. << osTypeToString (desc.componentManufacturer);
  25424. return s;
  25425. }
  25426. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25427. {
  25428. Handle componentNameHandle = NewHandle (sizeof (void*));
  25429. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25430. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25431. {
  25432. ComponentDescription desc;
  25433. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25434. {
  25435. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25436. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25437. if (nameString != 0 && nameString[0] != 0)
  25438. {
  25439. const String all ((const char*) nameString + 1, nameString[0]);
  25440. DBG ("name: "+ all);
  25441. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25442. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25443. }
  25444. if (infoString != 0 && infoString[0] != 0)
  25445. {
  25446. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25447. }
  25448. if (name.isEmpty())
  25449. name = "<Unknown>";
  25450. }
  25451. DisposeHandle (componentNameHandle);
  25452. DisposeHandle (componentInfoHandle);
  25453. }
  25454. }
  25455. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25456. String& name, String& version, String& manufacturer)
  25457. {
  25458. zerostruct (desc);
  25459. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25460. {
  25461. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25462. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25463. StringArray tokens;
  25464. tokens.addTokens (s, ",", String::empty);
  25465. tokens.trim();
  25466. tokens.removeEmptyStrings();
  25467. if (tokens.size() == 3)
  25468. {
  25469. desc.componentType = stringToOSType (tokens[0]);
  25470. desc.componentSubType = stringToOSType (tokens[1]);
  25471. desc.componentManufacturer = stringToOSType (tokens[2]);
  25472. ComponentRecord* comp = FindNextComponent (0, &desc);
  25473. if (comp != 0)
  25474. {
  25475. getAUDetails (comp, name, manufacturer);
  25476. return true;
  25477. }
  25478. }
  25479. }
  25480. return false;
  25481. }
  25482. }
  25483. class AudioUnitPluginWindowCarbon;
  25484. class AudioUnitPluginWindowCocoa;
  25485. class AudioUnitPluginInstance : public AudioPluginInstance
  25486. {
  25487. public:
  25488. ~AudioUnitPluginInstance();
  25489. // AudioPluginInstance methods:
  25490. void fillInPluginDescription (PluginDescription& desc) const
  25491. {
  25492. desc.name = pluginName;
  25493. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25494. desc.uid = ((int) componentDesc.componentType)
  25495. ^ ((int) componentDesc.componentSubType)
  25496. ^ ((int) componentDesc.componentManufacturer);
  25497. desc.lastFileModTime = 0;
  25498. desc.pluginFormatName = "AudioUnit";
  25499. desc.category = getCategory();
  25500. desc.manufacturerName = manufacturer;
  25501. desc.version = version;
  25502. desc.numInputChannels = getNumInputChannels();
  25503. desc.numOutputChannels = getNumOutputChannels();
  25504. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25505. }
  25506. const String getName() const { return pluginName; }
  25507. bool acceptsMidi() const { return wantsMidiMessages; }
  25508. bool producesMidi() const { return false; }
  25509. // AudioProcessor methods:
  25510. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25511. void releaseResources();
  25512. void processBlock (AudioSampleBuffer& buffer,
  25513. MidiBuffer& midiMessages);
  25514. AudioProcessorEditor* createEditor();
  25515. const String getInputChannelName (int index) const;
  25516. bool isInputChannelStereoPair (int index) const;
  25517. const String getOutputChannelName (int index) const;
  25518. bool isOutputChannelStereoPair (int index) const;
  25519. int getNumParameters();
  25520. float getParameter (int index);
  25521. void setParameter (int index, float newValue);
  25522. const String getParameterName (int index);
  25523. const String getParameterText (int index);
  25524. bool isParameterAutomatable (int index) const;
  25525. int getNumPrograms();
  25526. int getCurrentProgram();
  25527. void setCurrentProgram (int index);
  25528. const String getProgramName (int index);
  25529. void changeProgramName (int index, const String& newName);
  25530. void getStateInformation (MemoryBlock& destData);
  25531. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25532. void setStateInformation (const void* data, int sizeInBytes);
  25533. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25534. juce_UseDebuggingNewOperator
  25535. private:
  25536. friend class AudioUnitPluginWindowCarbon;
  25537. friend class AudioUnitPluginWindowCocoa;
  25538. friend class AudioUnitPluginFormat;
  25539. ComponentDescription componentDesc;
  25540. String pluginName, manufacturer, version;
  25541. String fileOrIdentifier;
  25542. CriticalSection lock;
  25543. bool initialised, wantsMidiMessages, wasPlaying;
  25544. HeapBlock <AudioBufferList> outputBufferList;
  25545. AudioTimeStamp timeStamp;
  25546. AudioSampleBuffer* currentBuffer;
  25547. AudioUnit audioUnit;
  25548. Array <int> parameterIds;
  25549. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25550. void initialise();
  25551. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25552. const AudioTimeStamp* inTimeStamp,
  25553. UInt32 inBusNumber,
  25554. UInt32 inNumberFrames,
  25555. AudioBufferList* ioData) const;
  25556. static OSStatus renderGetInputCallback (void* inRefCon,
  25557. AudioUnitRenderActionFlags* ioActionFlags,
  25558. const AudioTimeStamp* inTimeStamp,
  25559. UInt32 inBusNumber,
  25560. UInt32 inNumberFrames,
  25561. AudioBufferList* ioData)
  25562. {
  25563. return ((AudioUnitPluginInstance*) inRefCon)
  25564. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25565. }
  25566. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25567. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25568. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25569. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25570. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25571. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25572. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25573. {
  25574. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25575. }
  25576. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25577. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25578. Float64* outCurrentMeasureDownBeat)
  25579. {
  25580. return ((AudioUnitPluginInstance*) inHostUserData)
  25581. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25582. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25583. }
  25584. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25585. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25586. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25587. {
  25588. return ((AudioUnitPluginInstance*) inHostUserData)
  25589. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25590. outCurrentSampleInTimeLine, outIsCycling,
  25591. outCycleStartBeat, outCycleEndBeat);
  25592. }
  25593. void getNumChannels (int& numIns, int& numOuts)
  25594. {
  25595. numIns = 0;
  25596. numOuts = 0;
  25597. AUChannelInfo supportedChannels [128];
  25598. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25599. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25600. 0, supportedChannels, &supportedChannelsSize) == noErr
  25601. && supportedChannelsSize > 0)
  25602. {
  25603. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25604. {
  25605. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  25606. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  25607. }
  25608. }
  25609. else
  25610. {
  25611. // (this really means the plugin will take any number of ins/outs as long
  25612. // as they are the same)
  25613. numIns = numOuts = 2;
  25614. }
  25615. }
  25616. const String getCategory() const;
  25617. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25618. };
  25619. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25620. : fileOrIdentifier (fileOrIdentifier),
  25621. initialised (false),
  25622. wantsMidiMessages (false),
  25623. audioUnit (0),
  25624. currentBuffer (0)
  25625. {
  25626. using namespace AudioUnitFormatHelpers;
  25627. try
  25628. {
  25629. ++insideCallback;
  25630. log ("Opening AU: " + fileOrIdentifier);
  25631. if (getComponentDescFromFile (fileOrIdentifier))
  25632. {
  25633. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25634. if (comp != 0)
  25635. {
  25636. audioUnit = (AudioUnit) OpenComponent (comp);
  25637. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25638. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25639. }
  25640. }
  25641. --insideCallback;
  25642. }
  25643. catch (...)
  25644. {
  25645. --insideCallback;
  25646. }
  25647. }
  25648. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25649. {
  25650. const ScopedLock sl (lock);
  25651. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25652. if (audioUnit != 0)
  25653. {
  25654. AudioUnitUninitialize (audioUnit);
  25655. CloseComponent (audioUnit);
  25656. audioUnit = 0;
  25657. }
  25658. }
  25659. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25660. {
  25661. zerostruct (componentDesc);
  25662. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25663. return true;
  25664. const File file (fileOrIdentifier);
  25665. if (! file.hasFileExtension (".component"))
  25666. return false;
  25667. const char* const utf8 = fileOrIdentifier.toUTF8();
  25668. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25669. strlen (utf8), file.isDirectory());
  25670. if (url != 0)
  25671. {
  25672. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25673. CFRelease (url);
  25674. if (bundleRef != 0)
  25675. {
  25676. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25677. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25678. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25679. if (pluginName.isEmpty())
  25680. pluginName = file.getFileNameWithoutExtension();
  25681. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25682. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25683. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25684. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25685. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25686. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25687. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25688. UseResFile (resFileId);
  25689. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25690. {
  25691. Handle h = Get1IndResource ('thng', i);
  25692. if (h != 0)
  25693. {
  25694. HLock (h);
  25695. const uint32* const types = (const uint32*) *h;
  25696. if (types[0] == kAudioUnitType_MusicDevice
  25697. || types[0] == kAudioUnitType_MusicEffect
  25698. || types[0] == kAudioUnitType_Effect
  25699. || types[0] == kAudioUnitType_Generator
  25700. || types[0] == kAudioUnitType_Panner)
  25701. {
  25702. componentDesc.componentType = types[0];
  25703. componentDesc.componentSubType = types[1];
  25704. componentDesc.componentManufacturer = types[2];
  25705. break;
  25706. }
  25707. HUnlock (h);
  25708. ReleaseResource (h);
  25709. }
  25710. }
  25711. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25712. CFRelease (bundleRef);
  25713. }
  25714. }
  25715. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25716. }
  25717. void AudioUnitPluginInstance::initialise()
  25718. {
  25719. if (initialised || audioUnit == 0)
  25720. return;
  25721. log ("Initialising AU: " + pluginName);
  25722. parameterIds.clear();
  25723. {
  25724. UInt32 paramListSize = 0;
  25725. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25726. 0, 0, &paramListSize);
  25727. if (paramListSize > 0)
  25728. {
  25729. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25730. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25731. 0, &parameterIds.getReference(0), &paramListSize);
  25732. }
  25733. }
  25734. {
  25735. AURenderCallbackStruct info;
  25736. zerostruct (info);
  25737. info.inputProcRefCon = this;
  25738. info.inputProc = renderGetInputCallback;
  25739. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25740. 0, &info, sizeof (info));
  25741. }
  25742. {
  25743. HostCallbackInfo info;
  25744. zerostruct (info);
  25745. info.hostUserData = this;
  25746. info.beatAndTempoProc = getBeatAndTempoCallback;
  25747. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25748. info.transportStateProc = getTransportStateCallback;
  25749. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25750. 0, &info, sizeof (info));
  25751. }
  25752. int numIns, numOuts;
  25753. getNumChannels (numIns, numOuts);
  25754. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25755. initialised = AudioUnitInitialize (audioUnit) == noErr;
  25756. setLatencySamples (0);
  25757. }
  25758. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25759. int samplesPerBlockExpected)
  25760. {
  25761. if (audioUnit != 0)
  25762. {
  25763. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25764. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25765. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25766. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25767. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25768. {
  25769. if (initialised)
  25770. {
  25771. AudioUnitUninitialize (audioUnit);
  25772. initialised = false;
  25773. }
  25774. Float64 sr = sampleRate_;
  25775. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25776. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25777. }
  25778. }
  25779. initialise();
  25780. if (initialised)
  25781. {
  25782. int numIns, numOuts;
  25783. getNumChannels (numIns, numOuts);
  25784. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25785. Float64 latencySecs = 0.0;
  25786. UInt32 latencySize = sizeof (latencySecs);
  25787. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25788. 0, &latencySecs, &latencySize);
  25789. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25790. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25791. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25792. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25793. AudioStreamBasicDescription stream;
  25794. zerostruct (stream);
  25795. stream.mSampleRate = sampleRate_;
  25796. stream.mFormatID = kAudioFormatLinearPCM;
  25797. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25798. stream.mFramesPerPacket = 1;
  25799. stream.mBytesPerPacket = 4;
  25800. stream.mBytesPerFrame = 4;
  25801. stream.mBitsPerChannel = 32;
  25802. stream.mChannelsPerFrame = numIns;
  25803. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25804. 0, &stream, sizeof (stream));
  25805. stream.mChannelsPerFrame = numOuts;
  25806. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25807. 0, &stream, sizeof (stream));
  25808. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25809. outputBufferList->mNumberBuffers = numOuts;
  25810. for (int i = numOuts; --i >= 0;)
  25811. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25812. zerostruct (timeStamp);
  25813. timeStamp.mSampleTime = 0;
  25814. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25815. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25816. currentBuffer = 0;
  25817. wasPlaying = false;
  25818. }
  25819. }
  25820. void AudioUnitPluginInstance::releaseResources()
  25821. {
  25822. if (initialised)
  25823. {
  25824. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25825. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25826. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25827. outputBufferList.free();
  25828. currentBuffer = 0;
  25829. }
  25830. }
  25831. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25832. const AudioTimeStamp* inTimeStamp,
  25833. UInt32 inBusNumber,
  25834. UInt32 inNumberFrames,
  25835. AudioBufferList* ioData) const
  25836. {
  25837. if (inBusNumber == 0
  25838. && currentBuffer != 0)
  25839. {
  25840. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25841. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25842. {
  25843. if (i < currentBuffer->getNumChannels())
  25844. {
  25845. memcpy (ioData->mBuffers[i].mData,
  25846. currentBuffer->getSampleData (i, 0),
  25847. sizeof (float) * inNumberFrames);
  25848. }
  25849. else
  25850. {
  25851. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25852. }
  25853. }
  25854. }
  25855. return noErr;
  25856. }
  25857. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25858. MidiBuffer& midiMessages)
  25859. {
  25860. const int numSamples = buffer.getNumSamples();
  25861. if (initialised)
  25862. {
  25863. AudioUnitRenderActionFlags flags = 0;
  25864. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25865. for (int i = getNumOutputChannels(); --i >= 0;)
  25866. {
  25867. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25868. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25869. }
  25870. currentBuffer = &buffer;
  25871. if (wantsMidiMessages)
  25872. {
  25873. const uint8* midiEventData;
  25874. int midiEventSize, midiEventPosition;
  25875. MidiBuffer::Iterator i (midiMessages);
  25876. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25877. {
  25878. if (midiEventSize <= 3)
  25879. MusicDeviceMIDIEvent (audioUnit,
  25880. midiEventData[0], midiEventData[1], midiEventData[2],
  25881. midiEventPosition);
  25882. else
  25883. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25884. }
  25885. midiMessages.clear();
  25886. }
  25887. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25888. 0, numSamples, outputBufferList);
  25889. timeStamp.mSampleTime += numSamples;
  25890. }
  25891. else
  25892. {
  25893. // Not initialised, so just bypass..
  25894. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25895. buffer.clear (i, 0, buffer.getNumSamples());
  25896. }
  25897. }
  25898. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25899. {
  25900. AudioPlayHead* const ph = getPlayHead();
  25901. AudioPlayHead::CurrentPositionInfo result;
  25902. if (ph != 0 && ph->getCurrentPosition (result))
  25903. {
  25904. if (outCurrentBeat != 0)
  25905. *outCurrentBeat = result.ppqPosition;
  25906. if (outCurrentTempo != 0)
  25907. *outCurrentTempo = result.bpm;
  25908. }
  25909. else
  25910. {
  25911. if (outCurrentBeat != 0)
  25912. *outCurrentBeat = 0;
  25913. if (outCurrentTempo != 0)
  25914. *outCurrentTempo = 120.0;
  25915. }
  25916. return noErr;
  25917. }
  25918. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25919. Float32* outTimeSig_Numerator,
  25920. UInt32* outTimeSig_Denominator,
  25921. Float64* outCurrentMeasureDownBeat) const
  25922. {
  25923. AudioPlayHead* const ph = getPlayHead();
  25924. AudioPlayHead::CurrentPositionInfo result;
  25925. if (ph != 0 && ph->getCurrentPosition (result))
  25926. {
  25927. if (outTimeSig_Numerator != 0)
  25928. *outTimeSig_Numerator = result.timeSigNumerator;
  25929. if (outTimeSig_Denominator != 0)
  25930. *outTimeSig_Denominator = result.timeSigDenominator;
  25931. if (outDeltaSampleOffsetToNextBeat != 0)
  25932. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25933. if (outCurrentMeasureDownBeat != 0)
  25934. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25935. }
  25936. else
  25937. {
  25938. if (outDeltaSampleOffsetToNextBeat != 0)
  25939. *outDeltaSampleOffsetToNextBeat = 0;
  25940. if (outTimeSig_Numerator != 0)
  25941. *outTimeSig_Numerator = 4;
  25942. if (outTimeSig_Denominator != 0)
  25943. *outTimeSig_Denominator = 4;
  25944. if (outCurrentMeasureDownBeat != 0)
  25945. *outCurrentMeasureDownBeat = 0;
  25946. }
  25947. return noErr;
  25948. }
  25949. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25950. Boolean* outTransportStateChanged,
  25951. Float64* outCurrentSampleInTimeLine,
  25952. Boolean* outIsCycling,
  25953. Float64* outCycleStartBeat,
  25954. Float64* outCycleEndBeat)
  25955. {
  25956. AudioPlayHead* const ph = getPlayHead();
  25957. AudioPlayHead::CurrentPositionInfo result;
  25958. if (ph != 0 && ph->getCurrentPosition (result))
  25959. {
  25960. if (outIsPlaying != 0)
  25961. *outIsPlaying = result.isPlaying;
  25962. if (outTransportStateChanged != 0)
  25963. {
  25964. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25965. wasPlaying = result.isPlaying;
  25966. }
  25967. if (outCurrentSampleInTimeLine != 0)
  25968. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25969. if (outIsCycling != 0)
  25970. *outIsCycling = false;
  25971. if (outCycleStartBeat != 0)
  25972. *outCycleStartBeat = 0;
  25973. if (outCycleEndBeat != 0)
  25974. *outCycleEndBeat = 0;
  25975. }
  25976. else
  25977. {
  25978. if (outIsPlaying != 0)
  25979. *outIsPlaying = false;
  25980. if (outTransportStateChanged != 0)
  25981. *outTransportStateChanged = false;
  25982. if (outCurrentSampleInTimeLine != 0)
  25983. *outCurrentSampleInTimeLine = 0;
  25984. if (outIsCycling != 0)
  25985. *outIsCycling = false;
  25986. if (outCycleStartBeat != 0)
  25987. *outCycleStartBeat = 0;
  25988. if (outCycleEndBeat != 0)
  25989. *outCycleEndBeat = 0;
  25990. }
  25991. return noErr;
  25992. }
  25993. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  25994. {
  25995. public:
  25996. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25997. : AudioProcessorEditor (&plugin_),
  25998. plugin (plugin_)
  25999. {
  26000. addAndMakeVisible (&wrapper);
  26001. setOpaque (true);
  26002. setVisible (true);
  26003. setSize (100, 100);
  26004. createView (createGenericViewIfNeeded);
  26005. }
  26006. ~AudioUnitPluginWindowCocoa()
  26007. {
  26008. const bool wasValid = isValid();
  26009. wrapper.setView (0);
  26010. if (wasValid)
  26011. plugin.editorBeingDeleted (this);
  26012. }
  26013. bool isValid() const { return wrapper.getView() != 0; }
  26014. void paint (Graphics& g)
  26015. {
  26016. g.fillAll (Colours::white);
  26017. }
  26018. void resized()
  26019. {
  26020. wrapper.setSize (getWidth(), getHeight());
  26021. }
  26022. private:
  26023. AudioUnitPluginInstance& plugin;
  26024. NSViewComponent wrapper;
  26025. bool createView (const bool createGenericViewIfNeeded)
  26026. {
  26027. NSView* pluginView = 0;
  26028. UInt32 dataSize = 0;
  26029. Boolean isWritable = false;
  26030. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  26031. 0, &dataSize, &isWritable) == noErr
  26032. && dataSize != 0
  26033. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  26034. 0, &dataSize, &isWritable) == noErr)
  26035. {
  26036. HeapBlock <AudioUnitCocoaViewInfo> info;
  26037. info.calloc (dataSize, 1);
  26038. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  26039. 0, info, &dataSize) == noErr)
  26040. {
  26041. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  26042. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  26043. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  26044. Class viewClass = [viewBundle classNamed: viewClassName];
  26045. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  26046. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  26047. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  26048. {
  26049. id factory = [[[viewClass alloc] init] autorelease];
  26050. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  26051. withSize: NSMakeSize (getWidth(), getHeight())];
  26052. }
  26053. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  26054. {
  26055. CFRelease (info->mCocoaAUViewClass[i]);
  26056. CFRelease (info->mCocoaAUViewBundleLocation);
  26057. }
  26058. }
  26059. }
  26060. if (createGenericViewIfNeeded && (pluginView == 0))
  26061. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  26062. wrapper.setView (pluginView);
  26063. if (pluginView != 0)
  26064. setSize ([pluginView frame].size.width,
  26065. [pluginView frame].size.height);
  26066. return pluginView != 0;
  26067. }
  26068. };
  26069. #if JUCE_SUPPORT_CARBON
  26070. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  26071. {
  26072. public:
  26073. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  26074. : AudioProcessorEditor (&plugin_),
  26075. plugin (plugin_),
  26076. viewComponent (0)
  26077. {
  26078. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26079. setOpaque (true);
  26080. setVisible (true);
  26081. setSize (400, 300);
  26082. ComponentDescription viewList [16];
  26083. UInt32 viewListSize = sizeof (viewList);
  26084. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  26085. 0, &viewList, &viewListSize);
  26086. componentRecord = FindNextComponent (0, &viewList[0]);
  26087. }
  26088. ~AudioUnitPluginWindowCarbon()
  26089. {
  26090. innerWrapper = 0;
  26091. if (isValid())
  26092. plugin.editorBeingDeleted (this);
  26093. }
  26094. bool isValid() const throw() { return componentRecord != 0; }
  26095. void paint (Graphics& g)
  26096. {
  26097. g.fillAll (Colours::black);
  26098. }
  26099. void resized()
  26100. {
  26101. innerWrapper->setSize (getWidth(), getHeight());
  26102. }
  26103. bool keyStateChanged (bool)
  26104. {
  26105. return false;
  26106. }
  26107. bool keyPressed (const KeyPress&)
  26108. {
  26109. return false;
  26110. }
  26111. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  26112. AudioUnitCarbonView getViewComponent()
  26113. {
  26114. if (viewComponent == 0 && componentRecord != 0)
  26115. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  26116. return viewComponent;
  26117. }
  26118. void closeViewComponent()
  26119. {
  26120. if (viewComponent != 0)
  26121. {
  26122. log ("Closing AU GUI: " + plugin.getName());
  26123. CloseComponent (viewComponent);
  26124. viewComponent = 0;
  26125. }
  26126. }
  26127. juce_UseDebuggingNewOperator
  26128. private:
  26129. AudioUnitPluginInstance& plugin;
  26130. ComponentRecord* componentRecord;
  26131. AudioUnitCarbonView viewComponent;
  26132. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26133. {
  26134. public:
  26135. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  26136. : owner (owner_)
  26137. {
  26138. }
  26139. ~InnerWrapperComponent()
  26140. {
  26141. deleteWindow();
  26142. }
  26143. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26144. {
  26145. log ("Opening AU GUI: " + owner->plugin.getName());
  26146. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  26147. if (viewComponent == 0)
  26148. return 0;
  26149. Float32Point pos = { 0, 0 };
  26150. Float32Point size = { 250, 200 };
  26151. HIViewRef pluginView = 0;
  26152. AudioUnitCarbonViewCreate (viewComponent,
  26153. owner->getAudioUnit(),
  26154. windowRef,
  26155. rootView,
  26156. &pos,
  26157. &size,
  26158. (ControlRef*) &pluginView);
  26159. return pluginView;
  26160. }
  26161. void removeView (HIViewRef)
  26162. {
  26163. owner->closeViewComponent();
  26164. }
  26165. private:
  26166. AudioUnitPluginWindowCarbon* const owner;
  26167. };
  26168. friend class InnerWrapperComponent;
  26169. ScopedPointer<InnerWrapperComponent> innerWrapper;
  26170. };
  26171. #endif
  26172. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  26173. {
  26174. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  26175. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26176. w = 0;
  26177. #if JUCE_SUPPORT_CARBON
  26178. if (w == 0)
  26179. {
  26180. w = new AudioUnitPluginWindowCarbon (*this);
  26181. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  26182. w = 0;
  26183. }
  26184. #endif
  26185. if (w == 0)
  26186. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  26187. return w.release();
  26188. }
  26189. const String AudioUnitPluginInstance::getCategory() const
  26190. {
  26191. const char* result = 0;
  26192. switch (componentDesc.componentType)
  26193. {
  26194. case kAudioUnitType_Effect:
  26195. case kAudioUnitType_MusicEffect:
  26196. result = "Effect";
  26197. break;
  26198. case kAudioUnitType_MusicDevice:
  26199. result = "Synth";
  26200. break;
  26201. case kAudioUnitType_Generator:
  26202. result = "Generator";
  26203. break;
  26204. case kAudioUnitType_Panner:
  26205. result = "Panner";
  26206. break;
  26207. default:
  26208. break;
  26209. }
  26210. return result;
  26211. }
  26212. int AudioUnitPluginInstance::getNumParameters()
  26213. {
  26214. return parameterIds.size();
  26215. }
  26216. float AudioUnitPluginInstance::getParameter (int index)
  26217. {
  26218. const ScopedLock sl (lock);
  26219. Float32 value = 0.0f;
  26220. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26221. {
  26222. AudioUnitGetParameter (audioUnit,
  26223. (UInt32) parameterIds.getUnchecked (index),
  26224. kAudioUnitScope_Global, 0,
  26225. &value);
  26226. }
  26227. return value;
  26228. }
  26229. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  26230. {
  26231. const ScopedLock sl (lock);
  26232. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26233. {
  26234. AudioUnitSetParameter (audioUnit,
  26235. (UInt32) parameterIds.getUnchecked (index),
  26236. kAudioUnitScope_Global, 0,
  26237. newValue, 0);
  26238. }
  26239. }
  26240. const String AudioUnitPluginInstance::getParameterName (int index)
  26241. {
  26242. AudioUnitParameterInfo info;
  26243. zerostruct (info);
  26244. UInt32 sz = sizeof (info);
  26245. String name;
  26246. if (AudioUnitGetProperty (audioUnit,
  26247. kAudioUnitProperty_ParameterInfo,
  26248. kAudioUnitScope_Global,
  26249. parameterIds [index], &info, &sz) == noErr)
  26250. {
  26251. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26252. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26253. else
  26254. name = String (info.name, sizeof (info.name));
  26255. }
  26256. return name;
  26257. }
  26258. const String AudioUnitPluginInstance::getParameterText (int index)
  26259. {
  26260. return String (getParameter (index));
  26261. }
  26262. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26263. {
  26264. AudioUnitParameterInfo info;
  26265. UInt32 sz = sizeof (info);
  26266. if (AudioUnitGetProperty (audioUnit,
  26267. kAudioUnitProperty_ParameterInfo,
  26268. kAudioUnitScope_Global,
  26269. parameterIds [index], &info, &sz) == noErr)
  26270. {
  26271. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26272. }
  26273. return true;
  26274. }
  26275. int AudioUnitPluginInstance::getNumPrograms()
  26276. {
  26277. CFArrayRef presets;
  26278. UInt32 sz = sizeof (CFArrayRef);
  26279. int num = 0;
  26280. if (AudioUnitGetProperty (audioUnit,
  26281. kAudioUnitProperty_FactoryPresets,
  26282. kAudioUnitScope_Global,
  26283. 0, &presets, &sz) == noErr)
  26284. {
  26285. num = (int) CFArrayGetCount (presets);
  26286. CFRelease (presets);
  26287. }
  26288. return num;
  26289. }
  26290. int AudioUnitPluginInstance::getCurrentProgram()
  26291. {
  26292. AUPreset current;
  26293. current.presetNumber = 0;
  26294. UInt32 sz = sizeof (AUPreset);
  26295. AudioUnitGetProperty (audioUnit,
  26296. kAudioUnitProperty_FactoryPresets,
  26297. kAudioUnitScope_Global,
  26298. 0, &current, &sz);
  26299. return current.presetNumber;
  26300. }
  26301. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26302. {
  26303. AUPreset current;
  26304. current.presetNumber = newIndex;
  26305. current.presetName = 0;
  26306. AudioUnitSetProperty (audioUnit,
  26307. kAudioUnitProperty_FactoryPresets,
  26308. kAudioUnitScope_Global,
  26309. 0, &current, sizeof (AUPreset));
  26310. }
  26311. const String AudioUnitPluginInstance::getProgramName (int index)
  26312. {
  26313. String s;
  26314. CFArrayRef presets;
  26315. UInt32 sz = sizeof (CFArrayRef);
  26316. if (AudioUnitGetProperty (audioUnit,
  26317. kAudioUnitProperty_FactoryPresets,
  26318. kAudioUnitScope_Global,
  26319. 0, &presets, &sz) == noErr)
  26320. {
  26321. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26322. {
  26323. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26324. if (p != 0 && p->presetNumber == index)
  26325. {
  26326. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26327. break;
  26328. }
  26329. }
  26330. CFRelease (presets);
  26331. }
  26332. return s;
  26333. }
  26334. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26335. {
  26336. jassertfalse; // xxx not implemented!
  26337. }
  26338. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26339. {
  26340. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26341. return "Input " + String (index + 1);
  26342. return String::empty;
  26343. }
  26344. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26345. {
  26346. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26347. return false;
  26348. return true;
  26349. }
  26350. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26351. {
  26352. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26353. return "Output " + String (index + 1);
  26354. return String::empty;
  26355. }
  26356. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26357. {
  26358. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26359. return false;
  26360. return true;
  26361. }
  26362. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26363. {
  26364. getCurrentProgramStateInformation (destData);
  26365. }
  26366. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26367. {
  26368. CFPropertyListRef propertyList = 0;
  26369. UInt32 sz = sizeof (CFPropertyListRef);
  26370. if (AudioUnitGetProperty (audioUnit,
  26371. kAudioUnitProperty_ClassInfo,
  26372. kAudioUnitScope_Global,
  26373. 0, &propertyList, &sz) == noErr)
  26374. {
  26375. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26376. CFWriteStreamOpen (stream);
  26377. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26378. CFWriteStreamClose (stream);
  26379. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26380. destData.setSize (bytesWritten);
  26381. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26382. CFRelease (data);
  26383. CFRelease (stream);
  26384. CFRelease (propertyList);
  26385. }
  26386. }
  26387. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26388. {
  26389. setCurrentProgramStateInformation (data, sizeInBytes);
  26390. }
  26391. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26392. {
  26393. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26394. (const UInt8*) data,
  26395. sizeInBytes,
  26396. kCFAllocatorNull);
  26397. CFReadStreamOpen (stream);
  26398. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26399. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26400. stream,
  26401. 0,
  26402. kCFPropertyListImmutable,
  26403. &format,
  26404. 0);
  26405. CFRelease (stream);
  26406. if (propertyList != 0)
  26407. AudioUnitSetProperty (audioUnit,
  26408. kAudioUnitProperty_ClassInfo,
  26409. kAudioUnitScope_Global,
  26410. 0, &propertyList, sizeof (propertyList));
  26411. }
  26412. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26413. {
  26414. }
  26415. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26416. {
  26417. }
  26418. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26419. const String& fileOrIdentifier)
  26420. {
  26421. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26422. return;
  26423. PluginDescription desc;
  26424. desc.fileOrIdentifier = fileOrIdentifier;
  26425. desc.uid = 0;
  26426. try
  26427. {
  26428. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26429. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26430. if (auInstance != 0)
  26431. {
  26432. auInstance->fillInPluginDescription (desc);
  26433. results.add (new PluginDescription (desc));
  26434. }
  26435. }
  26436. catch (...)
  26437. {
  26438. // crashed while loading...
  26439. }
  26440. }
  26441. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26442. {
  26443. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26444. {
  26445. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26446. if (result->audioUnit != 0)
  26447. {
  26448. result->initialise();
  26449. return result.release();
  26450. }
  26451. }
  26452. return 0;
  26453. }
  26454. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26455. const bool /*recursive*/)
  26456. {
  26457. StringArray result;
  26458. ComponentRecord* comp = 0;
  26459. ComponentDescription desc;
  26460. zerostruct (desc);
  26461. for (;;)
  26462. {
  26463. zerostruct (desc);
  26464. comp = FindNextComponent (comp, &desc);
  26465. if (comp == 0)
  26466. break;
  26467. GetComponentInfo (comp, &desc, 0, 0, 0);
  26468. if (desc.componentType == kAudioUnitType_MusicDevice
  26469. || desc.componentType == kAudioUnitType_MusicEffect
  26470. || desc.componentType == kAudioUnitType_Effect
  26471. || desc.componentType == kAudioUnitType_Generator
  26472. || desc.componentType == kAudioUnitType_Panner)
  26473. {
  26474. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26475. DBG (s);
  26476. result.add (s);
  26477. }
  26478. }
  26479. return result;
  26480. }
  26481. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26482. {
  26483. ComponentDescription desc;
  26484. String name, version, manufacturer;
  26485. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26486. return FindNextComponent (0, &desc) != 0;
  26487. const File f (fileOrIdentifier);
  26488. return f.hasFileExtension (".component")
  26489. && f.isDirectory();
  26490. }
  26491. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26492. {
  26493. ComponentDescription desc;
  26494. String name, version, manufacturer;
  26495. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26496. if (name.isEmpty())
  26497. name = fileOrIdentifier;
  26498. return name;
  26499. }
  26500. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26501. {
  26502. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26503. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26504. else
  26505. return File (desc.fileOrIdentifier).exists();
  26506. }
  26507. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26508. {
  26509. return FileSearchPath ("/(Default AudioUnit locations)");
  26510. }
  26511. #endif
  26512. END_JUCE_NAMESPACE
  26513. #undef log
  26514. #endif
  26515. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26516. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26517. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26518. #define JUCE_MAC_VST_INCLUDED 1
  26519. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26520. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26521. #if JUCE_WINDOWS
  26522. #undef _WIN32_WINNT
  26523. #define _WIN32_WINNT 0x500
  26524. #undef STRICT
  26525. #define STRICT
  26526. #include <windows.h>
  26527. #include <float.h>
  26528. #pragma warning (disable : 4312 4355)
  26529. #elif JUCE_LINUX
  26530. #include <float.h>
  26531. #include <sys/time.h>
  26532. #include <X11/Xlib.h>
  26533. #include <X11/Xutil.h>
  26534. #include <X11/Xatom.h>
  26535. #undef Font
  26536. #undef KeyPress
  26537. #undef Drawable
  26538. #undef Time
  26539. #else
  26540. #include <Cocoa/Cocoa.h>
  26541. #include <Carbon/Carbon.h>
  26542. #endif
  26543. #if ! (JUCE_MAC && JUCE_64BIT)
  26544. BEGIN_JUCE_NAMESPACE
  26545. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26546. #endif
  26547. #undef PRAGMA_ALIGN_SUPPORTED
  26548. #define VST_FORCE_DEPRECATED 0
  26549. #if JUCE_MSVC
  26550. #pragma warning (push)
  26551. #pragma warning (disable: 4996)
  26552. #endif
  26553. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26554. your include path if you want to add VST support.
  26555. If you're not interested in VSTs, you can disable them by changing the
  26556. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26557. */
  26558. #include "pluginterfaces/vst2.x/aeffectx.h"
  26559. #if JUCE_MSVC
  26560. #pragma warning (pop)
  26561. #endif
  26562. #if JUCE_LINUX
  26563. #define Font JUCE_NAMESPACE::Font
  26564. #define KeyPress JUCE_NAMESPACE::KeyPress
  26565. #define Drawable JUCE_NAMESPACE::Drawable
  26566. #define Time JUCE_NAMESPACE::Time
  26567. #endif
  26568. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26569. #ifdef __aeffect__
  26570. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26571. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26572. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26573. events to the list.
  26574. This is used by both the VST hosting code and the plugin wrapper.
  26575. */
  26576. class VSTMidiEventList
  26577. {
  26578. public:
  26579. VSTMidiEventList()
  26580. : numEventsUsed (0), numEventsAllocated (0)
  26581. {
  26582. }
  26583. ~VSTMidiEventList()
  26584. {
  26585. freeEvents();
  26586. }
  26587. void clear()
  26588. {
  26589. numEventsUsed = 0;
  26590. if (events != 0)
  26591. events->numEvents = 0;
  26592. }
  26593. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26594. {
  26595. ensureSize (numEventsUsed + 1);
  26596. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26597. events->numEvents = ++numEventsUsed;
  26598. if (numBytes <= 4)
  26599. {
  26600. if (e->type == kVstSysExType)
  26601. {
  26602. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26603. e->type = kVstMidiType;
  26604. e->byteSize = sizeof (VstMidiEvent);
  26605. e->noteLength = 0;
  26606. e->noteOffset = 0;
  26607. e->detune = 0;
  26608. e->noteOffVelocity = 0;
  26609. }
  26610. e->deltaFrames = frameOffset;
  26611. memcpy (e->midiData, midiData, numBytes);
  26612. }
  26613. else
  26614. {
  26615. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26616. if (se->type == kVstSysExType)
  26617. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26618. else
  26619. se->sysexDump = (char*) juce_malloc (numBytes);
  26620. memcpy (se->sysexDump, midiData, numBytes);
  26621. se->type = kVstSysExType;
  26622. se->byteSize = sizeof (VstMidiSysexEvent);
  26623. se->deltaFrames = frameOffset;
  26624. se->flags = 0;
  26625. se->dumpBytes = numBytes;
  26626. se->resvd1 = 0;
  26627. se->resvd2 = 0;
  26628. }
  26629. }
  26630. // Handy method to pull the events out of an event buffer supplied by the host
  26631. // or plugin.
  26632. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26633. {
  26634. for (int i = 0; i < events->numEvents; ++i)
  26635. {
  26636. const VstEvent* const e = events->events[i];
  26637. if (e != 0)
  26638. {
  26639. if (e->type == kVstMidiType)
  26640. {
  26641. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26642. 4, e->deltaFrames);
  26643. }
  26644. else if (e->type == kVstSysExType)
  26645. {
  26646. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26647. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26648. e->deltaFrames);
  26649. }
  26650. }
  26651. }
  26652. }
  26653. void ensureSize (int numEventsNeeded)
  26654. {
  26655. if (numEventsNeeded > numEventsAllocated)
  26656. {
  26657. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26658. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26659. if (events == 0)
  26660. events.calloc (size, 1);
  26661. else
  26662. events.realloc (size, 1);
  26663. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26664. {
  26665. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26666. (int) sizeof (VstMidiSysexEvent)));
  26667. e->type = kVstMidiType;
  26668. e->byteSize = sizeof (VstMidiEvent);
  26669. events->events[i] = (VstEvent*) e;
  26670. }
  26671. numEventsAllocated = numEventsNeeded;
  26672. }
  26673. }
  26674. void freeEvents()
  26675. {
  26676. if (events != 0)
  26677. {
  26678. for (int i = numEventsAllocated; --i >= 0;)
  26679. {
  26680. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26681. if (e->type == kVstSysExType)
  26682. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26683. juce_free (e);
  26684. }
  26685. events.free();
  26686. numEventsUsed = 0;
  26687. numEventsAllocated = 0;
  26688. }
  26689. }
  26690. HeapBlock <VstEvents> events;
  26691. private:
  26692. int numEventsUsed, numEventsAllocated;
  26693. };
  26694. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26695. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26696. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26697. #if ! JUCE_WINDOWS
  26698. static void _fpreset() {}
  26699. static void _clearfp() {}
  26700. #endif
  26701. extern void juce_callAnyTimersSynchronously();
  26702. const int fxbVersionNum = 1;
  26703. struct fxProgram
  26704. {
  26705. long chunkMagic; // 'CcnK'
  26706. long byteSize; // of this chunk, excl. magic + byteSize
  26707. long fxMagic; // 'FxCk'
  26708. long version;
  26709. long fxID; // fx unique id
  26710. long fxVersion;
  26711. long numParams;
  26712. char prgName[28];
  26713. float params[1]; // variable no. of parameters
  26714. };
  26715. struct fxSet
  26716. {
  26717. long chunkMagic; // 'CcnK'
  26718. long byteSize; // of this chunk, excl. magic + byteSize
  26719. long fxMagic; // 'FxBk'
  26720. long version;
  26721. long fxID; // fx unique id
  26722. long fxVersion;
  26723. long numPrograms;
  26724. char future[128];
  26725. fxProgram programs[1]; // variable no. of programs
  26726. };
  26727. struct fxChunkSet
  26728. {
  26729. long chunkMagic; // 'CcnK'
  26730. long byteSize; // of this chunk, excl. magic + byteSize
  26731. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26732. long version;
  26733. long fxID; // fx unique id
  26734. long fxVersion;
  26735. long numPrograms;
  26736. char future[128];
  26737. long chunkSize;
  26738. char chunk[8]; // variable
  26739. };
  26740. struct fxProgramSet
  26741. {
  26742. long chunkMagic; // 'CcnK'
  26743. long byteSize; // of this chunk, excl. magic + byteSize
  26744. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26745. long version;
  26746. long fxID; // fx unique id
  26747. long fxVersion;
  26748. long numPrograms;
  26749. char name[28];
  26750. long chunkSize;
  26751. char chunk[8]; // variable
  26752. };
  26753. static long vst_swap (const long x) throw()
  26754. {
  26755. #ifdef JUCE_LITTLE_ENDIAN
  26756. return (long) ByteOrder::swap ((uint32) x);
  26757. #else
  26758. return x;
  26759. #endif
  26760. }
  26761. static float vst_swapFloat (const float x) throw()
  26762. {
  26763. #ifdef JUCE_LITTLE_ENDIAN
  26764. union { uint32 asInt; float asFloat; } n;
  26765. n.asFloat = x;
  26766. n.asInt = ByteOrder::swap (n.asInt);
  26767. return n.asFloat;
  26768. #else
  26769. return x;
  26770. #endif
  26771. }
  26772. static double getVSTHostTimeNanoseconds()
  26773. {
  26774. #if JUCE_WINDOWS
  26775. return timeGetTime() * 1000000.0;
  26776. #elif JUCE_LINUX
  26777. timeval micro;
  26778. gettimeofday (&micro, 0);
  26779. return micro.tv_usec * 1000.0;
  26780. #elif JUCE_MAC
  26781. UnsignedWide micro;
  26782. Microseconds (&micro);
  26783. return micro.lo * 1000.0;
  26784. #endif
  26785. }
  26786. typedef AEffect* (*MainCall) (audioMasterCallback);
  26787. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26788. static int shellUIDToCreate = 0;
  26789. static int insideVSTCallback = 0;
  26790. class VSTPluginWindow;
  26791. // Change this to disable logging of various VST activities
  26792. #ifndef VST_LOGGING
  26793. #define VST_LOGGING 1
  26794. #endif
  26795. #if VST_LOGGING
  26796. #define log(a) Logger::writeToLog(a);
  26797. #else
  26798. #define log(a)
  26799. #endif
  26800. #if JUCE_MAC && JUCE_PPC
  26801. static void* NewCFMFromMachO (void* const machofp) throw()
  26802. {
  26803. void* result = juce_malloc (8);
  26804. ((void**) result)[0] = machofp;
  26805. ((void**) result)[1] = result;
  26806. return result;
  26807. }
  26808. #endif
  26809. #if JUCE_LINUX
  26810. extern Display* display;
  26811. extern XContext windowHandleXContext;
  26812. typedef void (*EventProcPtr) (XEvent* ev);
  26813. static bool xErrorTriggered;
  26814. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26815. {
  26816. xErrorTriggered = true;
  26817. return 0;
  26818. }
  26819. static int getPropertyFromXWindow (Window handle, Atom atom)
  26820. {
  26821. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26822. xErrorTriggered = false;
  26823. int userSize;
  26824. unsigned long bytes, userCount;
  26825. unsigned char* data;
  26826. Atom userType;
  26827. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26828. &userType, &userSize, &userCount, &bytes, &data);
  26829. XSetErrorHandler (oldErrorHandler);
  26830. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26831. : 0;
  26832. }
  26833. static Window getChildWindow (Window windowToCheck)
  26834. {
  26835. Window rootWindow, parentWindow;
  26836. Window* childWindows;
  26837. unsigned int numChildren;
  26838. XQueryTree (display,
  26839. windowToCheck,
  26840. &rootWindow,
  26841. &parentWindow,
  26842. &childWindows,
  26843. &numChildren);
  26844. if (numChildren > 0)
  26845. return childWindows [0];
  26846. return 0;
  26847. }
  26848. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26849. {
  26850. if (e.mods.isLeftButtonDown())
  26851. {
  26852. ev.xbutton.button = Button1;
  26853. ev.xbutton.state |= Button1Mask;
  26854. }
  26855. else if (e.mods.isRightButtonDown())
  26856. {
  26857. ev.xbutton.button = Button3;
  26858. ev.xbutton.state |= Button3Mask;
  26859. }
  26860. else if (e.mods.isMiddleButtonDown())
  26861. {
  26862. ev.xbutton.button = Button2;
  26863. ev.xbutton.state |= Button2Mask;
  26864. }
  26865. }
  26866. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26867. {
  26868. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26869. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26870. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26871. }
  26872. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26873. {
  26874. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26875. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26876. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26877. }
  26878. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26879. {
  26880. if (increment < 0)
  26881. {
  26882. ev.xbutton.button = Button5;
  26883. ev.xbutton.state |= Button5Mask;
  26884. }
  26885. else if (increment > 0)
  26886. {
  26887. ev.xbutton.button = Button4;
  26888. ev.xbutton.state |= Button4Mask;
  26889. }
  26890. }
  26891. #endif
  26892. class ModuleHandle : public ReferenceCountedObject
  26893. {
  26894. public:
  26895. File file;
  26896. MainCall moduleMain;
  26897. String pluginName;
  26898. static Array <ModuleHandle*>& getActiveModules()
  26899. {
  26900. static Array <ModuleHandle*> activeModules;
  26901. return activeModules;
  26902. }
  26903. static ModuleHandle* findOrCreateModule (const File& file)
  26904. {
  26905. for (int i = getActiveModules().size(); --i >= 0;)
  26906. {
  26907. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26908. if (module->file == file)
  26909. return module;
  26910. }
  26911. _fpreset(); // (doesn't do any harm)
  26912. ++insideVSTCallback;
  26913. shellUIDToCreate = 0;
  26914. log ("Attempting to load VST: " + file.getFullPathName());
  26915. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26916. if (! m->open())
  26917. m = 0;
  26918. --insideVSTCallback;
  26919. _fpreset(); // (doesn't do any harm)
  26920. return m.release();
  26921. }
  26922. ModuleHandle (const File& file_)
  26923. : file (file_),
  26924. moduleMain (0),
  26925. #if JUCE_WINDOWS || JUCE_LINUX
  26926. hModule (0)
  26927. #elif JUCE_MAC
  26928. fragId (0),
  26929. resHandle (0),
  26930. bundleRef (0),
  26931. resFileId (0)
  26932. #endif
  26933. {
  26934. getActiveModules().add (this);
  26935. #if JUCE_WINDOWS || JUCE_LINUX
  26936. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26937. #elif JUCE_MAC
  26938. FSRef ref;
  26939. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26940. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26941. #endif
  26942. }
  26943. ~ModuleHandle()
  26944. {
  26945. getActiveModules().removeValue (this);
  26946. close();
  26947. }
  26948. juce_UseDebuggingNewOperator
  26949. #if JUCE_WINDOWS || JUCE_LINUX
  26950. void* hModule;
  26951. String fullParentDirectoryPathName;
  26952. bool open()
  26953. {
  26954. #if JUCE_WINDOWS
  26955. static bool timePeriodSet = false;
  26956. if (! timePeriodSet)
  26957. {
  26958. timePeriodSet = true;
  26959. timeBeginPeriod (2);
  26960. }
  26961. #endif
  26962. pluginName = file.getFileNameWithoutExtension();
  26963. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26964. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26965. if (moduleMain == 0)
  26966. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26967. return moduleMain != 0;
  26968. }
  26969. void close()
  26970. {
  26971. _fpreset(); // (doesn't do any harm)
  26972. PlatformUtilities::freeDynamicLibrary (hModule);
  26973. }
  26974. void closeEffect (AEffect* eff)
  26975. {
  26976. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26977. }
  26978. #else
  26979. CFragConnectionID fragId;
  26980. Handle resHandle;
  26981. CFBundleRef bundleRef;
  26982. FSSpec parentDirFSSpec;
  26983. short resFileId;
  26984. bool open()
  26985. {
  26986. bool ok = false;
  26987. const String filename (file.getFullPathName());
  26988. if (file.hasFileExtension (".vst"))
  26989. {
  26990. const char* const utf8 = filename.toUTF8();
  26991. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26992. strlen (utf8), file.isDirectory());
  26993. if (url != 0)
  26994. {
  26995. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26996. CFRelease (url);
  26997. if (bundleRef != 0)
  26998. {
  26999. if (CFBundleLoadExecutable (bundleRef))
  27000. {
  27001. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  27002. if (moduleMain == 0)
  27003. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  27004. if (moduleMain != 0)
  27005. {
  27006. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  27007. if (name != 0)
  27008. {
  27009. if (CFGetTypeID (name) == CFStringGetTypeID())
  27010. {
  27011. char buffer[1024];
  27012. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  27013. pluginName = buffer;
  27014. }
  27015. }
  27016. if (pluginName.isEmpty())
  27017. pluginName = file.getFileNameWithoutExtension();
  27018. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  27019. ok = true;
  27020. }
  27021. }
  27022. if (! ok)
  27023. {
  27024. CFBundleUnloadExecutable (bundleRef);
  27025. CFRelease (bundleRef);
  27026. bundleRef = 0;
  27027. }
  27028. }
  27029. }
  27030. }
  27031. #if JUCE_PPC
  27032. else
  27033. {
  27034. FSRef fn;
  27035. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  27036. {
  27037. resFileId = FSOpenResFile (&fn, fsRdPerm);
  27038. if (resFileId != -1)
  27039. {
  27040. const int numEffs = Count1Resources ('aEff');
  27041. for (int i = 0; i < numEffs; ++i)
  27042. {
  27043. resHandle = Get1IndResource ('aEff', i + 1);
  27044. if (resHandle != 0)
  27045. {
  27046. OSType type;
  27047. Str255 name;
  27048. SInt16 id;
  27049. GetResInfo (resHandle, &id, &type, name);
  27050. pluginName = String ((const char*) name + 1, name[0]);
  27051. DetachResource (resHandle);
  27052. HLock (resHandle);
  27053. Ptr ptr;
  27054. Str255 errorText;
  27055. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  27056. name, kPrivateCFragCopy,
  27057. &fragId, &ptr, errorText);
  27058. if (err == noErr)
  27059. {
  27060. moduleMain = (MainCall) newMachOFromCFM (ptr);
  27061. ok = true;
  27062. }
  27063. else
  27064. {
  27065. HUnlock (resHandle);
  27066. }
  27067. break;
  27068. }
  27069. }
  27070. if (! ok)
  27071. CloseResFile (resFileId);
  27072. }
  27073. }
  27074. }
  27075. #endif
  27076. return ok;
  27077. }
  27078. void close()
  27079. {
  27080. #if JUCE_PPC
  27081. if (fragId != 0)
  27082. {
  27083. if (moduleMain != 0)
  27084. disposeMachOFromCFM ((void*) moduleMain);
  27085. CloseConnection (&fragId);
  27086. HUnlock (resHandle);
  27087. if (resFileId != 0)
  27088. CloseResFile (resFileId);
  27089. }
  27090. else
  27091. #endif
  27092. if (bundleRef != 0)
  27093. {
  27094. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  27095. if (CFGetRetainCount (bundleRef) == 1)
  27096. CFBundleUnloadExecutable (bundleRef);
  27097. if (CFGetRetainCount (bundleRef) > 0)
  27098. CFRelease (bundleRef);
  27099. }
  27100. }
  27101. void closeEffect (AEffect* eff)
  27102. {
  27103. #if JUCE_PPC
  27104. if (fragId != 0)
  27105. {
  27106. Array<void*> thingsToDelete;
  27107. thingsToDelete.add ((void*) eff->dispatcher);
  27108. thingsToDelete.add ((void*) eff->process);
  27109. thingsToDelete.add ((void*) eff->setParameter);
  27110. thingsToDelete.add ((void*) eff->getParameter);
  27111. thingsToDelete.add ((void*) eff->processReplacing);
  27112. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  27113. for (int i = thingsToDelete.size(); --i >= 0;)
  27114. disposeMachOFromCFM (thingsToDelete[i]);
  27115. }
  27116. else
  27117. #endif
  27118. {
  27119. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  27120. }
  27121. }
  27122. #if JUCE_PPC
  27123. static void* newMachOFromCFM (void* cfmfp)
  27124. {
  27125. if (cfmfp == 0)
  27126. return 0;
  27127. UInt32* const mfp = new UInt32[6];
  27128. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  27129. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  27130. mfp[2] = 0x800c0000;
  27131. mfp[3] = 0x804c0004;
  27132. mfp[4] = 0x7c0903a6;
  27133. mfp[5] = 0x4e800420;
  27134. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  27135. return mfp;
  27136. }
  27137. static void disposeMachOFromCFM (void* ptr)
  27138. {
  27139. delete[] static_cast <UInt32*> (ptr);
  27140. }
  27141. void coerceAEffectFunctionCalls (AEffect* eff)
  27142. {
  27143. if (fragId != 0)
  27144. {
  27145. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  27146. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  27147. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  27148. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  27149. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  27150. }
  27151. }
  27152. #endif
  27153. #endif
  27154. };
  27155. /**
  27156. An instance of a plugin, created by a VSTPluginFormat.
  27157. */
  27158. class VSTPluginInstance : public AudioPluginInstance,
  27159. private Timer,
  27160. private AsyncUpdater
  27161. {
  27162. public:
  27163. ~VSTPluginInstance();
  27164. // AudioPluginInstance methods:
  27165. void fillInPluginDescription (PluginDescription& desc) const
  27166. {
  27167. desc.name = name;
  27168. desc.fileOrIdentifier = module->file.getFullPathName();
  27169. desc.uid = getUID();
  27170. desc.lastFileModTime = module->file.getLastModificationTime();
  27171. desc.pluginFormatName = "VST";
  27172. desc.category = getCategory();
  27173. {
  27174. char buffer [kVstMaxVendorStrLen + 8];
  27175. zerostruct (buffer);
  27176. dispatch (effGetVendorString, 0, 0, buffer, 0);
  27177. desc.manufacturerName = buffer;
  27178. }
  27179. desc.version = getVersion();
  27180. desc.numInputChannels = getNumInputChannels();
  27181. desc.numOutputChannels = getNumOutputChannels();
  27182. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  27183. }
  27184. const String getName() const { return name; }
  27185. int getUID() const;
  27186. bool acceptsMidi() const { return wantsMidiMessages; }
  27187. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  27188. // AudioProcessor methods:
  27189. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  27190. void releaseResources();
  27191. void processBlock (AudioSampleBuffer& buffer,
  27192. MidiBuffer& midiMessages);
  27193. AudioProcessorEditor* createEditor();
  27194. const String getInputChannelName (int index) const;
  27195. bool isInputChannelStereoPair (int index) const;
  27196. const String getOutputChannelName (int index) const;
  27197. bool isOutputChannelStereoPair (int index) const;
  27198. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  27199. float getParameter (int index);
  27200. void setParameter (int index, float newValue);
  27201. const String getParameterName (int index);
  27202. const String getParameterText (int index);
  27203. bool isParameterAutomatable (int index) const;
  27204. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  27205. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  27206. void setCurrentProgram (int index);
  27207. const String getProgramName (int index);
  27208. void changeProgramName (int index, const String& newName);
  27209. void getStateInformation (MemoryBlock& destData);
  27210. void getCurrentProgramStateInformation (MemoryBlock& destData);
  27211. void setStateInformation (const void* data, int sizeInBytes);
  27212. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27213. void timerCallback();
  27214. void handleAsyncUpdate();
  27215. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  27216. juce_UseDebuggingNewOperator
  27217. private:
  27218. friend class VSTPluginWindow;
  27219. friend class VSTPluginFormat;
  27220. AEffect* effect;
  27221. String name;
  27222. CriticalSection lock;
  27223. bool wantsMidiMessages, initialised, isPowerOn;
  27224. mutable StringArray programNames;
  27225. AudioSampleBuffer tempBuffer;
  27226. CriticalSection midiInLock;
  27227. MidiBuffer incomingMidi;
  27228. VSTMidiEventList midiEventsToSend;
  27229. VstTimeInfo vstHostTime;
  27230. ReferenceCountedObjectPtr <ModuleHandle> module;
  27231. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  27232. bool restoreProgramSettings (const fxProgram* const prog);
  27233. const String getCurrentProgramName();
  27234. void setParamsInProgramBlock (fxProgram* const prog);
  27235. void updateStoredProgramNames();
  27236. void initialise();
  27237. void handleMidiFromPlugin (const VstEvents* const events);
  27238. void createTempParameterStore (MemoryBlock& dest);
  27239. void restoreFromTempParameterStore (const MemoryBlock& mb);
  27240. const String getParameterLabel (int index) const;
  27241. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  27242. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  27243. void setChunkData (const char* data, int size, bool isPreset);
  27244. bool loadFromFXBFile (const void* data, int numBytes);
  27245. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  27246. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27247. const String getVersion() const;
  27248. const String getCategory() const;
  27249. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  27250. void setPower (const bool on);
  27251. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27252. };
  27253. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27254. : effect (0),
  27255. wantsMidiMessages (false),
  27256. initialised (false),
  27257. isPowerOn (false),
  27258. tempBuffer (1, 1),
  27259. module (module_)
  27260. {
  27261. try
  27262. {
  27263. _fpreset();
  27264. ++insideVSTCallback;
  27265. name = module->pluginName;
  27266. log ("Creating VST instance: " + name);
  27267. #if JUCE_MAC
  27268. if (module->resFileId != 0)
  27269. UseResFile (module->resFileId);
  27270. #if JUCE_PPC
  27271. if (module->fragId != 0)
  27272. {
  27273. static void* audioMasterCoerced = 0;
  27274. if (audioMasterCoerced == 0)
  27275. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27276. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27277. }
  27278. else
  27279. #endif
  27280. #endif
  27281. {
  27282. effect = module->moduleMain (&audioMaster);
  27283. }
  27284. --insideVSTCallback;
  27285. if (effect != 0 && effect->magic == kEffectMagic)
  27286. {
  27287. #if JUCE_PPC
  27288. module->coerceAEffectFunctionCalls (effect);
  27289. #endif
  27290. jassert (effect->resvd2 == 0);
  27291. jassert (effect->object != 0);
  27292. _fpreset(); // some dodgy plugs fuck around with this
  27293. }
  27294. else
  27295. {
  27296. effect = 0;
  27297. }
  27298. }
  27299. catch (...)
  27300. {
  27301. --insideVSTCallback;
  27302. }
  27303. }
  27304. VSTPluginInstance::~VSTPluginInstance()
  27305. {
  27306. const ScopedLock sl (lock);
  27307. jassert (insideVSTCallback == 0);
  27308. if (effect != 0 && effect->magic == kEffectMagic)
  27309. {
  27310. try
  27311. {
  27312. #if JUCE_MAC
  27313. if (module->resFileId != 0)
  27314. UseResFile (module->resFileId);
  27315. #endif
  27316. // Must delete any editors before deleting the plugin instance!
  27317. jassert (getActiveEditor() == 0);
  27318. _fpreset(); // some dodgy plugs fuck around with this
  27319. module->closeEffect (effect);
  27320. }
  27321. catch (...)
  27322. {}
  27323. }
  27324. module = 0;
  27325. effect = 0;
  27326. }
  27327. void VSTPluginInstance::initialise()
  27328. {
  27329. if (initialised || effect == 0)
  27330. return;
  27331. log ("Initialising VST: " + module->pluginName);
  27332. initialised = true;
  27333. dispatch (effIdentify, 0, 0, 0, 0);
  27334. // this code would ask the plugin for its name, but so few plugins
  27335. // actually bother implementing this correctly, that it's better to
  27336. // just ignore it and use the file name instead.
  27337. /* {
  27338. char buffer [256];
  27339. zerostruct (buffer);
  27340. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27341. name = String (buffer).trim();
  27342. if (name.isEmpty())
  27343. name = module->pluginName;
  27344. }
  27345. */
  27346. if (getSampleRate() > 0)
  27347. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27348. if (getBlockSize() > 0)
  27349. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27350. dispatch (effOpen, 0, 0, 0, 0);
  27351. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27352. getSampleRate(), getBlockSize());
  27353. if (getNumPrograms() > 1)
  27354. setCurrentProgram (0);
  27355. else
  27356. dispatch (effSetProgram, 0, 0, 0, 0);
  27357. int i;
  27358. for (i = effect->numInputs; --i >= 0;)
  27359. dispatch (effConnectInput, i, 1, 0, 0);
  27360. for (i = effect->numOutputs; --i >= 0;)
  27361. dispatch (effConnectOutput, i, 1, 0, 0);
  27362. updateStoredProgramNames();
  27363. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27364. setLatencySamples (effect->initialDelay);
  27365. }
  27366. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27367. int samplesPerBlockExpected)
  27368. {
  27369. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27370. sampleRate_, samplesPerBlockExpected);
  27371. setLatencySamples (effect->initialDelay);
  27372. vstHostTime.tempo = 120.0;
  27373. vstHostTime.timeSigNumerator = 4;
  27374. vstHostTime.timeSigDenominator = 4;
  27375. vstHostTime.sampleRate = sampleRate_;
  27376. vstHostTime.samplePos = 0;
  27377. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27378. initialise();
  27379. if (initialised)
  27380. {
  27381. wantsMidiMessages = wantsMidiMessages
  27382. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27383. if (wantsMidiMessages)
  27384. midiEventsToSend.ensureSize (256);
  27385. else
  27386. midiEventsToSend.freeEvents();
  27387. incomingMidi.clear();
  27388. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27389. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27390. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27391. if (! isPowerOn)
  27392. setPower (true);
  27393. // dodgy hack to force some plugins to initialise the sample rate..
  27394. if ((! hasEditor()) && getNumParameters() > 0)
  27395. {
  27396. const float old = getParameter (0);
  27397. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27398. setParameter (0, old);
  27399. }
  27400. dispatch (effStartProcess, 0, 0, 0, 0);
  27401. }
  27402. }
  27403. void VSTPluginInstance::releaseResources()
  27404. {
  27405. if (initialised)
  27406. {
  27407. dispatch (effStopProcess, 0, 0, 0, 0);
  27408. setPower (false);
  27409. }
  27410. tempBuffer.setSize (1, 1);
  27411. incomingMidi.clear();
  27412. midiEventsToSend.freeEvents();
  27413. }
  27414. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27415. MidiBuffer& midiMessages)
  27416. {
  27417. const int numSamples = buffer.getNumSamples();
  27418. if (initialised)
  27419. {
  27420. AudioPlayHead* playHead = getPlayHead();
  27421. if (playHead != 0)
  27422. {
  27423. AudioPlayHead::CurrentPositionInfo position;
  27424. playHead->getCurrentPosition (position);
  27425. vstHostTime.tempo = position.bpm;
  27426. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27427. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27428. vstHostTime.ppqPos = position.ppqPosition;
  27429. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27430. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27431. if (position.isPlaying)
  27432. vstHostTime.flags |= kVstTransportPlaying;
  27433. else
  27434. vstHostTime.flags &= ~kVstTransportPlaying;
  27435. }
  27436. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27437. if (wantsMidiMessages)
  27438. {
  27439. midiEventsToSend.clear();
  27440. midiEventsToSend.ensureSize (1);
  27441. MidiBuffer::Iterator iter (midiMessages);
  27442. const uint8* midiData;
  27443. int numBytesOfMidiData, samplePosition;
  27444. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27445. {
  27446. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27447. jlimit (0, numSamples - 1, samplePosition));
  27448. }
  27449. try
  27450. {
  27451. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27452. }
  27453. catch (...)
  27454. {}
  27455. }
  27456. _clearfp();
  27457. if ((effect->flags & effFlagsCanReplacing) != 0)
  27458. {
  27459. try
  27460. {
  27461. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27462. }
  27463. catch (...)
  27464. {}
  27465. }
  27466. else
  27467. {
  27468. tempBuffer.setSize (effect->numOutputs, numSamples);
  27469. tempBuffer.clear();
  27470. try
  27471. {
  27472. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27473. }
  27474. catch (...)
  27475. {}
  27476. for (int i = effect->numOutputs; --i >= 0;)
  27477. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27478. }
  27479. }
  27480. else
  27481. {
  27482. // Not initialised, so just bypass..
  27483. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27484. buffer.clear (i, 0, buffer.getNumSamples());
  27485. }
  27486. {
  27487. // copy any incoming midi..
  27488. const ScopedLock sl (midiInLock);
  27489. midiMessages.swapWith (incomingMidi);
  27490. incomingMidi.clear();
  27491. }
  27492. }
  27493. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27494. {
  27495. if (events != 0)
  27496. {
  27497. const ScopedLock sl (midiInLock);
  27498. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27499. }
  27500. }
  27501. static Array <VSTPluginWindow*> activeVSTWindows;
  27502. class VSTPluginWindow : public AudioProcessorEditor,
  27503. #if ! JUCE_MAC
  27504. public ComponentMovementWatcher,
  27505. #endif
  27506. public Timer
  27507. {
  27508. public:
  27509. VSTPluginWindow (VSTPluginInstance& plugin_)
  27510. : AudioProcessorEditor (&plugin_),
  27511. #if ! JUCE_MAC
  27512. ComponentMovementWatcher (this),
  27513. #endif
  27514. plugin (plugin_),
  27515. isOpen (false),
  27516. wasShowing (false),
  27517. pluginRefusesToResize (false),
  27518. pluginWantsKeys (false),
  27519. alreadyInside (false),
  27520. recursiveResize (false)
  27521. {
  27522. #if JUCE_WINDOWS
  27523. sizeCheckCount = 0;
  27524. pluginHWND = 0;
  27525. #elif JUCE_LINUX
  27526. pluginWindow = None;
  27527. pluginProc = None;
  27528. #else
  27529. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27530. #endif
  27531. activeVSTWindows.add (this);
  27532. setSize (1, 1);
  27533. setOpaque (true);
  27534. setVisible (true);
  27535. }
  27536. ~VSTPluginWindow()
  27537. {
  27538. #if JUCE_MAC
  27539. innerWrapper = 0;
  27540. #else
  27541. closePluginWindow();
  27542. #endif
  27543. activeVSTWindows.removeValue (this);
  27544. plugin.editorBeingDeleted (this);
  27545. }
  27546. #if ! JUCE_MAC
  27547. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27548. {
  27549. if (recursiveResize)
  27550. return;
  27551. Component* const topComp = getTopLevelComponent();
  27552. if (topComp->getPeer() != 0)
  27553. {
  27554. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27555. recursiveResize = true;
  27556. #if JUCE_WINDOWS
  27557. if (pluginHWND != 0)
  27558. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27559. #elif JUCE_LINUX
  27560. if (pluginWindow != 0)
  27561. {
  27562. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27563. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27564. XMapRaised (display, pluginWindow);
  27565. }
  27566. #endif
  27567. recursiveResize = false;
  27568. }
  27569. }
  27570. void componentVisibilityChanged (Component&)
  27571. {
  27572. const bool isShowingNow = isShowing();
  27573. if (wasShowing != isShowingNow)
  27574. {
  27575. wasShowing = isShowingNow;
  27576. if (isShowingNow)
  27577. openPluginWindow();
  27578. else
  27579. closePluginWindow();
  27580. }
  27581. componentMovedOrResized (true, true);
  27582. }
  27583. void componentPeerChanged()
  27584. {
  27585. closePluginWindow();
  27586. openPluginWindow();
  27587. }
  27588. #endif
  27589. bool keyStateChanged (bool)
  27590. {
  27591. return pluginWantsKeys;
  27592. }
  27593. bool keyPressed (const KeyPress&)
  27594. {
  27595. return pluginWantsKeys;
  27596. }
  27597. #if JUCE_MAC
  27598. void paint (Graphics& g)
  27599. {
  27600. g.fillAll (Colours::black);
  27601. }
  27602. #else
  27603. void paint (Graphics& g)
  27604. {
  27605. if (isOpen)
  27606. {
  27607. ComponentPeer* const peer = getPeer();
  27608. if (peer != 0)
  27609. {
  27610. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27611. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27612. #if JUCE_LINUX
  27613. if (pluginWindow != 0)
  27614. {
  27615. const Rectangle<int> clip (g.getClipBounds());
  27616. XEvent ev;
  27617. zerostruct (ev);
  27618. ev.xexpose.type = Expose;
  27619. ev.xexpose.display = display;
  27620. ev.xexpose.window = pluginWindow;
  27621. ev.xexpose.x = clip.getX();
  27622. ev.xexpose.y = clip.getY();
  27623. ev.xexpose.width = clip.getWidth();
  27624. ev.xexpose.height = clip.getHeight();
  27625. sendEventToChild (&ev);
  27626. }
  27627. #endif
  27628. }
  27629. }
  27630. else
  27631. {
  27632. g.fillAll (Colours::black);
  27633. }
  27634. }
  27635. #endif
  27636. void timerCallback()
  27637. {
  27638. #if JUCE_WINDOWS
  27639. if (--sizeCheckCount <= 0)
  27640. {
  27641. sizeCheckCount = 10;
  27642. checkPluginWindowSize();
  27643. }
  27644. #endif
  27645. try
  27646. {
  27647. static bool reentrant = false;
  27648. if (! reentrant)
  27649. {
  27650. reentrant = true;
  27651. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27652. reentrant = false;
  27653. }
  27654. }
  27655. catch (...)
  27656. {}
  27657. }
  27658. void mouseDown (const MouseEvent& e)
  27659. {
  27660. #if JUCE_LINUX
  27661. if (pluginWindow == 0)
  27662. return;
  27663. toFront (true);
  27664. XEvent ev;
  27665. zerostruct (ev);
  27666. ev.xbutton.display = display;
  27667. ev.xbutton.type = ButtonPress;
  27668. ev.xbutton.window = pluginWindow;
  27669. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27670. ev.xbutton.time = CurrentTime;
  27671. ev.xbutton.x = e.x;
  27672. ev.xbutton.y = e.y;
  27673. ev.xbutton.x_root = e.getScreenX();
  27674. ev.xbutton.y_root = e.getScreenY();
  27675. translateJuceToXButtonModifiers (e, ev);
  27676. sendEventToChild (&ev);
  27677. #elif JUCE_WINDOWS
  27678. (void) e;
  27679. toFront (true);
  27680. #endif
  27681. }
  27682. void broughtToFront()
  27683. {
  27684. activeVSTWindows.removeValue (this);
  27685. activeVSTWindows.add (this);
  27686. #if JUCE_MAC
  27687. dispatch (effEditTop, 0, 0, 0, 0);
  27688. #endif
  27689. }
  27690. juce_UseDebuggingNewOperator
  27691. private:
  27692. VSTPluginInstance& plugin;
  27693. bool isOpen, wasShowing, recursiveResize;
  27694. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27695. #if JUCE_WINDOWS
  27696. HWND pluginHWND;
  27697. void* originalWndProc;
  27698. int sizeCheckCount;
  27699. #elif JUCE_LINUX
  27700. Window pluginWindow;
  27701. EventProcPtr pluginProc;
  27702. #endif
  27703. #if JUCE_MAC
  27704. void openPluginWindow (WindowRef parentWindow)
  27705. {
  27706. if (isOpen || parentWindow == 0)
  27707. return;
  27708. isOpen = true;
  27709. ERect* rect = 0;
  27710. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27711. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27712. // do this before and after like in the steinberg example
  27713. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27714. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27715. // Install keyboard hooks
  27716. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27717. // double-check it's not too tiny
  27718. int w = 250, h = 150;
  27719. if (rect != 0)
  27720. {
  27721. w = rect->right - rect->left;
  27722. h = rect->bottom - rect->top;
  27723. if (w == 0 || h == 0)
  27724. {
  27725. w = 250;
  27726. h = 150;
  27727. }
  27728. }
  27729. w = jmax (w, 32);
  27730. h = jmax (h, 32);
  27731. setSize (w, h);
  27732. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27733. repaint();
  27734. }
  27735. #else
  27736. void openPluginWindow()
  27737. {
  27738. if (isOpen || getWindowHandle() == 0)
  27739. return;
  27740. log ("Opening VST UI: " + plugin.name);
  27741. isOpen = true;
  27742. ERect* rect = 0;
  27743. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27744. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27745. // do this before and after like in the steinberg example
  27746. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27747. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27748. // Install keyboard hooks
  27749. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27750. #if JUCE_WINDOWS
  27751. originalWndProc = 0;
  27752. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27753. if (pluginHWND == 0)
  27754. {
  27755. isOpen = false;
  27756. setSize (300, 150);
  27757. return;
  27758. }
  27759. #pragma warning (push)
  27760. #pragma warning (disable: 4244)
  27761. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  27762. if (! pluginWantsKeys)
  27763. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27764. #pragma warning (pop)
  27765. int w, h;
  27766. RECT r;
  27767. GetWindowRect (pluginHWND, &r);
  27768. w = r.right - r.left;
  27769. h = r.bottom - r.top;
  27770. if (rect != 0)
  27771. {
  27772. const int rw = rect->right - rect->left;
  27773. const int rh = rect->bottom - rect->top;
  27774. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27775. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27776. {
  27777. // very dodgy logic to decide which size is right.
  27778. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27779. {
  27780. SetWindowPos (pluginHWND, 0,
  27781. 0, 0, rw, rh,
  27782. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27783. GetWindowRect (pluginHWND, &r);
  27784. w = r.right - r.left;
  27785. h = r.bottom - r.top;
  27786. pluginRefusesToResize = (w != rw) || (h != rh);
  27787. w = rw;
  27788. h = rh;
  27789. }
  27790. }
  27791. }
  27792. #elif JUCE_LINUX
  27793. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27794. if (pluginWindow != 0)
  27795. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27796. XInternAtom (display, "_XEventProc", False));
  27797. int w = 250, h = 150;
  27798. if (rect != 0)
  27799. {
  27800. w = rect->right - rect->left;
  27801. h = rect->bottom - rect->top;
  27802. if (w == 0 || h == 0)
  27803. {
  27804. w = 250;
  27805. h = 150;
  27806. }
  27807. }
  27808. if (pluginWindow != 0)
  27809. XMapRaised (display, pluginWindow);
  27810. #endif
  27811. // double-check it's not too tiny
  27812. w = jmax (w, 32);
  27813. h = jmax (h, 32);
  27814. setSize (w, h);
  27815. #if JUCE_WINDOWS
  27816. checkPluginWindowSize();
  27817. #endif
  27818. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27819. repaint();
  27820. }
  27821. #endif
  27822. #if ! JUCE_MAC
  27823. void closePluginWindow()
  27824. {
  27825. if (isOpen)
  27826. {
  27827. log ("Closing VST UI: " + plugin.getName());
  27828. isOpen = false;
  27829. dispatch (effEditClose, 0, 0, 0, 0);
  27830. #if JUCE_WINDOWS
  27831. #pragma warning (push)
  27832. #pragma warning (disable: 4244)
  27833. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27834. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27835. #pragma warning (pop)
  27836. stopTimer();
  27837. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27838. DestroyWindow (pluginHWND);
  27839. pluginHWND = 0;
  27840. #elif JUCE_LINUX
  27841. stopTimer();
  27842. pluginWindow = 0;
  27843. pluginProc = 0;
  27844. #endif
  27845. }
  27846. }
  27847. #endif
  27848. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27849. {
  27850. return plugin.dispatch (opcode, index, value, ptr, opt);
  27851. }
  27852. #if JUCE_WINDOWS
  27853. void checkPluginWindowSize()
  27854. {
  27855. RECT r;
  27856. GetWindowRect (pluginHWND, &r);
  27857. const int w = r.right - r.left;
  27858. const int h = r.bottom - r.top;
  27859. if (isShowing() && w > 0 && h > 0
  27860. && (w != getWidth() || h != getHeight())
  27861. && ! pluginRefusesToResize)
  27862. {
  27863. setSize (w, h);
  27864. sizeCheckCount = 0;
  27865. }
  27866. }
  27867. // hooks to get keyboard events from VST windows..
  27868. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27869. {
  27870. for (int i = activeVSTWindows.size(); --i >= 0;)
  27871. {
  27872. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27873. if (w->pluginHWND == hW)
  27874. {
  27875. if (message == WM_CHAR
  27876. || message == WM_KEYDOWN
  27877. || message == WM_SYSKEYDOWN
  27878. || message == WM_KEYUP
  27879. || message == WM_SYSKEYUP
  27880. || message == WM_APPCOMMAND)
  27881. {
  27882. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27883. message, wParam, lParam);
  27884. }
  27885. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27886. (HWND) w->pluginHWND,
  27887. message,
  27888. wParam,
  27889. lParam);
  27890. }
  27891. }
  27892. return DefWindowProc (hW, message, wParam, lParam);
  27893. }
  27894. #endif
  27895. #if JUCE_LINUX
  27896. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27897. void sendEventToChild (XEvent* event)
  27898. {
  27899. if (pluginProc != 0)
  27900. {
  27901. // if the plugin publishes an event procedure, pass the event directly..
  27902. pluginProc (event);
  27903. }
  27904. else if (pluginWindow != 0)
  27905. {
  27906. // if the plugin has a window, then send the event to the window so that
  27907. // its message thread will pick it up..
  27908. XSendEvent (display, pluginWindow, False, 0L, event);
  27909. XFlush (display);
  27910. }
  27911. }
  27912. void mouseEnter (const MouseEvent& e)
  27913. {
  27914. if (pluginWindow != 0)
  27915. {
  27916. XEvent ev;
  27917. zerostruct (ev);
  27918. ev.xcrossing.display = display;
  27919. ev.xcrossing.type = EnterNotify;
  27920. ev.xcrossing.window = pluginWindow;
  27921. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27922. ev.xcrossing.time = CurrentTime;
  27923. ev.xcrossing.x = e.x;
  27924. ev.xcrossing.y = e.y;
  27925. ev.xcrossing.x_root = e.getScreenX();
  27926. ev.xcrossing.y_root = e.getScreenY();
  27927. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27928. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27929. translateJuceToXCrossingModifiers (e, ev);
  27930. sendEventToChild (&ev);
  27931. }
  27932. }
  27933. void mouseExit (const MouseEvent& e)
  27934. {
  27935. if (pluginWindow != 0)
  27936. {
  27937. XEvent ev;
  27938. zerostruct (ev);
  27939. ev.xcrossing.display = display;
  27940. ev.xcrossing.type = LeaveNotify;
  27941. ev.xcrossing.window = pluginWindow;
  27942. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27943. ev.xcrossing.time = CurrentTime;
  27944. ev.xcrossing.x = e.x;
  27945. ev.xcrossing.y = e.y;
  27946. ev.xcrossing.x_root = e.getScreenX();
  27947. ev.xcrossing.y_root = e.getScreenY();
  27948. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27949. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27950. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27951. translateJuceToXCrossingModifiers (e, ev);
  27952. sendEventToChild (&ev);
  27953. }
  27954. }
  27955. void mouseMove (const MouseEvent& e)
  27956. {
  27957. if (pluginWindow != 0)
  27958. {
  27959. XEvent ev;
  27960. zerostruct (ev);
  27961. ev.xmotion.display = display;
  27962. ev.xmotion.type = MotionNotify;
  27963. ev.xmotion.window = pluginWindow;
  27964. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27965. ev.xmotion.time = CurrentTime;
  27966. ev.xmotion.is_hint = NotifyNormal;
  27967. ev.xmotion.x = e.x;
  27968. ev.xmotion.y = e.y;
  27969. ev.xmotion.x_root = e.getScreenX();
  27970. ev.xmotion.y_root = e.getScreenY();
  27971. sendEventToChild (&ev);
  27972. }
  27973. }
  27974. void mouseDrag (const MouseEvent& e)
  27975. {
  27976. if (pluginWindow != 0)
  27977. {
  27978. XEvent ev;
  27979. zerostruct (ev);
  27980. ev.xmotion.display = display;
  27981. ev.xmotion.type = MotionNotify;
  27982. ev.xmotion.window = pluginWindow;
  27983. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27984. ev.xmotion.time = CurrentTime;
  27985. ev.xmotion.x = e.x ;
  27986. ev.xmotion.y = e.y;
  27987. ev.xmotion.x_root = e.getScreenX();
  27988. ev.xmotion.y_root = e.getScreenY();
  27989. ev.xmotion.is_hint = NotifyNormal;
  27990. translateJuceToXMotionModifiers (e, ev);
  27991. sendEventToChild (&ev);
  27992. }
  27993. }
  27994. void mouseUp (const MouseEvent& e)
  27995. {
  27996. if (pluginWindow != 0)
  27997. {
  27998. XEvent ev;
  27999. zerostruct (ev);
  28000. ev.xbutton.display = display;
  28001. ev.xbutton.type = ButtonRelease;
  28002. ev.xbutton.window = pluginWindow;
  28003. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  28004. ev.xbutton.time = CurrentTime;
  28005. ev.xbutton.x = e.x;
  28006. ev.xbutton.y = e.y;
  28007. ev.xbutton.x_root = e.getScreenX();
  28008. ev.xbutton.y_root = e.getScreenY();
  28009. translateJuceToXButtonModifiers (e, ev);
  28010. sendEventToChild (&ev);
  28011. }
  28012. }
  28013. void mouseWheelMove (const MouseEvent& e,
  28014. float incrementX,
  28015. float incrementY)
  28016. {
  28017. if (pluginWindow != 0)
  28018. {
  28019. XEvent ev;
  28020. zerostruct (ev);
  28021. ev.xbutton.display = display;
  28022. ev.xbutton.type = ButtonPress;
  28023. ev.xbutton.window = pluginWindow;
  28024. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  28025. ev.xbutton.time = CurrentTime;
  28026. ev.xbutton.x = e.x;
  28027. ev.xbutton.y = e.y;
  28028. ev.xbutton.x_root = e.getScreenX();
  28029. ev.xbutton.y_root = e.getScreenY();
  28030. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  28031. sendEventToChild (&ev);
  28032. // TODO - put a usleep here ?
  28033. ev.xbutton.type = ButtonRelease;
  28034. sendEventToChild (&ev);
  28035. }
  28036. }
  28037. #endif
  28038. #if JUCE_MAC
  28039. #if ! JUCE_SUPPORT_CARBON
  28040. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  28041. #endif
  28042. class InnerWrapperComponent : public CarbonViewWrapperComponent
  28043. {
  28044. public:
  28045. InnerWrapperComponent (VSTPluginWindow* const owner_)
  28046. : owner (owner_),
  28047. alreadyInside (false)
  28048. {
  28049. }
  28050. ~InnerWrapperComponent()
  28051. {
  28052. deleteWindow();
  28053. }
  28054. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  28055. {
  28056. owner->openPluginWindow (windowRef);
  28057. return 0;
  28058. }
  28059. void removeView (HIViewRef)
  28060. {
  28061. owner->dispatch (effEditClose, 0, 0, 0, 0);
  28062. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  28063. }
  28064. bool getEmbeddedViewSize (int& w, int& h)
  28065. {
  28066. ERect* rect = 0;
  28067. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  28068. w = rect->right - rect->left;
  28069. h = rect->bottom - rect->top;
  28070. return true;
  28071. }
  28072. void mouseDown (int x, int y)
  28073. {
  28074. if (! alreadyInside)
  28075. {
  28076. alreadyInside = true;
  28077. getTopLevelComponent()->toFront (true);
  28078. owner->dispatch (effEditMouse, x, y, 0, 0);
  28079. alreadyInside = false;
  28080. }
  28081. else
  28082. {
  28083. PostEvent (::mouseDown, 0);
  28084. }
  28085. }
  28086. void paint()
  28087. {
  28088. ComponentPeer* const peer = getPeer();
  28089. if (peer != 0)
  28090. {
  28091. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  28092. ERect r;
  28093. r.left = pos.getX();
  28094. r.right = r.left + getWidth();
  28095. r.top = pos.getY();
  28096. r.bottom = r.top + getHeight();
  28097. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  28098. }
  28099. }
  28100. private:
  28101. VSTPluginWindow* const owner;
  28102. bool alreadyInside;
  28103. };
  28104. friend class InnerWrapperComponent;
  28105. ScopedPointer <InnerWrapperComponent> innerWrapper;
  28106. void resized()
  28107. {
  28108. innerWrapper->setSize (getWidth(), getHeight());
  28109. }
  28110. #endif
  28111. };
  28112. AudioProcessorEditor* VSTPluginInstance::createEditor()
  28113. {
  28114. if (hasEditor())
  28115. return new VSTPluginWindow (*this);
  28116. return 0;
  28117. }
  28118. void VSTPluginInstance::handleAsyncUpdate()
  28119. {
  28120. // indicates that something about the plugin has changed..
  28121. updateHostDisplay();
  28122. }
  28123. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  28124. {
  28125. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  28126. {
  28127. changeProgramName (getCurrentProgram(), prog->prgName);
  28128. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28129. setParameter (i, vst_swapFloat (prog->params[i]));
  28130. return true;
  28131. }
  28132. return false;
  28133. }
  28134. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  28135. const int dataSize)
  28136. {
  28137. if (dataSize < 28)
  28138. return false;
  28139. const fxSet* const set = (const fxSet*) data;
  28140. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  28141. || vst_swap (set->version) > fxbVersionNum)
  28142. return false;
  28143. if (vst_swap (set->fxMagic) == 'FxBk')
  28144. {
  28145. // bank of programs
  28146. if (vst_swap (set->numPrograms) >= 0)
  28147. {
  28148. const int oldProg = getCurrentProgram();
  28149. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  28150. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28151. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  28152. {
  28153. if (i != oldProg)
  28154. {
  28155. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  28156. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28157. return false;
  28158. if (vst_swap (set->numPrograms) > 0)
  28159. setCurrentProgram (i);
  28160. if (! restoreProgramSettings (prog))
  28161. return false;
  28162. }
  28163. }
  28164. if (vst_swap (set->numPrograms) > 0)
  28165. setCurrentProgram (oldProg);
  28166. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  28167. if (((const char*) prog) - ((const char*) set) >= dataSize)
  28168. return false;
  28169. if (! restoreProgramSettings (prog))
  28170. return false;
  28171. }
  28172. }
  28173. else if (vst_swap (set->fxMagic) == 'FxCk')
  28174. {
  28175. // single program
  28176. const fxProgram* const prog = (const fxProgram*) data;
  28177. if (vst_swap (prog->chunkMagic) != 'CcnK')
  28178. return false;
  28179. changeProgramName (getCurrentProgram(), prog->prgName);
  28180. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  28181. setParameter (i, vst_swapFloat (prog->params[i]));
  28182. }
  28183. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  28184. {
  28185. // non-preset chunk
  28186. const fxChunkSet* const cset = (const fxChunkSet*) data;
  28187. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  28188. return false;
  28189. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  28190. }
  28191. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  28192. {
  28193. // preset chunk
  28194. const fxProgramSet* const cset = (const fxProgramSet*) data;
  28195. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  28196. return false;
  28197. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  28198. changeProgramName (getCurrentProgram(), cset->name);
  28199. }
  28200. else
  28201. {
  28202. return false;
  28203. }
  28204. return true;
  28205. }
  28206. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  28207. {
  28208. const int numParams = getNumParameters();
  28209. prog->chunkMagic = vst_swap ('CcnK');
  28210. prog->byteSize = 0;
  28211. prog->fxMagic = vst_swap ('FxCk');
  28212. prog->version = vst_swap (fxbVersionNum);
  28213. prog->fxID = vst_swap (getUID());
  28214. prog->fxVersion = vst_swap (getVersionNumber());
  28215. prog->numParams = vst_swap (numParams);
  28216. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  28217. for (int i = 0; i < numParams; ++i)
  28218. prog->params[i] = vst_swapFloat (getParameter (i));
  28219. }
  28220. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  28221. {
  28222. const int numPrograms = getNumPrograms();
  28223. const int numParams = getNumParameters();
  28224. if (usesChunks())
  28225. {
  28226. if (isFXB)
  28227. {
  28228. MemoryBlock chunk;
  28229. getChunkData (chunk, false, maxSizeMB);
  28230. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  28231. dest.setSize (totalLen, true);
  28232. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  28233. set->chunkMagic = vst_swap ('CcnK');
  28234. set->byteSize = 0;
  28235. set->fxMagic = vst_swap ('FBCh');
  28236. set->version = vst_swap (fxbVersionNum);
  28237. set->fxID = vst_swap (getUID());
  28238. set->fxVersion = vst_swap (getVersionNumber());
  28239. set->numPrograms = vst_swap (numPrograms);
  28240. set->chunkSize = vst_swap ((long) chunk.getSize());
  28241. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28242. }
  28243. else
  28244. {
  28245. MemoryBlock chunk;
  28246. getChunkData (chunk, true, maxSizeMB);
  28247. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28248. dest.setSize (totalLen, true);
  28249. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28250. set->chunkMagic = vst_swap ('CcnK');
  28251. set->byteSize = 0;
  28252. set->fxMagic = vst_swap ('FPCh');
  28253. set->version = vst_swap (fxbVersionNum);
  28254. set->fxID = vst_swap (getUID());
  28255. set->fxVersion = vst_swap (getVersionNumber());
  28256. set->numPrograms = vst_swap (numPrograms);
  28257. set->chunkSize = vst_swap ((long) chunk.getSize());
  28258. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28259. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28260. }
  28261. }
  28262. else
  28263. {
  28264. if (isFXB)
  28265. {
  28266. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28267. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28268. dest.setSize (len, true);
  28269. fxSet* const set = (fxSet*) dest.getData();
  28270. set->chunkMagic = vst_swap ('CcnK');
  28271. set->byteSize = 0;
  28272. set->fxMagic = vst_swap ('FxBk');
  28273. set->version = vst_swap (fxbVersionNum);
  28274. set->fxID = vst_swap (getUID());
  28275. set->fxVersion = vst_swap (getVersionNumber());
  28276. set->numPrograms = vst_swap (numPrograms);
  28277. const int oldProgram = getCurrentProgram();
  28278. MemoryBlock oldSettings;
  28279. createTempParameterStore (oldSettings);
  28280. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28281. for (int i = 0; i < numPrograms; ++i)
  28282. {
  28283. if (i != oldProgram)
  28284. {
  28285. setCurrentProgram (i);
  28286. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28287. }
  28288. }
  28289. setCurrentProgram (oldProgram);
  28290. restoreFromTempParameterStore (oldSettings);
  28291. }
  28292. else
  28293. {
  28294. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28295. dest.setSize (totalLen, true);
  28296. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28297. }
  28298. }
  28299. return true;
  28300. }
  28301. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28302. {
  28303. if (usesChunks())
  28304. {
  28305. void* data = 0;
  28306. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28307. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28308. {
  28309. mb.setSize (bytes);
  28310. mb.copyFrom (data, 0, bytes);
  28311. }
  28312. }
  28313. }
  28314. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28315. {
  28316. if (size > 0 && usesChunks())
  28317. {
  28318. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28319. if (! isPreset)
  28320. updateStoredProgramNames();
  28321. }
  28322. }
  28323. void VSTPluginInstance::timerCallback()
  28324. {
  28325. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28326. stopTimer();
  28327. }
  28328. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28329. {
  28330. const ScopedLock sl (lock);
  28331. ++insideVSTCallback;
  28332. int result = 0;
  28333. try
  28334. {
  28335. if (effect != 0)
  28336. {
  28337. #if JUCE_MAC
  28338. if (module->resFileId != 0)
  28339. UseResFile (module->resFileId);
  28340. #endif
  28341. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28342. #if JUCE_MAC
  28343. module->resFileId = CurResFile();
  28344. #endif
  28345. --insideVSTCallback;
  28346. return result;
  28347. }
  28348. }
  28349. catch (...)
  28350. {
  28351. }
  28352. --insideVSTCallback;
  28353. return result;
  28354. }
  28355. // handles non plugin-specific callbacks..
  28356. static const int defaultVSTSampleRateValue = 16384;
  28357. static const int defaultVSTBlockSizeValue = 512;
  28358. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28359. {
  28360. (void) index;
  28361. (void) value;
  28362. (void) opt;
  28363. switch (opcode)
  28364. {
  28365. case audioMasterCanDo:
  28366. {
  28367. static const char* canDos[] = { "supplyIdle",
  28368. "sendVstEvents",
  28369. "sendVstMidiEvent",
  28370. "sendVstTimeInfo",
  28371. "receiveVstEvents",
  28372. "receiveVstMidiEvent",
  28373. "supportShell",
  28374. "shellCategory" };
  28375. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28376. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28377. return 1;
  28378. return 0;
  28379. }
  28380. case audioMasterVersion: return 0x2400;
  28381. case audioMasterCurrentId: return shellUIDToCreate;
  28382. case audioMasterGetNumAutomatableParameters: return 0;
  28383. case audioMasterGetAutomationState: return 1;
  28384. case audioMasterGetVendorVersion: return 0x0101;
  28385. case audioMasterGetVendorString:
  28386. case audioMasterGetProductString:
  28387. {
  28388. String hostName ("Juce VST Host");
  28389. if (JUCEApplication::getInstance() != 0)
  28390. hostName = JUCEApplication::getInstance()->getApplicationName();
  28391. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28392. break;
  28393. }
  28394. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28395. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28396. case audioMasterSetOutputSampleRate: return 0;
  28397. default:
  28398. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28399. break;
  28400. }
  28401. return 0;
  28402. }
  28403. // handles callbacks for a specific plugin
  28404. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28405. {
  28406. switch (opcode)
  28407. {
  28408. case audioMasterAutomate:
  28409. sendParamChangeMessageToListeners (index, opt);
  28410. break;
  28411. case audioMasterProcessEvents:
  28412. handleMidiFromPlugin ((const VstEvents*) ptr);
  28413. break;
  28414. case audioMasterGetTime:
  28415. #if JUCE_MSVC
  28416. #pragma warning (push)
  28417. #pragma warning (disable: 4311)
  28418. #endif
  28419. return (VstIntPtr) &vstHostTime;
  28420. #if JUCE_MSVC
  28421. #pragma warning (pop)
  28422. #endif
  28423. break;
  28424. case audioMasterIdle:
  28425. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28426. {
  28427. ++insideVSTCallback;
  28428. #if JUCE_MAC
  28429. if (getActiveEditor() != 0)
  28430. dispatch (effEditIdle, 0, 0, 0, 0);
  28431. #endif
  28432. juce_callAnyTimersSynchronously();
  28433. handleUpdateNowIfNeeded();
  28434. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28435. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28436. --insideVSTCallback;
  28437. }
  28438. break;
  28439. case audioMasterUpdateDisplay:
  28440. triggerAsyncUpdate();
  28441. break;
  28442. case audioMasterTempoAt:
  28443. // returns (10000 * bpm)
  28444. break;
  28445. case audioMasterNeedIdle:
  28446. startTimer (50);
  28447. break;
  28448. case audioMasterSizeWindow:
  28449. if (getActiveEditor() != 0)
  28450. getActiveEditor()->setSize (index, value);
  28451. return 1;
  28452. case audioMasterGetSampleRate:
  28453. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28454. case audioMasterGetBlockSize:
  28455. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28456. case audioMasterWantMidi:
  28457. wantsMidiMessages = true;
  28458. break;
  28459. case audioMasterGetDirectory:
  28460. #if JUCE_MAC
  28461. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28462. #else
  28463. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28464. #endif
  28465. case audioMasterGetAutomationState:
  28466. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28467. break;
  28468. // none of these are handled (yet)..
  28469. case audioMasterBeginEdit:
  28470. case audioMasterEndEdit:
  28471. case audioMasterSetTime:
  28472. case audioMasterPinConnected:
  28473. case audioMasterGetParameterQuantization:
  28474. case audioMasterIOChanged:
  28475. case audioMasterGetInputLatency:
  28476. case audioMasterGetOutputLatency:
  28477. case audioMasterGetPreviousPlug:
  28478. case audioMasterGetNextPlug:
  28479. case audioMasterWillReplaceOrAccumulate:
  28480. case audioMasterGetCurrentProcessLevel:
  28481. case audioMasterOfflineStart:
  28482. case audioMasterOfflineRead:
  28483. case audioMasterOfflineWrite:
  28484. case audioMasterOfflineGetCurrentPass:
  28485. case audioMasterOfflineGetCurrentMetaPass:
  28486. case audioMasterVendorSpecific:
  28487. case audioMasterSetIcon:
  28488. case audioMasterGetLanguage:
  28489. case audioMasterOpenWindow:
  28490. case audioMasterCloseWindow:
  28491. break;
  28492. default:
  28493. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28494. }
  28495. return 0;
  28496. }
  28497. // entry point for all callbacks from the plugin
  28498. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28499. {
  28500. try
  28501. {
  28502. if (effect != 0 && effect->resvd2 != 0)
  28503. {
  28504. return ((VSTPluginInstance*)(effect->resvd2))
  28505. ->handleCallback (opcode, index, value, ptr, opt);
  28506. }
  28507. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28508. }
  28509. catch (...)
  28510. {
  28511. return 0;
  28512. }
  28513. }
  28514. const String VSTPluginInstance::getVersion() const
  28515. {
  28516. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28517. String s;
  28518. if (v == 0 || v == -1)
  28519. v = getVersionNumber();
  28520. if (v != 0)
  28521. {
  28522. int versionBits[4];
  28523. int n = 0;
  28524. while (v != 0)
  28525. {
  28526. versionBits [n++] = (v & 0xff);
  28527. v >>= 8;
  28528. }
  28529. s << 'V';
  28530. while (n > 0)
  28531. {
  28532. s << versionBits [--n];
  28533. if (n > 0)
  28534. s << '.';
  28535. }
  28536. }
  28537. return s;
  28538. }
  28539. int VSTPluginInstance::getUID() const
  28540. {
  28541. int uid = effect != 0 ? effect->uniqueID : 0;
  28542. if (uid == 0)
  28543. uid = module->file.hashCode();
  28544. return uid;
  28545. }
  28546. const String VSTPluginInstance::getCategory() const
  28547. {
  28548. const char* result = 0;
  28549. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28550. {
  28551. case kPlugCategEffect: result = "Effect"; break;
  28552. case kPlugCategSynth: result = "Synth"; break;
  28553. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28554. case kPlugCategMastering: result = "Mastering"; break;
  28555. case kPlugCategSpacializer: result = "Spacial"; break;
  28556. case kPlugCategRoomFx: result = "Reverb"; break;
  28557. case kPlugSurroundFx: result = "Surround"; break;
  28558. case kPlugCategRestoration: result = "Restoration"; break;
  28559. case kPlugCategGenerator: result = "Tone generation"; break;
  28560. default: break;
  28561. }
  28562. return result;
  28563. }
  28564. float VSTPluginInstance::getParameter (int index)
  28565. {
  28566. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28567. {
  28568. try
  28569. {
  28570. const ScopedLock sl (lock);
  28571. return effect->getParameter (effect, index);
  28572. }
  28573. catch (...)
  28574. {
  28575. }
  28576. }
  28577. return 0.0f;
  28578. }
  28579. void VSTPluginInstance::setParameter (int index, float newValue)
  28580. {
  28581. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28582. {
  28583. try
  28584. {
  28585. const ScopedLock sl (lock);
  28586. if (effect->getParameter (effect, index) != newValue)
  28587. effect->setParameter (effect, index, newValue);
  28588. }
  28589. catch (...)
  28590. {
  28591. }
  28592. }
  28593. }
  28594. const String VSTPluginInstance::getParameterName (int index)
  28595. {
  28596. if (effect != 0)
  28597. {
  28598. jassert (index >= 0 && index < effect->numParams);
  28599. char nm [256];
  28600. zerostruct (nm);
  28601. dispatch (effGetParamName, index, 0, nm, 0);
  28602. return String (nm).trim();
  28603. }
  28604. return String::empty;
  28605. }
  28606. const String VSTPluginInstance::getParameterLabel (int index) const
  28607. {
  28608. if (effect != 0)
  28609. {
  28610. jassert (index >= 0 && index < effect->numParams);
  28611. char nm [256];
  28612. zerostruct (nm);
  28613. dispatch (effGetParamLabel, index, 0, nm, 0);
  28614. return String (nm).trim();
  28615. }
  28616. return String::empty;
  28617. }
  28618. const String VSTPluginInstance::getParameterText (int index)
  28619. {
  28620. if (effect != 0)
  28621. {
  28622. jassert (index >= 0 && index < effect->numParams);
  28623. char nm [256];
  28624. zerostruct (nm);
  28625. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28626. return String (nm).trim();
  28627. }
  28628. return String::empty;
  28629. }
  28630. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28631. {
  28632. if (effect != 0)
  28633. {
  28634. jassert (index >= 0 && index < effect->numParams);
  28635. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28636. }
  28637. return false;
  28638. }
  28639. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28640. {
  28641. dest.setSize (64 + 4 * getNumParameters());
  28642. dest.fillWith (0);
  28643. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28644. float* const p = (float*) (((char*) dest.getData()) + 64);
  28645. for (int i = 0; i < getNumParameters(); ++i)
  28646. p[i] = getParameter(i);
  28647. }
  28648. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28649. {
  28650. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28651. float* p = (float*) (((char*) m.getData()) + 64);
  28652. for (int i = 0; i < getNumParameters(); ++i)
  28653. setParameter (i, p[i]);
  28654. }
  28655. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28656. {
  28657. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28658. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28659. }
  28660. const String VSTPluginInstance::getProgramName (int index)
  28661. {
  28662. if (index == getCurrentProgram())
  28663. {
  28664. return getCurrentProgramName();
  28665. }
  28666. else if (effect != 0)
  28667. {
  28668. char nm [256];
  28669. zerostruct (nm);
  28670. if (dispatch (effGetProgramNameIndexed,
  28671. jlimit (0, getNumPrograms(), index),
  28672. -1, nm, 0) != 0)
  28673. {
  28674. return String (nm).trim();
  28675. }
  28676. }
  28677. return programNames [index];
  28678. }
  28679. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28680. {
  28681. if (index == getCurrentProgram())
  28682. {
  28683. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28684. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28685. }
  28686. else
  28687. {
  28688. jassertfalse; // xxx not implemented!
  28689. }
  28690. }
  28691. void VSTPluginInstance::updateStoredProgramNames()
  28692. {
  28693. if (effect != 0 && getNumPrograms() > 0)
  28694. {
  28695. char nm [256];
  28696. zerostruct (nm);
  28697. // only do this if the plugin can't use indexed names..
  28698. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28699. {
  28700. const int oldProgram = getCurrentProgram();
  28701. MemoryBlock oldSettings;
  28702. createTempParameterStore (oldSettings);
  28703. for (int i = 0; i < getNumPrograms(); ++i)
  28704. {
  28705. setCurrentProgram (i);
  28706. getCurrentProgramName(); // (this updates the list)
  28707. }
  28708. setCurrentProgram (oldProgram);
  28709. restoreFromTempParameterStore (oldSettings);
  28710. }
  28711. }
  28712. }
  28713. const String VSTPluginInstance::getCurrentProgramName()
  28714. {
  28715. if (effect != 0)
  28716. {
  28717. char nm [256];
  28718. zerostruct (nm);
  28719. dispatch (effGetProgramName, 0, 0, nm, 0);
  28720. const int index = getCurrentProgram();
  28721. if (programNames[index].isEmpty())
  28722. {
  28723. while (programNames.size() < index)
  28724. programNames.add (String::empty);
  28725. programNames.set (index, String (nm).trim());
  28726. }
  28727. return String (nm).trim();
  28728. }
  28729. return String::empty;
  28730. }
  28731. const String VSTPluginInstance::getInputChannelName (int index) const
  28732. {
  28733. if (index >= 0 && index < getNumInputChannels())
  28734. {
  28735. VstPinProperties pinProps;
  28736. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28737. return String (pinProps.label, sizeof (pinProps.label));
  28738. }
  28739. return String::empty;
  28740. }
  28741. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28742. {
  28743. if (index < 0 || index >= getNumInputChannels())
  28744. return false;
  28745. VstPinProperties pinProps;
  28746. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28747. return (pinProps.flags & kVstPinIsStereo) != 0;
  28748. return true;
  28749. }
  28750. const String VSTPluginInstance::getOutputChannelName (int index) const
  28751. {
  28752. if (index >= 0 && index < getNumOutputChannels())
  28753. {
  28754. VstPinProperties pinProps;
  28755. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28756. return String (pinProps.label, sizeof (pinProps.label));
  28757. }
  28758. return String::empty;
  28759. }
  28760. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28761. {
  28762. if (index < 0 || index >= getNumOutputChannels())
  28763. return false;
  28764. VstPinProperties pinProps;
  28765. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28766. return (pinProps.flags & kVstPinIsStereo) != 0;
  28767. return true;
  28768. }
  28769. void VSTPluginInstance::setPower (const bool on)
  28770. {
  28771. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28772. isPowerOn = on;
  28773. }
  28774. const int defaultMaxSizeMB = 64;
  28775. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28776. {
  28777. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28778. }
  28779. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28780. {
  28781. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28782. }
  28783. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28784. {
  28785. loadFromFXBFile (data, sizeInBytes);
  28786. }
  28787. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28788. {
  28789. loadFromFXBFile (data, sizeInBytes);
  28790. }
  28791. VSTPluginFormat::VSTPluginFormat()
  28792. {
  28793. }
  28794. VSTPluginFormat::~VSTPluginFormat()
  28795. {
  28796. }
  28797. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28798. const String& fileOrIdentifier)
  28799. {
  28800. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28801. return;
  28802. PluginDescription desc;
  28803. desc.fileOrIdentifier = fileOrIdentifier;
  28804. desc.uid = 0;
  28805. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28806. if (instance == 0)
  28807. return;
  28808. try
  28809. {
  28810. #if JUCE_MAC
  28811. if (instance->module->resFileId != 0)
  28812. UseResFile (instance->module->resFileId);
  28813. #endif
  28814. instance->fillInPluginDescription (desc);
  28815. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28816. if (category != kPlugCategShell)
  28817. {
  28818. // Normal plugin...
  28819. results.add (new PluginDescription (desc));
  28820. ++insideVSTCallback;
  28821. instance->dispatch (effOpen, 0, 0, 0, 0);
  28822. --insideVSTCallback;
  28823. }
  28824. else
  28825. {
  28826. // It's a shell plugin, so iterate all the subtypes...
  28827. char shellEffectName [64];
  28828. for (;;)
  28829. {
  28830. zerostruct (shellEffectName);
  28831. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28832. if (uid == 0)
  28833. {
  28834. break;
  28835. }
  28836. else
  28837. {
  28838. desc.uid = uid;
  28839. desc.name = shellEffectName;
  28840. bool alreadyThere = false;
  28841. for (int i = results.size(); --i >= 0;)
  28842. {
  28843. PluginDescription* const d = results.getUnchecked(i);
  28844. if (d->isDuplicateOf (desc))
  28845. {
  28846. alreadyThere = true;
  28847. break;
  28848. }
  28849. }
  28850. if (! alreadyThere)
  28851. results.add (new PluginDescription (desc));
  28852. }
  28853. }
  28854. }
  28855. }
  28856. catch (...)
  28857. {
  28858. // crashed while loading...
  28859. }
  28860. }
  28861. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28862. {
  28863. ScopedPointer <VSTPluginInstance> result;
  28864. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28865. {
  28866. File file (desc.fileOrIdentifier);
  28867. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28868. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28869. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28870. if (module != 0)
  28871. {
  28872. shellUIDToCreate = desc.uid;
  28873. result = new VSTPluginInstance (module);
  28874. if (result->effect != 0)
  28875. {
  28876. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28877. result->initialise();
  28878. }
  28879. else
  28880. {
  28881. result = 0;
  28882. }
  28883. }
  28884. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28885. }
  28886. return result.release();
  28887. }
  28888. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28889. {
  28890. const File f (fileOrIdentifier);
  28891. #if JUCE_MAC
  28892. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28893. return true;
  28894. #if JUCE_PPC
  28895. FSRef fileRef;
  28896. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28897. {
  28898. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28899. if (resFileId != -1)
  28900. {
  28901. const int numEffects = Count1Resources ('aEff');
  28902. CloseResFile (resFileId);
  28903. if (numEffects > 0)
  28904. return true;
  28905. }
  28906. }
  28907. #endif
  28908. return false;
  28909. #elif JUCE_WINDOWS
  28910. return f.existsAsFile() && f.hasFileExtension (".dll");
  28911. #elif JUCE_LINUX
  28912. return f.existsAsFile() && f.hasFileExtension (".so");
  28913. #endif
  28914. }
  28915. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28916. {
  28917. return fileOrIdentifier;
  28918. }
  28919. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28920. {
  28921. return File (desc.fileOrIdentifier).exists();
  28922. }
  28923. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28924. {
  28925. StringArray results;
  28926. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28927. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28928. return results;
  28929. }
  28930. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28931. {
  28932. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28933. // .component or .vst directories.
  28934. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28935. while (iter.next())
  28936. {
  28937. const File f (iter.getFile());
  28938. bool isPlugin = false;
  28939. if (fileMightContainThisPluginType (f.getFullPathName()))
  28940. {
  28941. isPlugin = true;
  28942. results.add (f.getFullPathName());
  28943. }
  28944. if (recursive && (! isPlugin) && f.isDirectory())
  28945. recursiveFileSearch (results, f, true);
  28946. }
  28947. }
  28948. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28949. {
  28950. #if JUCE_MAC
  28951. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28952. #elif JUCE_WINDOWS
  28953. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28954. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28955. #elif JUCE_LINUX
  28956. return FileSearchPath ("/usr/lib/vst");
  28957. #endif
  28958. }
  28959. END_JUCE_NAMESPACE
  28960. #endif
  28961. #undef log
  28962. #endif
  28963. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28964. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28965. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28966. BEGIN_JUCE_NAMESPACE
  28967. AudioProcessor::AudioProcessor()
  28968. : playHead (0),
  28969. activeEditor (0),
  28970. sampleRate (0),
  28971. blockSize (0),
  28972. numInputChannels (0),
  28973. numOutputChannels (0),
  28974. latencySamples (0),
  28975. suspended (false),
  28976. nonRealtime (false)
  28977. {
  28978. }
  28979. AudioProcessor::~AudioProcessor()
  28980. {
  28981. // ooh, nasty - the editor should have been deleted before the filter
  28982. // that it refers to is deleted..
  28983. jassert (activeEditor == 0);
  28984. #if JUCE_DEBUG
  28985. // This will fail if you've called beginParameterChangeGesture() for one
  28986. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28987. jassert (changingParams.countNumberOfSetBits() == 0);
  28988. #endif
  28989. }
  28990. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28991. {
  28992. playHead = newPlayHead;
  28993. }
  28994. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28995. {
  28996. const ScopedLock sl (listenerLock);
  28997. listeners.addIfNotAlreadyThere (newListener);
  28998. }
  28999. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  29000. {
  29001. const ScopedLock sl (listenerLock);
  29002. listeners.removeValue (listenerToRemove);
  29003. }
  29004. void AudioProcessor::setPlayConfigDetails (const int numIns,
  29005. const int numOuts,
  29006. const double sampleRate_,
  29007. const int blockSize_) throw()
  29008. {
  29009. numInputChannels = numIns;
  29010. numOutputChannels = numOuts;
  29011. sampleRate = sampleRate_;
  29012. blockSize = blockSize_;
  29013. }
  29014. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  29015. {
  29016. nonRealtime = nonRealtime_;
  29017. }
  29018. void AudioProcessor::setLatencySamples (const int newLatency)
  29019. {
  29020. if (latencySamples != newLatency)
  29021. {
  29022. latencySamples = newLatency;
  29023. updateHostDisplay();
  29024. }
  29025. }
  29026. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  29027. const float newValue)
  29028. {
  29029. setParameter (parameterIndex, newValue);
  29030. sendParamChangeMessageToListeners (parameterIndex, newValue);
  29031. }
  29032. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  29033. {
  29034. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  29035. for (int i = listeners.size(); --i >= 0;)
  29036. {
  29037. AudioProcessorListener* l;
  29038. {
  29039. const ScopedLock sl (listenerLock);
  29040. l = listeners [i];
  29041. }
  29042. if (l != 0)
  29043. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  29044. }
  29045. }
  29046. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  29047. {
  29048. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  29049. #if JUCE_DEBUG
  29050. // This means you've called beginParameterChangeGesture twice in succession without a matching
  29051. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  29052. jassert (! changingParams [parameterIndex]);
  29053. changingParams.setBit (parameterIndex);
  29054. #endif
  29055. for (int i = listeners.size(); --i >= 0;)
  29056. {
  29057. AudioProcessorListener* l;
  29058. {
  29059. const ScopedLock sl (listenerLock);
  29060. l = listeners [i];
  29061. }
  29062. if (l != 0)
  29063. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  29064. }
  29065. }
  29066. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  29067. {
  29068. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  29069. #if JUCE_DEBUG
  29070. // This means you've called endParameterChangeGesture without having previously called
  29071. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  29072. // calls matched correctly.
  29073. jassert (changingParams [parameterIndex]);
  29074. changingParams.clearBit (parameterIndex);
  29075. #endif
  29076. for (int i = listeners.size(); --i >= 0;)
  29077. {
  29078. AudioProcessorListener* l;
  29079. {
  29080. const ScopedLock sl (listenerLock);
  29081. l = listeners [i];
  29082. }
  29083. if (l != 0)
  29084. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  29085. }
  29086. }
  29087. void AudioProcessor::updateHostDisplay()
  29088. {
  29089. for (int i = listeners.size(); --i >= 0;)
  29090. {
  29091. AudioProcessorListener* l;
  29092. {
  29093. const ScopedLock sl (listenerLock);
  29094. l = listeners [i];
  29095. }
  29096. if (l != 0)
  29097. l->audioProcessorChanged (this);
  29098. }
  29099. }
  29100. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  29101. {
  29102. return true;
  29103. }
  29104. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  29105. {
  29106. return false;
  29107. }
  29108. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  29109. {
  29110. const ScopedLock sl (callbackLock);
  29111. suspended = shouldBeSuspended;
  29112. }
  29113. void AudioProcessor::reset()
  29114. {
  29115. }
  29116. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  29117. {
  29118. const ScopedLock sl (callbackLock);
  29119. jassert (activeEditor == editor);
  29120. if (activeEditor == editor)
  29121. activeEditor = 0;
  29122. }
  29123. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  29124. {
  29125. if (activeEditor != 0)
  29126. return activeEditor;
  29127. AudioProcessorEditor* const ed = createEditor();
  29128. if (ed != 0)
  29129. {
  29130. // you must give your editor comp a size before returning it..
  29131. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  29132. const ScopedLock sl (callbackLock);
  29133. activeEditor = ed;
  29134. }
  29135. return ed;
  29136. }
  29137. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  29138. {
  29139. getStateInformation (destData);
  29140. }
  29141. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  29142. {
  29143. setStateInformation (data, sizeInBytes);
  29144. }
  29145. // magic number to identify memory blocks that we've stored as XML
  29146. const uint32 magicXmlNumber = 0x21324356;
  29147. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  29148. JUCE_NAMESPACE::MemoryBlock& destData)
  29149. {
  29150. const String xmlString (xml.createDocument (String::empty, true, false));
  29151. const int stringLength = xmlString.getNumBytesAsUTF8();
  29152. destData.setSize (stringLength + 10);
  29153. char* const d = static_cast<char*> (destData.getData());
  29154. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  29155. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  29156. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  29157. }
  29158. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  29159. const int sizeInBytes)
  29160. {
  29161. if (sizeInBytes > 8
  29162. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  29163. {
  29164. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  29165. if (stringLength > 0)
  29166. {
  29167. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  29168. jmin ((sizeInBytes - 8), stringLength)));
  29169. return doc.getDocumentElement();
  29170. }
  29171. }
  29172. return 0;
  29173. }
  29174. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  29175. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  29176. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  29177. {
  29178. return timeInSeconds == other.timeInSeconds
  29179. && ppqPosition == other.ppqPosition
  29180. && editOriginTime == other.editOriginTime
  29181. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  29182. && frameRate == other.frameRate
  29183. && isPlaying == other.isPlaying
  29184. && isRecording == other.isRecording
  29185. && bpm == other.bpm
  29186. && timeSigNumerator == other.timeSigNumerator
  29187. && timeSigDenominator == other.timeSigDenominator;
  29188. }
  29189. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  29190. {
  29191. return ! operator== (other);
  29192. }
  29193. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  29194. {
  29195. zerostruct (*this);
  29196. timeSigNumerator = 4;
  29197. timeSigDenominator = 4;
  29198. bpm = 120;
  29199. }
  29200. END_JUCE_NAMESPACE
  29201. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  29202. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  29203. BEGIN_JUCE_NAMESPACE
  29204. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  29205. : owner (owner_)
  29206. {
  29207. // the filter must be valid..
  29208. jassert (owner != 0);
  29209. }
  29210. AudioProcessorEditor::~AudioProcessorEditor()
  29211. {
  29212. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  29213. // filter for some reason..
  29214. jassert (owner->getActiveEditor() != this);
  29215. }
  29216. END_JUCE_NAMESPACE
  29217. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  29218. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  29219. BEGIN_JUCE_NAMESPACE
  29220. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  29221. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  29222. : id (id_),
  29223. processor (processor_),
  29224. isPrepared (false)
  29225. {
  29226. jassert (processor_ != 0);
  29227. }
  29228. AudioProcessorGraph::Node::~Node()
  29229. {
  29230. }
  29231. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  29232. AudioProcessorGraph* const graph)
  29233. {
  29234. if (! isPrepared)
  29235. {
  29236. isPrepared = true;
  29237. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29238. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  29239. if (ioProc != 0)
  29240. ioProc->setParentGraph (graph);
  29241. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  29242. processor->getNumOutputChannels(),
  29243. sampleRate, blockSize);
  29244. processor->prepareToPlay (sampleRate, blockSize);
  29245. }
  29246. }
  29247. void AudioProcessorGraph::Node::unprepare()
  29248. {
  29249. if (isPrepared)
  29250. {
  29251. isPrepared = false;
  29252. processor->releaseResources();
  29253. }
  29254. }
  29255. AudioProcessorGraph::AudioProcessorGraph()
  29256. : lastNodeId (0),
  29257. renderingBuffers (1, 1),
  29258. currentAudioOutputBuffer (1, 1)
  29259. {
  29260. }
  29261. AudioProcessorGraph::~AudioProcessorGraph()
  29262. {
  29263. clearRenderingSequence();
  29264. clear();
  29265. }
  29266. const String AudioProcessorGraph::getName() const
  29267. {
  29268. return "Audio Graph";
  29269. }
  29270. void AudioProcessorGraph::clear()
  29271. {
  29272. nodes.clear();
  29273. connections.clear();
  29274. triggerAsyncUpdate();
  29275. }
  29276. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29277. {
  29278. for (int i = nodes.size(); --i >= 0;)
  29279. if (nodes.getUnchecked(i)->id == nodeId)
  29280. return nodes.getUnchecked(i);
  29281. return 0;
  29282. }
  29283. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29284. uint32 nodeId)
  29285. {
  29286. if (newProcessor == 0)
  29287. {
  29288. jassertfalse;
  29289. return 0;
  29290. }
  29291. if (nodeId == 0)
  29292. {
  29293. nodeId = ++lastNodeId;
  29294. }
  29295. else
  29296. {
  29297. // you can't add a node with an id that already exists in the graph..
  29298. jassert (getNodeForId (nodeId) == 0);
  29299. removeNode (nodeId);
  29300. }
  29301. lastNodeId = nodeId;
  29302. Node* const n = new Node (nodeId, newProcessor);
  29303. nodes.add (n);
  29304. triggerAsyncUpdate();
  29305. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29306. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29307. if (ioProc != 0)
  29308. ioProc->setParentGraph (this);
  29309. return n;
  29310. }
  29311. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29312. {
  29313. disconnectNode (nodeId);
  29314. for (int i = nodes.size(); --i >= 0;)
  29315. {
  29316. if (nodes.getUnchecked(i)->id == nodeId)
  29317. {
  29318. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29319. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29320. if (ioProc != 0)
  29321. ioProc->setParentGraph (0);
  29322. nodes.remove (i);
  29323. triggerAsyncUpdate();
  29324. return true;
  29325. }
  29326. }
  29327. return false;
  29328. }
  29329. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29330. const int sourceChannelIndex,
  29331. const uint32 destNodeId,
  29332. const int destChannelIndex) const
  29333. {
  29334. for (int i = connections.size(); --i >= 0;)
  29335. {
  29336. const Connection* const c = connections.getUnchecked(i);
  29337. if (c->sourceNodeId == sourceNodeId
  29338. && c->destNodeId == destNodeId
  29339. && c->sourceChannelIndex == sourceChannelIndex
  29340. && c->destChannelIndex == destChannelIndex)
  29341. {
  29342. return c;
  29343. }
  29344. }
  29345. return 0;
  29346. }
  29347. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29348. const uint32 possibleDestNodeId) const
  29349. {
  29350. for (int i = connections.size(); --i >= 0;)
  29351. {
  29352. const Connection* const c = connections.getUnchecked(i);
  29353. if (c->sourceNodeId == possibleSourceNodeId
  29354. && c->destNodeId == possibleDestNodeId)
  29355. {
  29356. return true;
  29357. }
  29358. }
  29359. return false;
  29360. }
  29361. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29362. const int sourceChannelIndex,
  29363. const uint32 destNodeId,
  29364. const int destChannelIndex) const
  29365. {
  29366. if (sourceChannelIndex < 0
  29367. || destChannelIndex < 0
  29368. || sourceNodeId == destNodeId
  29369. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29370. return false;
  29371. const Node* const source = getNodeForId (sourceNodeId);
  29372. if (source == 0
  29373. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29374. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29375. return false;
  29376. const Node* const dest = getNodeForId (destNodeId);
  29377. if (dest == 0
  29378. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29379. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29380. return false;
  29381. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29382. destNodeId, destChannelIndex) == 0;
  29383. }
  29384. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29385. const int sourceChannelIndex,
  29386. const uint32 destNodeId,
  29387. const int destChannelIndex)
  29388. {
  29389. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29390. return false;
  29391. Connection* const c = new Connection();
  29392. c->sourceNodeId = sourceNodeId;
  29393. c->sourceChannelIndex = sourceChannelIndex;
  29394. c->destNodeId = destNodeId;
  29395. c->destChannelIndex = destChannelIndex;
  29396. connections.add (c);
  29397. triggerAsyncUpdate();
  29398. return true;
  29399. }
  29400. void AudioProcessorGraph::removeConnection (const int index)
  29401. {
  29402. connections.remove (index);
  29403. triggerAsyncUpdate();
  29404. }
  29405. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29406. const uint32 destNodeId, const int destChannelIndex)
  29407. {
  29408. bool doneAnything = false;
  29409. for (int i = connections.size(); --i >= 0;)
  29410. {
  29411. const Connection* const c = connections.getUnchecked(i);
  29412. if (c->sourceNodeId == sourceNodeId
  29413. && c->destNodeId == destNodeId
  29414. && c->sourceChannelIndex == sourceChannelIndex
  29415. && c->destChannelIndex == destChannelIndex)
  29416. {
  29417. removeConnection (i);
  29418. doneAnything = true;
  29419. triggerAsyncUpdate();
  29420. }
  29421. }
  29422. return doneAnything;
  29423. }
  29424. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29425. {
  29426. bool doneAnything = false;
  29427. for (int i = connections.size(); --i >= 0;)
  29428. {
  29429. const Connection* const c = connections.getUnchecked(i);
  29430. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29431. {
  29432. removeConnection (i);
  29433. doneAnything = true;
  29434. triggerAsyncUpdate();
  29435. }
  29436. }
  29437. return doneAnything;
  29438. }
  29439. bool AudioProcessorGraph::removeIllegalConnections()
  29440. {
  29441. bool doneAnything = false;
  29442. for (int i = connections.size(); --i >= 0;)
  29443. {
  29444. const Connection* const c = connections.getUnchecked(i);
  29445. const Node* const source = getNodeForId (c->sourceNodeId);
  29446. const Node* const dest = getNodeForId (c->destNodeId);
  29447. if (source == 0 || dest == 0
  29448. || (c->sourceChannelIndex != midiChannelIndex
  29449. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29450. || (c->sourceChannelIndex == midiChannelIndex
  29451. && ! source->processor->producesMidi())
  29452. || (c->destChannelIndex != midiChannelIndex
  29453. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29454. || (c->destChannelIndex == midiChannelIndex
  29455. && ! dest->processor->acceptsMidi()))
  29456. {
  29457. removeConnection (i);
  29458. doneAnything = true;
  29459. triggerAsyncUpdate();
  29460. }
  29461. }
  29462. return doneAnything;
  29463. }
  29464. namespace GraphRenderingOps
  29465. {
  29466. class AudioGraphRenderingOp
  29467. {
  29468. public:
  29469. AudioGraphRenderingOp() {}
  29470. virtual ~AudioGraphRenderingOp() {}
  29471. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29472. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29473. const int numSamples) = 0;
  29474. juce_UseDebuggingNewOperator
  29475. };
  29476. class ClearChannelOp : public AudioGraphRenderingOp
  29477. {
  29478. public:
  29479. ClearChannelOp (const int channelNum_)
  29480. : channelNum (channelNum_)
  29481. {}
  29482. ~ClearChannelOp() {}
  29483. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29484. {
  29485. sharedBufferChans.clear (channelNum, 0, numSamples);
  29486. }
  29487. private:
  29488. const int channelNum;
  29489. ClearChannelOp (const ClearChannelOp&);
  29490. ClearChannelOp& operator= (const ClearChannelOp&);
  29491. };
  29492. class CopyChannelOp : public AudioGraphRenderingOp
  29493. {
  29494. public:
  29495. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29496. : srcChannelNum (srcChannelNum_),
  29497. dstChannelNum (dstChannelNum_)
  29498. {}
  29499. ~CopyChannelOp() {}
  29500. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29501. {
  29502. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29503. }
  29504. private:
  29505. const int srcChannelNum, dstChannelNum;
  29506. CopyChannelOp (const CopyChannelOp&);
  29507. CopyChannelOp& operator= (const CopyChannelOp&);
  29508. };
  29509. class AddChannelOp : public AudioGraphRenderingOp
  29510. {
  29511. public:
  29512. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29513. : srcChannelNum (srcChannelNum_),
  29514. dstChannelNum (dstChannelNum_)
  29515. {}
  29516. ~AddChannelOp() {}
  29517. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29518. {
  29519. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29520. }
  29521. private:
  29522. const int srcChannelNum, dstChannelNum;
  29523. AddChannelOp (const AddChannelOp&);
  29524. AddChannelOp& operator= (const AddChannelOp&);
  29525. };
  29526. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29527. {
  29528. public:
  29529. ClearMidiBufferOp (const int bufferNum_)
  29530. : bufferNum (bufferNum_)
  29531. {}
  29532. ~ClearMidiBufferOp() {}
  29533. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29534. {
  29535. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29536. }
  29537. private:
  29538. const int bufferNum;
  29539. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29540. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29541. };
  29542. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29543. {
  29544. public:
  29545. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29546. : srcBufferNum (srcBufferNum_),
  29547. dstBufferNum (dstBufferNum_)
  29548. {}
  29549. ~CopyMidiBufferOp() {}
  29550. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29551. {
  29552. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29553. }
  29554. private:
  29555. const int srcBufferNum, dstBufferNum;
  29556. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29557. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29558. };
  29559. class AddMidiBufferOp : public AudioGraphRenderingOp
  29560. {
  29561. public:
  29562. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29563. : srcBufferNum (srcBufferNum_),
  29564. dstBufferNum (dstBufferNum_)
  29565. {}
  29566. ~AddMidiBufferOp() {}
  29567. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29568. {
  29569. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29570. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29571. }
  29572. private:
  29573. const int srcBufferNum, dstBufferNum;
  29574. AddMidiBufferOp (const AddMidiBufferOp&);
  29575. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29576. };
  29577. class ProcessBufferOp : public AudioGraphRenderingOp
  29578. {
  29579. public:
  29580. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29581. const Array <int>& audioChannelsToUse_,
  29582. const int totalChans_,
  29583. const int midiBufferToUse_)
  29584. : node (node_),
  29585. processor (node_->getProcessor()),
  29586. audioChannelsToUse (audioChannelsToUse_),
  29587. totalChans (jmax (1, totalChans_)),
  29588. midiBufferToUse (midiBufferToUse_)
  29589. {
  29590. channels.calloc (totalChans);
  29591. while (audioChannelsToUse.size() < totalChans)
  29592. audioChannelsToUse.add (0);
  29593. }
  29594. ~ProcessBufferOp()
  29595. {
  29596. }
  29597. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29598. {
  29599. for (int i = totalChans; --i >= 0;)
  29600. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29601. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29602. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29603. }
  29604. const AudioProcessorGraph::Node::Ptr node;
  29605. AudioProcessor* const processor;
  29606. private:
  29607. Array <int> audioChannelsToUse;
  29608. HeapBlock <float*> channels;
  29609. int totalChans;
  29610. int midiBufferToUse;
  29611. ProcessBufferOp (const ProcessBufferOp&);
  29612. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29613. };
  29614. /** Used to calculate the correct sequence of rendering ops needed, based on
  29615. the best re-use of shared buffers at each stage.
  29616. */
  29617. class RenderingOpSequenceCalculator
  29618. {
  29619. public:
  29620. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29621. const Array<void*>& orderedNodes_,
  29622. Array<void*>& renderingOps)
  29623. : graph (graph_),
  29624. orderedNodes (orderedNodes_)
  29625. {
  29626. nodeIds.add (-2); // first buffer is read-only zeros
  29627. channels.add (0);
  29628. midiNodeIds.add (-2);
  29629. for (int i = 0; i < orderedNodes.size(); ++i)
  29630. {
  29631. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29632. renderingOps, i);
  29633. markAnyUnusedBuffersAsFree (i);
  29634. }
  29635. }
  29636. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29637. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29638. juce_UseDebuggingNewOperator
  29639. private:
  29640. AudioProcessorGraph& graph;
  29641. const Array<void*>& orderedNodes;
  29642. Array <int> nodeIds, channels, midiNodeIds;
  29643. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29644. Array<void*>& renderingOps,
  29645. const int ourRenderingIndex)
  29646. {
  29647. const int numIns = node->getProcessor()->getNumInputChannels();
  29648. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29649. const int totalChans = jmax (numIns, numOuts);
  29650. Array <int> audioChannelsToUse;
  29651. int midiBufferToUse = -1;
  29652. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29653. {
  29654. // get a list of all the inputs to this node
  29655. Array <int> sourceNodes, sourceOutputChans;
  29656. for (int i = graph.getNumConnections(); --i >= 0;)
  29657. {
  29658. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29659. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29660. {
  29661. sourceNodes.add (c->sourceNodeId);
  29662. sourceOutputChans.add (c->sourceChannelIndex);
  29663. }
  29664. }
  29665. int bufIndex = -1;
  29666. if (sourceNodes.size() == 0)
  29667. {
  29668. // unconnected input channel
  29669. if (inputChan >= numOuts)
  29670. {
  29671. bufIndex = getReadOnlyEmptyBuffer();
  29672. jassert (bufIndex >= 0);
  29673. }
  29674. else
  29675. {
  29676. bufIndex = getFreeBuffer (false);
  29677. renderingOps.add (new ClearChannelOp (bufIndex));
  29678. }
  29679. }
  29680. else if (sourceNodes.size() == 1)
  29681. {
  29682. // channel with a straightforward single input..
  29683. const int srcNode = sourceNodes.getUnchecked(0);
  29684. const int srcChan = sourceOutputChans.getUnchecked(0);
  29685. bufIndex = getBufferContaining (srcNode, srcChan);
  29686. if (bufIndex < 0)
  29687. {
  29688. // if not found, this is probably a feedback loop
  29689. bufIndex = getReadOnlyEmptyBuffer();
  29690. jassert (bufIndex >= 0);
  29691. }
  29692. if (inputChan < numOuts
  29693. && isBufferNeededLater (ourRenderingIndex,
  29694. inputChan,
  29695. srcNode, srcChan))
  29696. {
  29697. // can't mess up this channel because it's needed later by another node, so we
  29698. // need to use a copy of it..
  29699. const int newFreeBuffer = getFreeBuffer (false);
  29700. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29701. bufIndex = newFreeBuffer;
  29702. }
  29703. }
  29704. else
  29705. {
  29706. // channel with a mix of several inputs..
  29707. // try to find a re-usable channel from our inputs..
  29708. int reusableInputIndex = -1;
  29709. for (int i = 0; i < sourceNodes.size(); ++i)
  29710. {
  29711. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29712. sourceOutputChans.getUnchecked(i));
  29713. if (sourceBufIndex >= 0
  29714. && ! isBufferNeededLater (ourRenderingIndex,
  29715. inputChan,
  29716. sourceNodes.getUnchecked(i),
  29717. sourceOutputChans.getUnchecked(i)))
  29718. {
  29719. // we've found one of our input chans that can be re-used..
  29720. reusableInputIndex = i;
  29721. bufIndex = sourceBufIndex;
  29722. break;
  29723. }
  29724. }
  29725. if (reusableInputIndex < 0)
  29726. {
  29727. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29728. bufIndex = getFreeBuffer (false);
  29729. jassert (bufIndex != 0);
  29730. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29731. sourceOutputChans.getUnchecked (0));
  29732. if (srcIndex < 0)
  29733. {
  29734. // if not found, this is probably a feedback loop
  29735. renderingOps.add (new ClearChannelOp (bufIndex));
  29736. }
  29737. else
  29738. {
  29739. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29740. }
  29741. reusableInputIndex = 0;
  29742. }
  29743. for (int j = 0; j < sourceNodes.size(); ++j)
  29744. {
  29745. if (j != reusableInputIndex)
  29746. {
  29747. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29748. sourceOutputChans.getUnchecked(j));
  29749. if (srcIndex >= 0)
  29750. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29751. }
  29752. }
  29753. }
  29754. jassert (bufIndex >= 0);
  29755. audioChannelsToUse.add (bufIndex);
  29756. if (inputChan < numOuts)
  29757. markBufferAsContaining (bufIndex, node->id, inputChan);
  29758. }
  29759. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29760. {
  29761. const int bufIndex = getFreeBuffer (false);
  29762. jassert (bufIndex != 0);
  29763. audioChannelsToUse.add (bufIndex);
  29764. markBufferAsContaining (bufIndex, node->id, outputChan);
  29765. }
  29766. // Now the same thing for midi..
  29767. Array <int> midiSourceNodes;
  29768. for (int i = graph.getNumConnections(); --i >= 0;)
  29769. {
  29770. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29771. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29772. midiSourceNodes.add (c->sourceNodeId);
  29773. }
  29774. if (midiSourceNodes.size() == 0)
  29775. {
  29776. // No midi inputs..
  29777. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29778. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29779. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29780. }
  29781. else if (midiSourceNodes.size() == 1)
  29782. {
  29783. // One midi input..
  29784. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29785. AudioProcessorGraph::midiChannelIndex);
  29786. if (midiBufferToUse >= 0)
  29787. {
  29788. if (isBufferNeededLater (ourRenderingIndex,
  29789. AudioProcessorGraph::midiChannelIndex,
  29790. midiSourceNodes.getUnchecked(0),
  29791. AudioProcessorGraph::midiChannelIndex))
  29792. {
  29793. // can't mess up this channel because it's needed later by another node, so we
  29794. // need to use a copy of it..
  29795. const int newFreeBuffer = getFreeBuffer (true);
  29796. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29797. midiBufferToUse = newFreeBuffer;
  29798. }
  29799. }
  29800. else
  29801. {
  29802. // probably a feedback loop, so just use an empty one..
  29803. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29804. }
  29805. }
  29806. else
  29807. {
  29808. // More than one midi input being mixed..
  29809. int reusableInputIndex = -1;
  29810. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29811. {
  29812. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29813. AudioProcessorGraph::midiChannelIndex);
  29814. if (sourceBufIndex >= 0
  29815. && ! isBufferNeededLater (ourRenderingIndex,
  29816. AudioProcessorGraph::midiChannelIndex,
  29817. midiSourceNodes.getUnchecked(i),
  29818. AudioProcessorGraph::midiChannelIndex))
  29819. {
  29820. // we've found one of our input buffers that can be re-used..
  29821. reusableInputIndex = i;
  29822. midiBufferToUse = sourceBufIndex;
  29823. break;
  29824. }
  29825. }
  29826. if (reusableInputIndex < 0)
  29827. {
  29828. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29829. midiBufferToUse = getFreeBuffer (true);
  29830. jassert (midiBufferToUse >= 0);
  29831. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29832. AudioProcessorGraph::midiChannelIndex);
  29833. if (srcIndex >= 0)
  29834. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29835. else
  29836. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29837. reusableInputIndex = 0;
  29838. }
  29839. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29840. {
  29841. if (j != reusableInputIndex)
  29842. {
  29843. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29844. AudioProcessorGraph::midiChannelIndex);
  29845. if (srcIndex >= 0)
  29846. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29847. }
  29848. }
  29849. }
  29850. if (node->getProcessor()->producesMidi())
  29851. markBufferAsContaining (midiBufferToUse, node->id,
  29852. AudioProcessorGraph::midiChannelIndex);
  29853. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29854. totalChans, midiBufferToUse));
  29855. }
  29856. int getFreeBuffer (const bool forMidi)
  29857. {
  29858. if (forMidi)
  29859. {
  29860. for (int i = 1; i < midiNodeIds.size(); ++i)
  29861. if (midiNodeIds.getUnchecked(i) < 0)
  29862. return i;
  29863. midiNodeIds.add (-1);
  29864. return midiNodeIds.size() - 1;
  29865. }
  29866. else
  29867. {
  29868. for (int i = 1; i < nodeIds.size(); ++i)
  29869. if (nodeIds.getUnchecked(i) < 0)
  29870. return i;
  29871. nodeIds.add (-1);
  29872. channels.add (0);
  29873. return nodeIds.size() - 1;
  29874. }
  29875. }
  29876. int getReadOnlyEmptyBuffer() const
  29877. {
  29878. return 0;
  29879. }
  29880. int getBufferContaining (const int nodeId, const int outputChannel) const
  29881. {
  29882. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29883. {
  29884. for (int i = midiNodeIds.size(); --i >= 0;)
  29885. if (midiNodeIds.getUnchecked(i) == nodeId)
  29886. return i;
  29887. }
  29888. else
  29889. {
  29890. for (int i = nodeIds.size(); --i >= 0;)
  29891. if (nodeIds.getUnchecked(i) == nodeId
  29892. && channels.getUnchecked(i) == outputChannel)
  29893. return i;
  29894. }
  29895. return -1;
  29896. }
  29897. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29898. {
  29899. int i;
  29900. for (i = 0; i < nodeIds.size(); ++i)
  29901. {
  29902. if (nodeIds.getUnchecked(i) >= 0
  29903. && ! isBufferNeededLater (stepIndex, -1,
  29904. nodeIds.getUnchecked(i),
  29905. channels.getUnchecked(i)))
  29906. {
  29907. nodeIds.set (i, -1);
  29908. }
  29909. }
  29910. for (i = 0; i < midiNodeIds.size(); ++i)
  29911. {
  29912. if (midiNodeIds.getUnchecked(i) >= 0
  29913. && ! isBufferNeededLater (stepIndex, -1,
  29914. midiNodeIds.getUnchecked(i),
  29915. AudioProcessorGraph::midiChannelIndex))
  29916. {
  29917. midiNodeIds.set (i, -1);
  29918. }
  29919. }
  29920. }
  29921. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29922. int inputChannelOfIndexToIgnore,
  29923. const int nodeId,
  29924. const int outputChanIndex) const
  29925. {
  29926. while (stepIndexToSearchFrom < orderedNodes.size())
  29927. {
  29928. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29929. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29930. {
  29931. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29932. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29933. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29934. return true;
  29935. }
  29936. else
  29937. {
  29938. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29939. if (i != inputChannelOfIndexToIgnore
  29940. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29941. node->id, i) != 0)
  29942. return true;
  29943. }
  29944. inputChannelOfIndexToIgnore = -1;
  29945. ++stepIndexToSearchFrom;
  29946. }
  29947. return false;
  29948. }
  29949. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29950. {
  29951. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29952. {
  29953. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29954. midiNodeIds.set (bufferNum, nodeId);
  29955. }
  29956. else
  29957. {
  29958. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29959. nodeIds.set (bufferNum, nodeId);
  29960. channels.set (bufferNum, outputIndex);
  29961. }
  29962. }
  29963. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29964. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29965. };
  29966. }
  29967. void AudioProcessorGraph::clearRenderingSequence()
  29968. {
  29969. const ScopedLock sl (renderLock);
  29970. for (int i = renderingOps.size(); --i >= 0;)
  29971. {
  29972. GraphRenderingOps::AudioGraphRenderingOp* const r
  29973. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29974. renderingOps.remove (i);
  29975. delete r;
  29976. }
  29977. }
  29978. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29979. const uint32 possibleDestinationId,
  29980. const int recursionCheck) const
  29981. {
  29982. if (recursionCheck > 0)
  29983. {
  29984. for (int i = connections.size(); --i >= 0;)
  29985. {
  29986. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29987. if (c->destNodeId == possibleDestinationId
  29988. && (c->sourceNodeId == possibleInputId
  29989. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29990. return true;
  29991. }
  29992. }
  29993. return false;
  29994. }
  29995. void AudioProcessorGraph::buildRenderingSequence()
  29996. {
  29997. Array<void*> newRenderingOps;
  29998. int numRenderingBuffersNeeded = 2;
  29999. int numMidiBuffersNeeded = 1;
  30000. {
  30001. MessageManagerLock mml;
  30002. Array<void*> orderedNodes;
  30003. int i;
  30004. for (i = 0; i < nodes.size(); ++i)
  30005. {
  30006. Node* const node = nodes.getUnchecked(i);
  30007. node->prepare (getSampleRate(), getBlockSize(), this);
  30008. int j = 0;
  30009. for (; j < orderedNodes.size(); ++j)
  30010. if (isAnInputTo (node->id,
  30011. ((Node*) orderedNodes.getUnchecked (j))->id,
  30012. nodes.size() + 1))
  30013. break;
  30014. orderedNodes.insert (j, node);
  30015. }
  30016. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  30017. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  30018. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  30019. }
  30020. Array<void*> oldRenderingOps (renderingOps);
  30021. {
  30022. // swap over to the new rendering sequence..
  30023. const ScopedLock sl (renderLock);
  30024. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  30025. renderingBuffers.clear();
  30026. for (int i = midiBuffers.size(); --i >= 0;)
  30027. midiBuffers.getUnchecked(i)->clear();
  30028. while (midiBuffers.size() < numMidiBuffersNeeded)
  30029. midiBuffers.add (new MidiBuffer());
  30030. renderingOps = newRenderingOps;
  30031. }
  30032. for (int i = oldRenderingOps.size(); --i >= 0;)
  30033. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  30034. }
  30035. void AudioProcessorGraph::handleAsyncUpdate()
  30036. {
  30037. buildRenderingSequence();
  30038. }
  30039. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  30040. {
  30041. currentAudioInputBuffer = 0;
  30042. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  30043. currentMidiInputBuffer = 0;
  30044. currentMidiOutputBuffer.clear();
  30045. clearRenderingSequence();
  30046. buildRenderingSequence();
  30047. }
  30048. void AudioProcessorGraph::releaseResources()
  30049. {
  30050. for (int i = 0; i < nodes.size(); ++i)
  30051. nodes.getUnchecked(i)->unprepare();
  30052. renderingBuffers.setSize (1, 1);
  30053. midiBuffers.clear();
  30054. currentAudioInputBuffer = 0;
  30055. currentAudioOutputBuffer.setSize (1, 1);
  30056. currentMidiInputBuffer = 0;
  30057. currentMidiOutputBuffer.clear();
  30058. }
  30059. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  30060. {
  30061. const int numSamples = buffer.getNumSamples();
  30062. const ScopedLock sl (renderLock);
  30063. currentAudioInputBuffer = &buffer;
  30064. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  30065. currentAudioOutputBuffer.clear();
  30066. currentMidiInputBuffer = &midiMessages;
  30067. currentMidiOutputBuffer.clear();
  30068. int i;
  30069. for (i = 0; i < renderingOps.size(); ++i)
  30070. {
  30071. GraphRenderingOps::AudioGraphRenderingOp* const op
  30072. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  30073. op->perform (renderingBuffers, midiBuffers, numSamples);
  30074. }
  30075. for (i = 0; i < buffer.getNumChannels(); ++i)
  30076. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  30077. midiMessages.clear();
  30078. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  30079. }
  30080. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  30081. {
  30082. return "Input " + String (channelIndex + 1);
  30083. }
  30084. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  30085. {
  30086. return "Output " + String (channelIndex + 1);
  30087. }
  30088. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  30089. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  30090. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  30091. bool AudioProcessorGraph::producesMidi() const { return true; }
  30092. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  30093. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  30094. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  30095. : type (type_),
  30096. graph (0)
  30097. {
  30098. }
  30099. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  30100. {
  30101. }
  30102. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  30103. {
  30104. switch (type)
  30105. {
  30106. case audioOutputNode: return "Audio Output";
  30107. case audioInputNode: return "Audio Input";
  30108. case midiOutputNode: return "Midi Output";
  30109. case midiInputNode: return "Midi Input";
  30110. default: break;
  30111. }
  30112. return String::empty;
  30113. }
  30114. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  30115. {
  30116. d.name = getName();
  30117. d.uid = d.name.hashCode();
  30118. d.category = "I/O devices";
  30119. d.pluginFormatName = "Internal";
  30120. d.manufacturerName = "Raw Material Software";
  30121. d.version = "1.0";
  30122. d.isInstrument = false;
  30123. d.numInputChannels = getNumInputChannels();
  30124. if (type == audioOutputNode && graph != 0)
  30125. d.numInputChannels = graph->getNumInputChannels();
  30126. d.numOutputChannels = getNumOutputChannels();
  30127. if (type == audioInputNode && graph != 0)
  30128. d.numOutputChannels = graph->getNumOutputChannels();
  30129. }
  30130. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  30131. {
  30132. jassert (graph != 0);
  30133. }
  30134. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  30135. {
  30136. }
  30137. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  30138. MidiBuffer& midiMessages)
  30139. {
  30140. jassert (graph != 0);
  30141. switch (type)
  30142. {
  30143. case audioOutputNode:
  30144. {
  30145. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  30146. buffer.getNumChannels()); --i >= 0;)
  30147. {
  30148. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  30149. }
  30150. break;
  30151. }
  30152. case audioInputNode:
  30153. {
  30154. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  30155. buffer.getNumChannels()); --i >= 0;)
  30156. {
  30157. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  30158. }
  30159. break;
  30160. }
  30161. case midiOutputNode:
  30162. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  30163. break;
  30164. case midiInputNode:
  30165. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  30166. break;
  30167. default:
  30168. break;
  30169. }
  30170. }
  30171. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  30172. {
  30173. return type == midiOutputNode;
  30174. }
  30175. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  30176. {
  30177. return type == midiInputNode;
  30178. }
  30179. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  30180. {
  30181. switch (type)
  30182. {
  30183. case audioOutputNode: return "Output " + String (channelIndex + 1);
  30184. case midiOutputNode: return "Midi Output";
  30185. default: break;
  30186. }
  30187. return String::empty;
  30188. }
  30189. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  30190. {
  30191. switch (type)
  30192. {
  30193. case audioInputNode: return "Input " + String (channelIndex + 1);
  30194. case midiInputNode: return "Midi Input";
  30195. default: break;
  30196. }
  30197. return String::empty;
  30198. }
  30199. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  30200. {
  30201. return type == audioInputNode || type == audioOutputNode;
  30202. }
  30203. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  30204. {
  30205. return isInputChannelStereoPair (index);
  30206. }
  30207. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  30208. {
  30209. return type == audioInputNode || type == midiInputNode;
  30210. }
  30211. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  30212. {
  30213. return type == audioOutputNode || type == midiOutputNode;
  30214. }
  30215. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  30216. {
  30217. return 0;
  30218. }
  30219. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  30220. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  30221. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  30222. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  30223. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  30224. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  30225. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  30226. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  30227. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  30228. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  30229. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  30230. {
  30231. }
  30232. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  30233. {
  30234. }
  30235. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  30236. {
  30237. graph = newGraph;
  30238. if (graph != 0)
  30239. {
  30240. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  30241. type == audioInputNode ? graph->getNumInputChannels() : 0,
  30242. getSampleRate(),
  30243. getBlockSize());
  30244. updateHostDisplay();
  30245. }
  30246. }
  30247. END_JUCE_NAMESPACE
  30248. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30249. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30250. BEGIN_JUCE_NAMESPACE
  30251. AudioProcessorPlayer::AudioProcessorPlayer()
  30252. : processor (0),
  30253. sampleRate (0),
  30254. blockSize (0),
  30255. isPrepared (false),
  30256. numInputChans (0),
  30257. numOutputChans (0),
  30258. tempBuffer (1, 1)
  30259. {
  30260. }
  30261. AudioProcessorPlayer::~AudioProcessorPlayer()
  30262. {
  30263. setProcessor (0);
  30264. }
  30265. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30266. {
  30267. if (processor != processorToPlay)
  30268. {
  30269. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30270. {
  30271. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30272. sampleRate, blockSize);
  30273. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30274. }
  30275. AudioProcessor* oldOne;
  30276. {
  30277. const ScopedLock sl (lock);
  30278. oldOne = isPrepared ? processor : 0;
  30279. processor = processorToPlay;
  30280. isPrepared = true;
  30281. }
  30282. if (oldOne != 0)
  30283. oldOne->releaseResources();
  30284. }
  30285. }
  30286. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30287. const int numInputChannels,
  30288. float** const outputChannelData,
  30289. const int numOutputChannels,
  30290. const int numSamples)
  30291. {
  30292. // these should have been prepared by audioDeviceAboutToStart()...
  30293. jassert (sampleRate > 0 && blockSize > 0);
  30294. incomingMidi.clear();
  30295. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30296. int i, totalNumChans = 0;
  30297. if (numInputChannels > numOutputChannels)
  30298. {
  30299. // if there aren't enough output channels for the number of
  30300. // inputs, we need to create some temporary extra ones (can't
  30301. // use the input data in case it gets written to)
  30302. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30303. false, false, true);
  30304. for (i = 0; i < numOutputChannels; ++i)
  30305. {
  30306. channels[totalNumChans] = outputChannelData[i];
  30307. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30308. ++totalNumChans;
  30309. }
  30310. for (i = numOutputChannels; i < numInputChannels; ++i)
  30311. {
  30312. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30313. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30314. ++totalNumChans;
  30315. }
  30316. }
  30317. else
  30318. {
  30319. for (i = 0; i < numInputChannels; ++i)
  30320. {
  30321. channels[totalNumChans] = outputChannelData[i];
  30322. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30323. ++totalNumChans;
  30324. }
  30325. for (i = numInputChannels; i < numOutputChannels; ++i)
  30326. {
  30327. channels[totalNumChans] = outputChannelData[i];
  30328. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30329. ++totalNumChans;
  30330. }
  30331. }
  30332. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30333. const ScopedLock sl (lock);
  30334. if (processor != 0)
  30335. {
  30336. const ScopedLock sl (processor->getCallbackLock());
  30337. if (processor->isSuspended())
  30338. {
  30339. for (i = 0; i < numOutputChannels; ++i)
  30340. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30341. }
  30342. else
  30343. {
  30344. processor->processBlock (buffer, incomingMidi);
  30345. }
  30346. }
  30347. }
  30348. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30349. {
  30350. const ScopedLock sl (lock);
  30351. sampleRate = device->getCurrentSampleRate();
  30352. blockSize = device->getCurrentBufferSizeSamples();
  30353. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30354. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30355. messageCollector.reset (sampleRate);
  30356. zeromem (channels, sizeof (channels));
  30357. if (processor != 0)
  30358. {
  30359. if (isPrepared)
  30360. processor->releaseResources();
  30361. AudioProcessor* const oldProcessor = processor;
  30362. setProcessor (0);
  30363. setProcessor (oldProcessor);
  30364. }
  30365. }
  30366. void AudioProcessorPlayer::audioDeviceStopped()
  30367. {
  30368. const ScopedLock sl (lock);
  30369. if (processor != 0 && isPrepared)
  30370. processor->releaseResources();
  30371. sampleRate = 0.0;
  30372. blockSize = 0;
  30373. isPrepared = false;
  30374. tempBuffer.setSize (1, 1);
  30375. }
  30376. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30377. {
  30378. messageCollector.addMessageToQueue (message);
  30379. }
  30380. END_JUCE_NAMESPACE
  30381. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30382. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30383. BEGIN_JUCE_NAMESPACE
  30384. class ProcessorParameterPropertyComp : public PropertyComponent,
  30385. public AudioProcessorListener,
  30386. public AsyncUpdater
  30387. {
  30388. public:
  30389. ProcessorParameterPropertyComp (const String& name,
  30390. AudioProcessor* const owner_,
  30391. const int index_)
  30392. : PropertyComponent (name),
  30393. owner (owner_),
  30394. index (index_)
  30395. {
  30396. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  30397. owner_->addListener (this);
  30398. }
  30399. ~ProcessorParameterPropertyComp()
  30400. {
  30401. owner->removeListener (this);
  30402. deleteAllChildren();
  30403. }
  30404. void refresh()
  30405. {
  30406. slider->setValue (owner->getParameter (index), false);
  30407. }
  30408. void audioProcessorChanged (AudioProcessor*) {}
  30409. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30410. {
  30411. if (parameterIndex == index)
  30412. triggerAsyncUpdate();
  30413. }
  30414. void handleAsyncUpdate()
  30415. {
  30416. refresh();
  30417. }
  30418. juce_UseDebuggingNewOperator
  30419. private:
  30420. AudioProcessor* const owner;
  30421. const int index;
  30422. Slider* slider;
  30423. class ParamSlider : public Slider
  30424. {
  30425. public:
  30426. ParamSlider (AudioProcessor* const owner_, const int index_)
  30427. : Slider (String::empty),
  30428. owner (owner_),
  30429. index (index_)
  30430. {
  30431. setRange (0.0, 1.0, 0.0);
  30432. setSliderStyle (Slider::LinearBar);
  30433. setTextBoxIsEditable (false);
  30434. setScrollWheelEnabled (false);
  30435. }
  30436. ~ParamSlider()
  30437. {
  30438. }
  30439. void valueChanged()
  30440. {
  30441. const float newVal = (float) getValue();
  30442. if (owner->getParameter (index) != newVal)
  30443. owner->setParameter (index, newVal);
  30444. }
  30445. const String getTextFromValue (double /*value*/)
  30446. {
  30447. return owner->getParameterText (index);
  30448. }
  30449. juce_UseDebuggingNewOperator
  30450. private:
  30451. AudioProcessor* const owner;
  30452. const int index;
  30453. ParamSlider (const ParamSlider&);
  30454. ParamSlider& operator= (const ParamSlider&);
  30455. };
  30456. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30457. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30458. };
  30459. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30460. : AudioProcessorEditor (owner_)
  30461. {
  30462. setOpaque (true);
  30463. addAndMakeVisible (panel = new PropertyPanel());
  30464. Array <PropertyComponent*> params;
  30465. const int numParams = owner_->getNumParameters();
  30466. int totalHeight = 0;
  30467. for (int i = 0; i < numParams; ++i)
  30468. {
  30469. String name (owner_->getParameterName (i));
  30470. if (name.trim().isEmpty())
  30471. name = "Unnamed";
  30472. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  30473. params.add (pc);
  30474. totalHeight += pc->getPreferredHeight();
  30475. }
  30476. panel->addProperties (params);
  30477. setSize (400, jlimit (25, 400, totalHeight));
  30478. }
  30479. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30480. {
  30481. deleteAllChildren();
  30482. }
  30483. void GenericAudioProcessorEditor::paint (Graphics& g)
  30484. {
  30485. g.fillAll (Colours::white);
  30486. }
  30487. void GenericAudioProcessorEditor::resized()
  30488. {
  30489. panel->setSize (getWidth(), getHeight());
  30490. }
  30491. END_JUCE_NAMESPACE
  30492. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30493. /*** Start of inlined file: juce_Sampler.cpp ***/
  30494. BEGIN_JUCE_NAMESPACE
  30495. SamplerSound::SamplerSound (const String& name_,
  30496. AudioFormatReader& source,
  30497. const BigInteger& midiNotes_,
  30498. const int midiNoteForNormalPitch,
  30499. const double attackTimeSecs,
  30500. const double releaseTimeSecs,
  30501. const double maxSampleLengthSeconds)
  30502. : name (name_),
  30503. midiNotes (midiNotes_),
  30504. midiRootNote (midiNoteForNormalPitch)
  30505. {
  30506. sourceSampleRate = source.sampleRate;
  30507. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30508. {
  30509. length = 0;
  30510. attackSamples = 0;
  30511. releaseSamples = 0;
  30512. }
  30513. else
  30514. {
  30515. length = jmin ((int) source.lengthInSamples,
  30516. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30517. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30518. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30519. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30520. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30521. }
  30522. }
  30523. SamplerSound::~SamplerSound()
  30524. {
  30525. }
  30526. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30527. {
  30528. return midiNotes [midiNoteNumber];
  30529. }
  30530. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30531. {
  30532. return true;
  30533. }
  30534. SamplerVoice::SamplerVoice()
  30535. : pitchRatio (0.0),
  30536. sourceSamplePosition (0.0),
  30537. lgain (0.0f),
  30538. rgain (0.0f),
  30539. isInAttack (false),
  30540. isInRelease (false)
  30541. {
  30542. }
  30543. SamplerVoice::~SamplerVoice()
  30544. {
  30545. }
  30546. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30547. {
  30548. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30549. }
  30550. void SamplerVoice::startNote (const int midiNoteNumber,
  30551. const float velocity,
  30552. SynthesiserSound* s,
  30553. const int /*currentPitchWheelPosition*/)
  30554. {
  30555. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30556. jassert (sound != 0); // this object can only play SamplerSounds!
  30557. if (sound != 0)
  30558. {
  30559. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30560. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30561. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30562. sourceSamplePosition = 0.0;
  30563. lgain = velocity;
  30564. rgain = velocity;
  30565. isInAttack = (sound->attackSamples > 0);
  30566. isInRelease = false;
  30567. if (isInAttack)
  30568. {
  30569. attackReleaseLevel = 0.0f;
  30570. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30571. }
  30572. else
  30573. {
  30574. attackReleaseLevel = 1.0f;
  30575. attackDelta = 0.0f;
  30576. }
  30577. if (sound->releaseSamples > 0)
  30578. {
  30579. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30580. }
  30581. else
  30582. {
  30583. releaseDelta = 0.0f;
  30584. }
  30585. }
  30586. }
  30587. void SamplerVoice::stopNote (const bool allowTailOff)
  30588. {
  30589. if (allowTailOff)
  30590. {
  30591. isInAttack = false;
  30592. isInRelease = true;
  30593. }
  30594. else
  30595. {
  30596. clearCurrentNote();
  30597. }
  30598. }
  30599. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30600. {
  30601. }
  30602. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30603. const int /*newValue*/)
  30604. {
  30605. }
  30606. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30607. {
  30608. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30609. if (playingSound != 0)
  30610. {
  30611. const float* const inL = playingSound->data->getSampleData (0, 0);
  30612. const float* const inR = playingSound->data->getNumChannels() > 1
  30613. ? playingSound->data->getSampleData (1, 0) : 0;
  30614. float* outL = outputBuffer.getSampleData (0, startSample);
  30615. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30616. while (--numSamples >= 0)
  30617. {
  30618. const int pos = (int) sourceSamplePosition;
  30619. const float alpha = (float) (sourceSamplePosition - pos);
  30620. const float invAlpha = 1.0f - alpha;
  30621. // just using a very simple linear interpolation here..
  30622. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30623. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30624. : l;
  30625. l *= lgain;
  30626. r *= rgain;
  30627. if (isInAttack)
  30628. {
  30629. l *= attackReleaseLevel;
  30630. r *= attackReleaseLevel;
  30631. attackReleaseLevel += attackDelta;
  30632. if (attackReleaseLevel >= 1.0f)
  30633. {
  30634. attackReleaseLevel = 1.0f;
  30635. isInAttack = false;
  30636. }
  30637. }
  30638. else if (isInRelease)
  30639. {
  30640. l *= attackReleaseLevel;
  30641. r *= attackReleaseLevel;
  30642. attackReleaseLevel += releaseDelta;
  30643. if (attackReleaseLevel <= 0.0f)
  30644. {
  30645. stopNote (false);
  30646. break;
  30647. }
  30648. }
  30649. if (outR != 0)
  30650. {
  30651. *outL++ += l;
  30652. *outR++ += r;
  30653. }
  30654. else
  30655. {
  30656. *outL++ += (l + r) * 0.5f;
  30657. }
  30658. sourceSamplePosition += pitchRatio;
  30659. if (sourceSamplePosition > playingSound->length)
  30660. {
  30661. stopNote (false);
  30662. break;
  30663. }
  30664. }
  30665. }
  30666. }
  30667. END_JUCE_NAMESPACE
  30668. /*** End of inlined file: juce_Sampler.cpp ***/
  30669. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30670. BEGIN_JUCE_NAMESPACE
  30671. SynthesiserSound::SynthesiserSound()
  30672. {
  30673. }
  30674. SynthesiserSound::~SynthesiserSound()
  30675. {
  30676. }
  30677. SynthesiserVoice::SynthesiserVoice()
  30678. : currentSampleRate (44100.0),
  30679. currentlyPlayingNote (-1),
  30680. noteOnTime (0),
  30681. currentlyPlayingSound (0)
  30682. {
  30683. }
  30684. SynthesiserVoice::~SynthesiserVoice()
  30685. {
  30686. }
  30687. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30688. {
  30689. return currentlyPlayingSound != 0
  30690. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30691. }
  30692. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30693. {
  30694. currentSampleRate = newRate;
  30695. }
  30696. void SynthesiserVoice::clearCurrentNote()
  30697. {
  30698. currentlyPlayingNote = -1;
  30699. currentlyPlayingSound = 0;
  30700. }
  30701. Synthesiser::Synthesiser()
  30702. : sampleRate (0),
  30703. lastNoteOnCounter (0),
  30704. shouldStealNotes (true)
  30705. {
  30706. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30707. lastPitchWheelValues[i] = 0x2000;
  30708. }
  30709. Synthesiser::~Synthesiser()
  30710. {
  30711. }
  30712. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30713. {
  30714. const ScopedLock sl (lock);
  30715. return voices [index];
  30716. }
  30717. void Synthesiser::clearVoices()
  30718. {
  30719. const ScopedLock sl (lock);
  30720. voices.clear();
  30721. }
  30722. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30723. {
  30724. const ScopedLock sl (lock);
  30725. voices.add (newVoice);
  30726. }
  30727. void Synthesiser::removeVoice (const int index)
  30728. {
  30729. const ScopedLock sl (lock);
  30730. voices.remove (index);
  30731. }
  30732. void Synthesiser::clearSounds()
  30733. {
  30734. const ScopedLock sl (lock);
  30735. sounds.clear();
  30736. }
  30737. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30738. {
  30739. const ScopedLock sl (lock);
  30740. sounds.add (newSound);
  30741. }
  30742. void Synthesiser::removeSound (const int index)
  30743. {
  30744. const ScopedLock sl (lock);
  30745. sounds.remove (index);
  30746. }
  30747. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30748. {
  30749. shouldStealNotes = shouldStealNotes_;
  30750. }
  30751. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30752. {
  30753. if (sampleRate != newRate)
  30754. {
  30755. const ScopedLock sl (lock);
  30756. allNotesOff (0, false);
  30757. sampleRate = newRate;
  30758. for (int i = voices.size(); --i >= 0;)
  30759. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30760. }
  30761. }
  30762. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30763. const MidiBuffer& midiData,
  30764. int startSample,
  30765. int numSamples)
  30766. {
  30767. // must set the sample rate before using this!
  30768. jassert (sampleRate != 0);
  30769. const ScopedLock sl (lock);
  30770. MidiBuffer::Iterator midiIterator (midiData);
  30771. midiIterator.setNextSamplePosition (startSample);
  30772. MidiMessage m (0xf4, 0.0);
  30773. while (numSamples > 0)
  30774. {
  30775. int midiEventPos;
  30776. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30777. && midiEventPos < startSample + numSamples;
  30778. const int numThisTime = useEvent ? midiEventPos - startSample
  30779. : numSamples;
  30780. if (numThisTime > 0)
  30781. {
  30782. for (int i = voices.size(); --i >= 0;)
  30783. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30784. }
  30785. if (useEvent)
  30786. {
  30787. if (m.isNoteOn())
  30788. {
  30789. const int channel = m.getChannel();
  30790. noteOn (channel,
  30791. m.getNoteNumber(),
  30792. m.getFloatVelocity());
  30793. }
  30794. else if (m.isNoteOff())
  30795. {
  30796. noteOff (m.getChannel(),
  30797. m.getNoteNumber(),
  30798. true);
  30799. }
  30800. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30801. {
  30802. allNotesOff (m.getChannel(), true);
  30803. }
  30804. else if (m.isPitchWheel())
  30805. {
  30806. const int channel = m.getChannel();
  30807. const int wheelPos = m.getPitchWheelValue();
  30808. lastPitchWheelValues [channel - 1] = wheelPos;
  30809. handlePitchWheel (channel, wheelPos);
  30810. }
  30811. else if (m.isController())
  30812. {
  30813. handleController (m.getChannel(),
  30814. m.getControllerNumber(),
  30815. m.getControllerValue());
  30816. }
  30817. }
  30818. startSample += numThisTime;
  30819. numSamples -= numThisTime;
  30820. }
  30821. }
  30822. void Synthesiser::noteOn (const int midiChannel,
  30823. const int midiNoteNumber,
  30824. const float velocity)
  30825. {
  30826. const ScopedLock sl (lock);
  30827. for (int i = sounds.size(); --i >= 0;)
  30828. {
  30829. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30830. if (sound->appliesToNote (midiNoteNumber)
  30831. && sound->appliesToChannel (midiChannel))
  30832. {
  30833. startVoice (findFreeVoice (sound, shouldStealNotes),
  30834. sound, midiChannel, midiNoteNumber, velocity);
  30835. }
  30836. }
  30837. }
  30838. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30839. SynthesiserSound* const sound,
  30840. const int midiChannel,
  30841. const int midiNoteNumber,
  30842. const float velocity)
  30843. {
  30844. if (voice != 0 && sound != 0)
  30845. {
  30846. if (voice->currentlyPlayingSound != 0)
  30847. voice->stopNote (false);
  30848. voice->startNote (midiNoteNumber,
  30849. velocity,
  30850. sound,
  30851. lastPitchWheelValues [midiChannel - 1]);
  30852. voice->currentlyPlayingNote = midiNoteNumber;
  30853. voice->noteOnTime = ++lastNoteOnCounter;
  30854. voice->currentlyPlayingSound = sound;
  30855. }
  30856. }
  30857. void Synthesiser::noteOff (const int midiChannel,
  30858. const int midiNoteNumber,
  30859. const bool allowTailOff)
  30860. {
  30861. const ScopedLock sl (lock);
  30862. for (int i = voices.size(); --i >= 0;)
  30863. {
  30864. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30865. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30866. {
  30867. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30868. if (sound != 0
  30869. && sound->appliesToNote (midiNoteNumber)
  30870. && sound->appliesToChannel (midiChannel))
  30871. {
  30872. voice->stopNote (allowTailOff);
  30873. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30874. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30875. }
  30876. }
  30877. }
  30878. }
  30879. void Synthesiser::allNotesOff (const int midiChannel,
  30880. const bool allowTailOff)
  30881. {
  30882. const ScopedLock sl (lock);
  30883. for (int i = voices.size(); --i >= 0;)
  30884. {
  30885. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30886. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30887. voice->stopNote (allowTailOff);
  30888. }
  30889. }
  30890. void Synthesiser::handlePitchWheel (const int midiChannel,
  30891. const int wheelValue)
  30892. {
  30893. const ScopedLock sl (lock);
  30894. for (int i = voices.size(); --i >= 0;)
  30895. {
  30896. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30897. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30898. {
  30899. voice->pitchWheelMoved (wheelValue);
  30900. }
  30901. }
  30902. }
  30903. void Synthesiser::handleController (const int midiChannel,
  30904. const int controllerNumber,
  30905. const int controllerValue)
  30906. {
  30907. const ScopedLock sl (lock);
  30908. for (int i = voices.size(); --i >= 0;)
  30909. {
  30910. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30911. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30912. voice->controllerMoved (controllerNumber, controllerValue);
  30913. }
  30914. }
  30915. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30916. const bool stealIfNoneAvailable) const
  30917. {
  30918. const ScopedLock sl (lock);
  30919. for (int i = voices.size(); --i >= 0;)
  30920. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30921. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30922. return voices.getUnchecked (i);
  30923. if (stealIfNoneAvailable)
  30924. {
  30925. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30926. SynthesiserVoice* oldest = 0;
  30927. for (int i = voices.size(); --i >= 0;)
  30928. {
  30929. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30930. if (voice->canPlaySound (soundToPlay)
  30931. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30932. oldest = voice;
  30933. }
  30934. jassert (oldest != 0);
  30935. return oldest;
  30936. }
  30937. return 0;
  30938. }
  30939. END_JUCE_NAMESPACE
  30940. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30941. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30942. BEGIN_JUCE_NAMESPACE
  30943. ActionBroadcaster::ActionBroadcaster() throw()
  30944. {
  30945. // are you trying to create this object before or after juce has been intialised??
  30946. jassert (MessageManager::instance != 0);
  30947. }
  30948. ActionBroadcaster::~ActionBroadcaster()
  30949. {
  30950. // all event-based objects must be deleted BEFORE juce is shut down!
  30951. jassert (MessageManager::instance != 0);
  30952. }
  30953. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30954. {
  30955. actionListenerList.addActionListener (listener);
  30956. }
  30957. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30958. {
  30959. jassert (actionListenerList.isValidMessageListener());
  30960. if (actionListenerList.isValidMessageListener())
  30961. actionListenerList.removeActionListener (listener);
  30962. }
  30963. void ActionBroadcaster::removeAllActionListeners()
  30964. {
  30965. actionListenerList.removeAllActionListeners();
  30966. }
  30967. void ActionBroadcaster::sendActionMessage (const String& message) const
  30968. {
  30969. actionListenerList.sendActionMessage (message);
  30970. }
  30971. END_JUCE_NAMESPACE
  30972. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30973. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30974. BEGIN_JUCE_NAMESPACE
  30975. // special message of our own with a string in it
  30976. class ActionMessage : public Message
  30977. {
  30978. public:
  30979. const String message;
  30980. ActionMessage (const String& messageText, void* const listener_) throw()
  30981. : message (messageText)
  30982. {
  30983. pointerParameter = listener_;
  30984. }
  30985. ~ActionMessage() throw()
  30986. {
  30987. }
  30988. private:
  30989. ActionMessage (const ActionMessage&);
  30990. ActionMessage& operator= (const ActionMessage&);
  30991. };
  30992. ActionListenerList::ActionListenerList()
  30993. {
  30994. }
  30995. ActionListenerList::~ActionListenerList()
  30996. {
  30997. }
  30998. void ActionListenerList::addActionListener (ActionListener* const listener)
  30999. {
  31000. const ScopedLock sl (actionListenerLock_);
  31001. jassert (listener != 0);
  31002. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  31003. if (listener != 0)
  31004. actionListeners_.add (listener);
  31005. }
  31006. void ActionListenerList::removeActionListener (ActionListener* const listener)
  31007. {
  31008. const ScopedLock sl (actionListenerLock_);
  31009. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  31010. actionListeners_.removeValue (listener);
  31011. }
  31012. void ActionListenerList::removeAllActionListeners()
  31013. {
  31014. const ScopedLock sl (actionListenerLock_);
  31015. actionListeners_.clear();
  31016. }
  31017. void ActionListenerList::sendActionMessage (const String& message) const
  31018. {
  31019. const ScopedLock sl (actionListenerLock_);
  31020. for (int i = actionListeners_.size(); --i >= 0;)
  31021. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  31022. }
  31023. void ActionListenerList::handleMessage (const Message& message)
  31024. {
  31025. const ActionMessage& am = (const ActionMessage&) message;
  31026. if (actionListeners_.contains (am.pointerParameter))
  31027. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  31028. }
  31029. END_JUCE_NAMESPACE
  31030. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  31031. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  31032. BEGIN_JUCE_NAMESPACE
  31033. AsyncUpdater::AsyncUpdater() throw()
  31034. : asyncMessagePending (false)
  31035. {
  31036. internalAsyncHandler.owner = this;
  31037. }
  31038. AsyncUpdater::~AsyncUpdater()
  31039. {
  31040. }
  31041. void AsyncUpdater::triggerAsyncUpdate()
  31042. {
  31043. if (! asyncMessagePending)
  31044. {
  31045. asyncMessagePending = true;
  31046. internalAsyncHandler.postMessage (new Message());
  31047. }
  31048. }
  31049. void AsyncUpdater::cancelPendingUpdate() throw()
  31050. {
  31051. asyncMessagePending = false;
  31052. }
  31053. void AsyncUpdater::handleUpdateNowIfNeeded()
  31054. {
  31055. if (asyncMessagePending)
  31056. {
  31057. asyncMessagePending = false;
  31058. handleAsyncUpdate();
  31059. }
  31060. }
  31061. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  31062. {
  31063. owner->handleUpdateNowIfNeeded();
  31064. }
  31065. END_JUCE_NAMESPACE
  31066. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  31067. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  31068. BEGIN_JUCE_NAMESPACE
  31069. ChangeBroadcaster::ChangeBroadcaster() throw()
  31070. {
  31071. // are you trying to create this object before or after juce has been intialised??
  31072. jassert (MessageManager::instance != 0);
  31073. }
  31074. ChangeBroadcaster::~ChangeBroadcaster()
  31075. {
  31076. // all event-based objects must be deleted BEFORE juce is shut down!
  31077. jassert (MessageManager::instance != 0);
  31078. }
  31079. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  31080. {
  31081. changeListenerList.addChangeListener (listener);
  31082. }
  31083. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  31084. {
  31085. jassert (changeListenerList.isValidMessageListener());
  31086. if (changeListenerList.isValidMessageListener())
  31087. changeListenerList.removeChangeListener (listener);
  31088. }
  31089. void ChangeBroadcaster::removeAllChangeListeners()
  31090. {
  31091. changeListenerList.removeAllChangeListeners();
  31092. }
  31093. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  31094. {
  31095. changeListenerList.sendChangeMessage (objectThatHasChanged);
  31096. }
  31097. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  31098. {
  31099. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  31100. }
  31101. void ChangeBroadcaster::dispatchPendingMessages()
  31102. {
  31103. changeListenerList.dispatchPendingMessages();
  31104. }
  31105. END_JUCE_NAMESPACE
  31106. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  31107. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  31108. BEGIN_JUCE_NAMESPACE
  31109. ChangeListenerList::ChangeListenerList()
  31110. : lastChangedObject (0),
  31111. messagePending (false)
  31112. {
  31113. }
  31114. ChangeListenerList::~ChangeListenerList()
  31115. {
  31116. }
  31117. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  31118. {
  31119. const ScopedLock sl (lock);
  31120. jassert (listener != 0);
  31121. if (listener != 0)
  31122. listeners.add (listener);
  31123. }
  31124. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  31125. {
  31126. const ScopedLock sl (lock);
  31127. listeners.removeValue (listener);
  31128. }
  31129. void ChangeListenerList::removeAllChangeListeners()
  31130. {
  31131. const ScopedLock sl (lock);
  31132. listeners.clear();
  31133. }
  31134. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  31135. {
  31136. const ScopedLock sl (lock);
  31137. if ((! messagePending) && (listeners.size() > 0))
  31138. {
  31139. lastChangedObject = objectThatHasChanged;
  31140. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  31141. messagePending = true;
  31142. }
  31143. }
  31144. void ChangeListenerList::handleMessage (const Message& message)
  31145. {
  31146. sendSynchronousChangeMessage (message.pointerParameter);
  31147. }
  31148. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  31149. {
  31150. const ScopedLock sl (lock);
  31151. messagePending = false;
  31152. for (int i = listeners.size(); --i >= 0;)
  31153. {
  31154. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  31155. {
  31156. const ScopedUnlock tempUnlocker (lock);
  31157. l->changeListenerCallback (objectThatHasChanged);
  31158. }
  31159. i = jmin (i, listeners.size());
  31160. }
  31161. }
  31162. void ChangeListenerList::dispatchPendingMessages()
  31163. {
  31164. if (messagePending)
  31165. sendSynchronousChangeMessage (lastChangedObject);
  31166. }
  31167. END_JUCE_NAMESPACE
  31168. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  31169. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  31170. BEGIN_JUCE_NAMESPACE
  31171. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  31172. const uint32 magicMessageHeaderNumber)
  31173. : Thread ("Juce IPC connection"),
  31174. callbackConnectionState (false),
  31175. useMessageThread (callbacksOnMessageThread),
  31176. magicMessageHeader (magicMessageHeaderNumber),
  31177. pipeReceiveMessageTimeout (-1)
  31178. {
  31179. }
  31180. InterprocessConnection::~InterprocessConnection()
  31181. {
  31182. callbackConnectionState = false;
  31183. disconnect();
  31184. }
  31185. bool InterprocessConnection::connectToSocket (const String& hostName,
  31186. const int portNumber,
  31187. const int timeOutMillisecs)
  31188. {
  31189. disconnect();
  31190. const ScopedLock sl (pipeAndSocketLock);
  31191. socket = new StreamingSocket();
  31192. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  31193. {
  31194. connectionMadeInt();
  31195. startThread();
  31196. return true;
  31197. }
  31198. else
  31199. {
  31200. socket = 0;
  31201. return false;
  31202. }
  31203. }
  31204. bool InterprocessConnection::connectToPipe (const String& pipeName,
  31205. const int pipeReceiveMessageTimeoutMs)
  31206. {
  31207. disconnect();
  31208. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31209. if (newPipe->openExisting (pipeName))
  31210. {
  31211. const ScopedLock sl (pipeAndSocketLock);
  31212. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31213. initialiseWithPipe (newPipe.release());
  31214. return true;
  31215. }
  31216. return false;
  31217. }
  31218. bool InterprocessConnection::createPipe (const String& pipeName,
  31219. const int pipeReceiveMessageTimeoutMs)
  31220. {
  31221. disconnect();
  31222. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31223. if (newPipe->createNewPipe (pipeName))
  31224. {
  31225. const ScopedLock sl (pipeAndSocketLock);
  31226. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31227. initialiseWithPipe (newPipe.release());
  31228. return true;
  31229. }
  31230. return false;
  31231. }
  31232. void InterprocessConnection::disconnect()
  31233. {
  31234. if (socket != 0)
  31235. socket->close();
  31236. if (pipe != 0)
  31237. {
  31238. pipe->cancelPendingReads();
  31239. pipe->close();
  31240. }
  31241. stopThread (4000);
  31242. {
  31243. const ScopedLock sl (pipeAndSocketLock);
  31244. socket = 0;
  31245. pipe = 0;
  31246. }
  31247. connectionLostInt();
  31248. }
  31249. bool InterprocessConnection::isConnected() const
  31250. {
  31251. const ScopedLock sl (pipeAndSocketLock);
  31252. return ((socket != 0 && socket->isConnected())
  31253. || (pipe != 0 && pipe->isOpen()))
  31254. && isThreadRunning();
  31255. }
  31256. const String InterprocessConnection::getConnectedHostName() const
  31257. {
  31258. if (pipe != 0)
  31259. {
  31260. return "localhost";
  31261. }
  31262. else if (socket != 0)
  31263. {
  31264. if (! socket->isLocal())
  31265. return socket->getHostName();
  31266. return "localhost";
  31267. }
  31268. return String::empty;
  31269. }
  31270. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31271. {
  31272. uint32 messageHeader[2];
  31273. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31274. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31275. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31276. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31277. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31278. size_t bytesWritten = 0;
  31279. const ScopedLock sl (pipeAndSocketLock);
  31280. if (socket != 0)
  31281. {
  31282. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31283. }
  31284. else if (pipe != 0)
  31285. {
  31286. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31287. }
  31288. if (bytesWritten < 0)
  31289. {
  31290. // error..
  31291. return false;
  31292. }
  31293. return (bytesWritten == messageData.getSize());
  31294. }
  31295. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31296. {
  31297. jassert (socket == 0);
  31298. socket = socket_;
  31299. connectionMadeInt();
  31300. startThread();
  31301. }
  31302. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31303. {
  31304. jassert (pipe == 0);
  31305. pipe = pipe_;
  31306. connectionMadeInt();
  31307. startThread();
  31308. }
  31309. const int messageMagicNumber = 0xb734128b;
  31310. void InterprocessConnection::handleMessage (const Message& message)
  31311. {
  31312. if (message.intParameter1 == messageMagicNumber)
  31313. {
  31314. switch (message.intParameter2)
  31315. {
  31316. case 0:
  31317. {
  31318. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31319. messageReceived (*data);
  31320. break;
  31321. }
  31322. case 1:
  31323. connectionMade();
  31324. break;
  31325. case 2:
  31326. connectionLost();
  31327. break;
  31328. }
  31329. }
  31330. }
  31331. void InterprocessConnection::connectionMadeInt()
  31332. {
  31333. if (! callbackConnectionState)
  31334. {
  31335. callbackConnectionState = true;
  31336. if (useMessageThread)
  31337. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31338. else
  31339. connectionMade();
  31340. }
  31341. }
  31342. void InterprocessConnection::connectionLostInt()
  31343. {
  31344. if (callbackConnectionState)
  31345. {
  31346. callbackConnectionState = false;
  31347. if (useMessageThread)
  31348. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31349. else
  31350. connectionLost();
  31351. }
  31352. }
  31353. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31354. {
  31355. jassert (callbackConnectionState);
  31356. if (useMessageThread)
  31357. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31358. else
  31359. messageReceived (data);
  31360. }
  31361. bool InterprocessConnection::readNextMessageInt()
  31362. {
  31363. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31364. uint32 messageHeader[2];
  31365. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31366. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31367. if (bytes == sizeof (messageHeader)
  31368. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31369. {
  31370. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31371. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31372. {
  31373. MemoryBlock messageData (bytesInMessage, true);
  31374. int bytesRead = 0;
  31375. while (bytesInMessage > 0)
  31376. {
  31377. if (threadShouldExit())
  31378. return false;
  31379. const int numThisTime = jmin (bytesInMessage, 65536);
  31380. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31381. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31382. if (bytesIn <= 0)
  31383. break;
  31384. bytesRead += bytesIn;
  31385. bytesInMessage -= bytesIn;
  31386. }
  31387. if (bytesRead >= 0)
  31388. deliverDataInt (messageData);
  31389. }
  31390. }
  31391. else if (bytes < 0)
  31392. {
  31393. {
  31394. const ScopedLock sl (pipeAndSocketLock);
  31395. socket = 0;
  31396. }
  31397. connectionLostInt();
  31398. return false;
  31399. }
  31400. return true;
  31401. }
  31402. void InterprocessConnection::run()
  31403. {
  31404. while (! threadShouldExit())
  31405. {
  31406. if (socket != 0)
  31407. {
  31408. const int ready = socket->waitUntilReady (true, 0);
  31409. if (ready < 0)
  31410. {
  31411. {
  31412. const ScopedLock sl (pipeAndSocketLock);
  31413. socket = 0;
  31414. }
  31415. connectionLostInt();
  31416. break;
  31417. }
  31418. else if (ready > 0)
  31419. {
  31420. if (! readNextMessageInt())
  31421. break;
  31422. }
  31423. else
  31424. {
  31425. Thread::sleep (2);
  31426. }
  31427. }
  31428. else if (pipe != 0)
  31429. {
  31430. if (! pipe->isOpen())
  31431. {
  31432. {
  31433. const ScopedLock sl (pipeAndSocketLock);
  31434. pipe = 0;
  31435. }
  31436. connectionLostInt();
  31437. break;
  31438. }
  31439. else
  31440. {
  31441. if (! readNextMessageInt())
  31442. break;
  31443. }
  31444. }
  31445. else
  31446. {
  31447. break;
  31448. }
  31449. }
  31450. }
  31451. END_JUCE_NAMESPACE
  31452. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31453. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31454. BEGIN_JUCE_NAMESPACE
  31455. InterprocessConnectionServer::InterprocessConnectionServer()
  31456. : Thread ("Juce IPC server")
  31457. {
  31458. }
  31459. InterprocessConnectionServer::~InterprocessConnectionServer()
  31460. {
  31461. stop();
  31462. }
  31463. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31464. {
  31465. stop();
  31466. socket = new StreamingSocket();
  31467. if (socket->createListener (portNumber))
  31468. {
  31469. startThread();
  31470. return true;
  31471. }
  31472. socket = 0;
  31473. return false;
  31474. }
  31475. void InterprocessConnectionServer::stop()
  31476. {
  31477. signalThreadShouldExit();
  31478. if (socket != 0)
  31479. socket->close();
  31480. stopThread (4000);
  31481. socket = 0;
  31482. }
  31483. void InterprocessConnectionServer::run()
  31484. {
  31485. while ((! threadShouldExit()) && socket != 0)
  31486. {
  31487. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31488. if (clientSocket != 0)
  31489. {
  31490. InterprocessConnection* newConnection = createConnectionObject();
  31491. if (newConnection != 0)
  31492. newConnection->initialiseWithSocket (clientSocket.release());
  31493. }
  31494. }
  31495. }
  31496. END_JUCE_NAMESPACE
  31497. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31498. /*** Start of inlined file: juce_Message.cpp ***/
  31499. BEGIN_JUCE_NAMESPACE
  31500. Message::Message() throw()
  31501. : intParameter1 (0),
  31502. intParameter2 (0),
  31503. intParameter3 (0),
  31504. pointerParameter (0)
  31505. {
  31506. }
  31507. Message::Message (const int intParameter1_,
  31508. const int intParameter2_,
  31509. const int intParameter3_,
  31510. void* const pointerParameter_) throw()
  31511. : intParameter1 (intParameter1_),
  31512. intParameter2 (intParameter2_),
  31513. intParameter3 (intParameter3_),
  31514. pointerParameter (pointerParameter_)
  31515. {
  31516. }
  31517. Message::~Message() throw()
  31518. {
  31519. }
  31520. END_JUCE_NAMESPACE
  31521. /*** End of inlined file: juce_Message.cpp ***/
  31522. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31523. BEGIN_JUCE_NAMESPACE
  31524. MessageListener::MessageListener() throw()
  31525. {
  31526. // are you trying to create a messagelistener before or after juce has been intialised??
  31527. jassert (MessageManager::instance != 0);
  31528. if (MessageManager::instance != 0)
  31529. MessageManager::instance->messageListeners.add (this);
  31530. }
  31531. MessageListener::~MessageListener()
  31532. {
  31533. if (MessageManager::instance != 0)
  31534. MessageManager::instance->messageListeners.removeValue (this);
  31535. }
  31536. void MessageListener::postMessage (Message* const message) const throw()
  31537. {
  31538. message->messageRecipient = const_cast <MessageListener*> (this);
  31539. if (MessageManager::instance == 0)
  31540. MessageManager::getInstance();
  31541. MessageManager::instance->postMessageToQueue (message);
  31542. }
  31543. bool MessageListener::isValidMessageListener() const throw()
  31544. {
  31545. return (MessageManager::instance != 0)
  31546. && MessageManager::instance->messageListeners.contains (this);
  31547. }
  31548. END_JUCE_NAMESPACE
  31549. /*** End of inlined file: juce_MessageListener.cpp ***/
  31550. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31551. BEGIN_JUCE_NAMESPACE
  31552. // platform-specific functions..
  31553. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31554. bool juce_postMessageToSystemQueue (Message* message);
  31555. MessageManager* MessageManager::instance = 0;
  31556. static const int quitMessageId = 0xfffff321;
  31557. MessageManager::MessageManager() throw()
  31558. : quitMessagePosted (false),
  31559. quitMessageReceived (false),
  31560. threadWithLock (0)
  31561. {
  31562. messageThreadId = Thread::getCurrentThreadId();
  31563. }
  31564. MessageManager::~MessageManager() throw()
  31565. {
  31566. broadcastListeners = 0;
  31567. doPlatformSpecificShutdown();
  31568. // If you hit this assertion, then you've probably leaked a Component or some other
  31569. // kind of MessageListener object...
  31570. jassert (messageListeners.size() == 0);
  31571. jassert (instance == this);
  31572. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31573. }
  31574. MessageManager* MessageManager::getInstance() throw()
  31575. {
  31576. if (instance == 0)
  31577. {
  31578. instance = new MessageManager();
  31579. doPlatformSpecificInitialisation();
  31580. }
  31581. return instance;
  31582. }
  31583. void MessageManager::postMessageToQueue (Message* const message)
  31584. {
  31585. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31586. delete message;
  31587. }
  31588. CallbackMessage::CallbackMessage() throw() {}
  31589. CallbackMessage::~CallbackMessage() throw() {}
  31590. void CallbackMessage::post()
  31591. {
  31592. if (MessageManager::instance != 0)
  31593. MessageManager::instance->postCallbackMessage (this);
  31594. }
  31595. void MessageManager::postCallbackMessage (Message* const message)
  31596. {
  31597. message->messageRecipient = 0;
  31598. postMessageToQueue (message);
  31599. }
  31600. // not for public use..
  31601. void MessageManager::deliverMessage (Message* const message)
  31602. {
  31603. const ScopedPointer <Message> messageDeleter (message);
  31604. MessageListener* const recipient = message->messageRecipient;
  31605. JUCE_TRY
  31606. {
  31607. if (messageListeners.contains (recipient))
  31608. {
  31609. recipient->handleMessage (*message);
  31610. }
  31611. else if (recipient == 0)
  31612. {
  31613. if (message->intParameter1 == quitMessageId)
  31614. {
  31615. quitMessageReceived = true;
  31616. }
  31617. else
  31618. {
  31619. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31620. if (cm != 0)
  31621. cm->messageCallback();
  31622. }
  31623. }
  31624. }
  31625. JUCE_CATCH_EXCEPTION
  31626. }
  31627. #if ! (JUCE_MAC || JUCE_IOS)
  31628. void MessageManager::runDispatchLoop()
  31629. {
  31630. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31631. runDispatchLoopUntil (-1);
  31632. }
  31633. void MessageManager::stopDispatchLoop()
  31634. {
  31635. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31636. m->messageRecipient = 0;
  31637. postMessageToQueue (m);
  31638. quitMessagePosted = true;
  31639. }
  31640. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31641. {
  31642. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31643. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31644. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31645. && ! quitMessageReceived)
  31646. {
  31647. JUCE_TRY
  31648. {
  31649. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31650. {
  31651. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31652. if (msToWait > 0)
  31653. Thread::sleep (jmin (5, msToWait));
  31654. }
  31655. }
  31656. JUCE_CATCH_EXCEPTION
  31657. }
  31658. return ! quitMessageReceived;
  31659. }
  31660. #endif
  31661. void MessageManager::deliverBroadcastMessage (const String& value)
  31662. {
  31663. if (broadcastListeners != 0)
  31664. broadcastListeners->sendActionMessage (value);
  31665. }
  31666. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31667. {
  31668. if (broadcastListeners == 0)
  31669. broadcastListeners = new ActionListenerList();
  31670. broadcastListeners->addActionListener (listener);
  31671. }
  31672. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31673. {
  31674. if (broadcastListeners != 0)
  31675. broadcastListeners->removeActionListener (listener);
  31676. }
  31677. bool MessageManager::isThisTheMessageThread() const throw()
  31678. {
  31679. return Thread::getCurrentThreadId() == messageThreadId;
  31680. }
  31681. void MessageManager::setCurrentThreadAsMessageThread()
  31682. {
  31683. if (messageThreadId != Thread::getCurrentThreadId())
  31684. {
  31685. messageThreadId = Thread::getCurrentThreadId();
  31686. // This is needed on windows to make sure the message window is created by this thread
  31687. doPlatformSpecificShutdown();
  31688. doPlatformSpecificInitialisation();
  31689. }
  31690. }
  31691. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31692. {
  31693. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31694. return thisThread == messageThreadId || thisThread == threadWithLock;
  31695. }
  31696. /* The only safe way to lock the message thread while another thread does
  31697. some work is by posting a special message, whose purpose is to tie up the event
  31698. loop until the other thread has finished its business.
  31699. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31700. get locked before making an event callback, because if the same OS lock gets indirectly
  31701. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31702. in Cocoa).
  31703. */
  31704. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31705. {
  31706. public:
  31707. SharedEvents() {}
  31708. ~SharedEvents() {}
  31709. /* This class just holds a couple of events to communicate between the BlockingMessage
  31710. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31711. this shared data must be kept in a separate, ref-counted container. */
  31712. WaitableEvent lockedEvent, releaseEvent;
  31713. private:
  31714. SharedEvents (const SharedEvents&);
  31715. SharedEvents& operator= (const SharedEvents&);
  31716. };
  31717. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31718. {
  31719. public:
  31720. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31721. ~BlockingMessage() throw() {}
  31722. void messageCallback()
  31723. {
  31724. events->lockedEvent.signal();
  31725. events->releaseEvent.wait();
  31726. }
  31727. juce_UseDebuggingNewOperator
  31728. private:
  31729. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31730. BlockingMessage (const BlockingMessage&);
  31731. BlockingMessage& operator= (const BlockingMessage&);
  31732. };
  31733. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31734. : sharedEvents (0),
  31735. locked (false)
  31736. {
  31737. init (threadToCheck, 0);
  31738. }
  31739. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31740. : sharedEvents (0),
  31741. locked (false)
  31742. {
  31743. init (0, jobToCheckForExitSignal);
  31744. }
  31745. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31746. {
  31747. if (MessageManager::instance != 0)
  31748. {
  31749. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31750. {
  31751. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31752. }
  31753. else
  31754. {
  31755. if (threadToCheck == 0 && job == 0)
  31756. {
  31757. MessageManager::instance->lockingLock.enter();
  31758. }
  31759. else
  31760. {
  31761. while (! MessageManager::instance->lockingLock.tryEnter())
  31762. {
  31763. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31764. || (job != 0 && job->shouldExit()))
  31765. return;
  31766. Thread::sleep (1);
  31767. }
  31768. }
  31769. sharedEvents = new SharedEvents();
  31770. sharedEvents->incReferenceCount();
  31771. (new BlockingMessage (sharedEvents))->post();
  31772. while (! sharedEvents->lockedEvent.wait (50))
  31773. {
  31774. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31775. || (job != 0 && job->shouldExit()))
  31776. {
  31777. sharedEvents->releaseEvent.signal();
  31778. sharedEvents->decReferenceCount();
  31779. sharedEvents = 0;
  31780. MessageManager::instance->lockingLock.exit();
  31781. return;
  31782. }
  31783. }
  31784. jassert (MessageManager::instance->threadWithLock == 0);
  31785. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31786. locked = true;
  31787. }
  31788. }
  31789. }
  31790. MessageManagerLock::~MessageManagerLock() throw()
  31791. {
  31792. if (sharedEvents != 0)
  31793. {
  31794. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31795. sharedEvents->releaseEvent.signal();
  31796. sharedEvents->decReferenceCount();
  31797. if (MessageManager::instance != 0)
  31798. {
  31799. MessageManager::instance->threadWithLock = 0;
  31800. MessageManager::instance->lockingLock.exit();
  31801. }
  31802. }
  31803. }
  31804. END_JUCE_NAMESPACE
  31805. /*** End of inlined file: juce_MessageManager.cpp ***/
  31806. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31807. BEGIN_JUCE_NAMESPACE
  31808. class MultiTimer::MultiTimerCallback : public Timer
  31809. {
  31810. public:
  31811. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31812. : timerId (timerId_),
  31813. owner (owner_)
  31814. {
  31815. }
  31816. ~MultiTimerCallback()
  31817. {
  31818. }
  31819. void timerCallback()
  31820. {
  31821. owner.timerCallback (timerId);
  31822. }
  31823. const int timerId;
  31824. private:
  31825. MultiTimer& owner;
  31826. };
  31827. MultiTimer::MultiTimer() throw()
  31828. {
  31829. }
  31830. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31831. {
  31832. }
  31833. MultiTimer::~MultiTimer()
  31834. {
  31835. const ScopedLock sl (timerListLock);
  31836. timers.clear();
  31837. }
  31838. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31839. {
  31840. const ScopedLock sl (timerListLock);
  31841. for (int i = timers.size(); --i >= 0;)
  31842. {
  31843. MultiTimerCallback* const t = timers.getUnchecked(i);
  31844. if (t->timerId == timerId)
  31845. {
  31846. t->startTimer (intervalInMilliseconds);
  31847. return;
  31848. }
  31849. }
  31850. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31851. timers.add (newTimer);
  31852. newTimer->startTimer (intervalInMilliseconds);
  31853. }
  31854. void MultiTimer::stopTimer (const int timerId) throw()
  31855. {
  31856. const ScopedLock sl (timerListLock);
  31857. for (int i = timers.size(); --i >= 0;)
  31858. {
  31859. MultiTimerCallback* const t = timers.getUnchecked(i);
  31860. if (t->timerId == timerId)
  31861. t->stopTimer();
  31862. }
  31863. }
  31864. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31865. {
  31866. const ScopedLock sl (timerListLock);
  31867. for (int i = timers.size(); --i >= 0;)
  31868. {
  31869. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31870. if (t->timerId == timerId)
  31871. return t->isTimerRunning();
  31872. }
  31873. return false;
  31874. }
  31875. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31876. {
  31877. const ScopedLock sl (timerListLock);
  31878. for (int i = timers.size(); --i >= 0;)
  31879. {
  31880. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31881. if (t->timerId == timerId)
  31882. return t->getTimerInterval();
  31883. }
  31884. return 0;
  31885. }
  31886. END_JUCE_NAMESPACE
  31887. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31888. /*** Start of inlined file: juce_Timer.cpp ***/
  31889. BEGIN_JUCE_NAMESPACE
  31890. class InternalTimerThread : private Thread,
  31891. private MessageListener,
  31892. private DeletedAtShutdown,
  31893. private AsyncUpdater
  31894. {
  31895. public:
  31896. InternalTimerThread()
  31897. : Thread ("Juce Timer"),
  31898. firstTimer (0),
  31899. callbackNeeded (0)
  31900. {
  31901. triggerAsyncUpdate();
  31902. }
  31903. ~InternalTimerThread() throw()
  31904. {
  31905. stopThread (4000);
  31906. jassert (instance == this || instance == 0);
  31907. if (instance == this)
  31908. instance = 0;
  31909. }
  31910. void run()
  31911. {
  31912. uint32 lastTime = Time::getMillisecondCounter();
  31913. while (! threadShouldExit())
  31914. {
  31915. const uint32 now = Time::getMillisecondCounter();
  31916. if (now <= lastTime)
  31917. {
  31918. wait (2);
  31919. continue;
  31920. }
  31921. const int elapsed = now - lastTime;
  31922. lastTime = now;
  31923. int timeUntilFirstTimer = 1000;
  31924. {
  31925. const ScopedLock sl (lock);
  31926. decrementAllCounters (elapsed);
  31927. if (firstTimer != 0)
  31928. timeUntilFirstTimer = firstTimer->countdownMs;
  31929. }
  31930. if (timeUntilFirstTimer <= 0)
  31931. {
  31932. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31933. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31934. but if it fails it means the message-thread changed the value from under us so at least
  31935. some processing is happenening and we can just loop around and try again
  31936. */
  31937. if (callbackNeeded.compareAndSetBool (1, 0))
  31938. {
  31939. postMessage (new Message());
  31940. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31941. when the app has a modal loop), so this is how long to wait before assuming the
  31942. message has been lost and trying again.
  31943. */
  31944. const uint32 messageDeliveryTimeout = now + 2000;
  31945. while (callbackNeeded.get() != 0)
  31946. {
  31947. wait (4);
  31948. if (threadShouldExit())
  31949. return;
  31950. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31951. break;
  31952. }
  31953. }
  31954. }
  31955. else
  31956. {
  31957. // don't wait for too long because running this loop also helps keep the
  31958. // Time::getApproximateMillisecondTimer value stay up-to-date
  31959. wait (jlimit (1, 50, timeUntilFirstTimer));
  31960. }
  31961. }
  31962. }
  31963. void callTimers()
  31964. {
  31965. const ScopedLock sl (lock);
  31966. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31967. {
  31968. Timer* const t = firstTimer;
  31969. t->countdownMs = t->periodMs;
  31970. removeTimer (t);
  31971. addTimer (t);
  31972. const ScopedUnlock ul (lock);
  31973. JUCE_TRY
  31974. {
  31975. t->timerCallback();
  31976. }
  31977. JUCE_CATCH_EXCEPTION
  31978. }
  31979. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31980. before the boolean is set. This set should never fail since if it was false in the first place,
  31981. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31982. get a message then the value is true and the other thread can only set it to true again and
  31983. we will get another callback to set it to false.
  31984. */
  31985. callbackNeeded.set (0);
  31986. }
  31987. void handleMessage (const Message&)
  31988. {
  31989. callTimers();
  31990. }
  31991. void callTimersSynchronously()
  31992. {
  31993. if (! isThreadRunning())
  31994. {
  31995. // (This is relied on by some plugins in cases where the MM has
  31996. // had to restart and the async callback never started)
  31997. cancelPendingUpdate();
  31998. triggerAsyncUpdate();
  31999. }
  32000. callTimers();
  32001. }
  32002. static void callAnyTimersSynchronously()
  32003. {
  32004. if (InternalTimerThread::instance != 0)
  32005. InternalTimerThread::instance->callTimersSynchronously();
  32006. }
  32007. static inline void add (Timer* const tim) throw()
  32008. {
  32009. if (instance == 0)
  32010. instance = new InternalTimerThread();
  32011. const ScopedLock sl (instance->lock);
  32012. instance->addTimer (tim);
  32013. }
  32014. static inline void remove (Timer* const tim) throw()
  32015. {
  32016. if (instance != 0)
  32017. {
  32018. const ScopedLock sl (instance->lock);
  32019. instance->removeTimer (tim);
  32020. }
  32021. }
  32022. static inline void resetCounter (Timer* const tim,
  32023. const int newCounter) throw()
  32024. {
  32025. if (instance != 0)
  32026. {
  32027. tim->countdownMs = newCounter;
  32028. tim->periodMs = newCounter;
  32029. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  32030. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  32031. {
  32032. const ScopedLock sl (instance->lock);
  32033. instance->removeTimer (tim);
  32034. instance->addTimer (tim);
  32035. }
  32036. }
  32037. }
  32038. private:
  32039. friend class Timer;
  32040. static InternalTimerThread* instance;
  32041. static CriticalSection lock;
  32042. Timer* volatile firstTimer;
  32043. Atomic <int> callbackNeeded;
  32044. void addTimer (Timer* const t) throw()
  32045. {
  32046. #if JUCE_DEBUG
  32047. Timer* tt = firstTimer;
  32048. while (tt != 0)
  32049. {
  32050. // trying to add a timer that's already here - shouldn't get to this point,
  32051. // so if you get this assertion, let me know!
  32052. jassert (tt != t);
  32053. tt = tt->next;
  32054. }
  32055. jassert (t->previous == 0 && t->next == 0);
  32056. #endif
  32057. Timer* i = firstTimer;
  32058. if (i == 0 || i->countdownMs > t->countdownMs)
  32059. {
  32060. t->next = firstTimer;
  32061. firstTimer = t;
  32062. }
  32063. else
  32064. {
  32065. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  32066. i = i->next;
  32067. jassert (i != 0);
  32068. t->next = i->next;
  32069. t->previous = i;
  32070. i->next = t;
  32071. }
  32072. if (t->next != 0)
  32073. t->next->previous = t;
  32074. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  32075. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  32076. notify();
  32077. }
  32078. void removeTimer (Timer* const t) throw()
  32079. {
  32080. #if JUCE_DEBUG
  32081. Timer* tt = firstTimer;
  32082. bool found = false;
  32083. while (tt != 0)
  32084. {
  32085. if (tt == t)
  32086. {
  32087. found = true;
  32088. break;
  32089. }
  32090. tt = tt->next;
  32091. }
  32092. // trying to remove a timer that's not here - shouldn't get to this point,
  32093. // so if you get this assertion, let me know!
  32094. jassert (found);
  32095. #endif
  32096. if (t->previous != 0)
  32097. {
  32098. jassert (firstTimer != t);
  32099. t->previous->next = t->next;
  32100. }
  32101. else
  32102. {
  32103. jassert (firstTimer == t);
  32104. firstTimer = t->next;
  32105. }
  32106. if (t->next != 0)
  32107. t->next->previous = t->previous;
  32108. t->next = 0;
  32109. t->previous = 0;
  32110. }
  32111. void decrementAllCounters (const int numMillisecs) const
  32112. {
  32113. Timer* t = firstTimer;
  32114. while (t != 0)
  32115. {
  32116. t->countdownMs -= numMillisecs;
  32117. t = t->next;
  32118. }
  32119. }
  32120. void handleAsyncUpdate()
  32121. {
  32122. startThread (7);
  32123. }
  32124. InternalTimerThread (const InternalTimerThread&);
  32125. InternalTimerThread& operator= (const InternalTimerThread&);
  32126. };
  32127. InternalTimerThread* InternalTimerThread::instance = 0;
  32128. CriticalSection InternalTimerThread::lock;
  32129. void juce_callAnyTimersSynchronously()
  32130. {
  32131. InternalTimerThread::callAnyTimersSynchronously();
  32132. }
  32133. #if JUCE_DEBUG
  32134. static SortedSet <Timer*> activeTimers;
  32135. #endif
  32136. Timer::Timer() throw()
  32137. : countdownMs (0),
  32138. periodMs (0),
  32139. previous (0),
  32140. next (0)
  32141. {
  32142. #if JUCE_DEBUG
  32143. activeTimers.add (this);
  32144. #endif
  32145. }
  32146. Timer::Timer (const Timer&) throw()
  32147. : countdownMs (0),
  32148. periodMs (0),
  32149. previous (0),
  32150. next (0)
  32151. {
  32152. #if JUCE_DEBUG
  32153. activeTimers.add (this);
  32154. #endif
  32155. }
  32156. Timer::~Timer()
  32157. {
  32158. stopTimer();
  32159. #if JUCE_DEBUG
  32160. activeTimers.removeValue (this);
  32161. #endif
  32162. }
  32163. void Timer::startTimer (const int interval) throw()
  32164. {
  32165. const ScopedLock sl (InternalTimerThread::lock);
  32166. #if JUCE_DEBUG
  32167. // this isn't a valid object! Your timer might be a dangling pointer or something..
  32168. jassert (activeTimers.contains (this));
  32169. #endif
  32170. if (periodMs == 0)
  32171. {
  32172. countdownMs = interval;
  32173. periodMs = jmax (1, interval);
  32174. InternalTimerThread::add (this);
  32175. }
  32176. else
  32177. {
  32178. InternalTimerThread::resetCounter (this, interval);
  32179. }
  32180. }
  32181. void Timer::stopTimer() throw()
  32182. {
  32183. const ScopedLock sl (InternalTimerThread::lock);
  32184. #if JUCE_DEBUG
  32185. // this isn't a valid object! Your timer might be a dangling pointer or something..
  32186. jassert (activeTimers.contains (this));
  32187. #endif
  32188. if (periodMs > 0)
  32189. {
  32190. InternalTimerThread::remove (this);
  32191. periodMs = 0;
  32192. }
  32193. }
  32194. END_JUCE_NAMESPACE
  32195. /*** End of inlined file: juce_Timer.cpp ***/
  32196. #endif
  32197. #if JUCE_BUILD_GUI
  32198. /*** Start of inlined file: juce_Component.cpp ***/
  32199. BEGIN_JUCE_NAMESPACE
  32200. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  32201. enum ComponentMessageNumbers
  32202. {
  32203. customCommandMessage = 0x7fff0001,
  32204. exitModalStateMessage = 0x7fff0002
  32205. };
  32206. static uint32 nextComponentUID = 0;
  32207. Component* Component::currentlyFocusedComponent = 0;
  32208. Component::Component()
  32209. : parentComponent_ (0),
  32210. componentUID (++nextComponentUID),
  32211. numDeepMouseListeners (0),
  32212. lookAndFeel_ (0),
  32213. effect_ (0),
  32214. bufferedImage_ (0),
  32215. mouseListeners_ (0),
  32216. keyListeners_ (0),
  32217. componentFlags_ (0)
  32218. {
  32219. }
  32220. Component::Component (const String& name)
  32221. : componentName_ (name),
  32222. parentComponent_ (0),
  32223. componentUID (++nextComponentUID),
  32224. numDeepMouseListeners (0),
  32225. lookAndFeel_ (0),
  32226. effect_ (0),
  32227. bufferedImage_ (0),
  32228. mouseListeners_ (0),
  32229. keyListeners_ (0),
  32230. componentFlags_ (0)
  32231. {
  32232. }
  32233. Component::~Component()
  32234. {
  32235. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32236. if (parentComponent_ != 0)
  32237. {
  32238. parentComponent_->removeChildComponent (this);
  32239. }
  32240. else if ((currentlyFocusedComponent == this)
  32241. || isParentOf (currentlyFocusedComponent))
  32242. {
  32243. giveAwayFocus();
  32244. }
  32245. if (flags.hasHeavyweightPeerFlag)
  32246. removeFromDesktop();
  32247. for (int i = childComponentList_.size(); --i >= 0;)
  32248. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  32249. delete mouseListeners_;
  32250. delete keyListeners_;
  32251. }
  32252. void Component::setName (const String& name)
  32253. {
  32254. // if component methods are being called from threads other than the message
  32255. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32256. checkMessageManagerIsLocked
  32257. if (componentName_ != name)
  32258. {
  32259. componentName_ = name;
  32260. if (flags.hasHeavyweightPeerFlag)
  32261. {
  32262. ComponentPeer* const peer = getPeer();
  32263. jassert (peer != 0);
  32264. if (peer != 0)
  32265. peer->setTitle (name);
  32266. }
  32267. BailOutChecker checker (this);
  32268. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32269. }
  32270. }
  32271. void Component::setVisible (bool shouldBeVisible)
  32272. {
  32273. if (flags.visibleFlag != shouldBeVisible)
  32274. {
  32275. // if component methods are being called from threads other than the message
  32276. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32277. checkMessageManagerIsLocked
  32278. SafePointer<Component> safePointer (this);
  32279. flags.visibleFlag = shouldBeVisible;
  32280. internalRepaint (0, 0, getWidth(), getHeight());
  32281. sendFakeMouseMove();
  32282. if (! shouldBeVisible)
  32283. {
  32284. if (currentlyFocusedComponent == this
  32285. || isParentOf (currentlyFocusedComponent))
  32286. {
  32287. if (parentComponent_ != 0)
  32288. parentComponent_->grabKeyboardFocus();
  32289. else
  32290. giveAwayFocus();
  32291. }
  32292. }
  32293. if (safePointer != 0)
  32294. {
  32295. sendVisibilityChangeMessage();
  32296. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32297. {
  32298. ComponentPeer* const peer = getPeer();
  32299. jassert (peer != 0);
  32300. if (peer != 0)
  32301. {
  32302. peer->setVisible (shouldBeVisible);
  32303. internalHierarchyChanged();
  32304. }
  32305. }
  32306. }
  32307. }
  32308. }
  32309. void Component::visibilityChanged()
  32310. {
  32311. }
  32312. void Component::sendVisibilityChangeMessage()
  32313. {
  32314. BailOutChecker checker (this);
  32315. visibilityChanged();
  32316. if (! checker.shouldBailOut())
  32317. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32318. }
  32319. bool Component::isShowing() const
  32320. {
  32321. if (flags.visibleFlag)
  32322. {
  32323. if (parentComponent_ != 0)
  32324. {
  32325. return parentComponent_->isShowing();
  32326. }
  32327. else
  32328. {
  32329. const ComponentPeer* const peer = getPeer();
  32330. return peer != 0 && ! peer->isMinimised();
  32331. }
  32332. }
  32333. return false;
  32334. }
  32335. class FadeOutProxyComponent : public Component,
  32336. public Timer
  32337. {
  32338. public:
  32339. FadeOutProxyComponent (Component* comp,
  32340. const int fadeLengthMs,
  32341. const int deltaXToMove,
  32342. const int deltaYToMove,
  32343. const float scaleFactorAtEnd)
  32344. : lastTime (0),
  32345. alpha (1.0f),
  32346. scale (1.0f)
  32347. {
  32348. image = comp->createComponentSnapshot (comp->getLocalBounds());
  32349. setBounds (comp->getBounds());
  32350. comp->getParentComponent()->addAndMakeVisible (this);
  32351. toBehind (comp);
  32352. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  32353. centreX = comp->getX() + comp->getWidth() * 0.5f;
  32354. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  32355. centreY = comp->getY() + comp->getHeight() * 0.5f;
  32356. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  32357. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  32358. setInterceptsMouseClicks (false, false);
  32359. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  32360. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  32361. }
  32362. ~FadeOutProxyComponent()
  32363. {
  32364. }
  32365. void paint (Graphics& g)
  32366. {
  32367. g.setOpacity (alpha);
  32368. g.drawImage (image,
  32369. 0, 0, getWidth(), getHeight(),
  32370. 0, 0, image.getWidth(), image.getHeight());
  32371. }
  32372. void timerCallback()
  32373. {
  32374. const uint32 now = Time::getMillisecondCounter();
  32375. if (lastTime == 0)
  32376. lastTime = now;
  32377. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  32378. lastTime = now;
  32379. alpha += alphaChangePerMs * msPassed;
  32380. if (alpha > 0)
  32381. {
  32382. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  32383. {
  32384. centreX += xChangePerMs * msPassed;
  32385. centreY += yChangePerMs * msPassed;
  32386. scale += scaleChangePerMs * msPassed;
  32387. const int w = roundToInt (image.getWidth() * scale);
  32388. const int h = roundToInt (image.getHeight() * scale);
  32389. setBounds (roundToInt (centreX) - w / 2,
  32390. roundToInt (centreY) - h / 2,
  32391. w, h);
  32392. }
  32393. repaint();
  32394. }
  32395. else
  32396. {
  32397. delete this;
  32398. }
  32399. }
  32400. juce_UseDebuggingNewOperator
  32401. private:
  32402. Image image;
  32403. uint32 lastTime;
  32404. float alpha, alphaChangePerMs;
  32405. float centreX, xChangePerMs;
  32406. float centreY, yChangePerMs;
  32407. float scale, scaleChangePerMs;
  32408. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32409. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32410. };
  32411. void Component::fadeOutComponent (const int millisecondsToFade,
  32412. const int deltaXToMove,
  32413. const int deltaYToMove,
  32414. const float scaleFactorAtEnd)
  32415. {
  32416. //xxx won't work for comps without parents
  32417. if (isShowing() && millisecondsToFade > 0)
  32418. new FadeOutProxyComponent (this, millisecondsToFade,
  32419. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32420. setVisible (false);
  32421. }
  32422. bool Component::isValidComponent() const
  32423. {
  32424. return (this != 0) && isValidMessageListener();
  32425. }
  32426. void* Component::getWindowHandle() const
  32427. {
  32428. const ComponentPeer* const peer = getPeer();
  32429. if (peer != 0)
  32430. return peer->getNativeHandle();
  32431. return 0;
  32432. }
  32433. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32434. {
  32435. // if component methods are being called from threads other than the message
  32436. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32437. checkMessageManagerIsLocked
  32438. if (isOpaque())
  32439. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32440. else
  32441. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32442. int currentStyleFlags = 0;
  32443. // don't use getPeer(), so that we only get the peer that's specifically
  32444. // for this comp, and not for one of its parents.
  32445. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32446. if (peer != 0)
  32447. currentStyleFlags = peer->getStyleFlags();
  32448. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32449. {
  32450. SafePointer<Component> safePointer (this);
  32451. #if JUCE_LINUX
  32452. // it's wise to give the component a non-zero size before
  32453. // putting it on the desktop, as X windows get confused by this, and
  32454. // a (1, 1) minimum size is enforced here.
  32455. setSize (jmax (1, getWidth()),
  32456. jmax (1, getHeight()));
  32457. #endif
  32458. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32459. bool wasFullscreen = false;
  32460. bool wasMinimised = false;
  32461. ComponentBoundsConstrainer* currentConstainer = 0;
  32462. Rectangle<int> oldNonFullScreenBounds;
  32463. if (peer != 0)
  32464. {
  32465. wasFullscreen = peer->isFullScreen();
  32466. wasMinimised = peer->isMinimised();
  32467. currentConstainer = peer->getConstrainer();
  32468. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32469. removeFromDesktop();
  32470. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32471. }
  32472. if (parentComponent_ != 0)
  32473. parentComponent_->removeChildComponent (this);
  32474. if (safePointer != 0)
  32475. {
  32476. flags.hasHeavyweightPeerFlag = true;
  32477. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32478. Desktop::getInstance().addDesktopComponent (this);
  32479. bounds_.setPosition (topLeft);
  32480. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32481. peer->setVisible (isVisible());
  32482. if (wasFullscreen)
  32483. {
  32484. peer->setFullScreen (true);
  32485. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32486. }
  32487. if (wasMinimised)
  32488. peer->setMinimised (true);
  32489. if (isAlwaysOnTop())
  32490. peer->setAlwaysOnTop (true);
  32491. peer->setConstrainer (currentConstainer);
  32492. repaint();
  32493. }
  32494. internalHierarchyChanged();
  32495. }
  32496. }
  32497. void Component::removeFromDesktop()
  32498. {
  32499. // if component methods are being called from threads other than the message
  32500. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32501. checkMessageManagerIsLocked
  32502. if (flags.hasHeavyweightPeerFlag)
  32503. {
  32504. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32505. flags.hasHeavyweightPeerFlag = false;
  32506. jassert (peer != 0);
  32507. delete peer;
  32508. Desktop::getInstance().removeDesktopComponent (this);
  32509. }
  32510. }
  32511. bool Component::isOnDesktop() const throw()
  32512. {
  32513. return flags.hasHeavyweightPeerFlag;
  32514. }
  32515. void Component::userTriedToCloseWindow()
  32516. {
  32517. /* This means that the user's trying to get rid of your window with the 'close window' system
  32518. menu option (on windows) or possibly the task manager - you should really handle this
  32519. and delete or hide your component in an appropriate way.
  32520. If you want to ignore the event and don't want to trigger this assertion, just override
  32521. this method and do nothing.
  32522. */
  32523. jassertfalse;
  32524. }
  32525. void Component::minimisationStateChanged (bool)
  32526. {
  32527. }
  32528. void Component::setOpaque (const bool shouldBeOpaque)
  32529. {
  32530. if (shouldBeOpaque != flags.opaqueFlag)
  32531. {
  32532. flags.opaqueFlag = shouldBeOpaque;
  32533. if (flags.hasHeavyweightPeerFlag)
  32534. {
  32535. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32536. if (peer != 0)
  32537. {
  32538. // to make it recreate the heavyweight window
  32539. addToDesktop (peer->getStyleFlags());
  32540. }
  32541. }
  32542. repaint();
  32543. }
  32544. }
  32545. bool Component::isOpaque() const throw()
  32546. {
  32547. return flags.opaqueFlag;
  32548. }
  32549. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32550. {
  32551. if (shouldBeBuffered != flags.bufferToImageFlag)
  32552. {
  32553. bufferedImage_ = Image::null;
  32554. flags.bufferToImageFlag = shouldBeBuffered;
  32555. }
  32556. }
  32557. void Component::toFront (const bool setAsForeground)
  32558. {
  32559. // if component methods are being called from threads other than the message
  32560. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32561. checkMessageManagerIsLocked
  32562. if (flags.hasHeavyweightPeerFlag)
  32563. {
  32564. ComponentPeer* const peer = getPeer();
  32565. if (peer != 0)
  32566. {
  32567. peer->toFront (setAsForeground);
  32568. if (setAsForeground && ! hasKeyboardFocus (true))
  32569. grabKeyboardFocus();
  32570. }
  32571. }
  32572. else if (parentComponent_ != 0)
  32573. {
  32574. Array<Component*>& childList = parentComponent_->childComponentList_;
  32575. if (childList.getLast() != this)
  32576. {
  32577. const int index = childList.indexOf (this);
  32578. if (index >= 0)
  32579. {
  32580. int insertIndex = -1;
  32581. if (! flags.alwaysOnTopFlag)
  32582. {
  32583. insertIndex = childList.size() - 1;
  32584. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32585. --insertIndex;
  32586. }
  32587. if (index != insertIndex)
  32588. {
  32589. childList.move (index, insertIndex);
  32590. sendFakeMouseMove();
  32591. repaintParent();
  32592. }
  32593. }
  32594. }
  32595. if (setAsForeground)
  32596. {
  32597. internalBroughtToFront();
  32598. grabKeyboardFocus();
  32599. }
  32600. }
  32601. }
  32602. void Component::toBehind (Component* const other)
  32603. {
  32604. if (other != 0 && other != this)
  32605. {
  32606. // the two components must belong to the same parent..
  32607. jassert (parentComponent_ == other->parentComponent_);
  32608. if (parentComponent_ != 0)
  32609. {
  32610. Array<Component*>& childList = parentComponent_->childComponentList_;
  32611. const int index = childList.indexOf (this);
  32612. if (index >= 0 && childList [index + 1] != other)
  32613. {
  32614. int otherIndex = childList.indexOf (other);
  32615. if (otherIndex >= 0)
  32616. {
  32617. if (index < otherIndex)
  32618. --otherIndex;
  32619. childList.move (index, otherIndex);
  32620. sendFakeMouseMove();
  32621. repaintParent();
  32622. }
  32623. }
  32624. }
  32625. else if (isOnDesktop())
  32626. {
  32627. jassert (other->isOnDesktop());
  32628. if (other->isOnDesktop())
  32629. {
  32630. ComponentPeer* const us = getPeer();
  32631. ComponentPeer* const them = other->getPeer();
  32632. jassert (us != 0 && them != 0);
  32633. if (us != 0 && them != 0)
  32634. us->toBehind (them);
  32635. }
  32636. }
  32637. }
  32638. }
  32639. void Component::toBack()
  32640. {
  32641. Array<Component*>& childList = parentComponent_->childComponentList_;
  32642. if (isOnDesktop())
  32643. {
  32644. jassertfalse; //xxx need to add this to native window
  32645. }
  32646. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32647. {
  32648. const int index = childList.indexOf (this);
  32649. if (index > 0)
  32650. {
  32651. int insertIndex = 0;
  32652. if (flags.alwaysOnTopFlag)
  32653. {
  32654. while (insertIndex < childList.size()
  32655. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32656. {
  32657. ++insertIndex;
  32658. }
  32659. }
  32660. if (index != insertIndex)
  32661. {
  32662. childList.move (index, insertIndex);
  32663. sendFakeMouseMove();
  32664. repaintParent();
  32665. }
  32666. }
  32667. }
  32668. }
  32669. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32670. {
  32671. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32672. {
  32673. flags.alwaysOnTopFlag = shouldStayOnTop;
  32674. if (isOnDesktop())
  32675. {
  32676. ComponentPeer* const peer = getPeer();
  32677. jassert (peer != 0);
  32678. if (peer != 0)
  32679. {
  32680. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32681. {
  32682. // some kinds of peer can't change their always-on-top status, so
  32683. // for these, we'll need to create a new window
  32684. const int oldFlags = peer->getStyleFlags();
  32685. removeFromDesktop();
  32686. addToDesktop (oldFlags);
  32687. }
  32688. }
  32689. }
  32690. if (shouldStayOnTop)
  32691. toFront (false);
  32692. internalHierarchyChanged();
  32693. }
  32694. }
  32695. bool Component::isAlwaysOnTop() const throw()
  32696. {
  32697. return flags.alwaysOnTopFlag;
  32698. }
  32699. int Component::proportionOfWidth (const float proportion) const throw()
  32700. {
  32701. return roundToInt (proportion * bounds_.getWidth());
  32702. }
  32703. int Component::proportionOfHeight (const float proportion) const throw()
  32704. {
  32705. return roundToInt (proportion * bounds_.getHeight());
  32706. }
  32707. int Component::getParentWidth() const throw()
  32708. {
  32709. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32710. : getParentMonitorArea().getWidth();
  32711. }
  32712. int Component::getParentHeight() const throw()
  32713. {
  32714. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32715. : getParentMonitorArea().getHeight();
  32716. }
  32717. int Component::getScreenX() const
  32718. {
  32719. return getScreenPosition().getX();
  32720. }
  32721. int Component::getScreenY() const
  32722. {
  32723. return getScreenPosition().getY();
  32724. }
  32725. const Point<int> Component::getScreenPosition() const
  32726. {
  32727. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32728. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32729. : getPosition());
  32730. }
  32731. const Rectangle<int> Component::getScreenBounds() const
  32732. {
  32733. return bounds_.withPosition (getScreenPosition());
  32734. }
  32735. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32736. {
  32737. const Component* c = this;
  32738. Point<int> p (relativePosition);
  32739. do
  32740. {
  32741. if (c->flags.hasHeavyweightPeerFlag)
  32742. return c->getPeer()->relativePositionToGlobal (p);
  32743. p += c->getPosition();
  32744. c = c->parentComponent_;
  32745. }
  32746. while (c != 0);
  32747. return p;
  32748. }
  32749. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32750. {
  32751. if (flags.hasHeavyweightPeerFlag)
  32752. {
  32753. return getPeer()->globalPositionToRelative (screenPosition);
  32754. }
  32755. else
  32756. {
  32757. if (parentComponent_ != 0)
  32758. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32759. return screenPosition - getPosition();
  32760. }
  32761. }
  32762. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32763. {
  32764. Point<int> p (positionRelativeToThis);
  32765. if (targetComponent != 0)
  32766. {
  32767. const Component* c = this;
  32768. do
  32769. {
  32770. if (c == targetComponent)
  32771. return p;
  32772. if (c->flags.hasHeavyweightPeerFlag)
  32773. {
  32774. p = c->getPeer()->relativePositionToGlobal (p);
  32775. break;
  32776. }
  32777. p += c->getPosition();
  32778. c = c->parentComponent_;
  32779. }
  32780. while (c != 0);
  32781. p = targetComponent->globalPositionToRelative (p);
  32782. }
  32783. return p;
  32784. }
  32785. void Component::setBounds (const int x, const int y, int w, int h)
  32786. {
  32787. // if component methods are being called from threads other than the message
  32788. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32789. checkMessageManagerIsLocked
  32790. if (w < 0) w = 0;
  32791. if (h < 0) h = 0;
  32792. const bool wasResized = (getWidth() != w || getHeight() != h);
  32793. const bool wasMoved = (getX() != x || getY() != y);
  32794. #if JUCE_DEBUG
  32795. // It's a very bad idea to try to resize a window during its paint() method!
  32796. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32797. #endif
  32798. if (wasMoved || wasResized)
  32799. {
  32800. if (flags.visibleFlag)
  32801. {
  32802. // send a fake mouse move to trigger enter/exit messages if needed..
  32803. sendFakeMouseMove();
  32804. if (! flags.hasHeavyweightPeerFlag)
  32805. repaintParent();
  32806. }
  32807. bounds_.setBounds (x, y, w, h);
  32808. if (wasResized)
  32809. repaint();
  32810. else if (! flags.hasHeavyweightPeerFlag)
  32811. repaintParent();
  32812. if (flags.hasHeavyweightPeerFlag)
  32813. {
  32814. ComponentPeer* const peer = getPeer();
  32815. if (peer != 0)
  32816. {
  32817. if (wasMoved && wasResized)
  32818. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32819. else if (wasMoved)
  32820. peer->setPosition (getX(), getY());
  32821. else if (wasResized)
  32822. peer->setSize (getWidth(), getHeight());
  32823. }
  32824. }
  32825. sendMovedResizedMessages (wasMoved, wasResized);
  32826. }
  32827. }
  32828. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32829. {
  32830. JUCE_TRY
  32831. {
  32832. if (wasMoved)
  32833. moved();
  32834. if (wasResized)
  32835. {
  32836. resized();
  32837. for (int i = childComponentList_.size(); --i >= 0;)
  32838. {
  32839. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32840. i = jmin (i, childComponentList_.size());
  32841. }
  32842. }
  32843. BailOutChecker checker (this);
  32844. if (parentComponent_ != 0)
  32845. parentComponent_->childBoundsChanged (this);
  32846. if (! checker.shouldBailOut())
  32847. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32848. *this, wasMoved, wasResized);
  32849. }
  32850. JUCE_CATCH_EXCEPTION
  32851. }
  32852. void Component::setSize (const int w, const int h)
  32853. {
  32854. setBounds (getX(), getY(), w, h);
  32855. }
  32856. void Component::setTopLeftPosition (const int x, const int y)
  32857. {
  32858. setBounds (x, y, getWidth(), getHeight());
  32859. }
  32860. void Component::setTopRightPosition (const int x, const int y)
  32861. {
  32862. setTopLeftPosition (x - getWidth(), y);
  32863. }
  32864. void Component::setBounds (const Rectangle<int>& r)
  32865. {
  32866. setBounds (r.getX(),
  32867. r.getY(),
  32868. r.getWidth(),
  32869. r.getHeight());
  32870. }
  32871. void Component::setBoundsRelative (const float x, const float y,
  32872. const float w, const float h)
  32873. {
  32874. const int pw = getParentWidth();
  32875. const int ph = getParentHeight();
  32876. setBounds (roundToInt (x * pw),
  32877. roundToInt (y * ph),
  32878. roundToInt (w * pw),
  32879. roundToInt (h * ph));
  32880. }
  32881. void Component::setCentrePosition (const int x, const int y)
  32882. {
  32883. setTopLeftPosition (x - getWidth() / 2,
  32884. y - getHeight() / 2);
  32885. }
  32886. void Component::setCentreRelative (const float x, const float y)
  32887. {
  32888. setCentrePosition (roundToInt (getParentWidth() * x),
  32889. roundToInt (getParentHeight() * y));
  32890. }
  32891. void Component::centreWithSize (const int width, const int height)
  32892. {
  32893. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32894. setBounds (parentArea.getCentreX() - width / 2,
  32895. parentArea.getCentreY() - height / 2,
  32896. width, height);
  32897. }
  32898. void Component::setBoundsInset (const BorderSize& borders)
  32899. {
  32900. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32901. }
  32902. void Component::setBoundsToFit (int x, int y, int width, int height,
  32903. const Justification& justification,
  32904. const bool onlyReduceInSize)
  32905. {
  32906. // it's no good calling this method unless both the component and
  32907. // target rectangle have a finite size.
  32908. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32909. if (getWidth() > 0 && getHeight() > 0
  32910. && width > 0 && height > 0)
  32911. {
  32912. int newW, newH;
  32913. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32914. {
  32915. newW = getWidth();
  32916. newH = getHeight();
  32917. }
  32918. else
  32919. {
  32920. const double imageRatio = getHeight() / (double) getWidth();
  32921. const double targetRatio = height / (double) width;
  32922. if (imageRatio <= targetRatio)
  32923. {
  32924. newW = width;
  32925. newH = jmin (height, roundToInt (newW * imageRatio));
  32926. }
  32927. else
  32928. {
  32929. newH = height;
  32930. newW = jmin (width, roundToInt (newH / imageRatio));
  32931. }
  32932. }
  32933. if (newW > 0 && newH > 0)
  32934. {
  32935. int newX, newY;
  32936. justification.applyToRectangle (newX, newY, newW, newH,
  32937. x, y, width, height);
  32938. setBounds (newX, newY, newW, newH);
  32939. }
  32940. }
  32941. }
  32942. bool Component::hitTest (int x, int y)
  32943. {
  32944. if (! flags.ignoresMouseClicksFlag)
  32945. return true;
  32946. if (flags.allowChildMouseClicksFlag)
  32947. {
  32948. for (int i = getNumChildComponents(); --i >= 0;)
  32949. {
  32950. Component* const c = getChildComponent (i);
  32951. if (c->isVisible()
  32952. && c->bounds_.contains (x, y)
  32953. && c->hitTest (x - c->getX(),
  32954. y - c->getY()))
  32955. {
  32956. return true;
  32957. }
  32958. }
  32959. }
  32960. return false;
  32961. }
  32962. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32963. const bool allowClicksOnChildComponents) throw()
  32964. {
  32965. flags.ignoresMouseClicksFlag = ! allowClicks;
  32966. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32967. }
  32968. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32969. bool& allowsClicksOnChildComponents) const throw()
  32970. {
  32971. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32972. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32973. }
  32974. bool Component::contains (const int x, const int y)
  32975. {
  32976. if (((unsigned int) x) < (unsigned int) getWidth()
  32977. && ((unsigned int) y) < (unsigned int) getHeight()
  32978. && hitTest (x, y))
  32979. {
  32980. if (parentComponent_ != 0)
  32981. {
  32982. return parentComponent_->contains (x + getX(),
  32983. y + getY());
  32984. }
  32985. else if (flags.hasHeavyweightPeerFlag)
  32986. {
  32987. const ComponentPeer* const peer = getPeer();
  32988. if (peer != 0)
  32989. return peer->contains (Point<int> (x, y), true);
  32990. }
  32991. }
  32992. return false;
  32993. }
  32994. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32995. {
  32996. if (! contains (x, y))
  32997. return false;
  32998. Component* p = this;
  32999. while (p->parentComponent_ != 0)
  33000. {
  33001. x += p->getX();
  33002. y += p->getY();
  33003. p = p->parentComponent_;
  33004. }
  33005. const Component* const c = p->getComponentAt (x, y);
  33006. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  33007. }
  33008. Component* Component::getComponentAt (const Point<int>& position)
  33009. {
  33010. return getComponentAt (position.getX(), position.getY());
  33011. }
  33012. Component* Component::getComponentAt (const int x, const int y)
  33013. {
  33014. if (flags.visibleFlag
  33015. && ((unsigned int) x) < (unsigned int) getWidth()
  33016. && ((unsigned int) y) < (unsigned int) getHeight()
  33017. && hitTest (x, y))
  33018. {
  33019. for (int i = childComponentList_.size(); --i >= 0;)
  33020. {
  33021. Component* const child = childComponentList_.getUnchecked(i);
  33022. Component* const c = child->getComponentAt (x - child->getX(),
  33023. y - child->getY());
  33024. if (c != 0)
  33025. return c;
  33026. }
  33027. return this;
  33028. }
  33029. return 0;
  33030. }
  33031. void Component::addChildComponent (Component* const child, int zOrder)
  33032. {
  33033. // if component methods are being called from threads other than the message
  33034. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33035. checkMessageManagerIsLocked
  33036. if (child != 0 && child->parentComponent_ != this)
  33037. {
  33038. if (child->parentComponent_ != 0)
  33039. child->parentComponent_->removeChildComponent (child);
  33040. else
  33041. child->removeFromDesktop();
  33042. child->parentComponent_ = this;
  33043. if (child->isVisible())
  33044. child->repaintParent();
  33045. if (! child->isAlwaysOnTop())
  33046. {
  33047. if (zOrder < 0 || zOrder > childComponentList_.size())
  33048. zOrder = childComponentList_.size();
  33049. while (zOrder > 0)
  33050. {
  33051. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  33052. break;
  33053. --zOrder;
  33054. }
  33055. }
  33056. childComponentList_.insert (zOrder, child);
  33057. child->internalHierarchyChanged();
  33058. internalChildrenChanged();
  33059. }
  33060. }
  33061. void Component::addAndMakeVisible (Component* const child, int zOrder)
  33062. {
  33063. if (child != 0)
  33064. {
  33065. child->setVisible (true);
  33066. addChildComponent (child, zOrder);
  33067. }
  33068. }
  33069. void Component::removeChildComponent (Component* const child)
  33070. {
  33071. removeChildComponent (childComponentList_.indexOf (child));
  33072. }
  33073. Component* Component::removeChildComponent (const int index)
  33074. {
  33075. // if component methods are being called from threads other than the message
  33076. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33077. checkMessageManagerIsLocked
  33078. Component* const child = childComponentList_ [index];
  33079. if (child != 0)
  33080. {
  33081. sendFakeMouseMove();
  33082. child->repaintParent();
  33083. childComponentList_.remove (index);
  33084. child->parentComponent_ = 0;
  33085. JUCE_TRY
  33086. {
  33087. if ((currentlyFocusedComponent == child)
  33088. || child->isParentOf (currentlyFocusedComponent))
  33089. {
  33090. // get rid first to force the grabKeyboardFocus to change to us.
  33091. giveAwayFocus();
  33092. grabKeyboardFocus();
  33093. }
  33094. }
  33095. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  33096. catch (const std::exception& e)
  33097. {
  33098. currentlyFocusedComponent = 0;
  33099. Desktop::getInstance().triggerFocusCallback();
  33100. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  33101. }
  33102. catch (...)
  33103. {
  33104. currentlyFocusedComponent = 0;
  33105. Desktop::getInstance().triggerFocusCallback();
  33106. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  33107. }
  33108. #endif
  33109. child->internalHierarchyChanged();
  33110. internalChildrenChanged();
  33111. }
  33112. return child;
  33113. }
  33114. void Component::removeAllChildren()
  33115. {
  33116. while (childComponentList_.size() > 0)
  33117. removeChildComponent (childComponentList_.size() - 1);
  33118. }
  33119. void Component::deleteAllChildren()
  33120. {
  33121. while (childComponentList_.size() > 0)
  33122. delete (removeChildComponent (childComponentList_.size() - 1));
  33123. }
  33124. int Component::getNumChildComponents() const throw()
  33125. {
  33126. return childComponentList_.size();
  33127. }
  33128. Component* Component::getChildComponent (const int index) const throw()
  33129. {
  33130. return childComponentList_ [index];
  33131. }
  33132. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  33133. {
  33134. return childComponentList_.indexOf (const_cast <Component*> (child));
  33135. }
  33136. Component* Component::getTopLevelComponent() const throw()
  33137. {
  33138. const Component* comp = this;
  33139. while (comp->parentComponent_ != 0)
  33140. comp = comp->parentComponent_;
  33141. return const_cast <Component*> (comp);
  33142. }
  33143. bool Component::isParentOf (const Component* possibleChild) const throw()
  33144. {
  33145. if (! possibleChild->isValidComponent())
  33146. {
  33147. jassert (possibleChild == 0);
  33148. return false;
  33149. }
  33150. while (possibleChild != 0)
  33151. {
  33152. possibleChild = possibleChild->parentComponent_;
  33153. if (possibleChild == this)
  33154. return true;
  33155. }
  33156. return false;
  33157. }
  33158. void Component::parentHierarchyChanged()
  33159. {
  33160. }
  33161. void Component::childrenChanged()
  33162. {
  33163. }
  33164. void Component::internalChildrenChanged()
  33165. {
  33166. if (componentListeners.isEmpty())
  33167. {
  33168. childrenChanged();
  33169. }
  33170. else
  33171. {
  33172. BailOutChecker checker (this);
  33173. childrenChanged();
  33174. if (! checker.shouldBailOut())
  33175. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  33176. }
  33177. }
  33178. void Component::internalHierarchyChanged()
  33179. {
  33180. BailOutChecker checker (this);
  33181. parentHierarchyChanged();
  33182. if (checker.shouldBailOut())
  33183. return;
  33184. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  33185. if (checker.shouldBailOut())
  33186. return;
  33187. for (int i = childComponentList_.size(); --i >= 0;)
  33188. {
  33189. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  33190. if (checker.shouldBailOut())
  33191. {
  33192. // you really shouldn't delete the parent component during a callback telling you
  33193. // that it's changed..
  33194. jassertfalse;
  33195. return;
  33196. }
  33197. i = jmin (i, childComponentList_.size());
  33198. }
  33199. }
  33200. void* Component::runModalLoopCallback (void* userData)
  33201. {
  33202. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  33203. }
  33204. int Component::runModalLoop()
  33205. {
  33206. if (! MessageManager::getInstance()->isThisTheMessageThread())
  33207. {
  33208. // use a callback so this can be called from non-gui threads
  33209. return (int) (pointer_sized_int) MessageManager::getInstance()
  33210. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  33211. }
  33212. if (! isCurrentlyModal())
  33213. enterModalState (true);
  33214. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  33215. }
  33216. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  33217. {
  33218. // if component methods are being called from threads other than the message
  33219. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33220. checkMessageManagerIsLocked
  33221. // Check for an attempt to make a component modal when it already is!
  33222. // This can cause nasty problems..
  33223. jassert (! flags.currentlyModalFlag);
  33224. if (! isCurrentlyModal())
  33225. {
  33226. ModalComponentManager::getInstance()->startModal (this, callback);
  33227. flags.currentlyModalFlag = true;
  33228. setVisible (true);
  33229. if (takeKeyboardFocus_)
  33230. grabKeyboardFocus();
  33231. }
  33232. }
  33233. void Component::exitModalState (const int returnValue)
  33234. {
  33235. if (isCurrentlyModal())
  33236. {
  33237. if (MessageManager::getInstance()->isThisTheMessageThread())
  33238. {
  33239. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33240. flags.currentlyModalFlag = false;
  33241. bringModalComponentToFront();
  33242. }
  33243. else
  33244. {
  33245. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  33246. }
  33247. }
  33248. }
  33249. bool Component::isCurrentlyModal() const throw()
  33250. {
  33251. return flags.currentlyModalFlag
  33252. && getCurrentlyModalComponent() == this;
  33253. }
  33254. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33255. {
  33256. Component* const mc = getCurrentlyModalComponent();
  33257. return mc != 0
  33258. && mc != this
  33259. && (! mc->isParentOf (this))
  33260. && ! mc->canModalEventBeSentToComponent (this);
  33261. }
  33262. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33263. {
  33264. return ModalComponentManager::getInstance()->getNumModalComponents();
  33265. }
  33266. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33267. {
  33268. return ModalComponentManager::getInstance()->getModalComponent (index);
  33269. }
  33270. void Component::bringModalComponentToFront()
  33271. {
  33272. ComponentPeer* lastOne = 0;
  33273. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  33274. {
  33275. Component* const c = getCurrentlyModalComponent (i);
  33276. if (c == 0)
  33277. break;
  33278. ComponentPeer* peer = c->getPeer();
  33279. if (peer != 0 && peer != lastOne)
  33280. {
  33281. if (lastOne == 0)
  33282. {
  33283. peer->toFront (true);
  33284. peer->grabFocus();
  33285. }
  33286. else
  33287. peer->toBehind (lastOne);
  33288. lastOne = peer;
  33289. }
  33290. }
  33291. }
  33292. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33293. {
  33294. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33295. }
  33296. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33297. {
  33298. return flags.bringToFrontOnClickFlag;
  33299. }
  33300. void Component::setMouseCursor (const MouseCursor& cursor)
  33301. {
  33302. if (cursor_ != cursor)
  33303. {
  33304. cursor_ = cursor;
  33305. if (flags.visibleFlag)
  33306. updateMouseCursor();
  33307. }
  33308. }
  33309. const MouseCursor Component::getMouseCursor()
  33310. {
  33311. return cursor_;
  33312. }
  33313. void Component::updateMouseCursor() const
  33314. {
  33315. sendFakeMouseMove();
  33316. }
  33317. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33318. {
  33319. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33320. }
  33321. void Component::repaintParent()
  33322. {
  33323. if (flags.visibleFlag)
  33324. internalRepaint (0, 0, getWidth(), getHeight());
  33325. }
  33326. void Component::repaint()
  33327. {
  33328. repaint (0, 0, getWidth(), getHeight());
  33329. }
  33330. void Component::repaint (const int x, const int y,
  33331. const int w, const int h)
  33332. {
  33333. bufferedImage_ = Image::null;
  33334. if (flags.visibleFlag)
  33335. internalRepaint (x, y, w, h);
  33336. }
  33337. void Component::repaint (const Rectangle<int>& area)
  33338. {
  33339. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33340. }
  33341. void Component::internalRepaint (int x, int y, int w, int h)
  33342. {
  33343. // if component methods are being called from threads other than the message
  33344. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33345. checkMessageManagerIsLocked
  33346. if (x < 0)
  33347. {
  33348. w += x;
  33349. x = 0;
  33350. }
  33351. if (x + w > getWidth())
  33352. w = getWidth() - x;
  33353. if (w > 0)
  33354. {
  33355. if (y < 0)
  33356. {
  33357. h += y;
  33358. y = 0;
  33359. }
  33360. if (y + h > getHeight())
  33361. h = getHeight() - y;
  33362. if (h > 0)
  33363. {
  33364. if (parentComponent_ != 0)
  33365. {
  33366. x += getX();
  33367. y += getY();
  33368. if (parentComponent_->flags.visibleFlag)
  33369. parentComponent_->internalRepaint (x, y, w, h);
  33370. }
  33371. else if (flags.hasHeavyweightPeerFlag)
  33372. {
  33373. ComponentPeer* const peer = getPeer();
  33374. if (peer != 0)
  33375. peer->repaint (Rectangle<int> (x, y, w, h));
  33376. }
  33377. }
  33378. }
  33379. }
  33380. void Component::renderComponent (Graphics& g)
  33381. {
  33382. const Rectangle<int> clipBounds (g.getClipBounds());
  33383. g.saveState();
  33384. clipObscuredRegions (g, clipBounds, 0, 0);
  33385. if (! g.isClipEmpty())
  33386. {
  33387. if (flags.bufferToImageFlag)
  33388. {
  33389. if (bufferedImage_.isNull())
  33390. {
  33391. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33392. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33393. Graphics imG (bufferedImage_);
  33394. paint (imG);
  33395. }
  33396. g.setColour (Colours::black);
  33397. g.drawImageAt (bufferedImage_, 0, 0);
  33398. }
  33399. else
  33400. {
  33401. paint (g);
  33402. }
  33403. }
  33404. g.restoreState();
  33405. for (int i = 0; i < childComponentList_.size(); ++i)
  33406. {
  33407. Component* const child = childComponentList_.getUnchecked (i);
  33408. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33409. {
  33410. g.saveState();
  33411. if (g.reduceClipRegion (child->getX(), child->getY(),
  33412. child->getWidth(), child->getHeight()))
  33413. {
  33414. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33415. {
  33416. const Component* const sibling = childComponentList_.getUnchecked (j);
  33417. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33418. g.excludeClipRegion (sibling->getBounds());
  33419. }
  33420. if (! g.isClipEmpty())
  33421. {
  33422. g.setOrigin (child->getX(), child->getY());
  33423. child->paintEntireComponent (g);
  33424. }
  33425. }
  33426. g.restoreState();
  33427. }
  33428. }
  33429. g.saveState();
  33430. paintOverChildren (g);
  33431. g.restoreState();
  33432. }
  33433. void Component::paintEntireComponent (Graphics& g)
  33434. {
  33435. jassert (! g.isClipEmpty());
  33436. #if JUCE_DEBUG
  33437. flags.isInsidePaintCall = true;
  33438. #endif
  33439. if (effect_ != 0)
  33440. {
  33441. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33442. getWidth(), getHeight(),
  33443. ! flags.opaqueFlag, Image::NativeImage);
  33444. {
  33445. Graphics g2 (effectImage);
  33446. renderComponent (g2);
  33447. }
  33448. effect_->applyEffect (effectImage, g);
  33449. }
  33450. else
  33451. {
  33452. renderComponent (g);
  33453. }
  33454. #if JUCE_DEBUG
  33455. flags.isInsidePaintCall = false;
  33456. #endif
  33457. }
  33458. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33459. const bool clipImageToComponentBounds)
  33460. {
  33461. Rectangle<int> r (areaToGrab);
  33462. if (clipImageToComponentBounds)
  33463. r = r.getIntersection (getLocalBounds());
  33464. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33465. jmax (1, r.getWidth()),
  33466. jmax (1, r.getHeight()),
  33467. true);
  33468. Graphics imageContext (componentImage);
  33469. imageContext.setOrigin (-r.getX(), -r.getY());
  33470. paintEntireComponent (imageContext);
  33471. return componentImage;
  33472. }
  33473. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33474. {
  33475. if (effect_ != effect)
  33476. {
  33477. effect_ = effect;
  33478. repaint();
  33479. }
  33480. }
  33481. LookAndFeel& Component::getLookAndFeel() const throw()
  33482. {
  33483. const Component* c = this;
  33484. do
  33485. {
  33486. if (c->lookAndFeel_ != 0)
  33487. return *(c->lookAndFeel_);
  33488. c = c->parentComponent_;
  33489. }
  33490. while (c != 0);
  33491. return LookAndFeel::getDefaultLookAndFeel();
  33492. }
  33493. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33494. {
  33495. if (lookAndFeel_ != newLookAndFeel)
  33496. {
  33497. lookAndFeel_ = newLookAndFeel;
  33498. sendLookAndFeelChange();
  33499. }
  33500. }
  33501. void Component::lookAndFeelChanged()
  33502. {
  33503. }
  33504. void Component::sendLookAndFeelChange()
  33505. {
  33506. repaint();
  33507. lookAndFeelChanged();
  33508. // (it's not a great idea to do anything that would delete this component
  33509. // during the lookAndFeelChanged() callback)
  33510. jassert (isValidComponent());
  33511. SafePointer<Component> safePointer (this);
  33512. for (int i = childComponentList_.size(); --i >= 0;)
  33513. {
  33514. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33515. if (safePointer == 0)
  33516. return;
  33517. i = jmin (i, childComponentList_.size());
  33518. }
  33519. }
  33520. static const Identifier getColourPropertyId (const int colourId)
  33521. {
  33522. String s;
  33523. s.preallocateStorage (18);
  33524. s << "jcclr_" << String::toHexString (colourId);
  33525. return s;
  33526. }
  33527. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33528. {
  33529. var* v = properties.getItem (getColourPropertyId (colourId));
  33530. if (v != 0)
  33531. return Colour ((int) *v);
  33532. if (inheritFromParent && parentComponent_ != 0)
  33533. return parentComponent_->findColour (colourId, true);
  33534. return getLookAndFeel().findColour (colourId);
  33535. }
  33536. bool Component::isColourSpecified (const int colourId) const
  33537. {
  33538. return properties.contains (getColourPropertyId (colourId));
  33539. }
  33540. void Component::removeColour (const int colourId)
  33541. {
  33542. if (properties.remove (getColourPropertyId (colourId)))
  33543. colourChanged();
  33544. }
  33545. void Component::setColour (const int colourId, const Colour& colour)
  33546. {
  33547. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33548. colourChanged();
  33549. }
  33550. void Component::copyAllExplicitColoursTo (Component& target) const
  33551. {
  33552. bool changed = false;
  33553. for (int i = properties.size(); --i >= 0;)
  33554. {
  33555. const Identifier name (properties.getName(i));
  33556. if (name.toString().startsWith ("jcclr_"))
  33557. if (target.properties.set (name, properties [name]))
  33558. changed = true;
  33559. }
  33560. if (changed)
  33561. target.colourChanged();
  33562. }
  33563. void Component::colourChanged()
  33564. {
  33565. }
  33566. const Rectangle<int> Component::getLocalBounds() const throw()
  33567. {
  33568. return Rectangle<int> (getWidth(), getHeight());
  33569. }
  33570. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33571. {
  33572. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33573. : Desktop::getInstance().getMainMonitorArea();
  33574. }
  33575. const Rectangle<int> Component::getUnclippedArea() const
  33576. {
  33577. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33578. Component* p = parentComponent_;
  33579. int px = getX();
  33580. int py = getY();
  33581. while (p != 0)
  33582. {
  33583. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33584. return Rectangle<int>();
  33585. px += p->getX();
  33586. py += p->getY();
  33587. p = p->parentComponent_;
  33588. }
  33589. return Rectangle<int> (x, y, w, h);
  33590. }
  33591. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33592. const int deltaX, const int deltaY) const
  33593. {
  33594. for (int i = childComponentList_.size(); --i >= 0;)
  33595. {
  33596. const Component* const c = childComponentList_.getUnchecked(i);
  33597. if (c->isVisible())
  33598. {
  33599. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33600. if (! newClip.isEmpty())
  33601. {
  33602. if (c->isOpaque())
  33603. {
  33604. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33605. }
  33606. else
  33607. {
  33608. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33609. c->getX() + deltaX,
  33610. c->getY() + deltaY);
  33611. }
  33612. }
  33613. }
  33614. }
  33615. }
  33616. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33617. {
  33618. result.clear();
  33619. const Rectangle<int> unclipped (getUnclippedArea());
  33620. if (! unclipped.isEmpty())
  33621. {
  33622. result.add (unclipped);
  33623. if (includeSiblings)
  33624. {
  33625. const Component* const c = getTopLevelComponent();
  33626. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33627. c->getLocalBounds(), this);
  33628. }
  33629. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33630. result.consolidate();
  33631. }
  33632. }
  33633. void Component::subtractObscuredRegions (RectangleList& result,
  33634. const Point<int>& delta,
  33635. const Rectangle<int>& clipRect,
  33636. const Component* const compToAvoid) const
  33637. {
  33638. for (int i = childComponentList_.size(); --i >= 0;)
  33639. {
  33640. const Component* const c = childComponentList_.getUnchecked(i);
  33641. if (c != compToAvoid && c->isVisible())
  33642. {
  33643. if (c->isOpaque())
  33644. {
  33645. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33646. childBounds.translate (delta.getX(), delta.getY());
  33647. result.subtract (childBounds);
  33648. }
  33649. else
  33650. {
  33651. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33652. newClip.translate (-c->getX(), -c->getY());
  33653. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33654. newClip, compToAvoid);
  33655. }
  33656. }
  33657. }
  33658. }
  33659. void Component::mouseEnter (const MouseEvent&)
  33660. {
  33661. // base class does nothing
  33662. }
  33663. void Component::mouseExit (const MouseEvent&)
  33664. {
  33665. // base class does nothing
  33666. }
  33667. void Component::mouseDown (const MouseEvent&)
  33668. {
  33669. // base class does nothing
  33670. }
  33671. void Component::mouseUp (const MouseEvent&)
  33672. {
  33673. // base class does nothing
  33674. }
  33675. void Component::mouseDrag (const MouseEvent&)
  33676. {
  33677. // base class does nothing
  33678. }
  33679. void Component::mouseMove (const MouseEvent&)
  33680. {
  33681. // base class does nothing
  33682. }
  33683. void Component::mouseDoubleClick (const MouseEvent&)
  33684. {
  33685. // base class does nothing
  33686. }
  33687. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33688. {
  33689. // the base class just passes this event up to its parent..
  33690. if (parentComponent_ != 0)
  33691. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33692. wheelIncrementX, wheelIncrementY);
  33693. }
  33694. void Component::resized()
  33695. {
  33696. // base class does nothing
  33697. }
  33698. void Component::moved()
  33699. {
  33700. // base class does nothing
  33701. }
  33702. void Component::childBoundsChanged (Component*)
  33703. {
  33704. // base class does nothing
  33705. }
  33706. void Component::parentSizeChanged()
  33707. {
  33708. // base class does nothing
  33709. }
  33710. void Component::addComponentListener (ComponentListener* const newListener)
  33711. {
  33712. jassert (isValidComponent());
  33713. componentListeners.add (newListener);
  33714. }
  33715. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33716. {
  33717. jassert (isValidComponent());
  33718. componentListeners.remove (listenerToRemove);
  33719. }
  33720. void Component::inputAttemptWhenModal()
  33721. {
  33722. bringModalComponentToFront();
  33723. getLookAndFeel().playAlertSound();
  33724. }
  33725. bool Component::canModalEventBeSentToComponent (const Component*)
  33726. {
  33727. return false;
  33728. }
  33729. void Component::internalModalInputAttempt()
  33730. {
  33731. Component* const current = getCurrentlyModalComponent();
  33732. if (current != 0)
  33733. current->inputAttemptWhenModal();
  33734. }
  33735. void Component::paint (Graphics&)
  33736. {
  33737. // all painting is done in the subclasses
  33738. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33739. }
  33740. void Component::paintOverChildren (Graphics&)
  33741. {
  33742. // all painting is done in the subclasses
  33743. }
  33744. void Component::handleMessage (const Message& message)
  33745. {
  33746. if (message.intParameter1 == exitModalStateMessage)
  33747. {
  33748. exitModalState (message.intParameter2);
  33749. }
  33750. else if (message.intParameter1 == customCommandMessage)
  33751. {
  33752. handleCommandMessage (message.intParameter2);
  33753. }
  33754. }
  33755. void Component::postCommandMessage (const int commandId)
  33756. {
  33757. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33758. }
  33759. void Component::handleCommandMessage (int)
  33760. {
  33761. // used by subclasses
  33762. }
  33763. void Component::addMouseListener (MouseListener* const newListener,
  33764. const bool wantsEventsForAllNestedChildComponents)
  33765. {
  33766. // if component methods are being called from threads other than the message
  33767. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33768. checkMessageManagerIsLocked
  33769. if (mouseListeners_ == 0)
  33770. mouseListeners_ = new Array<MouseListener*>();
  33771. if (! mouseListeners_->contains (newListener))
  33772. {
  33773. if (wantsEventsForAllNestedChildComponents)
  33774. {
  33775. mouseListeners_->insert (0, newListener);
  33776. ++numDeepMouseListeners;
  33777. }
  33778. else
  33779. {
  33780. mouseListeners_->add (newListener);
  33781. }
  33782. }
  33783. }
  33784. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33785. {
  33786. // if component methods are being called from threads other than the message
  33787. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33788. checkMessageManagerIsLocked
  33789. if (mouseListeners_ != 0)
  33790. {
  33791. const int index = mouseListeners_->indexOf (listenerToRemove);
  33792. if (index >= 0)
  33793. {
  33794. if (index < numDeepMouseListeners)
  33795. --numDeepMouseListeners;
  33796. mouseListeners_->remove (index);
  33797. }
  33798. }
  33799. }
  33800. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33801. {
  33802. if (isCurrentlyBlockedByAnotherModalComponent())
  33803. {
  33804. // if something else is modal, always just show a normal mouse cursor
  33805. source.showMouseCursor (MouseCursor::NormalCursor);
  33806. return;
  33807. }
  33808. if (! flags.mouseInsideFlag)
  33809. {
  33810. flags.mouseInsideFlag = true;
  33811. flags.mouseOverFlag = true;
  33812. flags.draggingFlag = false;
  33813. BailOutChecker checker (this);
  33814. if (flags.repaintOnMouseActivityFlag)
  33815. repaint();
  33816. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33817. this, this, time, relativePos,
  33818. time, 0, false);
  33819. mouseEnter (me);
  33820. if (checker.shouldBailOut())
  33821. return;
  33822. Desktop::getInstance().resetTimer();
  33823. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33824. if (checker.shouldBailOut())
  33825. return;
  33826. if (mouseListeners_ != 0)
  33827. {
  33828. for (int i = mouseListeners_->size(); --i >= 0;)
  33829. {
  33830. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33831. if (checker.shouldBailOut())
  33832. return;
  33833. i = jmin (i, mouseListeners_->size());
  33834. }
  33835. }
  33836. Component* p = parentComponent_;
  33837. while (p != 0)
  33838. {
  33839. if (p->numDeepMouseListeners > 0)
  33840. {
  33841. BailOutChecker checker2 (this, p);
  33842. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33843. {
  33844. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33845. if (checker2.shouldBailOut())
  33846. return;
  33847. i = jmin (i, p->numDeepMouseListeners);
  33848. }
  33849. }
  33850. p = p->parentComponent_;
  33851. }
  33852. }
  33853. }
  33854. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33855. {
  33856. BailOutChecker checker (this);
  33857. if (flags.draggingFlag)
  33858. {
  33859. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33860. if (checker.shouldBailOut())
  33861. return;
  33862. }
  33863. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33864. {
  33865. flags.mouseInsideFlag = false;
  33866. flags.mouseOverFlag = false;
  33867. flags.draggingFlag = false;
  33868. if (flags.repaintOnMouseActivityFlag)
  33869. repaint();
  33870. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33871. this, this, time, relativePos,
  33872. time, 0, false);
  33873. mouseExit (me);
  33874. if (checker.shouldBailOut())
  33875. return;
  33876. Desktop::getInstance().resetTimer();
  33877. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33878. if (checker.shouldBailOut())
  33879. return;
  33880. if (mouseListeners_ != 0)
  33881. {
  33882. for (int i = mouseListeners_->size(); --i >= 0;)
  33883. {
  33884. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33885. if (checker.shouldBailOut())
  33886. return;
  33887. i = jmin (i, mouseListeners_->size());
  33888. }
  33889. }
  33890. Component* p = parentComponent_;
  33891. while (p != 0)
  33892. {
  33893. if (p->numDeepMouseListeners > 0)
  33894. {
  33895. BailOutChecker checker2 (this, p);
  33896. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33897. {
  33898. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33899. if (checker2.shouldBailOut())
  33900. return;
  33901. i = jmin (i, p->numDeepMouseListeners);
  33902. }
  33903. }
  33904. p = p->parentComponent_;
  33905. }
  33906. }
  33907. }
  33908. class InternalDragRepeater : public Timer
  33909. {
  33910. public:
  33911. InternalDragRepeater()
  33912. {}
  33913. ~InternalDragRepeater()
  33914. {
  33915. clearSingletonInstance();
  33916. }
  33917. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33918. void timerCallback()
  33919. {
  33920. Desktop& desktop = Desktop::getInstance();
  33921. int numMiceDown = 0;
  33922. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33923. {
  33924. MouseInputSource* const source = desktop.getMouseSource(i);
  33925. if (source->isDragging())
  33926. {
  33927. source->triggerFakeMove();
  33928. ++numMiceDown;
  33929. }
  33930. }
  33931. if (numMiceDown == 0)
  33932. deleteInstance();
  33933. }
  33934. juce_UseDebuggingNewOperator
  33935. private:
  33936. InternalDragRepeater (const InternalDragRepeater&);
  33937. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33938. };
  33939. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33940. void Component::beginDragAutoRepeat (const int interval)
  33941. {
  33942. if (interval > 0)
  33943. {
  33944. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33945. InternalDragRepeater::getInstance()->startTimer (interval);
  33946. }
  33947. else
  33948. {
  33949. InternalDragRepeater::deleteInstance();
  33950. }
  33951. }
  33952. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33953. {
  33954. Desktop& desktop = Desktop::getInstance();
  33955. BailOutChecker checker (this);
  33956. if (isCurrentlyBlockedByAnotherModalComponent())
  33957. {
  33958. internalModalInputAttempt();
  33959. if (checker.shouldBailOut())
  33960. return;
  33961. // If processing the input attempt has exited the modal loop, we'll allow the event
  33962. // to be delivered..
  33963. if (isCurrentlyBlockedByAnotherModalComponent())
  33964. {
  33965. // allow blocked mouse-events to go to global listeners..
  33966. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33967. this, this, time, relativePos, time,
  33968. source.getNumberOfMultipleClicks(), false);
  33969. desktop.resetTimer();
  33970. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33971. return;
  33972. }
  33973. }
  33974. {
  33975. Component* c = this;
  33976. while (c != 0)
  33977. {
  33978. if (c->isBroughtToFrontOnMouseClick())
  33979. {
  33980. c->toFront (true);
  33981. if (checker.shouldBailOut())
  33982. return;
  33983. }
  33984. c = c->parentComponent_;
  33985. }
  33986. }
  33987. if (! flags.dontFocusOnMouseClickFlag)
  33988. {
  33989. grabFocusInternal (focusChangedByMouseClick);
  33990. if (checker.shouldBailOut())
  33991. return;
  33992. }
  33993. flags.draggingFlag = true;
  33994. flags.mouseOverFlag = true;
  33995. if (flags.repaintOnMouseActivityFlag)
  33996. repaint();
  33997. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33998. this, this, time, relativePos, time,
  33999. source.getNumberOfMultipleClicks(), false);
  34000. mouseDown (me);
  34001. if (checker.shouldBailOut())
  34002. return;
  34003. desktop.resetTimer();
  34004. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  34005. if (checker.shouldBailOut())
  34006. return;
  34007. if (mouseListeners_ != 0)
  34008. {
  34009. for (int i = mouseListeners_->size(); --i >= 0;)
  34010. {
  34011. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  34012. if (checker.shouldBailOut())
  34013. return;
  34014. i = jmin (i, mouseListeners_->size());
  34015. }
  34016. }
  34017. Component* p = parentComponent_;
  34018. while (p != 0)
  34019. {
  34020. if (p->numDeepMouseListeners > 0)
  34021. {
  34022. BailOutChecker checker2 (this, p);
  34023. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34024. {
  34025. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  34026. if (checker2.shouldBailOut())
  34027. return;
  34028. i = jmin (i, p->numDeepMouseListeners);
  34029. }
  34030. }
  34031. p = p->parentComponent_;
  34032. }
  34033. }
  34034. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  34035. {
  34036. if (flags.draggingFlag)
  34037. {
  34038. Desktop& desktop = Desktop::getInstance();
  34039. flags.draggingFlag = false;
  34040. BailOutChecker checker (this);
  34041. if (flags.repaintOnMouseActivityFlag)
  34042. repaint();
  34043. const MouseEvent me (source, relativePos,
  34044. oldModifiers, this, this, time,
  34045. globalPositionToRelative (source.getLastMouseDownPosition()),
  34046. source.getLastMouseDownTime(),
  34047. source.getNumberOfMultipleClicks(),
  34048. source.hasMouseMovedSignificantlySincePressed());
  34049. mouseUp (me);
  34050. if (checker.shouldBailOut())
  34051. return;
  34052. desktop.resetTimer();
  34053. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  34054. if (checker.shouldBailOut())
  34055. return;
  34056. if (mouseListeners_ != 0)
  34057. {
  34058. for (int i = mouseListeners_->size(); --i >= 0;)
  34059. {
  34060. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  34061. if (checker.shouldBailOut())
  34062. return;
  34063. i = jmin (i, mouseListeners_->size());
  34064. }
  34065. }
  34066. {
  34067. Component* p = parentComponent_;
  34068. while (p != 0)
  34069. {
  34070. if (p->numDeepMouseListeners > 0)
  34071. {
  34072. BailOutChecker checker2 (this, p);
  34073. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34074. {
  34075. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  34076. if (checker2.shouldBailOut())
  34077. return;
  34078. i = jmin (i, p->numDeepMouseListeners);
  34079. }
  34080. }
  34081. p = p->parentComponent_;
  34082. }
  34083. }
  34084. // check for double-click
  34085. if (me.getNumberOfClicks() >= 2)
  34086. {
  34087. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  34088. mouseDoubleClick (me);
  34089. if (checker.shouldBailOut())
  34090. return;
  34091. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  34092. if (checker.shouldBailOut())
  34093. return;
  34094. for (int i = numListeners; --i >= 0;)
  34095. {
  34096. if (checker.shouldBailOut())
  34097. return;
  34098. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  34099. if (ml != 0)
  34100. ml->mouseDoubleClick (me);
  34101. }
  34102. if (checker.shouldBailOut())
  34103. return;
  34104. Component* p = parentComponent_;
  34105. while (p != 0)
  34106. {
  34107. if (p->numDeepMouseListeners > 0)
  34108. {
  34109. BailOutChecker checker2 (this, p);
  34110. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34111. {
  34112. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  34113. if (checker2.shouldBailOut())
  34114. return;
  34115. i = jmin (i, p->numDeepMouseListeners);
  34116. }
  34117. }
  34118. p = p->parentComponent_;
  34119. }
  34120. }
  34121. }
  34122. }
  34123. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  34124. {
  34125. if (flags.draggingFlag)
  34126. {
  34127. Desktop& desktop = Desktop::getInstance();
  34128. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  34129. BailOutChecker checker (this);
  34130. const MouseEvent me (source, relativePos,
  34131. source.getCurrentModifiers(), this, this, time,
  34132. globalPositionToRelative (source.getLastMouseDownPosition()),
  34133. source.getLastMouseDownTime(),
  34134. source.getNumberOfMultipleClicks(),
  34135. source.hasMouseMovedSignificantlySincePressed());
  34136. mouseDrag (me);
  34137. if (checker.shouldBailOut())
  34138. return;
  34139. desktop.resetTimer();
  34140. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34141. if (checker.shouldBailOut())
  34142. return;
  34143. if (mouseListeners_ != 0)
  34144. {
  34145. for (int i = mouseListeners_->size(); --i >= 0;)
  34146. {
  34147. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  34148. if (checker.shouldBailOut())
  34149. return;
  34150. i = jmin (i, mouseListeners_->size());
  34151. }
  34152. }
  34153. Component* p = parentComponent_;
  34154. while (p != 0)
  34155. {
  34156. if (p->numDeepMouseListeners > 0)
  34157. {
  34158. BailOutChecker checker2 (this, p);
  34159. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34160. {
  34161. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  34162. if (checker2.shouldBailOut())
  34163. return;
  34164. i = jmin (i, p->numDeepMouseListeners);
  34165. }
  34166. }
  34167. p = p->parentComponent_;
  34168. }
  34169. }
  34170. }
  34171. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  34172. {
  34173. Desktop& desktop = Desktop::getInstance();
  34174. BailOutChecker checker (this);
  34175. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  34176. this, this, time, relativePos,
  34177. time, 0, false);
  34178. if (isCurrentlyBlockedByAnotherModalComponent())
  34179. {
  34180. // allow blocked mouse-events to go to global listeners..
  34181. desktop.sendMouseMove();
  34182. }
  34183. else
  34184. {
  34185. flags.mouseOverFlag = true;
  34186. mouseMove (me);
  34187. if (checker.shouldBailOut())
  34188. return;
  34189. desktop.resetTimer();
  34190. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34191. if (checker.shouldBailOut())
  34192. return;
  34193. if (mouseListeners_ != 0)
  34194. {
  34195. for (int i = mouseListeners_->size(); --i >= 0;)
  34196. {
  34197. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  34198. if (checker.shouldBailOut())
  34199. return;
  34200. i = jmin (i, mouseListeners_->size());
  34201. }
  34202. }
  34203. Component* p = parentComponent_;
  34204. while (p != 0)
  34205. {
  34206. if (p->numDeepMouseListeners > 0)
  34207. {
  34208. BailOutChecker checker2 (this, p);
  34209. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34210. {
  34211. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  34212. if (checker2.shouldBailOut())
  34213. return;
  34214. i = jmin (i, p->numDeepMouseListeners);
  34215. }
  34216. }
  34217. p = p->parentComponent_;
  34218. }
  34219. }
  34220. }
  34221. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  34222. const Time& time, const float amountX, const float amountY)
  34223. {
  34224. Desktop& desktop = Desktop::getInstance();
  34225. BailOutChecker checker (this);
  34226. const float wheelIncrementX = amountX / 256.0f;
  34227. const float wheelIncrementY = amountY / 256.0f;
  34228. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  34229. this, this, time, relativePos, time, 0, false);
  34230. if (isCurrentlyBlockedByAnotherModalComponent())
  34231. {
  34232. // allow blocked mouse-events to go to global listeners..
  34233. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  34234. }
  34235. else
  34236. {
  34237. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34238. if (checker.shouldBailOut())
  34239. return;
  34240. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  34241. if (checker.shouldBailOut())
  34242. return;
  34243. if (mouseListeners_ != 0)
  34244. {
  34245. for (int i = mouseListeners_->size(); --i >= 0;)
  34246. {
  34247. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34248. if (checker.shouldBailOut())
  34249. return;
  34250. i = jmin (i, mouseListeners_->size());
  34251. }
  34252. }
  34253. Component* p = parentComponent_;
  34254. while (p != 0)
  34255. {
  34256. if (p->numDeepMouseListeners > 0)
  34257. {
  34258. BailOutChecker checker2 (this, p);
  34259. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34260. {
  34261. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34262. if (checker2.shouldBailOut())
  34263. return;
  34264. i = jmin (i, p->numDeepMouseListeners);
  34265. }
  34266. }
  34267. p = p->parentComponent_;
  34268. }
  34269. }
  34270. }
  34271. void Component::sendFakeMouseMove() const
  34272. {
  34273. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  34274. }
  34275. void Component::broughtToFront()
  34276. {
  34277. }
  34278. void Component::internalBroughtToFront()
  34279. {
  34280. if (! isValidComponent())
  34281. return;
  34282. if (flags.hasHeavyweightPeerFlag)
  34283. Desktop::getInstance().componentBroughtToFront (this);
  34284. BailOutChecker checker (this);
  34285. broughtToFront();
  34286. if (checker.shouldBailOut())
  34287. return;
  34288. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  34289. if (checker.shouldBailOut())
  34290. return;
  34291. // When brought to the front and there's a modal component blocking this one,
  34292. // we need to bring the modal one to the front instead..
  34293. Component* const cm = getCurrentlyModalComponent();
  34294. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  34295. bringModalComponentToFront();
  34296. }
  34297. void Component::focusGained (FocusChangeType)
  34298. {
  34299. // base class does nothing
  34300. }
  34301. void Component::internalFocusGain (const FocusChangeType cause)
  34302. {
  34303. SafePointer<Component> safePointer (this);
  34304. focusGained (cause);
  34305. if (safePointer != 0)
  34306. internalChildFocusChange (cause);
  34307. }
  34308. void Component::focusLost (FocusChangeType)
  34309. {
  34310. // base class does nothing
  34311. }
  34312. void Component::internalFocusLoss (const FocusChangeType cause)
  34313. {
  34314. SafePointer<Component> safePointer (this);
  34315. focusLost (focusChangedDirectly);
  34316. if (safePointer != 0)
  34317. internalChildFocusChange (cause);
  34318. }
  34319. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  34320. {
  34321. // base class does nothing
  34322. }
  34323. void Component::internalChildFocusChange (FocusChangeType cause)
  34324. {
  34325. const bool childIsNowFocused = hasKeyboardFocus (true);
  34326. if (flags.childCompFocusedFlag != childIsNowFocused)
  34327. {
  34328. flags.childCompFocusedFlag = childIsNowFocused;
  34329. SafePointer<Component> safePointer (this);
  34330. focusOfChildComponentChanged (cause);
  34331. if (safePointer == 0)
  34332. return;
  34333. }
  34334. if (parentComponent_ != 0)
  34335. parentComponent_->internalChildFocusChange (cause);
  34336. }
  34337. bool Component::isEnabled() const throw()
  34338. {
  34339. return (! flags.isDisabledFlag)
  34340. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34341. }
  34342. void Component::setEnabled (const bool shouldBeEnabled)
  34343. {
  34344. if (flags.isDisabledFlag == shouldBeEnabled)
  34345. {
  34346. flags.isDisabledFlag = ! shouldBeEnabled;
  34347. // if any parent components are disabled, setting our flag won't make a difference,
  34348. // so no need to send a change message
  34349. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34350. sendEnablementChangeMessage();
  34351. }
  34352. }
  34353. void Component::sendEnablementChangeMessage()
  34354. {
  34355. SafePointer<Component> safePointer (this);
  34356. enablementChanged();
  34357. if (safePointer == 0)
  34358. return;
  34359. for (int i = getNumChildComponents(); --i >= 0;)
  34360. {
  34361. Component* const c = getChildComponent (i);
  34362. if (c != 0)
  34363. {
  34364. c->sendEnablementChangeMessage();
  34365. if (safePointer == 0)
  34366. return;
  34367. }
  34368. }
  34369. }
  34370. void Component::enablementChanged()
  34371. {
  34372. }
  34373. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34374. {
  34375. flags.wantsFocusFlag = wantsFocus;
  34376. }
  34377. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34378. {
  34379. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34380. }
  34381. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34382. {
  34383. return ! flags.dontFocusOnMouseClickFlag;
  34384. }
  34385. bool Component::getWantsKeyboardFocus() const throw()
  34386. {
  34387. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34388. }
  34389. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34390. {
  34391. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34392. }
  34393. bool Component::isFocusContainer() const throw()
  34394. {
  34395. return flags.isFocusContainerFlag;
  34396. }
  34397. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34398. int Component::getExplicitFocusOrder() const
  34399. {
  34400. return properties [juce_explicitFocusOrderId];
  34401. }
  34402. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34403. {
  34404. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34405. }
  34406. KeyboardFocusTraverser* Component::createFocusTraverser()
  34407. {
  34408. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34409. return new KeyboardFocusTraverser();
  34410. return parentComponent_->createFocusTraverser();
  34411. }
  34412. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34413. {
  34414. // give the focus to this component
  34415. if (currentlyFocusedComponent != this)
  34416. {
  34417. JUCE_TRY
  34418. {
  34419. // get the focus onto our desktop window
  34420. ComponentPeer* const peer = getPeer();
  34421. if (peer != 0)
  34422. {
  34423. SafePointer<Component> safePointer (this);
  34424. peer->grabFocus();
  34425. if (peer->isFocused() && currentlyFocusedComponent != this)
  34426. {
  34427. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34428. currentlyFocusedComponent = this;
  34429. Desktop::getInstance().triggerFocusCallback();
  34430. // call this after setting currentlyFocusedComponent so that the one that's
  34431. // losing it has a chance to see where focus is going
  34432. if (componentLosingFocus != 0)
  34433. componentLosingFocus->internalFocusLoss (cause);
  34434. if (currentlyFocusedComponent == this)
  34435. {
  34436. focusGained (cause);
  34437. if (safePointer != 0)
  34438. internalChildFocusChange (cause);
  34439. }
  34440. }
  34441. }
  34442. }
  34443. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34444. catch (const std::exception& e)
  34445. {
  34446. currentlyFocusedComponent = 0;
  34447. Desktop::getInstance().triggerFocusCallback();
  34448. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34449. }
  34450. catch (...)
  34451. {
  34452. currentlyFocusedComponent = 0;
  34453. Desktop::getInstance().triggerFocusCallback();
  34454. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34455. }
  34456. #endif
  34457. }
  34458. }
  34459. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34460. {
  34461. if (isShowing())
  34462. {
  34463. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34464. {
  34465. takeKeyboardFocus (cause);
  34466. }
  34467. else
  34468. {
  34469. if (isParentOf (currentlyFocusedComponent)
  34470. && currentlyFocusedComponent->isShowing())
  34471. {
  34472. // do nothing if the focused component is actually a child of ours..
  34473. }
  34474. else
  34475. {
  34476. // find the default child component..
  34477. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34478. if (traverser != 0)
  34479. {
  34480. Component* const defaultComp = traverser->getDefaultComponent (this);
  34481. traverser = 0;
  34482. if (defaultComp != 0)
  34483. {
  34484. defaultComp->grabFocusInternal (cause, false);
  34485. return;
  34486. }
  34487. }
  34488. if (canTryParent && parentComponent_ != 0)
  34489. {
  34490. // if no children want it and we're allowed to try our parent comp,
  34491. // then pass up to parent, which will try our siblings.
  34492. parentComponent_->grabFocusInternal (cause, true);
  34493. }
  34494. }
  34495. }
  34496. }
  34497. }
  34498. void Component::grabKeyboardFocus()
  34499. {
  34500. // if component methods are being called from threads other than the message
  34501. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34502. checkMessageManagerIsLocked
  34503. grabFocusInternal (focusChangedDirectly);
  34504. }
  34505. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34506. {
  34507. // if component methods are being called from threads other than the message
  34508. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34509. checkMessageManagerIsLocked
  34510. if (parentComponent_ != 0)
  34511. {
  34512. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34513. if (traverser != 0)
  34514. {
  34515. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34516. : traverser->getPreviousComponent (this);
  34517. traverser = 0;
  34518. if (nextComp != 0)
  34519. {
  34520. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34521. {
  34522. SafePointer<Component> nextCompPointer (nextComp);
  34523. internalModalInputAttempt();
  34524. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34525. return;
  34526. }
  34527. nextComp->grabFocusInternal (focusChangedByTabKey);
  34528. return;
  34529. }
  34530. }
  34531. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34532. }
  34533. }
  34534. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34535. {
  34536. return (currentlyFocusedComponent == this)
  34537. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34538. }
  34539. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34540. {
  34541. return currentlyFocusedComponent;
  34542. }
  34543. void Component::giveAwayFocus()
  34544. {
  34545. // use a copy so we can clear the value before the call
  34546. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34547. currentlyFocusedComponent = 0;
  34548. Desktop::getInstance().triggerFocusCallback();
  34549. if (componentLosingFocus != 0)
  34550. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34551. }
  34552. bool Component::isMouseOver() const throw()
  34553. {
  34554. return flags.mouseOverFlag;
  34555. }
  34556. bool Component::isMouseButtonDown() const throw()
  34557. {
  34558. return flags.draggingFlag;
  34559. }
  34560. bool Component::isMouseOverOrDragging() const throw()
  34561. {
  34562. return flags.mouseOverFlag || flags.draggingFlag;
  34563. }
  34564. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34565. {
  34566. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34567. }
  34568. const Point<int> Component::getMouseXYRelative() const
  34569. {
  34570. return globalPositionToRelative (Desktop::getMousePosition());
  34571. }
  34572. const Rectangle<int> Component::getParentMonitorArea() const
  34573. {
  34574. return Desktop::getInstance()
  34575. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34576. }
  34577. void Component::addKeyListener (KeyListener* const newListener)
  34578. {
  34579. if (keyListeners_ == 0)
  34580. keyListeners_ = new Array <KeyListener*>();
  34581. keyListeners_->addIfNotAlreadyThere (newListener);
  34582. }
  34583. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34584. {
  34585. if (keyListeners_ != 0)
  34586. keyListeners_->removeValue (listenerToRemove);
  34587. }
  34588. bool Component::keyPressed (const KeyPress&)
  34589. {
  34590. return false;
  34591. }
  34592. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34593. {
  34594. return false;
  34595. }
  34596. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34597. {
  34598. if (parentComponent_ != 0)
  34599. parentComponent_->modifierKeysChanged (modifiers);
  34600. }
  34601. void Component::internalModifierKeysChanged()
  34602. {
  34603. sendFakeMouseMove();
  34604. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34605. }
  34606. ComponentPeer* Component::getPeer() const
  34607. {
  34608. if (flags.hasHeavyweightPeerFlag)
  34609. return ComponentPeer::getPeerFor (this);
  34610. else if (parentComponent_ != 0)
  34611. return parentComponent_->getPeer();
  34612. else
  34613. return 0;
  34614. }
  34615. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34616. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34617. {
  34618. jassert (component1 != 0);
  34619. }
  34620. bool Component::BailOutChecker::shouldBailOut() const throw()
  34621. {
  34622. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34623. }
  34624. END_JUCE_NAMESPACE
  34625. /*** End of inlined file: juce_Component.cpp ***/
  34626. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34627. BEGIN_JUCE_NAMESPACE
  34628. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34629. void ComponentListener::componentBroughtToFront (Component&) {}
  34630. void ComponentListener::componentVisibilityChanged (Component&) {}
  34631. void ComponentListener::componentChildrenChanged (Component&) {}
  34632. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34633. void ComponentListener::componentNameChanged (Component&) {}
  34634. void ComponentListener::componentBeingDeleted (Component&) {}
  34635. END_JUCE_NAMESPACE
  34636. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34637. /*** Start of inlined file: juce_Desktop.cpp ***/
  34638. BEGIN_JUCE_NAMESPACE
  34639. Desktop::Desktop()
  34640. : mouseClickCounter (0),
  34641. kioskModeComponent (0)
  34642. {
  34643. createMouseInputSources();
  34644. refreshMonitorSizes();
  34645. }
  34646. Desktop::~Desktop()
  34647. {
  34648. jassert (instance == this);
  34649. instance = 0;
  34650. // doh! If you don't delete all your windows before exiting, you're going to
  34651. // be leaking memory!
  34652. jassert (desktopComponents.size() == 0);
  34653. }
  34654. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34655. {
  34656. if (instance == 0)
  34657. instance = new Desktop();
  34658. return *instance;
  34659. }
  34660. Desktop* Desktop::instance = 0;
  34661. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34662. const bool clipToWorkArea);
  34663. void Desktop::refreshMonitorSizes()
  34664. {
  34665. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34666. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34667. monitorCoordsClipped.clear();
  34668. monitorCoordsUnclipped.clear();
  34669. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34670. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34671. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34672. if (oldClipped != monitorCoordsClipped
  34673. || oldUnclipped != monitorCoordsUnclipped)
  34674. {
  34675. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34676. {
  34677. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34678. if (p != 0)
  34679. p->handleScreenSizeChange();
  34680. }
  34681. }
  34682. }
  34683. int Desktop::getNumDisplayMonitors() const throw()
  34684. {
  34685. return monitorCoordsClipped.size();
  34686. }
  34687. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34688. {
  34689. return clippedToWorkArea ? monitorCoordsClipped [index]
  34690. : monitorCoordsUnclipped [index];
  34691. }
  34692. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34693. {
  34694. RectangleList rl;
  34695. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34696. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34697. return rl;
  34698. }
  34699. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34700. {
  34701. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34702. }
  34703. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34704. {
  34705. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34706. double bestDistance = 1.0e10;
  34707. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34708. {
  34709. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34710. if (rect.contains (position))
  34711. return rect;
  34712. const double distance = rect.getCentre().getDistanceFrom (position);
  34713. if (distance < bestDistance)
  34714. {
  34715. bestDistance = distance;
  34716. best = rect;
  34717. }
  34718. }
  34719. return best;
  34720. }
  34721. int Desktop::getNumComponents() const throw()
  34722. {
  34723. return desktopComponents.size();
  34724. }
  34725. Component* Desktop::getComponent (const int index) const throw()
  34726. {
  34727. return desktopComponents [index];
  34728. }
  34729. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34730. {
  34731. for (int i = desktopComponents.size(); --i >= 0;)
  34732. {
  34733. Component* const c = desktopComponents.getUnchecked(i);
  34734. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34735. if (c->contains (relative.getX(), relative.getY()))
  34736. return c->getComponentAt (relative.getX(), relative.getY());
  34737. }
  34738. return 0;
  34739. }
  34740. void Desktop::addDesktopComponent (Component* const c)
  34741. {
  34742. jassert (c != 0);
  34743. jassert (! desktopComponents.contains (c));
  34744. desktopComponents.addIfNotAlreadyThere (c);
  34745. }
  34746. void Desktop::removeDesktopComponent (Component* const c)
  34747. {
  34748. desktopComponents.removeValue (c);
  34749. }
  34750. void Desktop::componentBroughtToFront (Component* const c)
  34751. {
  34752. const int index = desktopComponents.indexOf (c);
  34753. jassert (index >= 0);
  34754. if (index >= 0)
  34755. {
  34756. int newIndex = -1;
  34757. if (! c->isAlwaysOnTop())
  34758. {
  34759. newIndex = desktopComponents.size();
  34760. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34761. --newIndex;
  34762. --newIndex;
  34763. }
  34764. desktopComponents.move (index, newIndex);
  34765. }
  34766. }
  34767. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34768. {
  34769. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34770. }
  34771. int Desktop::getMouseButtonClickCounter() throw()
  34772. {
  34773. return getInstance().mouseClickCounter;
  34774. }
  34775. void Desktop::incrementMouseClickCounter() throw()
  34776. {
  34777. ++mouseClickCounter;
  34778. }
  34779. int Desktop::getNumDraggingMouseSources() const throw()
  34780. {
  34781. int num = 0;
  34782. for (int i = mouseSources.size(); --i >= 0;)
  34783. if (mouseSources.getUnchecked(i)->isDragging())
  34784. ++num;
  34785. return num;
  34786. }
  34787. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34788. {
  34789. int num = 0;
  34790. for (int i = mouseSources.size(); --i >= 0;)
  34791. {
  34792. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34793. if (mi->isDragging())
  34794. {
  34795. if (index == num)
  34796. return mi;
  34797. ++num;
  34798. }
  34799. }
  34800. return 0;
  34801. }
  34802. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34803. {
  34804. focusListeners.add (listener);
  34805. }
  34806. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34807. {
  34808. focusListeners.remove (listener);
  34809. }
  34810. void Desktop::triggerFocusCallback()
  34811. {
  34812. triggerAsyncUpdate();
  34813. }
  34814. void Desktop::handleAsyncUpdate()
  34815. {
  34816. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34817. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34818. }
  34819. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34820. {
  34821. mouseListeners.add (listener);
  34822. resetTimer();
  34823. }
  34824. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34825. {
  34826. mouseListeners.remove (listener);
  34827. resetTimer();
  34828. }
  34829. void Desktop::timerCallback()
  34830. {
  34831. if (lastFakeMouseMove != getMousePosition())
  34832. sendMouseMove();
  34833. }
  34834. void Desktop::sendMouseMove()
  34835. {
  34836. if (! mouseListeners.isEmpty())
  34837. {
  34838. startTimer (20);
  34839. lastFakeMouseMove = getMousePosition();
  34840. Component* const target = findComponentAt (lastFakeMouseMove);
  34841. if (target != 0)
  34842. {
  34843. Component::BailOutChecker checker (target);
  34844. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34845. const Time now (Time::getCurrentTime());
  34846. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34847. target, target, now, pos, now, 0, false);
  34848. if (me.mods.isAnyMouseButtonDown())
  34849. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34850. else
  34851. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34852. }
  34853. }
  34854. }
  34855. void Desktop::resetTimer()
  34856. {
  34857. if (mouseListeners.size() == 0)
  34858. stopTimer();
  34859. else
  34860. startTimer (100);
  34861. lastFakeMouseMove = getMousePosition();
  34862. }
  34863. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34864. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34865. {
  34866. if (kioskModeComponent != componentToUse)
  34867. {
  34868. // agh! Don't delete a component without first stopping it being the kiosk comp
  34869. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34870. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34871. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34872. if (kioskModeComponent->isValidComponent())
  34873. {
  34874. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34875. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34876. }
  34877. kioskModeComponent = componentToUse;
  34878. if (kioskModeComponent != 0)
  34879. {
  34880. jassert (kioskModeComponent->isValidComponent());
  34881. // Only components that are already on the desktop can be put into kiosk mode!
  34882. jassert (kioskModeComponent->isOnDesktop());
  34883. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34884. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34885. }
  34886. }
  34887. }
  34888. END_JUCE_NAMESPACE
  34889. /*** End of inlined file: juce_Desktop.cpp ***/
  34890. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34891. BEGIN_JUCE_NAMESPACE
  34892. class ModalComponentManager::ModalItem : public ComponentListener
  34893. {
  34894. public:
  34895. ModalItem (Component* const comp, Callback* const callback)
  34896. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34897. {
  34898. if (callback != 0)
  34899. callbacks.add (callback);
  34900. jassert (comp != 0);
  34901. component->addComponentListener (this);
  34902. }
  34903. ~ModalItem()
  34904. {
  34905. if (! isDeleted)
  34906. component->removeComponentListener (this);
  34907. }
  34908. void componentBeingDeleted (Component&)
  34909. {
  34910. isDeleted = true;
  34911. cancel();
  34912. }
  34913. void componentVisibilityChanged (Component&)
  34914. {
  34915. if (! component->isShowing())
  34916. cancel();
  34917. }
  34918. void componentParentHierarchyChanged (Component&)
  34919. {
  34920. if (! component->isShowing())
  34921. cancel();
  34922. }
  34923. void cancel()
  34924. {
  34925. if (isActive)
  34926. {
  34927. isActive = false;
  34928. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34929. }
  34930. }
  34931. Component* component;
  34932. OwnedArray<Callback> callbacks;
  34933. int returnValue;
  34934. bool isActive, isDeleted;
  34935. private:
  34936. ModalItem (const ModalItem&);
  34937. ModalItem& operator= (const ModalItem&);
  34938. };
  34939. ModalComponentManager::ModalComponentManager()
  34940. {
  34941. }
  34942. ModalComponentManager::~ModalComponentManager()
  34943. {
  34944. clearSingletonInstance();
  34945. }
  34946. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34947. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34948. {
  34949. if (component != 0)
  34950. stack.add (new ModalItem (component, callback));
  34951. }
  34952. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34953. {
  34954. if (callback != 0)
  34955. {
  34956. ScopedPointer<Callback> callbackDeleter (callback);
  34957. for (int i = stack.size(); --i >= 0;)
  34958. {
  34959. ModalItem* const item = stack.getUnchecked(i);
  34960. if (item->component == component)
  34961. {
  34962. item->callbacks.add (callback);
  34963. callbackDeleter.release();
  34964. break;
  34965. }
  34966. }
  34967. }
  34968. }
  34969. void ModalComponentManager::endModal (Component* component)
  34970. {
  34971. for (int i = stack.size(); --i >= 0;)
  34972. {
  34973. ModalItem* const item = stack.getUnchecked(i);
  34974. if (item->component == component)
  34975. item->cancel();
  34976. }
  34977. }
  34978. void ModalComponentManager::endModal (Component* component, int returnValue)
  34979. {
  34980. for (int i = stack.size(); --i >= 0;)
  34981. {
  34982. ModalItem* const item = stack.getUnchecked(i);
  34983. if (item->component == component)
  34984. {
  34985. item->returnValue = returnValue;
  34986. item->cancel();
  34987. }
  34988. }
  34989. }
  34990. int ModalComponentManager::getNumModalComponents() const
  34991. {
  34992. int n = 0;
  34993. for (int i = 0; i < stack.size(); ++i)
  34994. if (stack.getUnchecked(i)->isActive)
  34995. ++n;
  34996. return n;
  34997. }
  34998. Component* ModalComponentManager::getModalComponent (const int index) const
  34999. {
  35000. int n = 0;
  35001. for (int i = stack.size(); --i >= 0;)
  35002. {
  35003. const ModalItem* const item = stack.getUnchecked(i);
  35004. if (item->isActive)
  35005. if (n++ == index)
  35006. return item->component;
  35007. }
  35008. return 0;
  35009. }
  35010. bool ModalComponentManager::isModal (Component* const comp) const
  35011. {
  35012. for (int i = stack.size(); --i >= 0;)
  35013. {
  35014. const ModalItem* const item = stack.getUnchecked(i);
  35015. if (item->isActive && item->component == comp)
  35016. return true;
  35017. }
  35018. return false;
  35019. }
  35020. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  35021. {
  35022. return comp == getModalComponent (0);
  35023. }
  35024. void ModalComponentManager::handleAsyncUpdate()
  35025. {
  35026. for (int i = stack.size(); --i >= 0;)
  35027. {
  35028. const ModalItem* const item = stack.getUnchecked(i);
  35029. if (! item->isActive)
  35030. {
  35031. for (int j = item->callbacks.size(); --j >= 0;)
  35032. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  35033. stack.remove (i);
  35034. }
  35035. }
  35036. }
  35037. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  35038. {
  35039. public:
  35040. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  35041. ~ReturnValueRetriever() {}
  35042. void modalStateFinished (int returnValue)
  35043. {
  35044. finished = true;
  35045. value = returnValue;
  35046. }
  35047. private:
  35048. int& value;
  35049. bool& finished;
  35050. ReturnValueRetriever (const ReturnValueRetriever&);
  35051. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  35052. };
  35053. int ModalComponentManager::runEventLoopForCurrentComponent()
  35054. {
  35055. // This can only be run from the message thread!
  35056. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  35057. Component* currentlyModal = getModalComponent (0);
  35058. if (currentlyModal == 0)
  35059. return 0;
  35060. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  35061. int returnValue = 0;
  35062. bool finished = false;
  35063. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  35064. JUCE_TRY
  35065. {
  35066. while (! finished)
  35067. {
  35068. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  35069. break;
  35070. }
  35071. }
  35072. JUCE_CATCH_EXCEPTION
  35073. if (prevFocused != 0)
  35074. prevFocused->grabKeyboardFocus();
  35075. return returnValue;
  35076. }
  35077. END_JUCE_NAMESPACE
  35078. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  35079. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  35080. BEGIN_JUCE_NAMESPACE
  35081. ArrowButton::ArrowButton (const String& name,
  35082. float arrowDirectionInRadians,
  35083. const Colour& arrowColour)
  35084. : Button (name),
  35085. colour (arrowColour)
  35086. {
  35087. path.lineTo (0.0f, 1.0f);
  35088. path.lineTo (1.0f, 0.5f);
  35089. path.closeSubPath();
  35090. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  35091. 0.5f, 0.5f));
  35092. setComponentEffect (&shadow);
  35093. buttonStateChanged();
  35094. }
  35095. ArrowButton::~ArrowButton()
  35096. {
  35097. }
  35098. void ArrowButton::paintButton (Graphics& g,
  35099. bool /*isMouseOverButton*/,
  35100. bool /*isButtonDown*/)
  35101. {
  35102. g.setColour (colour);
  35103. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  35104. (float) offset,
  35105. (float) (getWidth() - 3),
  35106. (float) (getHeight() - 3),
  35107. false));
  35108. }
  35109. void ArrowButton::buttonStateChanged()
  35110. {
  35111. offset = (isDown()) ? 1 : 0;
  35112. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  35113. 0.3f, -1, 0);
  35114. }
  35115. END_JUCE_NAMESPACE
  35116. /*** End of inlined file: juce_ArrowButton.cpp ***/
  35117. /*** Start of inlined file: juce_Button.cpp ***/
  35118. BEGIN_JUCE_NAMESPACE
  35119. class Button::RepeatTimer : public Timer
  35120. {
  35121. public:
  35122. RepeatTimer (Button& owner_) : owner (owner_) {}
  35123. void timerCallback() { owner.repeatTimerCallback(); }
  35124. juce_UseDebuggingNewOperator
  35125. private:
  35126. Button& owner;
  35127. RepeatTimer (const RepeatTimer&);
  35128. RepeatTimer& operator= (const RepeatTimer&);
  35129. };
  35130. Button::Button (const String& name)
  35131. : Component (name),
  35132. text (name),
  35133. buttonPressTime (0),
  35134. lastTimeCallbackTime (0),
  35135. commandManagerToUse (0),
  35136. autoRepeatDelay (-1),
  35137. autoRepeatSpeed (0),
  35138. autoRepeatMinimumDelay (-1),
  35139. radioGroupId (0),
  35140. commandID (0),
  35141. connectedEdgeFlags (0),
  35142. buttonState (buttonNormal),
  35143. lastToggleState (false),
  35144. clickTogglesState (false),
  35145. needsToRelease (false),
  35146. needsRepainting (false),
  35147. isKeyDown (false),
  35148. triggerOnMouseDown (false),
  35149. generateTooltip (false)
  35150. {
  35151. setWantsKeyboardFocus (true);
  35152. isOn.addListener (this);
  35153. }
  35154. Button::~Button()
  35155. {
  35156. isOn.removeListener (this);
  35157. if (commandManagerToUse != 0)
  35158. commandManagerToUse->removeListener (this);
  35159. repeatTimer = 0;
  35160. clearShortcuts();
  35161. }
  35162. void Button::setButtonText (const String& newText)
  35163. {
  35164. if (text != newText)
  35165. {
  35166. text = newText;
  35167. repaint();
  35168. }
  35169. }
  35170. void Button::setTooltip (const String& newTooltip)
  35171. {
  35172. SettableTooltipClient::setTooltip (newTooltip);
  35173. generateTooltip = false;
  35174. }
  35175. const String Button::getTooltip()
  35176. {
  35177. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  35178. {
  35179. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  35180. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  35181. for (int i = 0; i < keyPresses.size(); ++i)
  35182. {
  35183. const String key (keyPresses.getReference(i).getTextDescription());
  35184. tt << " [";
  35185. if (key.length() == 1)
  35186. tt << TRANS("shortcut") << ": '" << key << "']";
  35187. else
  35188. tt << key << ']';
  35189. }
  35190. return tt;
  35191. }
  35192. return SettableTooltipClient::getTooltip();
  35193. }
  35194. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  35195. {
  35196. if (connectedEdgeFlags != connectedEdgeFlags_)
  35197. {
  35198. connectedEdgeFlags = connectedEdgeFlags_;
  35199. repaint();
  35200. }
  35201. }
  35202. void Button::setToggleState (const bool shouldBeOn,
  35203. const bool sendChangeNotification)
  35204. {
  35205. if (shouldBeOn != lastToggleState)
  35206. {
  35207. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  35208. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  35209. lastToggleState = shouldBeOn;
  35210. repaint();
  35211. if (sendChangeNotification)
  35212. {
  35213. Component::SafePointer<Component> deletionWatcher (this);
  35214. sendClickMessage (ModifierKeys());
  35215. if (deletionWatcher == 0)
  35216. return;
  35217. }
  35218. if (lastToggleState)
  35219. turnOffOtherButtonsInGroup (sendChangeNotification);
  35220. }
  35221. }
  35222. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  35223. {
  35224. clickTogglesState = shouldToggle;
  35225. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35226. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35227. // it is that this button represents, and the button will update its state to reflect this
  35228. // in the applicationCommandListChanged() method.
  35229. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35230. }
  35231. bool Button::getClickingTogglesState() const throw()
  35232. {
  35233. return clickTogglesState;
  35234. }
  35235. void Button::valueChanged (Value& value)
  35236. {
  35237. if (value.refersToSameSourceAs (isOn))
  35238. setToggleState (isOn.getValue(), true);
  35239. }
  35240. void Button::setRadioGroupId (const int newGroupId)
  35241. {
  35242. if (radioGroupId != newGroupId)
  35243. {
  35244. radioGroupId = newGroupId;
  35245. if (lastToggleState)
  35246. turnOffOtherButtonsInGroup (true);
  35247. }
  35248. }
  35249. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  35250. {
  35251. Component* const p = getParentComponent();
  35252. if (p != 0 && radioGroupId != 0)
  35253. {
  35254. Component::SafePointer<Component> deletionWatcher (this);
  35255. for (int i = p->getNumChildComponents(); --i >= 0;)
  35256. {
  35257. Component* const c = p->getChildComponent (i);
  35258. if (c != this)
  35259. {
  35260. Button* const b = dynamic_cast <Button*> (c);
  35261. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  35262. {
  35263. b->setToggleState (false, sendChangeNotification);
  35264. if (deletionWatcher == 0)
  35265. return;
  35266. }
  35267. }
  35268. }
  35269. }
  35270. }
  35271. void Button::enablementChanged()
  35272. {
  35273. updateState (0);
  35274. repaint();
  35275. }
  35276. Button::ButtonState Button::updateState (const MouseEvent* const e)
  35277. {
  35278. ButtonState state = buttonNormal;
  35279. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  35280. {
  35281. Point<int> mousePos;
  35282. if (e == 0)
  35283. mousePos = getMouseXYRelative();
  35284. else
  35285. mousePos = e->getEventRelativeTo (this).getPosition();
  35286. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  35287. const bool down = isMouseButtonDown();
  35288. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  35289. state = buttonDown;
  35290. else if (over)
  35291. state = buttonOver;
  35292. }
  35293. setState (state);
  35294. return state;
  35295. }
  35296. void Button::setState (const ButtonState newState)
  35297. {
  35298. if (buttonState != newState)
  35299. {
  35300. buttonState = newState;
  35301. repaint();
  35302. if (buttonState == buttonDown)
  35303. {
  35304. buttonPressTime = Time::getApproximateMillisecondCounter();
  35305. lastTimeCallbackTime = buttonPressTime;
  35306. }
  35307. sendStateMessage();
  35308. }
  35309. }
  35310. bool Button::isDown() const throw()
  35311. {
  35312. return buttonState == buttonDown;
  35313. }
  35314. bool Button::isOver() const throw()
  35315. {
  35316. return buttonState != buttonNormal;
  35317. }
  35318. void Button::buttonStateChanged()
  35319. {
  35320. }
  35321. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35322. {
  35323. const uint32 now = Time::getApproximateMillisecondCounter();
  35324. return now > buttonPressTime ? now - buttonPressTime : 0;
  35325. }
  35326. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35327. {
  35328. triggerOnMouseDown = isTriggeredOnMouseDown;
  35329. }
  35330. void Button::clicked()
  35331. {
  35332. }
  35333. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35334. {
  35335. clicked();
  35336. }
  35337. static const int clickMessageId = 0x2f3f4f99;
  35338. void Button::triggerClick()
  35339. {
  35340. postCommandMessage (clickMessageId);
  35341. }
  35342. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35343. {
  35344. if (clickTogglesState)
  35345. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35346. sendClickMessage (modifiers);
  35347. }
  35348. void Button::flashButtonState()
  35349. {
  35350. if (isEnabled())
  35351. {
  35352. needsToRelease = true;
  35353. setState (buttonDown);
  35354. getRepeatTimer().startTimer (100);
  35355. }
  35356. }
  35357. void Button::handleCommandMessage (int commandId)
  35358. {
  35359. if (commandId == clickMessageId)
  35360. {
  35361. if (isEnabled())
  35362. {
  35363. flashButtonState();
  35364. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35365. }
  35366. }
  35367. else
  35368. {
  35369. Component::handleCommandMessage (commandId);
  35370. }
  35371. }
  35372. void Button::addButtonListener (Listener* const newListener)
  35373. {
  35374. buttonListeners.add (newListener);
  35375. }
  35376. void Button::removeButtonListener (Listener* const listener)
  35377. {
  35378. buttonListeners.remove (listener);
  35379. }
  35380. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35381. {
  35382. Component::BailOutChecker checker (this);
  35383. if (commandManagerToUse != 0 && commandID != 0)
  35384. {
  35385. ApplicationCommandTarget::InvocationInfo info (commandID);
  35386. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35387. info.originatingComponent = this;
  35388. commandManagerToUse->invoke (info, true);
  35389. }
  35390. clicked (modifiers);
  35391. if (! checker.shouldBailOut())
  35392. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35393. }
  35394. void Button::sendStateMessage()
  35395. {
  35396. Component::BailOutChecker checker (this);
  35397. buttonStateChanged();
  35398. if (! checker.shouldBailOut())
  35399. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35400. }
  35401. void Button::paint (Graphics& g)
  35402. {
  35403. if (needsToRelease && isEnabled())
  35404. {
  35405. needsToRelease = false;
  35406. needsRepainting = true;
  35407. }
  35408. paintButton (g, isOver(), isDown());
  35409. }
  35410. void Button::mouseEnter (const MouseEvent& e)
  35411. {
  35412. updateState (&e);
  35413. }
  35414. void Button::mouseExit (const MouseEvent& e)
  35415. {
  35416. updateState (&e);
  35417. }
  35418. void Button::mouseDown (const MouseEvent& e)
  35419. {
  35420. updateState (&e);
  35421. if (isDown())
  35422. {
  35423. if (autoRepeatDelay >= 0)
  35424. getRepeatTimer().startTimer (autoRepeatDelay);
  35425. if (triggerOnMouseDown)
  35426. internalClickCallback (e.mods);
  35427. }
  35428. }
  35429. void Button::mouseUp (const MouseEvent& e)
  35430. {
  35431. const bool wasDown = isDown();
  35432. updateState (&e);
  35433. if (wasDown && isOver() && ! triggerOnMouseDown)
  35434. internalClickCallback (e.mods);
  35435. }
  35436. void Button::mouseDrag (const MouseEvent& e)
  35437. {
  35438. const ButtonState oldState = buttonState;
  35439. updateState (&e);
  35440. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35441. getRepeatTimer().startTimer (autoRepeatSpeed);
  35442. }
  35443. void Button::focusGained (FocusChangeType)
  35444. {
  35445. updateState (0);
  35446. repaint();
  35447. }
  35448. void Button::focusLost (FocusChangeType)
  35449. {
  35450. updateState (0);
  35451. repaint();
  35452. }
  35453. void Button::setVisible (bool shouldBeVisible)
  35454. {
  35455. if (shouldBeVisible != isVisible())
  35456. {
  35457. Component::setVisible (shouldBeVisible);
  35458. if (! shouldBeVisible)
  35459. needsToRelease = false;
  35460. updateState (0);
  35461. }
  35462. else
  35463. {
  35464. Component::setVisible (shouldBeVisible);
  35465. }
  35466. }
  35467. void Button::parentHierarchyChanged()
  35468. {
  35469. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35470. if (newKeySource != keySource.getComponent())
  35471. {
  35472. if (keySource != 0)
  35473. keySource->removeKeyListener (this);
  35474. keySource = newKeySource;
  35475. if (keySource != 0)
  35476. keySource->addKeyListener (this);
  35477. }
  35478. }
  35479. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35480. const int commandID_,
  35481. const bool generateTooltip_)
  35482. {
  35483. commandID = commandID_;
  35484. generateTooltip = generateTooltip_;
  35485. if (commandManagerToUse != commandManagerToUse_)
  35486. {
  35487. if (commandManagerToUse != 0)
  35488. commandManagerToUse->removeListener (this);
  35489. commandManagerToUse = commandManagerToUse_;
  35490. if (commandManagerToUse != 0)
  35491. commandManagerToUse->addListener (this);
  35492. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35493. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35494. // it is that this button represents, and the button will update its state to reflect this
  35495. // in the applicationCommandListChanged() method.
  35496. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35497. }
  35498. if (commandManagerToUse != 0)
  35499. applicationCommandListChanged();
  35500. else
  35501. setEnabled (true);
  35502. }
  35503. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35504. {
  35505. if (info.commandID == commandID
  35506. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35507. {
  35508. flashButtonState();
  35509. }
  35510. }
  35511. void Button::applicationCommandListChanged()
  35512. {
  35513. if (commandManagerToUse != 0)
  35514. {
  35515. ApplicationCommandInfo info (0);
  35516. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35517. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35518. if (target != 0)
  35519. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35520. }
  35521. }
  35522. void Button::addShortcut (const KeyPress& key)
  35523. {
  35524. if (key.isValid())
  35525. {
  35526. jassert (! isRegisteredForShortcut (key)); // already registered!
  35527. shortcuts.add (key);
  35528. parentHierarchyChanged();
  35529. }
  35530. }
  35531. void Button::clearShortcuts()
  35532. {
  35533. shortcuts.clear();
  35534. parentHierarchyChanged();
  35535. }
  35536. bool Button::isShortcutPressed() const
  35537. {
  35538. if (! isCurrentlyBlockedByAnotherModalComponent())
  35539. {
  35540. for (int i = shortcuts.size(); --i >= 0;)
  35541. if (shortcuts.getReference(i).isCurrentlyDown())
  35542. return true;
  35543. }
  35544. return false;
  35545. }
  35546. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35547. {
  35548. for (int i = shortcuts.size(); --i >= 0;)
  35549. if (key == shortcuts.getReference(i))
  35550. return true;
  35551. return false;
  35552. }
  35553. bool Button::keyStateChanged (const bool, Component*)
  35554. {
  35555. if (! isEnabled())
  35556. return false;
  35557. const bool wasDown = isKeyDown;
  35558. isKeyDown = isShortcutPressed();
  35559. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35560. getRepeatTimer().startTimer (autoRepeatDelay);
  35561. updateState (0);
  35562. if (isEnabled() && wasDown && ! isKeyDown)
  35563. {
  35564. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35565. // (return immediately - this button may now have been deleted)
  35566. return true;
  35567. }
  35568. return wasDown || isKeyDown;
  35569. }
  35570. bool Button::keyPressed (const KeyPress&, Component*)
  35571. {
  35572. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35573. return isShortcutPressed();
  35574. }
  35575. bool Button::keyPressed (const KeyPress& key)
  35576. {
  35577. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35578. {
  35579. triggerClick();
  35580. return true;
  35581. }
  35582. return false;
  35583. }
  35584. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35585. const int repeatMillisecs,
  35586. const int minimumDelayInMillisecs) throw()
  35587. {
  35588. autoRepeatDelay = initialDelayMillisecs;
  35589. autoRepeatSpeed = repeatMillisecs;
  35590. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35591. }
  35592. void Button::repeatTimerCallback()
  35593. {
  35594. if (needsRepainting)
  35595. {
  35596. getRepeatTimer().stopTimer();
  35597. updateState (0);
  35598. needsRepainting = false;
  35599. }
  35600. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35601. {
  35602. int repeatSpeed = autoRepeatSpeed;
  35603. if (autoRepeatMinimumDelay >= 0)
  35604. {
  35605. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35606. timeHeldDown *= timeHeldDown;
  35607. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35608. }
  35609. repeatSpeed = jmax (1, repeatSpeed);
  35610. getRepeatTimer().startTimer (repeatSpeed);
  35611. const uint32 now = Time::getApproximateMillisecondCounter();
  35612. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35613. lastTimeCallbackTime = now;
  35614. Component::SafePointer<Component> deletionWatcher (this);
  35615. for (int i = numTimesToCallback; --i >= 0;)
  35616. {
  35617. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35618. if (deletionWatcher == 0 || ! isDown())
  35619. return;
  35620. }
  35621. }
  35622. else if (! needsToRelease)
  35623. {
  35624. getRepeatTimer().stopTimer();
  35625. }
  35626. }
  35627. Button::RepeatTimer& Button::getRepeatTimer()
  35628. {
  35629. if (repeatTimer == 0)
  35630. repeatTimer = new RepeatTimer (*this);
  35631. return *repeatTimer;
  35632. }
  35633. END_JUCE_NAMESPACE
  35634. /*** End of inlined file: juce_Button.cpp ***/
  35635. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35636. BEGIN_JUCE_NAMESPACE
  35637. DrawableButton::DrawableButton (const String& name,
  35638. const DrawableButton::ButtonStyle buttonStyle)
  35639. : Button (name),
  35640. style (buttonStyle),
  35641. edgeIndent (3)
  35642. {
  35643. if (buttonStyle == ImageOnButtonBackground)
  35644. {
  35645. backgroundOff = Colour (0xffbbbbff);
  35646. backgroundOn = Colour (0xff3333ff);
  35647. }
  35648. else
  35649. {
  35650. backgroundOff = Colours::transparentBlack;
  35651. backgroundOn = Colour (0xaabbbbff);
  35652. }
  35653. }
  35654. DrawableButton::~DrawableButton()
  35655. {
  35656. deleteImages();
  35657. }
  35658. void DrawableButton::deleteImages()
  35659. {
  35660. }
  35661. void DrawableButton::setImages (const Drawable* normal,
  35662. const Drawable* over,
  35663. const Drawable* down,
  35664. const Drawable* disabled,
  35665. const Drawable* normalOn,
  35666. const Drawable* overOn,
  35667. const Drawable* downOn,
  35668. const Drawable* disabledOn)
  35669. {
  35670. deleteImages();
  35671. jassert (normal != 0); // you really need to give it at least a normal image..
  35672. if (normal != 0)
  35673. normalImage = normal->createCopy();
  35674. if (over != 0)
  35675. overImage = over->createCopy();
  35676. if (down != 0)
  35677. downImage = down->createCopy();
  35678. if (disabled != 0)
  35679. disabledImage = disabled->createCopy();
  35680. if (normalOn != 0)
  35681. normalImageOn = normalOn->createCopy();
  35682. if (overOn != 0)
  35683. overImageOn = overOn->createCopy();
  35684. if (downOn != 0)
  35685. downImageOn = downOn->createCopy();
  35686. if (disabledOn != 0)
  35687. disabledImageOn = disabledOn->createCopy();
  35688. repaint();
  35689. }
  35690. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35691. {
  35692. if (style != newStyle)
  35693. {
  35694. style = newStyle;
  35695. repaint();
  35696. }
  35697. }
  35698. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35699. const Colour& toggledOnColour)
  35700. {
  35701. if (backgroundOff != toggledOffColour
  35702. || backgroundOn != toggledOnColour)
  35703. {
  35704. backgroundOff = toggledOffColour;
  35705. backgroundOn = toggledOnColour;
  35706. repaint();
  35707. }
  35708. }
  35709. const Colour& DrawableButton::getBackgroundColour() const throw()
  35710. {
  35711. return getToggleState() ? backgroundOn
  35712. : backgroundOff;
  35713. }
  35714. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35715. {
  35716. edgeIndent = numPixelsIndent;
  35717. repaint();
  35718. }
  35719. void DrawableButton::paintButton (Graphics& g,
  35720. bool isMouseOverButton,
  35721. bool isButtonDown)
  35722. {
  35723. Rectangle<int> imageSpace;
  35724. if (style == ImageOnButtonBackground)
  35725. {
  35726. const int insetX = getWidth() / 4;
  35727. const int insetY = getHeight() / 4;
  35728. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35729. getLookAndFeel().drawButtonBackground (g, *this,
  35730. getBackgroundColour(),
  35731. isMouseOverButton,
  35732. isButtonDown);
  35733. }
  35734. else
  35735. {
  35736. g.fillAll (getBackgroundColour());
  35737. const int textH = (style == ImageAboveTextLabel)
  35738. ? jmin (16, proportionOfHeight (0.25f))
  35739. : 0;
  35740. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35741. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35742. imageSpace.setBounds (indentX, indentY,
  35743. getWidth() - indentX * 2,
  35744. getHeight() - indentY * 2 - textH);
  35745. if (textH > 0)
  35746. {
  35747. g.setFont ((float) textH);
  35748. g.setColour (findColour (DrawableButton::textColourId)
  35749. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35750. g.drawFittedText (getButtonText(),
  35751. 2, getHeight() - textH - 1,
  35752. getWidth() - 4, textH,
  35753. Justification::centred, 1);
  35754. }
  35755. }
  35756. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35757. g.setOpacity (1.0f);
  35758. const Drawable* imageToDraw = 0;
  35759. if (isEnabled())
  35760. {
  35761. imageToDraw = getCurrentImage();
  35762. }
  35763. else
  35764. {
  35765. imageToDraw = getToggleState() ? disabledImageOn
  35766. : disabledImage;
  35767. if (imageToDraw == 0)
  35768. {
  35769. g.setOpacity (0.4f);
  35770. imageToDraw = getNormalImage();
  35771. }
  35772. }
  35773. if (imageToDraw != 0)
  35774. {
  35775. if (style == ImageRaw)
  35776. {
  35777. imageToDraw->draw (g, 1.0f);
  35778. }
  35779. else
  35780. {
  35781. imageToDraw->drawWithin (g,
  35782. imageSpace.getX(),
  35783. imageSpace.getY(),
  35784. imageSpace.getWidth(),
  35785. imageSpace.getHeight(),
  35786. RectanglePlacement::centred,
  35787. 1.0f);
  35788. }
  35789. }
  35790. }
  35791. const Drawable* DrawableButton::getCurrentImage() const throw()
  35792. {
  35793. if (isDown())
  35794. return getDownImage();
  35795. if (isOver())
  35796. return getOverImage();
  35797. return getNormalImage();
  35798. }
  35799. const Drawable* DrawableButton::getNormalImage() const throw()
  35800. {
  35801. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35802. : normalImage;
  35803. }
  35804. const Drawable* DrawableButton::getOverImage() const throw()
  35805. {
  35806. const Drawable* d = normalImage;
  35807. if (getToggleState())
  35808. {
  35809. if (overImageOn != 0)
  35810. d = overImageOn;
  35811. else if (normalImageOn != 0)
  35812. d = normalImageOn;
  35813. else if (overImage != 0)
  35814. d = overImage;
  35815. }
  35816. else
  35817. {
  35818. if (overImage != 0)
  35819. d = overImage;
  35820. }
  35821. return d;
  35822. }
  35823. const Drawable* DrawableButton::getDownImage() const throw()
  35824. {
  35825. const Drawable* d = normalImage;
  35826. if (getToggleState())
  35827. {
  35828. if (downImageOn != 0)
  35829. d = downImageOn;
  35830. else if (overImageOn != 0)
  35831. d = overImageOn;
  35832. else if (normalImageOn != 0)
  35833. d = normalImageOn;
  35834. else if (downImage != 0)
  35835. d = downImage;
  35836. else
  35837. d = getOverImage();
  35838. }
  35839. else
  35840. {
  35841. if (downImage != 0)
  35842. d = downImage;
  35843. else
  35844. d = getOverImage();
  35845. }
  35846. return d;
  35847. }
  35848. END_JUCE_NAMESPACE
  35849. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35850. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35851. BEGIN_JUCE_NAMESPACE
  35852. HyperlinkButton::HyperlinkButton (const String& linkText,
  35853. const URL& linkURL)
  35854. : Button (linkText),
  35855. url (linkURL),
  35856. font (14.0f, Font::underlined),
  35857. resizeFont (true),
  35858. justification (Justification::centred)
  35859. {
  35860. setMouseCursor (MouseCursor::PointingHandCursor);
  35861. setTooltip (linkURL.toString (false));
  35862. }
  35863. HyperlinkButton::~HyperlinkButton()
  35864. {
  35865. }
  35866. void HyperlinkButton::setFont (const Font& newFont,
  35867. const bool resizeToMatchComponentHeight,
  35868. const Justification& justificationType)
  35869. {
  35870. font = newFont;
  35871. resizeFont = resizeToMatchComponentHeight;
  35872. justification = justificationType;
  35873. repaint();
  35874. }
  35875. void HyperlinkButton::setURL (const URL& newURL) throw()
  35876. {
  35877. url = newURL;
  35878. setTooltip (newURL.toString (false));
  35879. }
  35880. const Font HyperlinkButton::getFontToUse() const
  35881. {
  35882. Font f (font);
  35883. if (resizeFont)
  35884. f.setHeight (getHeight() * 0.7f);
  35885. return f;
  35886. }
  35887. void HyperlinkButton::changeWidthToFitText()
  35888. {
  35889. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35890. }
  35891. void HyperlinkButton::colourChanged()
  35892. {
  35893. repaint();
  35894. }
  35895. void HyperlinkButton::clicked()
  35896. {
  35897. if (url.isWellFormed())
  35898. url.launchInDefaultBrowser();
  35899. }
  35900. void HyperlinkButton::paintButton (Graphics& g,
  35901. bool isMouseOverButton,
  35902. bool isButtonDown)
  35903. {
  35904. const Colour textColour (findColour (textColourId));
  35905. if (isEnabled())
  35906. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35907. : textColour);
  35908. else
  35909. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35910. g.setFont (getFontToUse());
  35911. g.drawText (getButtonText(),
  35912. 2, 0, getWidth() - 2, getHeight(),
  35913. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35914. true);
  35915. }
  35916. END_JUCE_NAMESPACE
  35917. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35918. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35919. BEGIN_JUCE_NAMESPACE
  35920. ImageButton::ImageButton (const String& text_)
  35921. : Button (text_),
  35922. scaleImageToFit (true),
  35923. preserveProportions (true),
  35924. alphaThreshold (0),
  35925. imageX (0),
  35926. imageY (0),
  35927. imageW (0),
  35928. imageH (0),
  35929. normalImage (0),
  35930. overImage (0),
  35931. downImage (0)
  35932. {
  35933. }
  35934. ImageButton::~ImageButton()
  35935. {
  35936. }
  35937. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35938. const bool rescaleImagesWhenButtonSizeChanges,
  35939. const bool preserveImageProportions,
  35940. const Image& normalImage_,
  35941. const float imageOpacityWhenNormal,
  35942. const Colour& overlayColourWhenNormal,
  35943. const Image& overImage_,
  35944. const float imageOpacityWhenOver,
  35945. const Colour& overlayColourWhenOver,
  35946. const Image& downImage_,
  35947. const float imageOpacityWhenDown,
  35948. const Colour& overlayColourWhenDown,
  35949. const float hitTestAlphaThreshold)
  35950. {
  35951. normalImage = normalImage_;
  35952. overImage = overImage_;
  35953. downImage = downImage_;
  35954. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35955. {
  35956. imageW = normalImage.getWidth();
  35957. imageH = normalImage.getHeight();
  35958. setSize (imageW, imageH);
  35959. }
  35960. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35961. preserveProportions = preserveImageProportions;
  35962. normalOpacity = imageOpacityWhenNormal;
  35963. normalOverlay = overlayColourWhenNormal;
  35964. overOpacity = imageOpacityWhenOver;
  35965. overOverlay = overlayColourWhenOver;
  35966. downOpacity = imageOpacityWhenDown;
  35967. downOverlay = overlayColourWhenDown;
  35968. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35969. repaint();
  35970. }
  35971. const Image ImageButton::getCurrentImage() const
  35972. {
  35973. if (isDown() || getToggleState())
  35974. return getDownImage();
  35975. if (isOver())
  35976. return getOverImage();
  35977. return getNormalImage();
  35978. }
  35979. const Image ImageButton::getNormalImage() const
  35980. {
  35981. return normalImage;
  35982. }
  35983. const Image ImageButton::getOverImage() const
  35984. {
  35985. return overImage.isValid() ? overImage
  35986. : normalImage;
  35987. }
  35988. const Image ImageButton::getDownImage() const
  35989. {
  35990. return downImage.isValid() ? downImage
  35991. : getOverImage();
  35992. }
  35993. void ImageButton::paintButton (Graphics& g,
  35994. bool isMouseOverButton,
  35995. bool isButtonDown)
  35996. {
  35997. if (! isEnabled())
  35998. {
  35999. isMouseOverButton = false;
  36000. isButtonDown = false;
  36001. }
  36002. Image im (getCurrentImage());
  36003. if (im.isValid())
  36004. {
  36005. const int iw = im.getWidth();
  36006. const int ih = im.getHeight();
  36007. imageW = getWidth();
  36008. imageH = getHeight();
  36009. imageX = (imageW - iw) >> 1;
  36010. imageY = (imageH - ih) >> 1;
  36011. if (scaleImageToFit)
  36012. {
  36013. if (preserveProportions)
  36014. {
  36015. int newW, newH;
  36016. const float imRatio = ih / (float)iw;
  36017. const float destRatio = imageH / (float)imageW;
  36018. if (imRatio > destRatio)
  36019. {
  36020. newW = roundToInt (imageH / imRatio);
  36021. newH = imageH;
  36022. }
  36023. else
  36024. {
  36025. newW = imageW;
  36026. newH = roundToInt (imageW * imRatio);
  36027. }
  36028. imageX = (imageW - newW) / 2;
  36029. imageY = (imageH - newH) / 2;
  36030. imageW = newW;
  36031. imageH = newH;
  36032. }
  36033. else
  36034. {
  36035. imageX = 0;
  36036. imageY = 0;
  36037. }
  36038. }
  36039. if (! scaleImageToFit)
  36040. {
  36041. imageW = iw;
  36042. imageH = ih;
  36043. }
  36044. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  36045. isButtonDown ? downOverlay
  36046. : (isMouseOverButton ? overOverlay
  36047. : normalOverlay),
  36048. isButtonDown ? downOpacity
  36049. : (isMouseOverButton ? overOpacity
  36050. : normalOpacity),
  36051. *this);
  36052. }
  36053. }
  36054. bool ImageButton::hitTest (int x, int y)
  36055. {
  36056. if (alphaThreshold == 0)
  36057. return true;
  36058. Image im (getCurrentImage());
  36059. return im.isNull() || (imageW > 0 && imageH > 0
  36060. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  36061. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  36062. }
  36063. END_JUCE_NAMESPACE
  36064. /*** End of inlined file: juce_ImageButton.cpp ***/
  36065. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  36066. BEGIN_JUCE_NAMESPACE
  36067. ShapeButton::ShapeButton (const String& text_,
  36068. const Colour& normalColour_,
  36069. const Colour& overColour_,
  36070. const Colour& downColour_)
  36071. : Button (text_),
  36072. normalColour (normalColour_),
  36073. overColour (overColour_),
  36074. downColour (downColour_),
  36075. maintainShapeProportions (false),
  36076. outlineWidth (0.0f)
  36077. {
  36078. }
  36079. ShapeButton::~ShapeButton()
  36080. {
  36081. }
  36082. void ShapeButton::setColours (const Colour& newNormalColour,
  36083. const Colour& newOverColour,
  36084. const Colour& newDownColour)
  36085. {
  36086. normalColour = newNormalColour;
  36087. overColour = newOverColour;
  36088. downColour = newDownColour;
  36089. }
  36090. void ShapeButton::setOutline (const Colour& newOutlineColour,
  36091. const float newOutlineWidth)
  36092. {
  36093. outlineColour = newOutlineColour;
  36094. outlineWidth = newOutlineWidth;
  36095. }
  36096. void ShapeButton::setShape (const Path& newShape,
  36097. const bool resizeNowToFitThisShape,
  36098. const bool maintainShapeProportions_,
  36099. const bool hasShadow)
  36100. {
  36101. shape = newShape;
  36102. maintainShapeProportions = maintainShapeProportions_;
  36103. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  36104. setComponentEffect ((hasShadow) ? &shadow : 0);
  36105. if (resizeNowToFitThisShape)
  36106. {
  36107. Rectangle<float> bounds (shape.getBounds());
  36108. if (hasShadow)
  36109. bounds.expand (4.0f, 4.0f);
  36110. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  36111. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  36112. 1 + (int) (bounds.getHeight() + outlineWidth));
  36113. }
  36114. }
  36115. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  36116. {
  36117. if (! isEnabled())
  36118. {
  36119. isMouseOverButton = false;
  36120. isButtonDown = false;
  36121. }
  36122. g.setColour ((isButtonDown) ? downColour
  36123. : (isMouseOverButton) ? overColour
  36124. : normalColour);
  36125. int w = getWidth();
  36126. int h = getHeight();
  36127. if (getComponentEffect() != 0)
  36128. {
  36129. w -= 4;
  36130. h -= 4;
  36131. }
  36132. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  36133. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  36134. w - offset - outlineWidth,
  36135. h - offset - outlineWidth,
  36136. maintainShapeProportions));
  36137. g.fillPath (shape, trans);
  36138. if (outlineWidth > 0.0f)
  36139. {
  36140. g.setColour (outlineColour);
  36141. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  36142. }
  36143. }
  36144. END_JUCE_NAMESPACE
  36145. /*** End of inlined file: juce_ShapeButton.cpp ***/
  36146. /*** Start of inlined file: juce_TextButton.cpp ***/
  36147. BEGIN_JUCE_NAMESPACE
  36148. TextButton::TextButton (const String& name,
  36149. const String& toolTip)
  36150. : Button (name)
  36151. {
  36152. setTooltip (toolTip);
  36153. }
  36154. TextButton::~TextButton()
  36155. {
  36156. }
  36157. void TextButton::paintButton (Graphics& g,
  36158. bool isMouseOverButton,
  36159. bool isButtonDown)
  36160. {
  36161. getLookAndFeel().drawButtonBackground (g, *this,
  36162. findColour (getToggleState() ? buttonOnColourId
  36163. : buttonColourId),
  36164. isMouseOverButton,
  36165. isButtonDown);
  36166. getLookAndFeel().drawButtonText (g, *this,
  36167. isMouseOverButton,
  36168. isButtonDown);
  36169. }
  36170. void TextButton::colourChanged()
  36171. {
  36172. repaint();
  36173. }
  36174. const Font TextButton::getFont()
  36175. {
  36176. return Font (jmin (15.0f, getHeight() * 0.6f));
  36177. }
  36178. void TextButton::changeWidthToFitText (const int newHeight)
  36179. {
  36180. if (newHeight >= 0)
  36181. setSize (jmax (1, getWidth()), newHeight);
  36182. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  36183. getHeight());
  36184. }
  36185. END_JUCE_NAMESPACE
  36186. /*** End of inlined file: juce_TextButton.cpp ***/
  36187. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  36188. BEGIN_JUCE_NAMESPACE
  36189. ToggleButton::ToggleButton (const String& buttonText)
  36190. : Button (buttonText)
  36191. {
  36192. setClickingTogglesState (true);
  36193. }
  36194. ToggleButton::~ToggleButton()
  36195. {
  36196. }
  36197. void ToggleButton::paintButton (Graphics& g,
  36198. bool isMouseOverButton,
  36199. bool isButtonDown)
  36200. {
  36201. getLookAndFeel().drawToggleButton (g, *this,
  36202. isMouseOverButton,
  36203. isButtonDown);
  36204. }
  36205. void ToggleButton::changeWidthToFitText()
  36206. {
  36207. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  36208. }
  36209. void ToggleButton::colourChanged()
  36210. {
  36211. repaint();
  36212. }
  36213. END_JUCE_NAMESPACE
  36214. /*** End of inlined file: juce_ToggleButton.cpp ***/
  36215. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  36216. BEGIN_JUCE_NAMESPACE
  36217. ToolbarButton::ToolbarButton (const int itemId_,
  36218. const String& buttonText,
  36219. Drawable* const normalImage_,
  36220. Drawable* const toggledOnImage_)
  36221. : ToolbarItemComponent (itemId_, buttonText, true),
  36222. normalImage (normalImage_),
  36223. toggledOnImage (toggledOnImage_)
  36224. {
  36225. jassert (normalImage_ != 0);
  36226. }
  36227. ToolbarButton::~ToolbarButton()
  36228. {
  36229. }
  36230. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  36231. bool /*isToolbarVertical*/,
  36232. int& preferredSize,
  36233. int& minSize, int& maxSize)
  36234. {
  36235. preferredSize = minSize = maxSize = toolbarDepth;
  36236. return true;
  36237. }
  36238. void ToolbarButton::paintButtonArea (Graphics& g,
  36239. int width, int height,
  36240. bool /*isMouseOver*/,
  36241. bool /*isMouseDown*/)
  36242. {
  36243. Drawable* d = normalImage;
  36244. if (getToggleState() && toggledOnImage != 0)
  36245. d = toggledOnImage;
  36246. if (! isEnabled())
  36247. {
  36248. Image im (Image::ARGB, width, height, true);
  36249. {
  36250. Graphics g2 (im);
  36251. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  36252. }
  36253. im.desaturate();
  36254. g.drawImageAt (im, 0, 0);
  36255. }
  36256. else
  36257. {
  36258. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  36259. }
  36260. }
  36261. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  36262. {
  36263. }
  36264. END_JUCE_NAMESPACE
  36265. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  36266. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  36267. BEGIN_JUCE_NAMESPACE
  36268. class CodeDocumentLine
  36269. {
  36270. public:
  36271. CodeDocumentLine (const juce_wchar* const line_,
  36272. const int lineLength_,
  36273. const int numNewLineChars,
  36274. const int lineStartInFile_)
  36275. : line (line_, lineLength_),
  36276. lineStartInFile (lineStartInFile_),
  36277. lineLength (lineLength_),
  36278. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  36279. {
  36280. }
  36281. ~CodeDocumentLine()
  36282. {
  36283. }
  36284. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  36285. {
  36286. const juce_wchar* const t = text;
  36287. int pos = 0;
  36288. while (t [pos] != 0)
  36289. {
  36290. const int startOfLine = pos;
  36291. int numNewLineChars = 0;
  36292. while (t[pos] != 0)
  36293. {
  36294. if (t[pos] == '\r')
  36295. {
  36296. ++numNewLineChars;
  36297. ++pos;
  36298. if (t[pos] == '\n')
  36299. {
  36300. ++numNewLineChars;
  36301. ++pos;
  36302. }
  36303. break;
  36304. }
  36305. if (t[pos] == '\n')
  36306. {
  36307. ++numNewLineChars;
  36308. ++pos;
  36309. break;
  36310. }
  36311. ++pos;
  36312. }
  36313. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36314. numNewLineChars, startOfLine));
  36315. }
  36316. jassert (pos == text.length());
  36317. }
  36318. bool endsWithLineBreak() const throw()
  36319. {
  36320. return lineLengthWithoutNewLines != lineLength;
  36321. }
  36322. void updateLength() throw()
  36323. {
  36324. lineLengthWithoutNewLines = lineLength = line.length();
  36325. while (lineLengthWithoutNewLines > 0
  36326. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36327. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36328. {
  36329. --lineLengthWithoutNewLines;
  36330. }
  36331. }
  36332. String line;
  36333. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36334. };
  36335. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36336. : document (document_),
  36337. currentLine (document_->lines[0]),
  36338. line (0),
  36339. position (0)
  36340. {
  36341. }
  36342. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36343. : document (other.document),
  36344. currentLine (other.currentLine),
  36345. line (other.line),
  36346. position (other.position)
  36347. {
  36348. }
  36349. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36350. {
  36351. document = other.document;
  36352. currentLine = other.currentLine;
  36353. line = other.line;
  36354. position = other.position;
  36355. return *this;
  36356. }
  36357. CodeDocument::Iterator::~Iterator() throw()
  36358. {
  36359. }
  36360. juce_wchar CodeDocument::Iterator::nextChar()
  36361. {
  36362. if (currentLine == 0)
  36363. return 0;
  36364. jassert (currentLine == document->lines.getUnchecked (line));
  36365. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36366. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36367. {
  36368. ++line;
  36369. currentLine = document->lines [line];
  36370. }
  36371. return result;
  36372. }
  36373. void CodeDocument::Iterator::skip()
  36374. {
  36375. if (currentLine != 0)
  36376. {
  36377. jassert (currentLine == document->lines.getUnchecked (line));
  36378. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36379. {
  36380. ++line;
  36381. currentLine = document->lines [line];
  36382. }
  36383. }
  36384. }
  36385. void CodeDocument::Iterator::skipToEndOfLine()
  36386. {
  36387. if (currentLine != 0)
  36388. {
  36389. jassert (currentLine == document->lines.getUnchecked (line));
  36390. ++line;
  36391. currentLine = document->lines [line];
  36392. if (currentLine != 0)
  36393. position = currentLine->lineStartInFile;
  36394. else
  36395. position = document->getNumCharacters();
  36396. }
  36397. }
  36398. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36399. {
  36400. if (currentLine == 0)
  36401. return 0;
  36402. jassert (currentLine == document->lines.getUnchecked (line));
  36403. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36404. }
  36405. void CodeDocument::Iterator::skipWhitespace()
  36406. {
  36407. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36408. skip();
  36409. }
  36410. bool CodeDocument::Iterator::isEOF() const throw()
  36411. {
  36412. return currentLine == 0;
  36413. }
  36414. CodeDocument::Position::Position() throw()
  36415. : owner (0), characterPos (0), line (0),
  36416. indexInLine (0), positionMaintained (false)
  36417. {
  36418. }
  36419. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36420. const int line_, const int indexInLine_) throw()
  36421. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36422. characterPos (0), line (line_),
  36423. indexInLine (indexInLine_), positionMaintained (false)
  36424. {
  36425. setLineAndIndex (line_, indexInLine_);
  36426. }
  36427. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36428. const int characterPos_) throw()
  36429. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36430. positionMaintained (false)
  36431. {
  36432. setPosition (characterPos_);
  36433. }
  36434. CodeDocument::Position::Position (const Position& other) throw()
  36435. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36436. indexInLine (other.indexInLine), positionMaintained (false)
  36437. {
  36438. jassert (*this == other);
  36439. }
  36440. CodeDocument::Position::~Position()
  36441. {
  36442. setPositionMaintained (false);
  36443. }
  36444. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36445. {
  36446. if (this != &other)
  36447. {
  36448. const bool wasPositionMaintained = positionMaintained;
  36449. if (owner != other.owner)
  36450. setPositionMaintained (false);
  36451. owner = other.owner;
  36452. line = other.line;
  36453. indexInLine = other.indexInLine;
  36454. characterPos = other.characterPos;
  36455. setPositionMaintained (wasPositionMaintained);
  36456. jassert (*this == other);
  36457. }
  36458. return *this;
  36459. }
  36460. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36461. {
  36462. jassert ((characterPos == other.characterPos)
  36463. == (line == other.line && indexInLine == other.indexInLine));
  36464. return characterPos == other.characterPos
  36465. && line == other.line
  36466. && indexInLine == other.indexInLine
  36467. && owner == other.owner;
  36468. }
  36469. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36470. {
  36471. return ! operator== (other);
  36472. }
  36473. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36474. {
  36475. jassert (owner != 0);
  36476. if (owner->lines.size() == 0)
  36477. {
  36478. line = 0;
  36479. indexInLine = 0;
  36480. characterPos = 0;
  36481. }
  36482. else
  36483. {
  36484. if (newLine >= owner->lines.size())
  36485. {
  36486. line = owner->lines.size() - 1;
  36487. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36488. jassert (l != 0);
  36489. indexInLine = l->lineLengthWithoutNewLines;
  36490. characterPos = l->lineStartInFile + indexInLine;
  36491. }
  36492. else
  36493. {
  36494. line = jmax (0, newLine);
  36495. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36496. jassert (l != 0);
  36497. if (l->lineLengthWithoutNewLines > 0)
  36498. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36499. else
  36500. indexInLine = 0;
  36501. characterPos = l->lineStartInFile + indexInLine;
  36502. }
  36503. }
  36504. }
  36505. void CodeDocument::Position::setPosition (const int newPosition)
  36506. {
  36507. jassert (owner != 0);
  36508. line = 0;
  36509. indexInLine = 0;
  36510. characterPos = 0;
  36511. if (newPosition > 0)
  36512. {
  36513. int lineStart = 0;
  36514. int lineEnd = owner->lines.size();
  36515. for (;;)
  36516. {
  36517. if (lineEnd - lineStart < 4)
  36518. {
  36519. for (int i = lineStart; i < lineEnd; ++i)
  36520. {
  36521. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36522. int index = newPosition - l->lineStartInFile;
  36523. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36524. {
  36525. line = i;
  36526. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36527. characterPos = l->lineStartInFile + indexInLine;
  36528. }
  36529. }
  36530. break;
  36531. }
  36532. else
  36533. {
  36534. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36535. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36536. if (newPosition >= mid->lineStartInFile)
  36537. lineStart = midIndex;
  36538. else
  36539. lineEnd = midIndex;
  36540. }
  36541. }
  36542. }
  36543. }
  36544. void CodeDocument::Position::moveBy (int characterDelta)
  36545. {
  36546. jassert (owner != 0);
  36547. if (characterDelta == 1)
  36548. {
  36549. setPosition (getPosition());
  36550. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36551. if (line < owner->lines.size())
  36552. {
  36553. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36554. if (indexInLine + characterDelta < l->lineLength
  36555. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36556. ++characterDelta;
  36557. }
  36558. }
  36559. setPosition (characterPos + characterDelta);
  36560. }
  36561. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36562. {
  36563. CodeDocument::Position p (*this);
  36564. p.moveBy (characterDelta);
  36565. return p;
  36566. }
  36567. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36568. {
  36569. CodeDocument::Position p (*this);
  36570. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36571. return p;
  36572. }
  36573. const juce_wchar CodeDocument::Position::getCharacter() const
  36574. {
  36575. const CodeDocumentLine* const l = owner->lines [line];
  36576. return l == 0 ? 0 : l->line [getIndexInLine()];
  36577. }
  36578. const String CodeDocument::Position::getLineText() const
  36579. {
  36580. const CodeDocumentLine* const l = owner->lines [line];
  36581. return l == 0 ? String::empty : l->line;
  36582. }
  36583. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36584. {
  36585. if (isMaintained != positionMaintained)
  36586. {
  36587. positionMaintained = isMaintained;
  36588. if (owner != 0)
  36589. {
  36590. if (isMaintained)
  36591. {
  36592. jassert (! owner->positionsToMaintain.contains (this));
  36593. owner->positionsToMaintain.add (this);
  36594. }
  36595. else
  36596. {
  36597. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36598. jassert (owner->positionsToMaintain.contains (this));
  36599. owner->positionsToMaintain.removeValue (this);
  36600. }
  36601. }
  36602. }
  36603. }
  36604. CodeDocument::CodeDocument()
  36605. : undoManager (std::numeric_limits<int>::max(), 10000),
  36606. currentActionIndex (0),
  36607. indexOfSavedState (-1),
  36608. maximumLineLength (-1),
  36609. newLineChars ("\r\n")
  36610. {
  36611. }
  36612. CodeDocument::~CodeDocument()
  36613. {
  36614. }
  36615. const String CodeDocument::getAllContent() const
  36616. {
  36617. return getTextBetween (Position (this, 0),
  36618. Position (this, lines.size(), 0));
  36619. }
  36620. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36621. {
  36622. if (end.getPosition() <= start.getPosition())
  36623. return String::empty;
  36624. const int startLine = start.getLineNumber();
  36625. const int endLine = end.getLineNumber();
  36626. if (startLine == endLine)
  36627. {
  36628. CodeDocumentLine* const line = lines [startLine];
  36629. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36630. }
  36631. String result;
  36632. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36633. String::Concatenator concatenator (result);
  36634. const int maxLine = jmin (lines.size() - 1, endLine);
  36635. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36636. {
  36637. const CodeDocumentLine* line = lines.getUnchecked(i);
  36638. int len = line->lineLength;
  36639. if (i == startLine)
  36640. {
  36641. const int index = start.getIndexInLine();
  36642. concatenator.append (line->line.substring (index, len));
  36643. }
  36644. else if (i == endLine)
  36645. {
  36646. len = end.getIndexInLine();
  36647. concatenator.append (line->line.substring (0, len));
  36648. }
  36649. else
  36650. {
  36651. concatenator.append (line->line);
  36652. }
  36653. }
  36654. return result;
  36655. }
  36656. int CodeDocument::getNumCharacters() const throw()
  36657. {
  36658. const CodeDocumentLine* const lastLine = lines.getLast();
  36659. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36660. }
  36661. const String CodeDocument::getLine (const int lineIndex) const throw()
  36662. {
  36663. const CodeDocumentLine* const line = lines [lineIndex];
  36664. return (line == 0) ? String::empty : line->line;
  36665. }
  36666. int CodeDocument::getMaximumLineLength() throw()
  36667. {
  36668. if (maximumLineLength < 0)
  36669. {
  36670. maximumLineLength = 0;
  36671. for (int i = lines.size(); --i >= 0;)
  36672. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36673. }
  36674. return maximumLineLength;
  36675. }
  36676. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36677. {
  36678. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36679. }
  36680. void CodeDocument::insertText (const Position& position, const String& text)
  36681. {
  36682. insert (text, position.getPosition(), true);
  36683. }
  36684. void CodeDocument::replaceAllContent (const String& newContent)
  36685. {
  36686. remove (0, getNumCharacters(), true);
  36687. insert (newContent, 0, true);
  36688. }
  36689. bool CodeDocument::loadFromStream (InputStream& stream)
  36690. {
  36691. replaceAllContent (stream.readEntireStreamAsString());
  36692. setSavePoint();
  36693. clearUndoHistory();
  36694. return true;
  36695. }
  36696. bool CodeDocument::writeToStream (OutputStream& stream)
  36697. {
  36698. for (int i = 0; i < lines.size(); ++i)
  36699. {
  36700. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36701. const char* utf8 = temp.toUTF8();
  36702. if (! stream.write (utf8, (int) strlen (utf8)))
  36703. return false;
  36704. }
  36705. return true;
  36706. }
  36707. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36708. {
  36709. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36710. newLineChars = newLine;
  36711. }
  36712. void CodeDocument::newTransaction()
  36713. {
  36714. undoManager.beginNewTransaction (String::empty);
  36715. }
  36716. void CodeDocument::undo()
  36717. {
  36718. newTransaction();
  36719. undoManager.undo();
  36720. }
  36721. void CodeDocument::redo()
  36722. {
  36723. undoManager.redo();
  36724. }
  36725. void CodeDocument::clearUndoHistory()
  36726. {
  36727. undoManager.clearUndoHistory();
  36728. }
  36729. void CodeDocument::setSavePoint() throw()
  36730. {
  36731. indexOfSavedState = currentActionIndex;
  36732. }
  36733. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36734. {
  36735. return currentActionIndex != indexOfSavedState;
  36736. }
  36737. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36738. {
  36739. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36740. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36741. }
  36742. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36743. {
  36744. Position p (position);
  36745. const int maxDistance = 256;
  36746. int i = 0;
  36747. while (i < maxDistance
  36748. && CharacterFunctions::isWhitespace (p.getCharacter())
  36749. && (i == 0 || (p.getCharacter() != '\n'
  36750. && p.getCharacter() != '\r')))
  36751. {
  36752. ++i;
  36753. p.moveBy (1);
  36754. }
  36755. if (i == 0)
  36756. {
  36757. const int type = getCodeCharacterCategory (p.getCharacter());
  36758. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36759. {
  36760. ++i;
  36761. p.moveBy (1);
  36762. }
  36763. while (i < maxDistance
  36764. && CharacterFunctions::isWhitespace (p.getCharacter())
  36765. && (i == 0 || (p.getCharacter() != '\n'
  36766. && p.getCharacter() != '\r')))
  36767. {
  36768. ++i;
  36769. p.moveBy (1);
  36770. }
  36771. }
  36772. return p;
  36773. }
  36774. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36775. {
  36776. Position p (position);
  36777. const int maxDistance = 256;
  36778. int i = 0;
  36779. bool stoppedAtLineStart = false;
  36780. while (i < maxDistance)
  36781. {
  36782. const juce_wchar c = p.movedBy (-1).getCharacter();
  36783. if (c == '\r' || c == '\n')
  36784. {
  36785. stoppedAtLineStart = true;
  36786. if (i > 0)
  36787. break;
  36788. }
  36789. if (! CharacterFunctions::isWhitespace (c))
  36790. break;
  36791. p.moveBy (-1);
  36792. ++i;
  36793. }
  36794. if (i < maxDistance && ! stoppedAtLineStart)
  36795. {
  36796. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36797. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36798. {
  36799. p.moveBy (-1);
  36800. ++i;
  36801. }
  36802. }
  36803. return p;
  36804. }
  36805. void CodeDocument::checkLastLineStatus()
  36806. {
  36807. while (lines.size() > 0
  36808. && lines.getLast()->lineLength == 0
  36809. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36810. {
  36811. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36812. lines.removeLast();
  36813. }
  36814. const CodeDocumentLine* const lastLine = lines.getLast();
  36815. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36816. {
  36817. // check that there's an empty line at the end if the preceding one ends in a newline..
  36818. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36819. }
  36820. }
  36821. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36822. {
  36823. listeners.add (listener);
  36824. }
  36825. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36826. {
  36827. listeners.remove (listener);
  36828. }
  36829. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36830. {
  36831. Position startPos (this, startLine, 0);
  36832. Position endPos (this, endLine, 0);
  36833. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36834. }
  36835. class CodeDocumentInsertAction : public UndoableAction
  36836. {
  36837. CodeDocument& owner;
  36838. const String text;
  36839. int insertPos;
  36840. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36841. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36842. public:
  36843. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36844. : owner (owner_),
  36845. text (text_),
  36846. insertPos (insertPos_)
  36847. {
  36848. }
  36849. ~CodeDocumentInsertAction() {}
  36850. bool perform()
  36851. {
  36852. owner.currentActionIndex++;
  36853. owner.insert (text, insertPos, false);
  36854. return true;
  36855. }
  36856. bool undo()
  36857. {
  36858. owner.currentActionIndex--;
  36859. owner.remove (insertPos, insertPos + text.length(), false);
  36860. return true;
  36861. }
  36862. int getSizeInUnits() { return text.length() + 32; }
  36863. };
  36864. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36865. {
  36866. if (text.isEmpty())
  36867. return;
  36868. if (undoable)
  36869. {
  36870. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36871. }
  36872. else
  36873. {
  36874. Position pos (this, insertPos);
  36875. const int firstAffectedLine = pos.getLineNumber();
  36876. int lastAffectedLine = firstAffectedLine + 1;
  36877. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36878. String textInsideOriginalLine (text);
  36879. if (firstLine != 0)
  36880. {
  36881. const int index = pos.getIndexInLine();
  36882. textInsideOriginalLine = firstLine->line.substring (0, index)
  36883. + textInsideOriginalLine
  36884. + firstLine->line.substring (index);
  36885. }
  36886. maximumLineLength = -1;
  36887. Array <CodeDocumentLine*> newLines;
  36888. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36889. jassert (newLines.size() > 0);
  36890. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36891. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36892. lines.set (firstAffectedLine, newFirstLine);
  36893. if (newLines.size() > 1)
  36894. {
  36895. for (int i = 1; i < newLines.size(); ++i)
  36896. {
  36897. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36898. lines.insert (firstAffectedLine + i, l);
  36899. }
  36900. lastAffectedLine = lines.size();
  36901. }
  36902. int i, lineStart = newFirstLine->lineStartInFile;
  36903. for (i = firstAffectedLine; i < lines.size(); ++i)
  36904. {
  36905. CodeDocumentLine* const l = lines.getUnchecked (i);
  36906. l->lineStartInFile = lineStart;
  36907. lineStart += l->lineLength;
  36908. }
  36909. checkLastLineStatus();
  36910. const int newTextLength = text.length();
  36911. for (i = 0; i < positionsToMaintain.size(); ++i)
  36912. {
  36913. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36914. if (p->getPosition() >= insertPos)
  36915. p->setPosition (p->getPosition() + newTextLength);
  36916. }
  36917. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36918. }
  36919. }
  36920. class CodeDocumentDeleteAction : public UndoableAction
  36921. {
  36922. CodeDocument& owner;
  36923. int startPos, endPos;
  36924. String removedText;
  36925. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36926. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36927. public:
  36928. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36929. : owner (owner_),
  36930. startPos (startPos_),
  36931. endPos (endPos_)
  36932. {
  36933. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36934. CodeDocument::Position (&owner, endPos));
  36935. }
  36936. ~CodeDocumentDeleteAction() {}
  36937. bool perform()
  36938. {
  36939. owner.currentActionIndex++;
  36940. owner.remove (startPos, endPos, false);
  36941. return true;
  36942. }
  36943. bool undo()
  36944. {
  36945. owner.currentActionIndex--;
  36946. owner.insert (removedText, startPos, false);
  36947. return true;
  36948. }
  36949. int getSizeInUnits() { return removedText.length() + 32; }
  36950. };
  36951. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36952. {
  36953. if (endPos <= startPos)
  36954. return;
  36955. if (undoable)
  36956. {
  36957. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36958. }
  36959. else
  36960. {
  36961. Position startPosition (this, startPos);
  36962. Position endPosition (this, endPos);
  36963. maximumLineLength = -1;
  36964. const int firstAffectedLine = startPosition.getLineNumber();
  36965. const int endLine = endPosition.getLineNumber();
  36966. int lastAffectedLine = firstAffectedLine + 1;
  36967. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36968. if (firstAffectedLine == endLine)
  36969. {
  36970. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36971. + firstLine->line.substring (endPosition.getIndexInLine());
  36972. firstLine->updateLength();
  36973. }
  36974. else
  36975. {
  36976. lastAffectedLine = lines.size();
  36977. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36978. jassert (lastLine != 0);
  36979. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36980. + lastLine->line.substring (endPosition.getIndexInLine());
  36981. firstLine->updateLength();
  36982. int numLinesToRemove = endLine - firstAffectedLine;
  36983. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36984. }
  36985. int i;
  36986. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36987. {
  36988. CodeDocumentLine* const l = lines.getUnchecked (i);
  36989. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36990. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36991. }
  36992. checkLastLineStatus();
  36993. const int totalChars = getNumCharacters();
  36994. for (i = 0; i < positionsToMaintain.size(); ++i)
  36995. {
  36996. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36997. if (p->getPosition() > startPosition.getPosition())
  36998. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36999. if (p->getPosition() > totalChars)
  37000. p->setPosition (totalChars);
  37001. }
  37002. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  37003. }
  37004. }
  37005. END_JUCE_NAMESPACE
  37006. /*** End of inlined file: juce_CodeDocument.cpp ***/
  37007. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  37008. BEGIN_JUCE_NAMESPACE
  37009. class CodeEditorComponent::CaretComponent : public Component,
  37010. public Timer
  37011. {
  37012. public:
  37013. CaretComponent (CodeEditorComponent& owner_)
  37014. : owner (owner_)
  37015. {
  37016. setAlwaysOnTop (true);
  37017. setInterceptsMouseClicks (false, false);
  37018. }
  37019. ~CaretComponent()
  37020. {
  37021. }
  37022. void paint (Graphics& g)
  37023. {
  37024. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  37025. }
  37026. void timerCallback()
  37027. {
  37028. setVisible (shouldBeShown() && ! isVisible());
  37029. }
  37030. void updatePosition()
  37031. {
  37032. startTimer (400);
  37033. setVisible (shouldBeShown());
  37034. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  37035. }
  37036. private:
  37037. CodeEditorComponent& owner;
  37038. CaretComponent (const CaretComponent&);
  37039. CaretComponent& operator= (const CaretComponent&);
  37040. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  37041. };
  37042. class CodeEditorComponent::CodeEditorLine
  37043. {
  37044. public:
  37045. CodeEditorLine() throw()
  37046. : highlightColumnStart (0), highlightColumnEnd (0)
  37047. {
  37048. }
  37049. ~CodeEditorLine() throw()
  37050. {
  37051. }
  37052. bool update (CodeDocument& document, int lineNum,
  37053. CodeDocument::Iterator& source,
  37054. CodeTokeniser* analyser, const int spacesPerTab,
  37055. const CodeDocument::Position& selectionStart,
  37056. const CodeDocument::Position& selectionEnd)
  37057. {
  37058. Array <SyntaxToken> newTokens;
  37059. newTokens.ensureStorageAllocated (8);
  37060. if (analyser == 0)
  37061. {
  37062. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  37063. }
  37064. else if (lineNum < document.getNumLines())
  37065. {
  37066. const CodeDocument::Position pos (&document, lineNum, 0);
  37067. createTokens (pos.getPosition(), pos.getLineText(),
  37068. source, analyser, newTokens);
  37069. }
  37070. replaceTabsWithSpaces (newTokens, spacesPerTab);
  37071. int newHighlightStart = 0;
  37072. int newHighlightEnd = 0;
  37073. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  37074. {
  37075. const String line (document.getLine (lineNum));
  37076. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  37077. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  37078. line, spacesPerTab);
  37079. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  37080. line, spacesPerTab);
  37081. }
  37082. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  37083. {
  37084. highlightColumnStart = newHighlightStart;
  37085. highlightColumnEnd = newHighlightEnd;
  37086. }
  37087. else
  37088. {
  37089. if (tokens.size() == newTokens.size())
  37090. {
  37091. bool allTheSame = true;
  37092. for (int i = newTokens.size(); --i >= 0;)
  37093. {
  37094. if (tokens.getReference(i) != newTokens.getReference(i))
  37095. {
  37096. allTheSame = false;
  37097. break;
  37098. }
  37099. }
  37100. if (allTheSame)
  37101. return false;
  37102. }
  37103. }
  37104. tokens.swapWithArray (newTokens);
  37105. return true;
  37106. }
  37107. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  37108. float x, const int y, const int baselineOffset, const int lineHeight,
  37109. const Colour& highlightColour) const
  37110. {
  37111. if (highlightColumnStart < highlightColumnEnd)
  37112. {
  37113. g.setColour (highlightColour);
  37114. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  37115. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  37116. }
  37117. int lastType = std::numeric_limits<int>::min();
  37118. for (int i = 0; i < tokens.size(); ++i)
  37119. {
  37120. SyntaxToken& token = tokens.getReference(i);
  37121. if (lastType != token.tokenType)
  37122. {
  37123. lastType = token.tokenType;
  37124. g.setColour (owner.getColourForTokenType (lastType));
  37125. }
  37126. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  37127. if (i < tokens.size() - 1)
  37128. {
  37129. if (token.width < 0)
  37130. token.width = font.getStringWidthFloat (token.text);
  37131. x += token.width;
  37132. }
  37133. }
  37134. }
  37135. private:
  37136. struct SyntaxToken
  37137. {
  37138. String text;
  37139. int tokenType;
  37140. float width;
  37141. SyntaxToken (const String& text_, const int type) throw()
  37142. : text (text_), tokenType (type), width (-1.0f)
  37143. {
  37144. }
  37145. bool operator!= (const SyntaxToken& other) const throw()
  37146. {
  37147. return text != other.text || tokenType != other.tokenType;
  37148. }
  37149. };
  37150. Array <SyntaxToken> tokens;
  37151. int highlightColumnStart, highlightColumnEnd;
  37152. static void createTokens (int startPosition, const String& lineText,
  37153. CodeDocument::Iterator& source,
  37154. CodeTokeniser* analyser,
  37155. Array <SyntaxToken>& newTokens)
  37156. {
  37157. CodeDocument::Iterator lastIterator (source);
  37158. const int lineLength = lineText.length();
  37159. for (;;)
  37160. {
  37161. int tokenType = analyser->readNextToken (source);
  37162. int tokenStart = lastIterator.getPosition();
  37163. int tokenEnd = source.getPosition();
  37164. if (tokenEnd <= tokenStart)
  37165. break;
  37166. tokenEnd -= startPosition;
  37167. if (tokenEnd > 0)
  37168. {
  37169. tokenStart -= startPosition;
  37170. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  37171. tokenType));
  37172. if (tokenEnd >= lineLength)
  37173. break;
  37174. }
  37175. lastIterator = source;
  37176. }
  37177. source = lastIterator;
  37178. }
  37179. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  37180. {
  37181. int x = 0;
  37182. for (int i = 0; i < tokens.size(); ++i)
  37183. {
  37184. SyntaxToken& t = tokens.getReference(i);
  37185. for (;;)
  37186. {
  37187. int tabPos = t.text.indexOfChar ('\t');
  37188. if (tabPos < 0)
  37189. break;
  37190. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  37191. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  37192. }
  37193. x += t.text.length();
  37194. }
  37195. }
  37196. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  37197. {
  37198. jassert (index <= line.length());
  37199. int col = 0;
  37200. for (int i = 0; i < index; ++i)
  37201. {
  37202. if (line[i] != '\t')
  37203. ++col;
  37204. else
  37205. col += spacesPerTab - (col % spacesPerTab);
  37206. }
  37207. return col;
  37208. }
  37209. };
  37210. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  37211. CodeTokeniser* const codeTokeniser_)
  37212. : document (document_),
  37213. firstLineOnScreen (0),
  37214. gutter (5),
  37215. spacesPerTab (4),
  37216. lineHeight (0),
  37217. linesOnScreen (0),
  37218. columnsOnScreen (0),
  37219. scrollbarThickness (16),
  37220. columnToTryToMaintain (-1),
  37221. useSpacesForTabs (false),
  37222. xOffset (0),
  37223. codeTokeniser (codeTokeniser_)
  37224. {
  37225. caretPos = CodeDocument::Position (&document_, 0, 0);
  37226. caretPos.setPositionMaintained (true);
  37227. selectionStart = CodeDocument::Position (&document_, 0, 0);
  37228. selectionStart.setPositionMaintained (true);
  37229. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  37230. selectionEnd.setPositionMaintained (true);
  37231. setOpaque (true);
  37232. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  37233. setWantsKeyboardFocus (true);
  37234. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  37235. verticalScrollBar->setSingleStepSize (1.0);
  37236. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  37237. horizontalScrollBar->setSingleStepSize (1.0);
  37238. addAndMakeVisible (caret = new CaretComponent (*this));
  37239. Font f (12.0f);
  37240. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  37241. setFont (f);
  37242. resetToDefaultColours();
  37243. verticalScrollBar->addListener (this);
  37244. horizontalScrollBar->addListener (this);
  37245. document.addListener (this);
  37246. }
  37247. CodeEditorComponent::~CodeEditorComponent()
  37248. {
  37249. document.removeListener (this);
  37250. deleteAllChildren();
  37251. }
  37252. void CodeEditorComponent::loadContent (const String& newContent)
  37253. {
  37254. clearCachedIterators (0);
  37255. document.replaceAllContent (newContent);
  37256. document.clearUndoHistory();
  37257. document.setSavePoint();
  37258. caretPos.setPosition (0);
  37259. selectionStart.setPosition (0);
  37260. selectionEnd.setPosition (0);
  37261. scrollToLine (0);
  37262. }
  37263. bool CodeEditorComponent::isTextInputActive() const
  37264. {
  37265. return true;
  37266. }
  37267. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  37268. const CodeDocument::Position& affectedTextEnd)
  37269. {
  37270. clearCachedIterators (affectedTextStart.getLineNumber());
  37271. triggerAsyncUpdate();
  37272. caret->updatePosition();
  37273. columnToTryToMaintain = -1;
  37274. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  37275. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  37276. deselectAll();
  37277. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  37278. || caretPos.getPosition() < affectedTextStart.getPosition())
  37279. moveCaretTo (affectedTextStart, false);
  37280. updateScrollBars();
  37281. }
  37282. void CodeEditorComponent::resized()
  37283. {
  37284. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  37285. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  37286. lines.clear();
  37287. rebuildLineTokens();
  37288. caret->updatePosition();
  37289. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  37290. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  37291. updateScrollBars();
  37292. }
  37293. void CodeEditorComponent::paint (Graphics& g)
  37294. {
  37295. handleUpdateNowIfNeeded();
  37296. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37297. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  37298. g.setFont (font);
  37299. const int baselineOffset = (int) font.getAscent();
  37300. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37301. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37302. const Rectangle<int> clip (g.getClipBounds());
  37303. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37304. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37305. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37306. {
  37307. lines.getUnchecked(j)->draw (*this, g, font,
  37308. (float) (gutter - xOffset * charWidth),
  37309. lineHeight * j, baselineOffset, lineHeight,
  37310. highlightColour);
  37311. }
  37312. }
  37313. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37314. {
  37315. if (scrollbarThickness != thickness)
  37316. {
  37317. scrollbarThickness = thickness;
  37318. resized();
  37319. }
  37320. }
  37321. void CodeEditorComponent::handleAsyncUpdate()
  37322. {
  37323. rebuildLineTokens();
  37324. }
  37325. void CodeEditorComponent::rebuildLineTokens()
  37326. {
  37327. cancelPendingUpdate();
  37328. const int numNeeded = linesOnScreen + 1;
  37329. int minLineToRepaint = numNeeded;
  37330. int maxLineToRepaint = 0;
  37331. if (numNeeded != lines.size())
  37332. {
  37333. lines.clear();
  37334. for (int i = numNeeded; --i >= 0;)
  37335. lines.add (new CodeEditorLine());
  37336. minLineToRepaint = 0;
  37337. maxLineToRepaint = numNeeded;
  37338. }
  37339. jassert (numNeeded == lines.size());
  37340. CodeDocument::Iterator source (&document);
  37341. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37342. for (int i = 0; i < numNeeded; ++i)
  37343. {
  37344. CodeEditorLine* const line = lines.getUnchecked(i);
  37345. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37346. selectionStart, selectionEnd))
  37347. {
  37348. minLineToRepaint = jmin (minLineToRepaint, i);
  37349. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37350. }
  37351. }
  37352. if (minLineToRepaint <= maxLineToRepaint)
  37353. {
  37354. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37355. verticalScrollBar->getX() - gutter,
  37356. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37357. }
  37358. }
  37359. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37360. {
  37361. caretPos = newPos;
  37362. columnToTryToMaintain = -1;
  37363. if (highlighting)
  37364. {
  37365. if (dragType == notDragging)
  37366. {
  37367. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37368. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37369. dragType = draggingSelectionStart;
  37370. else
  37371. dragType = draggingSelectionEnd;
  37372. }
  37373. if (dragType == draggingSelectionStart)
  37374. {
  37375. selectionStart = caretPos;
  37376. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37377. {
  37378. const CodeDocument::Position temp (selectionStart);
  37379. selectionStart = selectionEnd;
  37380. selectionEnd = temp;
  37381. dragType = draggingSelectionEnd;
  37382. }
  37383. }
  37384. else
  37385. {
  37386. selectionEnd = caretPos;
  37387. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37388. {
  37389. const CodeDocument::Position temp (selectionStart);
  37390. selectionStart = selectionEnd;
  37391. selectionEnd = temp;
  37392. dragType = draggingSelectionStart;
  37393. }
  37394. }
  37395. triggerAsyncUpdate();
  37396. }
  37397. else
  37398. {
  37399. deselectAll();
  37400. }
  37401. caret->updatePosition();
  37402. scrollToKeepCaretOnScreen();
  37403. updateScrollBars();
  37404. }
  37405. void CodeEditorComponent::deselectAll()
  37406. {
  37407. if (selectionStart != selectionEnd)
  37408. triggerAsyncUpdate();
  37409. selectionStart = caretPos;
  37410. selectionEnd = caretPos;
  37411. }
  37412. void CodeEditorComponent::updateScrollBars()
  37413. {
  37414. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37415. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37416. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37417. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37418. }
  37419. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37420. {
  37421. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37422. newFirstLineOnScreen);
  37423. if (newFirstLineOnScreen != firstLineOnScreen)
  37424. {
  37425. firstLineOnScreen = newFirstLineOnScreen;
  37426. caret->updatePosition();
  37427. updateCachedIterators (firstLineOnScreen);
  37428. triggerAsyncUpdate();
  37429. }
  37430. }
  37431. void CodeEditorComponent::scrollToColumnInternal (double column)
  37432. {
  37433. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37434. if (xOffset != newOffset)
  37435. {
  37436. xOffset = newOffset;
  37437. caret->updatePosition();
  37438. repaint();
  37439. }
  37440. }
  37441. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37442. {
  37443. scrollToLineInternal (newFirstLineOnScreen);
  37444. updateScrollBars();
  37445. }
  37446. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37447. {
  37448. scrollToColumnInternal (newFirstColumnOnScreen);
  37449. updateScrollBars();
  37450. }
  37451. void CodeEditorComponent::scrollBy (int deltaLines)
  37452. {
  37453. scrollToLine (firstLineOnScreen + deltaLines);
  37454. }
  37455. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37456. {
  37457. if (caretPos.getLineNumber() < firstLineOnScreen)
  37458. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37459. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37460. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37461. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37462. if (column >= xOffset + columnsOnScreen - 1)
  37463. scrollToColumn (column + 1 - columnsOnScreen);
  37464. else if (column < xOffset)
  37465. scrollToColumn (column);
  37466. }
  37467. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37468. {
  37469. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37470. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37471. roundToInt (charWidth),
  37472. lineHeight);
  37473. }
  37474. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37475. {
  37476. const int line = y / lineHeight + firstLineOnScreen;
  37477. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37478. const int index = columnToIndex (line, column);
  37479. return CodeDocument::Position (&document, line, index);
  37480. }
  37481. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37482. {
  37483. document.deleteSection (selectionStart, selectionEnd);
  37484. if (newText.isNotEmpty())
  37485. document.insertText (caretPos, newText);
  37486. scrollToKeepCaretOnScreen();
  37487. }
  37488. void CodeEditorComponent::insertTabAtCaret()
  37489. {
  37490. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37491. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37492. {
  37493. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37494. }
  37495. if (useSpacesForTabs)
  37496. {
  37497. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37498. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37499. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37500. }
  37501. else
  37502. {
  37503. insertTextAtCaret ("\t");
  37504. }
  37505. }
  37506. void CodeEditorComponent::cut()
  37507. {
  37508. insertTextAtCaret (String::empty);
  37509. }
  37510. void CodeEditorComponent::copy()
  37511. {
  37512. newTransaction();
  37513. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37514. if (selection.isNotEmpty())
  37515. SystemClipboard::copyTextToClipboard (selection);
  37516. }
  37517. void CodeEditorComponent::copyThenCut()
  37518. {
  37519. copy();
  37520. cut();
  37521. newTransaction();
  37522. }
  37523. void CodeEditorComponent::paste()
  37524. {
  37525. newTransaction();
  37526. const String clip (SystemClipboard::getTextFromClipboard());
  37527. if (clip.isNotEmpty())
  37528. insertTextAtCaret (clip);
  37529. newTransaction();
  37530. }
  37531. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37532. {
  37533. newTransaction();
  37534. if (moveInWholeWordSteps)
  37535. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37536. else
  37537. moveCaretTo (caretPos.movedBy (-1), selecting);
  37538. }
  37539. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37540. {
  37541. newTransaction();
  37542. if (moveInWholeWordSteps)
  37543. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37544. else
  37545. moveCaretTo (caretPos.movedBy (1), selecting);
  37546. }
  37547. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37548. {
  37549. CodeDocument::Position pos (caretPos);
  37550. const int newLineNum = pos.getLineNumber() + delta;
  37551. if (columnToTryToMaintain < 0)
  37552. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37553. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37554. const int colToMaintain = columnToTryToMaintain;
  37555. moveCaretTo (pos, selecting);
  37556. columnToTryToMaintain = colToMaintain;
  37557. }
  37558. void CodeEditorComponent::cursorDown (const bool selecting)
  37559. {
  37560. newTransaction();
  37561. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37562. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37563. else
  37564. moveLineDelta (1, selecting);
  37565. }
  37566. void CodeEditorComponent::cursorUp (const bool selecting)
  37567. {
  37568. newTransaction();
  37569. if (caretPos.getLineNumber() == 0)
  37570. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37571. else
  37572. moveLineDelta (-1, selecting);
  37573. }
  37574. void CodeEditorComponent::pageDown (const bool selecting)
  37575. {
  37576. newTransaction();
  37577. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37578. moveLineDelta (linesOnScreen, selecting);
  37579. }
  37580. void CodeEditorComponent::pageUp (const bool selecting)
  37581. {
  37582. newTransaction();
  37583. scrollBy (-linesOnScreen);
  37584. moveLineDelta (-linesOnScreen, selecting);
  37585. }
  37586. void CodeEditorComponent::scrollUp()
  37587. {
  37588. newTransaction();
  37589. scrollBy (1);
  37590. if (caretPos.getLineNumber() < firstLineOnScreen)
  37591. moveLineDelta (1, false);
  37592. }
  37593. void CodeEditorComponent::scrollDown()
  37594. {
  37595. newTransaction();
  37596. scrollBy (-1);
  37597. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37598. moveLineDelta (-1, false);
  37599. }
  37600. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37601. {
  37602. newTransaction();
  37603. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37604. }
  37605. static int findFirstNonWhitespaceChar (const String& line) throw()
  37606. {
  37607. const int len = line.length();
  37608. for (int i = 0; i < len; ++i)
  37609. if (! CharacterFunctions::isWhitespace (line [i]))
  37610. return i;
  37611. return 0;
  37612. }
  37613. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37614. {
  37615. newTransaction();
  37616. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37617. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37618. index = 0;
  37619. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37620. }
  37621. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37622. {
  37623. newTransaction();
  37624. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37625. }
  37626. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37627. {
  37628. newTransaction();
  37629. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37630. }
  37631. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37632. {
  37633. if (moveInWholeWordSteps)
  37634. {
  37635. cut(); // in case something is already highlighted
  37636. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37637. }
  37638. else
  37639. {
  37640. if (selectionStart == selectionEnd)
  37641. selectionStart.moveBy (-1);
  37642. }
  37643. cut();
  37644. }
  37645. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37646. {
  37647. if (moveInWholeWordSteps)
  37648. {
  37649. cut(); // in case something is already highlighted
  37650. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37651. }
  37652. else
  37653. {
  37654. if (selectionStart == selectionEnd)
  37655. selectionEnd.moveBy (1);
  37656. else
  37657. newTransaction();
  37658. }
  37659. cut();
  37660. }
  37661. void CodeEditorComponent::selectAll()
  37662. {
  37663. newTransaction();
  37664. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37665. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37666. }
  37667. void CodeEditorComponent::undo()
  37668. {
  37669. document.undo();
  37670. scrollToKeepCaretOnScreen();
  37671. }
  37672. void CodeEditorComponent::redo()
  37673. {
  37674. document.redo();
  37675. scrollToKeepCaretOnScreen();
  37676. }
  37677. void CodeEditorComponent::newTransaction()
  37678. {
  37679. document.newTransaction();
  37680. startTimer (600);
  37681. }
  37682. void CodeEditorComponent::timerCallback()
  37683. {
  37684. newTransaction();
  37685. }
  37686. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37687. {
  37688. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37689. }
  37690. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37691. {
  37692. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37693. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37694. }
  37695. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37696. {
  37697. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37698. CodeDocument::Position (&document, range.getEnd()));
  37699. }
  37700. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37701. {
  37702. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37703. const bool shiftDown = key.getModifiers().isShiftDown();
  37704. if (key.isKeyCode (KeyPress::leftKey))
  37705. {
  37706. cursorLeft (moveInWholeWordSteps, shiftDown);
  37707. }
  37708. else if (key.isKeyCode (KeyPress::rightKey))
  37709. {
  37710. cursorRight (moveInWholeWordSteps, shiftDown);
  37711. }
  37712. else if (key.isKeyCode (KeyPress::upKey))
  37713. {
  37714. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37715. scrollDown();
  37716. #if JUCE_MAC
  37717. else if (key.getModifiers().isCommandDown())
  37718. goToStartOfDocument (shiftDown);
  37719. #endif
  37720. else
  37721. cursorUp (shiftDown);
  37722. }
  37723. else if (key.isKeyCode (KeyPress::downKey))
  37724. {
  37725. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37726. scrollUp();
  37727. #if JUCE_MAC
  37728. else if (key.getModifiers().isCommandDown())
  37729. goToEndOfDocument (shiftDown);
  37730. #endif
  37731. else
  37732. cursorDown (shiftDown);
  37733. }
  37734. else if (key.isKeyCode (KeyPress::pageDownKey))
  37735. {
  37736. pageDown (shiftDown);
  37737. }
  37738. else if (key.isKeyCode (KeyPress::pageUpKey))
  37739. {
  37740. pageUp (shiftDown);
  37741. }
  37742. else if (key.isKeyCode (KeyPress::homeKey))
  37743. {
  37744. if (moveInWholeWordSteps)
  37745. goToStartOfDocument (shiftDown);
  37746. else
  37747. goToStartOfLine (shiftDown);
  37748. }
  37749. else if (key.isKeyCode (KeyPress::endKey))
  37750. {
  37751. if (moveInWholeWordSteps)
  37752. goToEndOfDocument (shiftDown);
  37753. else
  37754. goToEndOfLine (shiftDown);
  37755. }
  37756. else if (key.isKeyCode (KeyPress::backspaceKey))
  37757. {
  37758. backspace (moveInWholeWordSteps);
  37759. }
  37760. else if (key.isKeyCode (KeyPress::deleteKey))
  37761. {
  37762. deleteForward (moveInWholeWordSteps);
  37763. }
  37764. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37765. {
  37766. copy();
  37767. }
  37768. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37769. {
  37770. copyThenCut();
  37771. }
  37772. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37773. {
  37774. paste();
  37775. }
  37776. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37777. {
  37778. undo();
  37779. }
  37780. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37781. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37782. {
  37783. redo();
  37784. }
  37785. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37786. {
  37787. selectAll();
  37788. }
  37789. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37790. {
  37791. insertTabAtCaret();
  37792. }
  37793. else if (key == KeyPress::returnKey)
  37794. {
  37795. newTransaction();
  37796. insertTextAtCaret (document.getNewLineCharacters());
  37797. }
  37798. else if (key.isKeyCode (KeyPress::escapeKey))
  37799. {
  37800. newTransaction();
  37801. }
  37802. else if (key.getTextCharacter() >= ' ')
  37803. {
  37804. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37805. }
  37806. else
  37807. {
  37808. return false;
  37809. }
  37810. return true;
  37811. }
  37812. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37813. {
  37814. newTransaction();
  37815. dragType = notDragging;
  37816. if (! e.mods.isPopupMenu())
  37817. {
  37818. beginDragAutoRepeat (100);
  37819. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37820. }
  37821. else
  37822. {
  37823. /*PopupMenu m;
  37824. addPopupMenuItems (m, &e);
  37825. const int result = m.show();
  37826. if (result != 0)
  37827. performPopupMenuAction (result);
  37828. */
  37829. }
  37830. }
  37831. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37832. {
  37833. if (! e.mods.isPopupMenu())
  37834. moveCaretTo (getPositionAt (e.x, e.y), true);
  37835. }
  37836. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37837. {
  37838. newTransaction();
  37839. beginDragAutoRepeat (0);
  37840. dragType = notDragging;
  37841. }
  37842. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37843. {
  37844. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37845. CodeDocument::Position tokenEnd (tokenStart);
  37846. if (e.getNumberOfClicks() > 2)
  37847. {
  37848. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37849. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37850. }
  37851. else
  37852. {
  37853. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37854. tokenEnd.moveBy (1);
  37855. tokenStart = tokenEnd;
  37856. while (tokenStart.getIndexInLine() > 0
  37857. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37858. tokenStart.moveBy (-1);
  37859. }
  37860. moveCaretTo (tokenEnd, false);
  37861. moveCaretTo (tokenStart, true);
  37862. }
  37863. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37864. {
  37865. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37866. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37867. {
  37868. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37869. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37870. }
  37871. else
  37872. {
  37873. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37874. }
  37875. }
  37876. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37877. {
  37878. if (scrollBarThatHasMoved == verticalScrollBar)
  37879. scrollToLineInternal ((int) newRangeStart);
  37880. else
  37881. scrollToColumnInternal (newRangeStart);
  37882. }
  37883. void CodeEditorComponent::focusGained (FocusChangeType)
  37884. {
  37885. caret->updatePosition();
  37886. }
  37887. void CodeEditorComponent::focusLost (FocusChangeType)
  37888. {
  37889. caret->updatePosition();
  37890. }
  37891. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37892. {
  37893. useSpacesForTabs = insertSpaces;
  37894. if (spacesPerTab != numSpaces)
  37895. {
  37896. spacesPerTab = numSpaces;
  37897. triggerAsyncUpdate();
  37898. }
  37899. }
  37900. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37901. {
  37902. const String line (document.getLine (lineNum));
  37903. jassert (index <= line.length());
  37904. int col = 0;
  37905. for (int i = 0; i < index; ++i)
  37906. {
  37907. if (line[i] != '\t')
  37908. ++col;
  37909. else
  37910. col += getTabSize() - (col % getTabSize());
  37911. }
  37912. return col;
  37913. }
  37914. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37915. {
  37916. const String line (document.getLine (lineNum));
  37917. const int lineLength = line.length();
  37918. int i, col = 0;
  37919. for (i = 0; i < lineLength; ++i)
  37920. {
  37921. if (line[i] != '\t')
  37922. ++col;
  37923. else
  37924. col += getTabSize() - (col % getTabSize());
  37925. if (col > column)
  37926. break;
  37927. }
  37928. return i;
  37929. }
  37930. void CodeEditorComponent::setFont (const Font& newFont)
  37931. {
  37932. font = newFont;
  37933. charWidth = font.getStringWidthFloat ("0");
  37934. lineHeight = roundToInt (font.getHeight());
  37935. resized();
  37936. }
  37937. void CodeEditorComponent::resetToDefaultColours()
  37938. {
  37939. coloursForTokenCategories.clear();
  37940. if (codeTokeniser != 0)
  37941. {
  37942. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37943. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37944. }
  37945. }
  37946. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37947. {
  37948. jassert (tokenType < 256);
  37949. while (coloursForTokenCategories.size() < tokenType)
  37950. coloursForTokenCategories.add (Colours::black);
  37951. coloursForTokenCategories.set (tokenType, colour);
  37952. repaint();
  37953. }
  37954. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37955. {
  37956. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37957. return findColour (CodeEditorComponent::defaultTextColourId);
  37958. return coloursForTokenCategories.getReference (tokenType);
  37959. }
  37960. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37961. {
  37962. int i;
  37963. for (i = cachedIterators.size(); --i >= 0;)
  37964. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37965. break;
  37966. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37967. }
  37968. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37969. {
  37970. const int maxNumCachedPositions = 5000;
  37971. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37972. if (cachedIterators.size() == 0)
  37973. cachedIterators.add (new CodeDocument::Iterator (&document));
  37974. if (codeTokeniser == 0)
  37975. return;
  37976. for (;;)
  37977. {
  37978. CodeDocument::Iterator* last = cachedIterators.getLast();
  37979. if (last->getLine() >= maxLineNum)
  37980. break;
  37981. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37982. cachedIterators.add (t);
  37983. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37984. for (;;)
  37985. {
  37986. codeTokeniser->readNextToken (*t);
  37987. if (t->getLine() >= targetLine)
  37988. break;
  37989. if (t->isEOF())
  37990. return;
  37991. }
  37992. }
  37993. }
  37994. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37995. {
  37996. if (codeTokeniser == 0)
  37997. return;
  37998. for (int i = cachedIterators.size(); --i >= 0;)
  37999. {
  38000. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  38001. if (t->getPosition() <= position)
  38002. {
  38003. source = *t;
  38004. break;
  38005. }
  38006. }
  38007. while (source.getPosition() < position)
  38008. {
  38009. const CodeDocument::Iterator original (source);
  38010. codeTokeniser->readNextToken (source);
  38011. if (source.getPosition() > position || source.isEOF())
  38012. {
  38013. source = original;
  38014. break;
  38015. }
  38016. }
  38017. }
  38018. END_JUCE_NAMESPACE
  38019. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  38020. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38021. BEGIN_JUCE_NAMESPACE
  38022. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  38023. {
  38024. }
  38025. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  38026. {
  38027. }
  38028. namespace CppTokeniser
  38029. {
  38030. static bool isIdentifierStart (const juce_wchar c) throw()
  38031. {
  38032. return CharacterFunctions::isLetter (c)
  38033. || c == '_' || c == '@';
  38034. }
  38035. static bool isIdentifierBody (const juce_wchar c) throw()
  38036. {
  38037. return CharacterFunctions::isLetterOrDigit (c)
  38038. || c == '_' || c == '@';
  38039. }
  38040. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  38041. {
  38042. static const juce_wchar* const keywords2Char[] =
  38043. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  38044. static const juce_wchar* const keywords3Char[] =
  38045. { 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 };
  38046. static const juce_wchar* const keywords4Char[] =
  38047. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  38048. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  38049. static const juce_wchar* const keywords5Char[] =
  38050. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  38051. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  38052. static const juce_wchar* const keywords6Char[] =
  38053. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  38054. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  38055. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  38056. static const juce_wchar* const keywordsOther[] =
  38057. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  38058. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  38059. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  38060. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  38061. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  38062. const juce_wchar* const* k;
  38063. switch (tokenLength)
  38064. {
  38065. case 2: k = keywords2Char; break;
  38066. case 3: k = keywords3Char; break;
  38067. case 4: k = keywords4Char; break;
  38068. case 5: k = keywords5Char; break;
  38069. case 6: k = keywords6Char; break;
  38070. default:
  38071. if (tokenLength < 2 || tokenLength > 16)
  38072. return false;
  38073. k = keywordsOther;
  38074. break;
  38075. }
  38076. int i = 0;
  38077. while (k[i] != 0)
  38078. {
  38079. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  38080. return true;
  38081. ++i;
  38082. }
  38083. return false;
  38084. }
  38085. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  38086. {
  38087. int tokenLength = 0;
  38088. juce_wchar possibleIdentifier [19];
  38089. while (isIdentifierBody (source.peekNextChar()))
  38090. {
  38091. const juce_wchar c = source.nextChar();
  38092. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  38093. possibleIdentifier [tokenLength] = c;
  38094. ++tokenLength;
  38095. }
  38096. if (tokenLength > 1 && tokenLength <= 16)
  38097. {
  38098. possibleIdentifier [tokenLength] = 0;
  38099. if (isReservedKeyword (possibleIdentifier, tokenLength))
  38100. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  38101. }
  38102. return CPlusPlusCodeTokeniser::tokenType_identifier;
  38103. }
  38104. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  38105. {
  38106. const juce_wchar c = source.peekNextChar();
  38107. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  38108. source.skip();
  38109. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  38110. return false;
  38111. return true;
  38112. }
  38113. static bool isHexDigit (const juce_wchar c) throw()
  38114. {
  38115. return (c >= '0' && c <= '9')
  38116. || (c >= 'a' && c <= 'f')
  38117. || (c >= 'A' && c <= 'F');
  38118. }
  38119. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  38120. {
  38121. if (source.nextChar() != '0')
  38122. return false;
  38123. juce_wchar c = source.nextChar();
  38124. if (c != 'x' && c != 'X')
  38125. return false;
  38126. int numDigits = 0;
  38127. while (isHexDigit (source.peekNextChar()))
  38128. {
  38129. ++numDigits;
  38130. source.skip();
  38131. }
  38132. if (numDigits == 0)
  38133. return false;
  38134. return skipNumberSuffix (source);
  38135. }
  38136. static bool isOctalDigit (const juce_wchar c) throw()
  38137. {
  38138. return c >= '0' && c <= '7';
  38139. }
  38140. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  38141. {
  38142. if (source.nextChar() != '0')
  38143. return false;
  38144. if (! isOctalDigit (source.nextChar()))
  38145. return false;
  38146. while (isOctalDigit (source.peekNextChar()))
  38147. source.skip();
  38148. return skipNumberSuffix (source);
  38149. }
  38150. static bool isDecimalDigit (const juce_wchar c) throw()
  38151. {
  38152. return c >= '0' && c <= '9';
  38153. }
  38154. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  38155. {
  38156. int numChars = 0;
  38157. while (isDecimalDigit (source.peekNextChar()))
  38158. {
  38159. ++numChars;
  38160. source.skip();
  38161. }
  38162. if (numChars == 0)
  38163. return false;
  38164. return skipNumberSuffix (source);
  38165. }
  38166. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  38167. {
  38168. int numDigits = 0;
  38169. while (isDecimalDigit (source.peekNextChar()))
  38170. {
  38171. source.skip();
  38172. ++numDigits;
  38173. }
  38174. const bool hasPoint = (source.peekNextChar() == '.');
  38175. if (hasPoint)
  38176. {
  38177. source.skip();
  38178. while (isDecimalDigit (source.peekNextChar()))
  38179. {
  38180. source.skip();
  38181. ++numDigits;
  38182. }
  38183. }
  38184. if (numDigits == 0)
  38185. return false;
  38186. juce_wchar c = source.peekNextChar();
  38187. const bool hasExponent = (c == 'e' || c == 'E');
  38188. if (hasExponent)
  38189. {
  38190. source.skip();
  38191. c = source.peekNextChar();
  38192. if (c == '+' || c == '-')
  38193. source.skip();
  38194. int numExpDigits = 0;
  38195. while (isDecimalDigit (source.peekNextChar()))
  38196. {
  38197. source.skip();
  38198. ++numExpDigits;
  38199. }
  38200. if (numExpDigits == 0)
  38201. return false;
  38202. }
  38203. c = source.peekNextChar();
  38204. if (c == 'f' || c == 'F')
  38205. source.skip();
  38206. else if (! (hasExponent || hasPoint))
  38207. return false;
  38208. return true;
  38209. }
  38210. static int parseNumber (CodeDocument::Iterator& source)
  38211. {
  38212. const CodeDocument::Iterator original (source);
  38213. if (parseFloatLiteral (source))
  38214. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  38215. source = original;
  38216. if (parseHexLiteral (source))
  38217. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  38218. source = original;
  38219. if (parseOctalLiteral (source))
  38220. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  38221. source = original;
  38222. if (parseDecimalLiteral (source))
  38223. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  38224. source = original;
  38225. source.skip();
  38226. return CPlusPlusCodeTokeniser::tokenType_error;
  38227. }
  38228. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  38229. {
  38230. const juce_wchar quote = source.nextChar();
  38231. for (;;)
  38232. {
  38233. const juce_wchar c = source.nextChar();
  38234. if (c == quote || c == 0)
  38235. break;
  38236. if (c == '\\')
  38237. source.skip();
  38238. }
  38239. }
  38240. static void skipComment (CodeDocument::Iterator& source) throw()
  38241. {
  38242. bool lastWasStar = false;
  38243. for (;;)
  38244. {
  38245. const juce_wchar c = source.nextChar();
  38246. if (c == 0 || (c == '/' && lastWasStar))
  38247. break;
  38248. lastWasStar = (c == '*');
  38249. }
  38250. }
  38251. }
  38252. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  38253. {
  38254. int result = tokenType_error;
  38255. source.skipWhitespace();
  38256. juce_wchar firstChar = source.peekNextChar();
  38257. switch (firstChar)
  38258. {
  38259. case 0:
  38260. source.skip();
  38261. break;
  38262. case '0':
  38263. case '1':
  38264. case '2':
  38265. case '3':
  38266. case '4':
  38267. case '5':
  38268. case '6':
  38269. case '7':
  38270. case '8':
  38271. case '9':
  38272. result = CppTokeniser::parseNumber (source);
  38273. break;
  38274. case '.':
  38275. result = CppTokeniser::parseNumber (source);
  38276. if (result == tokenType_error)
  38277. result = tokenType_punctuation;
  38278. break;
  38279. case ',':
  38280. case ';':
  38281. case ':':
  38282. source.skip();
  38283. result = tokenType_punctuation;
  38284. break;
  38285. case '(':
  38286. case ')':
  38287. case '{':
  38288. case '}':
  38289. case '[':
  38290. case ']':
  38291. source.skip();
  38292. result = tokenType_bracket;
  38293. break;
  38294. case '"':
  38295. case '\'':
  38296. CppTokeniser::skipQuotedString (source);
  38297. result = tokenType_stringLiteral;
  38298. break;
  38299. case '+':
  38300. result = tokenType_operator;
  38301. source.skip();
  38302. if (source.peekNextChar() == '+')
  38303. source.skip();
  38304. else if (source.peekNextChar() == '=')
  38305. source.skip();
  38306. break;
  38307. case '-':
  38308. source.skip();
  38309. result = CppTokeniser::parseNumber (source);
  38310. if (result == tokenType_error)
  38311. {
  38312. result = tokenType_operator;
  38313. if (source.peekNextChar() == '-')
  38314. source.skip();
  38315. else if (source.peekNextChar() == '=')
  38316. source.skip();
  38317. }
  38318. break;
  38319. case '*':
  38320. case '%':
  38321. case '=':
  38322. case '!':
  38323. result = tokenType_operator;
  38324. source.skip();
  38325. if (source.peekNextChar() == '=')
  38326. source.skip();
  38327. break;
  38328. case '/':
  38329. result = tokenType_operator;
  38330. source.skip();
  38331. if (source.peekNextChar() == '=')
  38332. {
  38333. source.skip();
  38334. }
  38335. else if (source.peekNextChar() == '/')
  38336. {
  38337. result = tokenType_comment;
  38338. source.skipToEndOfLine();
  38339. }
  38340. else if (source.peekNextChar() == '*')
  38341. {
  38342. source.skip();
  38343. result = tokenType_comment;
  38344. CppTokeniser::skipComment (source);
  38345. }
  38346. break;
  38347. case '?':
  38348. case '~':
  38349. source.skip();
  38350. result = tokenType_operator;
  38351. break;
  38352. case '<':
  38353. source.skip();
  38354. result = tokenType_operator;
  38355. if (source.peekNextChar() == '=')
  38356. {
  38357. source.skip();
  38358. }
  38359. else if (source.peekNextChar() == '<')
  38360. {
  38361. source.skip();
  38362. if (source.peekNextChar() == '=')
  38363. source.skip();
  38364. }
  38365. break;
  38366. case '>':
  38367. source.skip();
  38368. result = tokenType_operator;
  38369. if (source.peekNextChar() == '=')
  38370. {
  38371. source.skip();
  38372. }
  38373. else if (source.peekNextChar() == '<')
  38374. {
  38375. source.skip();
  38376. if (source.peekNextChar() == '=')
  38377. source.skip();
  38378. }
  38379. break;
  38380. case '|':
  38381. source.skip();
  38382. result = tokenType_operator;
  38383. if (source.peekNextChar() == '=')
  38384. {
  38385. source.skip();
  38386. }
  38387. else if (source.peekNextChar() == '|')
  38388. {
  38389. source.skip();
  38390. if (source.peekNextChar() == '=')
  38391. source.skip();
  38392. }
  38393. break;
  38394. case '&':
  38395. source.skip();
  38396. result = tokenType_operator;
  38397. if (source.peekNextChar() == '=')
  38398. {
  38399. source.skip();
  38400. }
  38401. else if (source.peekNextChar() == '&')
  38402. {
  38403. source.skip();
  38404. if (source.peekNextChar() == '=')
  38405. source.skip();
  38406. }
  38407. break;
  38408. case '^':
  38409. source.skip();
  38410. result = tokenType_operator;
  38411. if (source.peekNextChar() == '=')
  38412. {
  38413. source.skip();
  38414. }
  38415. else if (source.peekNextChar() == '^')
  38416. {
  38417. source.skip();
  38418. if (source.peekNextChar() == '=')
  38419. source.skip();
  38420. }
  38421. break;
  38422. case '#':
  38423. result = tokenType_preprocessor;
  38424. source.skipToEndOfLine();
  38425. break;
  38426. default:
  38427. if (CppTokeniser::isIdentifierStart (firstChar))
  38428. result = CppTokeniser::parseIdentifier (source);
  38429. else
  38430. source.skip();
  38431. break;
  38432. }
  38433. return result;
  38434. }
  38435. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38436. {
  38437. const char* const types[] =
  38438. {
  38439. "Error",
  38440. "Comment",
  38441. "C++ keyword",
  38442. "Identifier",
  38443. "Integer literal",
  38444. "Float literal",
  38445. "String literal",
  38446. "Operator",
  38447. "Bracket",
  38448. "Punctuation",
  38449. "Preprocessor line",
  38450. 0
  38451. };
  38452. return StringArray (types);
  38453. }
  38454. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38455. {
  38456. const uint32 colours[] =
  38457. {
  38458. 0xffcc0000, // error
  38459. 0xff00aa00, // comment
  38460. 0xff0000cc, // keyword
  38461. 0xff000000, // identifier
  38462. 0xff880000, // int literal
  38463. 0xff885500, // float literal
  38464. 0xff990099, // string literal
  38465. 0xff225500, // operator
  38466. 0xff000055, // bracket
  38467. 0xff004400, // punctuation
  38468. 0xff660000 // preprocessor
  38469. };
  38470. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38471. return Colour (colours [tokenType]);
  38472. return Colours::black;
  38473. }
  38474. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38475. {
  38476. return CppTokeniser::isReservedKeyword (token, token.length());
  38477. }
  38478. END_JUCE_NAMESPACE
  38479. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38480. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38481. BEGIN_JUCE_NAMESPACE
  38482. ComboBox::ComboBox (const String& name)
  38483. : Component (name),
  38484. lastCurrentId (0),
  38485. isButtonDown (false),
  38486. separatorPending (false),
  38487. menuActive (false),
  38488. label (0)
  38489. {
  38490. noChoicesMessage = TRANS("(no choices)");
  38491. setRepaintsOnMouseActivity (true);
  38492. lookAndFeelChanged();
  38493. currentId.addListener (this);
  38494. }
  38495. ComboBox::~ComboBox()
  38496. {
  38497. currentId.removeListener (this);
  38498. if (menuActive)
  38499. PopupMenu::dismissAllActiveMenus();
  38500. label = 0;
  38501. deleteAllChildren();
  38502. }
  38503. void ComboBox::setEditableText (const bool isEditable)
  38504. {
  38505. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38506. {
  38507. label->setEditable (isEditable, isEditable, false);
  38508. setWantsKeyboardFocus (! isEditable);
  38509. resized();
  38510. }
  38511. }
  38512. bool ComboBox::isTextEditable() const throw()
  38513. {
  38514. return label->isEditable();
  38515. }
  38516. void ComboBox::setJustificationType (const Justification& justification)
  38517. {
  38518. label->setJustificationType (justification);
  38519. }
  38520. const Justification ComboBox::getJustificationType() const throw()
  38521. {
  38522. return label->getJustificationType();
  38523. }
  38524. void ComboBox::setTooltip (const String& newTooltip)
  38525. {
  38526. SettableTooltipClient::setTooltip (newTooltip);
  38527. label->setTooltip (newTooltip);
  38528. }
  38529. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38530. {
  38531. // you can't add empty strings to the list..
  38532. jassert (newItemText.isNotEmpty());
  38533. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38534. jassert (newItemId != 0);
  38535. // you shouldn't use duplicate item IDs!
  38536. jassert (getItemForId (newItemId) == 0);
  38537. if (newItemText.isNotEmpty() && newItemId != 0)
  38538. {
  38539. if (separatorPending)
  38540. {
  38541. separatorPending = false;
  38542. ItemInfo* const item = new ItemInfo();
  38543. item->itemId = 0;
  38544. item->isEnabled = false;
  38545. item->isHeading = false;
  38546. items.add (item);
  38547. }
  38548. ItemInfo* const item = new ItemInfo();
  38549. item->name = newItemText;
  38550. item->itemId = newItemId;
  38551. item->isEnabled = true;
  38552. item->isHeading = false;
  38553. items.add (item);
  38554. }
  38555. }
  38556. void ComboBox::addSeparator()
  38557. {
  38558. separatorPending = (items.size() > 0);
  38559. }
  38560. void ComboBox::addSectionHeading (const String& headingName)
  38561. {
  38562. // you can't add empty strings to the list..
  38563. jassert (headingName.isNotEmpty());
  38564. if (headingName.isNotEmpty())
  38565. {
  38566. if (separatorPending)
  38567. {
  38568. separatorPending = false;
  38569. ItemInfo* const item = new ItemInfo();
  38570. item->itemId = 0;
  38571. item->isEnabled = false;
  38572. item->isHeading = false;
  38573. items.add (item);
  38574. }
  38575. ItemInfo* const item = new ItemInfo();
  38576. item->name = headingName;
  38577. item->itemId = 0;
  38578. item->isEnabled = true;
  38579. item->isHeading = true;
  38580. items.add (item);
  38581. }
  38582. }
  38583. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38584. {
  38585. ItemInfo* const item = getItemForId (itemId);
  38586. if (item != 0)
  38587. item->isEnabled = shouldBeEnabled;
  38588. }
  38589. void ComboBox::changeItemText (const int itemId, const String& newText)
  38590. {
  38591. ItemInfo* const item = getItemForId (itemId);
  38592. jassert (item != 0);
  38593. if (item != 0)
  38594. item->name = newText;
  38595. }
  38596. void ComboBox::clear (const bool dontSendChangeMessage)
  38597. {
  38598. items.clear();
  38599. separatorPending = false;
  38600. if (! label->isEditable())
  38601. setSelectedItemIndex (-1, dontSendChangeMessage);
  38602. }
  38603. bool ComboBox::ItemInfo::isSeparator() const throw()
  38604. {
  38605. return name.isEmpty();
  38606. }
  38607. bool ComboBox::ItemInfo::isRealItem() const throw()
  38608. {
  38609. return ! (isHeading || name.isEmpty());
  38610. }
  38611. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38612. {
  38613. if (itemId != 0)
  38614. {
  38615. for (int i = items.size(); --i >= 0;)
  38616. if (items.getUnchecked(i)->itemId == itemId)
  38617. return items.getUnchecked(i);
  38618. }
  38619. return 0;
  38620. }
  38621. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38622. {
  38623. int n = 0;
  38624. for (int i = 0; i < items.size(); ++i)
  38625. {
  38626. ItemInfo* const item = items.getUnchecked(i);
  38627. if (item->isRealItem())
  38628. if (n++ == index)
  38629. return item;
  38630. }
  38631. return 0;
  38632. }
  38633. int ComboBox::getNumItems() const throw()
  38634. {
  38635. int n = 0;
  38636. for (int i = items.size(); --i >= 0;)
  38637. if (items.getUnchecked(i)->isRealItem())
  38638. ++n;
  38639. return n;
  38640. }
  38641. const String ComboBox::getItemText (const int index) const
  38642. {
  38643. const ItemInfo* const item = getItemForIndex (index);
  38644. if (item != 0)
  38645. return item->name;
  38646. return String::empty;
  38647. }
  38648. int ComboBox::getItemId (const int index) const throw()
  38649. {
  38650. const ItemInfo* const item = getItemForIndex (index);
  38651. return (item != 0) ? item->itemId : 0;
  38652. }
  38653. int ComboBox::indexOfItemId (const int itemId) const throw()
  38654. {
  38655. int n = 0;
  38656. for (int i = 0; i < items.size(); ++i)
  38657. {
  38658. const ItemInfo* const item = items.getUnchecked(i);
  38659. if (item->isRealItem())
  38660. {
  38661. if (item->itemId == itemId)
  38662. return n;
  38663. ++n;
  38664. }
  38665. }
  38666. return -1;
  38667. }
  38668. int ComboBox::getSelectedItemIndex() const
  38669. {
  38670. int index = indexOfItemId (currentId.getValue());
  38671. if (getText() != getItemText (index))
  38672. index = -1;
  38673. return index;
  38674. }
  38675. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38676. {
  38677. setSelectedId (getItemId (index), dontSendChangeMessage);
  38678. }
  38679. int ComboBox::getSelectedId() const throw()
  38680. {
  38681. const ItemInfo* const item = getItemForId (currentId.getValue());
  38682. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38683. }
  38684. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38685. {
  38686. const ItemInfo* const item = getItemForId (newItemId);
  38687. const String newItemText (item != 0 ? item->name : String::empty);
  38688. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38689. {
  38690. if (! dontSendChangeMessage)
  38691. triggerAsyncUpdate();
  38692. label->setText (newItemText, false);
  38693. lastCurrentId = newItemId;
  38694. currentId = newItemId;
  38695. repaint(); // for the benefit of the 'none selected' text
  38696. }
  38697. }
  38698. void ComboBox::valueChanged (Value&)
  38699. {
  38700. if (lastCurrentId != (int) currentId.getValue())
  38701. setSelectedId (currentId.getValue(), false);
  38702. }
  38703. const String ComboBox::getText() const
  38704. {
  38705. return label->getText();
  38706. }
  38707. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38708. {
  38709. for (int i = items.size(); --i >= 0;)
  38710. {
  38711. const ItemInfo* const item = items.getUnchecked(i);
  38712. if (item->isRealItem()
  38713. && item->name == newText)
  38714. {
  38715. setSelectedId (item->itemId, dontSendChangeMessage);
  38716. return;
  38717. }
  38718. }
  38719. lastCurrentId = 0;
  38720. currentId = 0;
  38721. if (label->getText() != newText)
  38722. {
  38723. label->setText (newText, false);
  38724. if (! dontSendChangeMessage)
  38725. triggerAsyncUpdate();
  38726. }
  38727. repaint();
  38728. }
  38729. void ComboBox::showEditor()
  38730. {
  38731. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38732. label->showEditor();
  38733. }
  38734. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38735. {
  38736. if (textWhenNothingSelected != newMessage)
  38737. {
  38738. textWhenNothingSelected = newMessage;
  38739. repaint();
  38740. }
  38741. }
  38742. const String ComboBox::getTextWhenNothingSelected() const
  38743. {
  38744. return textWhenNothingSelected;
  38745. }
  38746. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38747. {
  38748. noChoicesMessage = newMessage;
  38749. }
  38750. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38751. {
  38752. return noChoicesMessage;
  38753. }
  38754. void ComboBox::paint (Graphics& g)
  38755. {
  38756. getLookAndFeel().drawComboBox (g,
  38757. getWidth(),
  38758. getHeight(),
  38759. isButtonDown,
  38760. label->getRight(),
  38761. 0,
  38762. getWidth() - label->getRight(),
  38763. getHeight(),
  38764. *this);
  38765. if (textWhenNothingSelected.isNotEmpty()
  38766. && label->getText().isEmpty()
  38767. && ! label->isBeingEdited())
  38768. {
  38769. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38770. g.setFont (label->getFont());
  38771. g.drawFittedText (textWhenNothingSelected,
  38772. label->getX() + 2, label->getY() + 1,
  38773. label->getWidth() - 4, label->getHeight() - 2,
  38774. label->getJustificationType(),
  38775. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38776. }
  38777. }
  38778. void ComboBox::resized()
  38779. {
  38780. if (getHeight() > 0 && getWidth() > 0)
  38781. getLookAndFeel().positionComboBoxText (*this, *label);
  38782. }
  38783. void ComboBox::enablementChanged()
  38784. {
  38785. repaint();
  38786. }
  38787. void ComboBox::lookAndFeelChanged()
  38788. {
  38789. repaint();
  38790. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38791. if (label != 0)
  38792. {
  38793. newLabel->setEditable (label->isEditable());
  38794. newLabel->setJustificationType (label->getJustificationType());
  38795. newLabel->setTooltip (label->getTooltip());
  38796. newLabel->setText (label->getText(), false);
  38797. }
  38798. label = newLabel;
  38799. addAndMakeVisible (newLabel);
  38800. newLabel->addListener (this);
  38801. newLabel->addMouseListener (this, false);
  38802. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38803. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38804. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38805. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38806. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38807. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38808. resized();
  38809. }
  38810. void ComboBox::colourChanged()
  38811. {
  38812. lookAndFeelChanged();
  38813. }
  38814. bool ComboBox::keyPressed (const KeyPress& key)
  38815. {
  38816. bool used = false;
  38817. if (key.isKeyCode (KeyPress::upKey)
  38818. || key.isKeyCode (KeyPress::leftKey))
  38819. {
  38820. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38821. used = true;
  38822. }
  38823. else if (key.isKeyCode (KeyPress::downKey)
  38824. || key.isKeyCode (KeyPress::rightKey))
  38825. {
  38826. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38827. used = true;
  38828. }
  38829. else if (key.isKeyCode (KeyPress::returnKey))
  38830. {
  38831. showPopup();
  38832. used = true;
  38833. }
  38834. return used;
  38835. }
  38836. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38837. {
  38838. // only forward key events that aren't used by this component
  38839. return isKeyDown
  38840. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38841. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38842. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38843. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38844. }
  38845. void ComboBox::focusGained (FocusChangeType)
  38846. {
  38847. repaint();
  38848. }
  38849. void ComboBox::focusLost (FocusChangeType)
  38850. {
  38851. repaint();
  38852. }
  38853. void ComboBox::labelTextChanged (Label*)
  38854. {
  38855. triggerAsyncUpdate();
  38856. }
  38857. class ComboBox::Callback : public ModalComponentManager::Callback
  38858. {
  38859. public:
  38860. Callback (ComboBox* const box_)
  38861. : box (box_)
  38862. {
  38863. }
  38864. void modalStateFinished (int returnValue)
  38865. {
  38866. if (box != 0)
  38867. {
  38868. box->menuActive = false;
  38869. if (returnValue != 0)
  38870. box->setSelectedId (returnValue);
  38871. }
  38872. }
  38873. private:
  38874. Component::SafePointer<ComboBox> box;
  38875. Callback (const Callback&);
  38876. Callback& operator= (const Callback&);
  38877. };
  38878. void ComboBox::showPopup()
  38879. {
  38880. if (! menuActive)
  38881. {
  38882. const int selectedId = getSelectedId();
  38883. PopupMenu menu;
  38884. menu.setLookAndFeel (&getLookAndFeel());
  38885. for (int i = 0; i < items.size(); ++i)
  38886. {
  38887. const ItemInfo* const item = items.getUnchecked(i);
  38888. if (item->isSeparator())
  38889. menu.addSeparator();
  38890. else if (item->isHeading)
  38891. menu.addSectionHeader (item->name);
  38892. else
  38893. menu.addItem (item->itemId, item->name,
  38894. item->isEnabled, item->itemId == selectedId);
  38895. }
  38896. if (items.size() == 0)
  38897. menu.addItem (1, noChoicesMessage, false);
  38898. menuActive = true;
  38899. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38900. new Callback (this));
  38901. }
  38902. }
  38903. void ComboBox::mouseDown (const MouseEvent& e)
  38904. {
  38905. beginDragAutoRepeat (300);
  38906. isButtonDown = isEnabled();
  38907. if (isButtonDown
  38908. && (e.eventComponent == this || ! label->isEditable()))
  38909. {
  38910. showPopup();
  38911. }
  38912. }
  38913. void ComboBox::mouseDrag (const MouseEvent& e)
  38914. {
  38915. beginDragAutoRepeat (50);
  38916. if (isButtonDown && ! e.mouseWasClicked())
  38917. showPopup();
  38918. }
  38919. void ComboBox::mouseUp (const MouseEvent& e2)
  38920. {
  38921. if (isButtonDown)
  38922. {
  38923. isButtonDown = false;
  38924. repaint();
  38925. const MouseEvent e (e2.getEventRelativeTo (this));
  38926. if (reallyContains (e.x, e.y, true)
  38927. && (e2.eventComponent == this || ! label->isEditable()))
  38928. {
  38929. showPopup();
  38930. }
  38931. }
  38932. }
  38933. void ComboBox::addListener (Listener* const listener)
  38934. {
  38935. listeners.add (listener);
  38936. }
  38937. void ComboBox::removeListener (Listener* const listener)
  38938. {
  38939. listeners.remove (listener);
  38940. }
  38941. void ComboBox::handleAsyncUpdate()
  38942. {
  38943. Component::BailOutChecker checker (this);
  38944. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38945. }
  38946. END_JUCE_NAMESPACE
  38947. /*** End of inlined file: juce_ComboBox.cpp ***/
  38948. /*** Start of inlined file: juce_Label.cpp ***/
  38949. BEGIN_JUCE_NAMESPACE
  38950. Label::Label (const String& componentName,
  38951. const String& labelText)
  38952. : Component (componentName),
  38953. textValue (labelText),
  38954. lastTextValue (labelText),
  38955. font (15.0f),
  38956. justification (Justification::centredLeft),
  38957. ownerComponent (0),
  38958. horizontalBorderSize (5),
  38959. verticalBorderSize (1),
  38960. minimumHorizontalScale (0.7f),
  38961. editSingleClick (false),
  38962. editDoubleClick (false),
  38963. lossOfFocusDiscardsChanges (false)
  38964. {
  38965. setColour (TextEditor::textColourId, Colours::black);
  38966. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38967. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38968. textValue.addListener (this);
  38969. }
  38970. Label::~Label()
  38971. {
  38972. textValue.removeListener (this);
  38973. if (ownerComponent != 0)
  38974. ownerComponent->removeComponentListener (this);
  38975. editor = 0;
  38976. }
  38977. void Label::setText (const String& newText,
  38978. const bool broadcastChangeMessage)
  38979. {
  38980. hideEditor (true);
  38981. if (lastTextValue != newText)
  38982. {
  38983. lastTextValue = newText;
  38984. textValue = newText;
  38985. repaint();
  38986. textWasChanged();
  38987. if (ownerComponent != 0)
  38988. componentMovedOrResized (*ownerComponent, true, true);
  38989. if (broadcastChangeMessage)
  38990. callChangeListeners();
  38991. }
  38992. }
  38993. const String Label::getText (const bool returnActiveEditorContents) const
  38994. {
  38995. return (returnActiveEditorContents && isBeingEdited())
  38996. ? editor->getText()
  38997. : textValue.toString();
  38998. }
  38999. void Label::valueChanged (Value&)
  39000. {
  39001. if (lastTextValue != textValue.toString())
  39002. setText (textValue.toString(), true);
  39003. }
  39004. void Label::setFont (const Font& newFont)
  39005. {
  39006. if (font != newFont)
  39007. {
  39008. font = newFont;
  39009. repaint();
  39010. }
  39011. }
  39012. const Font& Label::getFont() const throw()
  39013. {
  39014. return font;
  39015. }
  39016. void Label::setEditable (const bool editOnSingleClick,
  39017. const bool editOnDoubleClick,
  39018. const bool lossOfFocusDiscardsChanges_)
  39019. {
  39020. editSingleClick = editOnSingleClick;
  39021. editDoubleClick = editOnDoubleClick;
  39022. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  39023. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  39024. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  39025. }
  39026. void Label::setJustificationType (const Justification& newJustification)
  39027. {
  39028. if (justification != newJustification)
  39029. {
  39030. justification = newJustification;
  39031. repaint();
  39032. }
  39033. }
  39034. void Label::setBorderSize (int h, int v)
  39035. {
  39036. if (horizontalBorderSize != h || verticalBorderSize != v)
  39037. {
  39038. horizontalBorderSize = h;
  39039. verticalBorderSize = v;
  39040. repaint();
  39041. }
  39042. }
  39043. Component* Label::getAttachedComponent() const
  39044. {
  39045. return static_cast<Component*> (ownerComponent);
  39046. }
  39047. void Label::attachToComponent (Component* owner,
  39048. const bool onLeft)
  39049. {
  39050. if (ownerComponent != 0)
  39051. ownerComponent->removeComponentListener (this);
  39052. ownerComponent = owner;
  39053. leftOfOwnerComp = onLeft;
  39054. if (ownerComponent != 0)
  39055. {
  39056. setVisible (owner->isVisible());
  39057. ownerComponent->addComponentListener (this);
  39058. componentParentHierarchyChanged (*ownerComponent);
  39059. componentMovedOrResized (*ownerComponent, true, true);
  39060. }
  39061. }
  39062. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  39063. {
  39064. if (leftOfOwnerComp)
  39065. {
  39066. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  39067. component.getHeight());
  39068. setTopRightPosition (component.getX(), component.getY());
  39069. }
  39070. else
  39071. {
  39072. setSize (component.getWidth(),
  39073. 8 + roundToInt (getFont().getHeight()));
  39074. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  39075. }
  39076. }
  39077. void Label::componentParentHierarchyChanged (Component& component)
  39078. {
  39079. if (component.getParentComponent() != 0)
  39080. component.getParentComponent()->addChildComponent (this);
  39081. }
  39082. void Label::componentVisibilityChanged (Component& component)
  39083. {
  39084. setVisible (component.isVisible());
  39085. }
  39086. void Label::textWasEdited()
  39087. {
  39088. }
  39089. void Label::textWasChanged()
  39090. {
  39091. }
  39092. void Label::showEditor()
  39093. {
  39094. if (editor == 0)
  39095. {
  39096. addAndMakeVisible (editor = createEditorComponent());
  39097. editor->setText (getText(), false);
  39098. editor->addListener (this);
  39099. editor->grabKeyboardFocus();
  39100. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  39101. editor->addListener (this);
  39102. resized();
  39103. repaint();
  39104. editorShown (editor);
  39105. enterModalState (false);
  39106. editor->grabKeyboardFocus();
  39107. }
  39108. }
  39109. void Label::editorShown (TextEditor* /*editorComponent*/)
  39110. {
  39111. }
  39112. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  39113. {
  39114. }
  39115. bool Label::updateFromTextEditorContents()
  39116. {
  39117. jassert (editor != 0);
  39118. const String newText (editor->getText());
  39119. if (textValue.toString() != newText)
  39120. {
  39121. lastTextValue = newText;
  39122. textValue = newText;
  39123. repaint();
  39124. textWasChanged();
  39125. if (ownerComponent != 0)
  39126. componentMovedOrResized (*ownerComponent, true, true);
  39127. return true;
  39128. }
  39129. return false;
  39130. }
  39131. void Label::hideEditor (const bool discardCurrentEditorContents)
  39132. {
  39133. if (editor != 0)
  39134. {
  39135. Component::SafePointer<Component> deletionChecker (this);
  39136. editorAboutToBeHidden (editor);
  39137. const bool changed = (! discardCurrentEditorContents)
  39138. && updateFromTextEditorContents();
  39139. editor = 0;
  39140. repaint();
  39141. if (changed)
  39142. textWasEdited();
  39143. if (deletionChecker != 0)
  39144. exitModalState (0);
  39145. if (changed && deletionChecker != 0)
  39146. callChangeListeners();
  39147. }
  39148. }
  39149. void Label::inputAttemptWhenModal()
  39150. {
  39151. if (editor != 0)
  39152. {
  39153. if (lossOfFocusDiscardsChanges)
  39154. textEditorEscapeKeyPressed (*editor);
  39155. else
  39156. textEditorReturnKeyPressed (*editor);
  39157. }
  39158. }
  39159. bool Label::isBeingEdited() const throw()
  39160. {
  39161. return editor != 0;
  39162. }
  39163. TextEditor* Label::createEditorComponent()
  39164. {
  39165. TextEditor* const ed = new TextEditor (getName());
  39166. ed->setFont (font);
  39167. // copy these colours from our own settings..
  39168. const int cols[] = { TextEditor::backgroundColourId,
  39169. TextEditor::textColourId,
  39170. TextEditor::highlightColourId,
  39171. TextEditor::highlightedTextColourId,
  39172. TextEditor::caretColourId,
  39173. TextEditor::outlineColourId,
  39174. TextEditor::focusedOutlineColourId,
  39175. TextEditor::shadowColourId };
  39176. for (int i = 0; i < numElementsInArray (cols); ++i)
  39177. ed->setColour (cols[i], findColour (cols[i]));
  39178. return ed;
  39179. }
  39180. void Label::paint (Graphics& g)
  39181. {
  39182. getLookAndFeel().drawLabel (g, *this);
  39183. }
  39184. void Label::mouseUp (const MouseEvent& e)
  39185. {
  39186. if (editSingleClick
  39187. && e.mouseWasClicked()
  39188. && contains (e.x, e.y)
  39189. && ! e.mods.isPopupMenu())
  39190. {
  39191. showEditor();
  39192. }
  39193. }
  39194. void Label::mouseDoubleClick (const MouseEvent& e)
  39195. {
  39196. if (editDoubleClick && ! e.mods.isPopupMenu())
  39197. showEditor();
  39198. }
  39199. void Label::resized()
  39200. {
  39201. if (editor != 0)
  39202. editor->setBoundsInset (BorderSize (0));
  39203. }
  39204. void Label::focusGained (FocusChangeType cause)
  39205. {
  39206. if (editSingleClick && cause == focusChangedByTabKey)
  39207. showEditor();
  39208. }
  39209. void Label::enablementChanged()
  39210. {
  39211. repaint();
  39212. }
  39213. void Label::colourChanged()
  39214. {
  39215. repaint();
  39216. }
  39217. void Label::setMinimumHorizontalScale (const float newScale)
  39218. {
  39219. if (minimumHorizontalScale != newScale)
  39220. {
  39221. minimumHorizontalScale = newScale;
  39222. repaint();
  39223. }
  39224. }
  39225. // We'll use a custom focus traverser here to make sure focus goes from the
  39226. // text editor to another component rather than back to the label itself.
  39227. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  39228. {
  39229. public:
  39230. LabelKeyboardFocusTraverser() {}
  39231. Component* getNextComponent (Component* current)
  39232. {
  39233. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  39234. ? current->getParentComponent() : current);
  39235. }
  39236. Component* getPreviousComponent (Component* current)
  39237. {
  39238. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  39239. ? current->getParentComponent() : current);
  39240. }
  39241. };
  39242. KeyboardFocusTraverser* Label::createFocusTraverser()
  39243. {
  39244. return new LabelKeyboardFocusTraverser();
  39245. }
  39246. void Label::addListener (Listener* const listener)
  39247. {
  39248. listeners.add (listener);
  39249. }
  39250. void Label::removeListener (Listener* const listener)
  39251. {
  39252. listeners.remove (listener);
  39253. }
  39254. void Label::callChangeListeners()
  39255. {
  39256. Component::BailOutChecker checker (this);
  39257. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  39258. }
  39259. void Label::textEditorTextChanged (TextEditor& ed)
  39260. {
  39261. if (editor != 0)
  39262. {
  39263. jassert (&ed == editor);
  39264. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  39265. {
  39266. if (lossOfFocusDiscardsChanges)
  39267. textEditorEscapeKeyPressed (ed);
  39268. else
  39269. textEditorReturnKeyPressed (ed);
  39270. }
  39271. }
  39272. }
  39273. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  39274. {
  39275. if (editor != 0)
  39276. {
  39277. jassert (&ed == editor);
  39278. (void) ed;
  39279. const bool changed = updateFromTextEditorContents();
  39280. hideEditor (true);
  39281. if (changed)
  39282. {
  39283. Component::SafePointer<Component> deletionChecker (this);
  39284. textWasEdited();
  39285. if (deletionChecker != 0)
  39286. callChangeListeners();
  39287. }
  39288. }
  39289. }
  39290. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  39291. {
  39292. if (editor != 0)
  39293. {
  39294. jassert (&ed == editor);
  39295. (void) ed;
  39296. editor->setText (textValue.toString(), false);
  39297. hideEditor (true);
  39298. }
  39299. }
  39300. void Label::textEditorFocusLost (TextEditor& ed)
  39301. {
  39302. textEditorTextChanged (ed);
  39303. }
  39304. END_JUCE_NAMESPACE
  39305. /*** End of inlined file: juce_Label.cpp ***/
  39306. /*** Start of inlined file: juce_ListBox.cpp ***/
  39307. BEGIN_JUCE_NAMESPACE
  39308. class ListBoxRowComponent : public Component,
  39309. public TooltipClient
  39310. {
  39311. public:
  39312. ListBoxRowComponent (ListBox& owner_)
  39313. : owner (owner_),
  39314. row (-1),
  39315. selected (false),
  39316. isDragging (false)
  39317. {
  39318. }
  39319. ~ListBoxRowComponent()
  39320. {
  39321. deleteAllChildren();
  39322. }
  39323. void paint (Graphics& g)
  39324. {
  39325. if (owner.getModel() != 0)
  39326. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39327. }
  39328. void update (const int row_, const bool selected_)
  39329. {
  39330. if (row != row_ || selected != selected_)
  39331. {
  39332. repaint();
  39333. row = row_;
  39334. selected = selected_;
  39335. }
  39336. if (owner.getModel() != 0)
  39337. {
  39338. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  39339. if (customComp != 0)
  39340. {
  39341. addAndMakeVisible (customComp);
  39342. customComp->setBounds (getLocalBounds());
  39343. for (int i = getNumChildComponents(); --i >= 0;)
  39344. if (getChildComponent (i) != customComp)
  39345. delete getChildComponent (i);
  39346. }
  39347. else
  39348. {
  39349. deleteAllChildren();
  39350. }
  39351. }
  39352. }
  39353. void mouseDown (const MouseEvent& e)
  39354. {
  39355. isDragging = false;
  39356. selectRowOnMouseUp = false;
  39357. if (isEnabled())
  39358. {
  39359. if (! selected)
  39360. {
  39361. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39362. if (owner.getModel() != 0)
  39363. owner.getModel()->listBoxItemClicked (row, e);
  39364. }
  39365. else
  39366. {
  39367. selectRowOnMouseUp = true;
  39368. }
  39369. }
  39370. }
  39371. void mouseUp (const MouseEvent& e)
  39372. {
  39373. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39374. {
  39375. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39376. if (owner.getModel() != 0)
  39377. owner.getModel()->listBoxItemClicked (row, e);
  39378. }
  39379. }
  39380. void mouseDoubleClick (const MouseEvent& e)
  39381. {
  39382. if (owner.getModel() != 0 && isEnabled())
  39383. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39384. }
  39385. void mouseDrag (const MouseEvent& e)
  39386. {
  39387. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39388. {
  39389. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39390. if (selectedRows.size() > 0)
  39391. {
  39392. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39393. if (dragDescription.isNotEmpty())
  39394. {
  39395. isDragging = true;
  39396. owner.startDragAndDrop (e, dragDescription);
  39397. }
  39398. }
  39399. }
  39400. }
  39401. void resized()
  39402. {
  39403. if (getNumChildComponents() > 0)
  39404. getChildComponent(0)->setBounds (getLocalBounds());
  39405. }
  39406. const String getTooltip()
  39407. {
  39408. if (owner.getModel() != 0)
  39409. return owner.getModel()->getTooltipForRow (row);
  39410. return String::empty;
  39411. }
  39412. juce_UseDebuggingNewOperator
  39413. bool neededFlag;
  39414. private:
  39415. ListBox& owner;
  39416. int row;
  39417. bool selected, isDragging, selectRowOnMouseUp;
  39418. ListBoxRowComponent (const ListBoxRowComponent&);
  39419. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39420. };
  39421. class ListViewport : public Viewport
  39422. {
  39423. public:
  39424. int firstIndex, firstWholeIndex, lastWholeIndex;
  39425. bool hasUpdated;
  39426. ListViewport (ListBox& owner_)
  39427. : owner (owner_)
  39428. {
  39429. setWantsKeyboardFocus (false);
  39430. setViewedComponent (new Component());
  39431. getViewedComponent()->addMouseListener (this, false);
  39432. getViewedComponent()->setWantsKeyboardFocus (false);
  39433. }
  39434. ~ListViewport()
  39435. {
  39436. getViewedComponent()->removeMouseListener (this);
  39437. getViewedComponent()->deleteAllChildren();
  39438. }
  39439. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39440. {
  39441. return static_cast <ListBoxRowComponent*>
  39442. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39443. }
  39444. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39445. {
  39446. const int index = getIndexOfChildComponent (rowComponent);
  39447. const int num = getViewedComponent()->getNumChildComponents();
  39448. for (int i = num; --i >= 0;)
  39449. if (((firstIndex + i) % jmax (1, num)) == index)
  39450. return firstIndex + i;
  39451. return -1;
  39452. }
  39453. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39454. {
  39455. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39456. ? getComponentForRow (row) : 0;
  39457. }
  39458. void visibleAreaChanged (int, int, int, int)
  39459. {
  39460. updateVisibleArea (true);
  39461. if (owner.getModel() != 0)
  39462. owner.getModel()->listWasScrolled();
  39463. }
  39464. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39465. {
  39466. hasUpdated = false;
  39467. const int newX = getViewedComponent()->getX();
  39468. int newY = getViewedComponent()->getY();
  39469. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39470. const int newH = owner.totalItems * owner.getRowHeight();
  39471. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39472. newY = getMaximumVisibleHeight() - newH;
  39473. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39474. if (makeSureItUpdatesContent && ! hasUpdated)
  39475. updateContents();
  39476. }
  39477. void updateContents()
  39478. {
  39479. hasUpdated = true;
  39480. const int rowHeight = owner.getRowHeight();
  39481. if (rowHeight > 0)
  39482. {
  39483. const int y = getViewPositionY();
  39484. const int w = getViewedComponent()->getWidth();
  39485. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39486. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39487. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39488. jassert (numNeeded >= 0);
  39489. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39490. {
  39491. Component* const rowToRemove
  39492. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39493. delete rowToRemove;
  39494. }
  39495. firstIndex = y / rowHeight;
  39496. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39497. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39498. for (int i = 0; i < numNeeded; ++i)
  39499. {
  39500. const int row = i + firstIndex;
  39501. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39502. if (rowComp != 0)
  39503. {
  39504. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39505. rowComp->update (row, owner.isRowSelected (row));
  39506. }
  39507. }
  39508. }
  39509. if (owner.headerComponent != 0)
  39510. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39511. owner.outlineThickness,
  39512. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39513. getViewedComponent()->getWidth()),
  39514. owner.headerComponent->getHeight());
  39515. }
  39516. void paint (Graphics& g)
  39517. {
  39518. if (isOpaque())
  39519. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39520. }
  39521. bool keyPressed (const KeyPress& key)
  39522. {
  39523. if (key.isKeyCode (KeyPress::upKey)
  39524. || key.isKeyCode (KeyPress::downKey)
  39525. || key.isKeyCode (KeyPress::pageUpKey)
  39526. || key.isKeyCode (KeyPress::pageDownKey)
  39527. || key.isKeyCode (KeyPress::homeKey)
  39528. || key.isKeyCode (KeyPress::endKey))
  39529. {
  39530. // we want to avoid these keypresses going to the viewport, and instead allow
  39531. // them to pass up to our listbox..
  39532. return false;
  39533. }
  39534. return Viewport::keyPressed (key);
  39535. }
  39536. juce_UseDebuggingNewOperator
  39537. private:
  39538. ListBox& owner;
  39539. ListViewport (const ListViewport&);
  39540. ListViewport& operator= (const ListViewport&);
  39541. };
  39542. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39543. : Component (name),
  39544. model (model_),
  39545. totalItems (0),
  39546. rowHeight (22),
  39547. minimumRowWidth (0),
  39548. outlineThickness (0),
  39549. lastRowSelected (-1),
  39550. mouseMoveSelects (false),
  39551. multipleSelection (false),
  39552. hasDoneInitialUpdate (false)
  39553. {
  39554. addAndMakeVisible (viewport = new ListViewport (*this));
  39555. setWantsKeyboardFocus (true);
  39556. colourChanged();
  39557. }
  39558. ListBox::~ListBox()
  39559. {
  39560. headerComponent = 0;
  39561. viewport = 0;
  39562. }
  39563. void ListBox::setModel (ListBoxModel* const newModel)
  39564. {
  39565. if (model != newModel)
  39566. {
  39567. model = newModel;
  39568. updateContent();
  39569. }
  39570. }
  39571. void ListBox::setMultipleSelectionEnabled (bool b)
  39572. {
  39573. multipleSelection = b;
  39574. }
  39575. void ListBox::setMouseMoveSelectsRows (bool b)
  39576. {
  39577. mouseMoveSelects = b;
  39578. if (b)
  39579. addMouseListener (this, true);
  39580. }
  39581. void ListBox::paint (Graphics& g)
  39582. {
  39583. if (! hasDoneInitialUpdate)
  39584. updateContent();
  39585. g.fillAll (findColour (backgroundColourId));
  39586. }
  39587. void ListBox::paintOverChildren (Graphics& g)
  39588. {
  39589. if (outlineThickness > 0)
  39590. {
  39591. g.setColour (findColour (outlineColourId));
  39592. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39593. }
  39594. }
  39595. void ListBox::resized()
  39596. {
  39597. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39598. outlineThickness,
  39599. outlineThickness,
  39600. outlineThickness));
  39601. viewport->setSingleStepSizes (20, getRowHeight());
  39602. viewport->updateVisibleArea (false);
  39603. }
  39604. void ListBox::visibilityChanged()
  39605. {
  39606. viewport->updateVisibleArea (true);
  39607. }
  39608. Viewport* ListBox::getViewport() const throw()
  39609. {
  39610. return viewport;
  39611. }
  39612. void ListBox::updateContent()
  39613. {
  39614. hasDoneInitialUpdate = true;
  39615. totalItems = (model != 0) ? model->getNumRows() : 0;
  39616. bool selectionChanged = false;
  39617. if (selected [selected.size() - 1] >= totalItems)
  39618. {
  39619. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39620. lastRowSelected = getSelectedRow (0);
  39621. selectionChanged = true;
  39622. }
  39623. viewport->updateVisibleArea (isVisible());
  39624. viewport->resized();
  39625. if (selectionChanged && model != 0)
  39626. model->selectedRowsChanged (lastRowSelected);
  39627. }
  39628. void ListBox::selectRow (const int row,
  39629. bool dontScroll,
  39630. bool deselectOthersFirst)
  39631. {
  39632. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39633. }
  39634. void ListBox::selectRowInternal (const int row,
  39635. bool dontScroll,
  39636. bool deselectOthersFirst,
  39637. bool isMouseClick)
  39638. {
  39639. if (! multipleSelection)
  39640. deselectOthersFirst = true;
  39641. if ((! isRowSelected (row))
  39642. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39643. {
  39644. if (((unsigned int) row) < (unsigned int) totalItems)
  39645. {
  39646. if (deselectOthersFirst)
  39647. selected.clear();
  39648. selected.addRange (Range<int> (row, row + 1));
  39649. if (getHeight() == 0 || getWidth() == 0)
  39650. dontScroll = true;
  39651. viewport->hasUpdated = false;
  39652. if (row < viewport->firstWholeIndex && ! dontScroll)
  39653. {
  39654. viewport->setViewPosition (viewport->getViewPositionX(),
  39655. row * getRowHeight());
  39656. }
  39657. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39658. {
  39659. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39660. if (row >= lastRowSelected + rowsOnScreen
  39661. && rowsOnScreen < totalItems - 1
  39662. && ! isMouseClick)
  39663. {
  39664. viewport->setViewPosition (viewport->getViewPositionX(),
  39665. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39666. * getRowHeight());
  39667. }
  39668. else
  39669. {
  39670. viewport->setViewPosition (viewport->getViewPositionX(),
  39671. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39672. }
  39673. }
  39674. if (! viewport->hasUpdated)
  39675. viewport->updateContents();
  39676. lastRowSelected = row;
  39677. model->selectedRowsChanged (row);
  39678. }
  39679. else
  39680. {
  39681. if (deselectOthersFirst)
  39682. deselectAllRows();
  39683. }
  39684. }
  39685. }
  39686. void ListBox::deselectRow (const int row)
  39687. {
  39688. if (selected.contains (row))
  39689. {
  39690. selected.removeRange (Range <int> (row, row + 1));
  39691. if (row == lastRowSelected)
  39692. lastRowSelected = getSelectedRow (0);
  39693. viewport->updateContents();
  39694. model->selectedRowsChanged (lastRowSelected);
  39695. }
  39696. }
  39697. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39698. const bool sendNotificationEventToModel)
  39699. {
  39700. selected = setOfRowsToBeSelected;
  39701. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39702. if (! isRowSelected (lastRowSelected))
  39703. lastRowSelected = getSelectedRow (0);
  39704. viewport->updateContents();
  39705. if ((model != 0) && sendNotificationEventToModel)
  39706. model->selectedRowsChanged (lastRowSelected);
  39707. }
  39708. const SparseSet<int> ListBox::getSelectedRows() const
  39709. {
  39710. return selected;
  39711. }
  39712. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39713. {
  39714. if (multipleSelection && (firstRow != lastRow))
  39715. {
  39716. const int numRows = totalItems - 1;
  39717. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39718. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39719. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39720. jmax (firstRow, lastRow) + 1));
  39721. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39722. }
  39723. selectRowInternal (lastRow, false, false, true);
  39724. }
  39725. void ListBox::flipRowSelection (const int row)
  39726. {
  39727. if (isRowSelected (row))
  39728. deselectRow (row);
  39729. else
  39730. selectRowInternal (row, false, false, true);
  39731. }
  39732. void ListBox::deselectAllRows()
  39733. {
  39734. if (! selected.isEmpty())
  39735. {
  39736. selected.clear();
  39737. lastRowSelected = -1;
  39738. viewport->updateContents();
  39739. if (model != 0)
  39740. model->selectedRowsChanged (lastRowSelected);
  39741. }
  39742. }
  39743. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39744. const ModifierKeys& mods)
  39745. {
  39746. if (multipleSelection && mods.isCommandDown())
  39747. {
  39748. flipRowSelection (row);
  39749. }
  39750. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39751. {
  39752. selectRangeOfRows (lastRowSelected, row);
  39753. }
  39754. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39755. {
  39756. selectRowInternal (row, false, true, true);
  39757. }
  39758. }
  39759. int ListBox::getNumSelectedRows() const
  39760. {
  39761. return selected.size();
  39762. }
  39763. int ListBox::getSelectedRow (const int index) const
  39764. {
  39765. return (((unsigned int) index) < (unsigned int) selected.size())
  39766. ? selected [index] : -1;
  39767. }
  39768. bool ListBox::isRowSelected (const int row) const
  39769. {
  39770. return selected.contains (row);
  39771. }
  39772. int ListBox::getLastRowSelected() const
  39773. {
  39774. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39775. }
  39776. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39777. {
  39778. if (((unsigned int) x) < (unsigned int) getWidth())
  39779. {
  39780. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39781. if (((unsigned int) row) < (unsigned int) totalItems)
  39782. return row;
  39783. }
  39784. return -1;
  39785. }
  39786. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39787. {
  39788. if (((unsigned int) x) < (unsigned int) getWidth())
  39789. {
  39790. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39791. return jlimit (0, totalItems, row);
  39792. }
  39793. return -1;
  39794. }
  39795. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39796. {
  39797. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39798. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39799. }
  39800. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39801. {
  39802. return viewport->getRowNumberOfComponent (rowComponent);
  39803. }
  39804. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39805. const bool relativeToComponentTopLeft) const throw()
  39806. {
  39807. int y = viewport->getY() + rowHeight * rowNumber;
  39808. if (relativeToComponentTopLeft)
  39809. y -= viewport->getViewPositionY();
  39810. return Rectangle<int> (viewport->getX(), y,
  39811. viewport->getViewedComponent()->getWidth(), rowHeight);
  39812. }
  39813. void ListBox::setVerticalPosition (const double proportion)
  39814. {
  39815. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39816. viewport->setViewPosition (viewport->getViewPositionX(),
  39817. jmax (0, roundToInt (proportion * offscreen)));
  39818. }
  39819. double ListBox::getVerticalPosition() const
  39820. {
  39821. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39822. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39823. : 0;
  39824. }
  39825. int ListBox::getVisibleRowWidth() const throw()
  39826. {
  39827. return viewport->getViewWidth();
  39828. }
  39829. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39830. {
  39831. if (row < viewport->firstWholeIndex)
  39832. {
  39833. viewport->setViewPosition (viewport->getViewPositionX(),
  39834. row * getRowHeight());
  39835. }
  39836. else if (row >= viewport->lastWholeIndex)
  39837. {
  39838. viewport->setViewPosition (viewport->getViewPositionX(),
  39839. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39840. }
  39841. }
  39842. bool ListBox::keyPressed (const KeyPress& key)
  39843. {
  39844. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39845. const bool multiple = multipleSelection
  39846. && (lastRowSelected >= 0)
  39847. && (key.getModifiers().isShiftDown()
  39848. || key.getModifiers().isCtrlDown()
  39849. || key.getModifiers().isCommandDown());
  39850. if (key.isKeyCode (KeyPress::upKey))
  39851. {
  39852. if (multiple)
  39853. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39854. else
  39855. selectRow (jmax (0, lastRowSelected - 1));
  39856. }
  39857. else if (key.isKeyCode (KeyPress::returnKey)
  39858. && isRowSelected (lastRowSelected))
  39859. {
  39860. if (model != 0)
  39861. model->returnKeyPressed (lastRowSelected);
  39862. }
  39863. else if (key.isKeyCode (KeyPress::pageUpKey))
  39864. {
  39865. if (multiple)
  39866. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39867. else
  39868. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39869. }
  39870. else if (key.isKeyCode (KeyPress::pageDownKey))
  39871. {
  39872. if (multiple)
  39873. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39874. else
  39875. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39876. }
  39877. else if (key.isKeyCode (KeyPress::homeKey))
  39878. {
  39879. if (multiple && key.getModifiers().isShiftDown())
  39880. selectRangeOfRows (lastRowSelected, 0);
  39881. else
  39882. selectRow (0);
  39883. }
  39884. else if (key.isKeyCode (KeyPress::endKey))
  39885. {
  39886. if (multiple && key.getModifiers().isShiftDown())
  39887. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39888. else
  39889. selectRow (totalItems - 1);
  39890. }
  39891. else if (key.isKeyCode (KeyPress::downKey))
  39892. {
  39893. if (multiple)
  39894. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39895. else
  39896. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39897. }
  39898. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39899. && isRowSelected (lastRowSelected))
  39900. {
  39901. if (model != 0)
  39902. model->deleteKeyPressed (lastRowSelected);
  39903. }
  39904. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39905. {
  39906. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39907. }
  39908. else
  39909. {
  39910. return false;
  39911. }
  39912. return true;
  39913. }
  39914. bool ListBox::keyStateChanged (const bool isKeyDown)
  39915. {
  39916. return isKeyDown
  39917. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39918. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39919. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39920. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39921. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39922. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39923. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39924. }
  39925. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39926. {
  39927. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39928. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39929. }
  39930. void ListBox::mouseMove (const MouseEvent& e)
  39931. {
  39932. if (mouseMoveSelects)
  39933. {
  39934. const MouseEvent e2 (e.getEventRelativeTo (this));
  39935. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39936. }
  39937. }
  39938. void ListBox::mouseExit (const MouseEvent& e)
  39939. {
  39940. mouseMove (e);
  39941. }
  39942. void ListBox::mouseUp (const MouseEvent& e)
  39943. {
  39944. if (e.mouseWasClicked() && model != 0)
  39945. model->backgroundClicked();
  39946. }
  39947. void ListBox::setRowHeight (const int newHeight)
  39948. {
  39949. rowHeight = jmax (1, newHeight);
  39950. viewport->setSingleStepSizes (20, rowHeight);
  39951. updateContent();
  39952. }
  39953. int ListBox::getNumRowsOnScreen() const throw()
  39954. {
  39955. return viewport->getMaximumVisibleHeight() / rowHeight;
  39956. }
  39957. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39958. {
  39959. minimumRowWidth = newMinimumWidth;
  39960. updateContent();
  39961. }
  39962. int ListBox::getVisibleContentWidth() const throw()
  39963. {
  39964. return viewport->getMaximumVisibleWidth();
  39965. }
  39966. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39967. {
  39968. return viewport->getVerticalScrollBar();
  39969. }
  39970. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39971. {
  39972. return viewport->getHorizontalScrollBar();
  39973. }
  39974. void ListBox::colourChanged()
  39975. {
  39976. setOpaque (findColour (backgroundColourId).isOpaque());
  39977. viewport->setOpaque (isOpaque());
  39978. repaint();
  39979. }
  39980. void ListBox::setOutlineThickness (const int outlineThickness_)
  39981. {
  39982. outlineThickness = outlineThickness_;
  39983. resized();
  39984. }
  39985. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39986. {
  39987. if (newHeaderComponent != headerComponent)
  39988. {
  39989. headerComponent = newHeaderComponent;
  39990. addAndMakeVisible (newHeaderComponent);
  39991. ListBox::resized();
  39992. }
  39993. }
  39994. void ListBox::repaintRow (const int rowNumber) throw()
  39995. {
  39996. repaint (getRowPosition (rowNumber, true));
  39997. }
  39998. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39999. {
  40000. Rectangle<int> imageArea;
  40001. const int firstRow = getRowContainingPosition (0, 0);
  40002. int i;
  40003. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  40004. {
  40005. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  40006. if (rowComp != 0 && isRowSelected (firstRow + i))
  40007. {
  40008. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  40009. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  40010. imageArea = imageArea.getUnion (rowRect);
  40011. }
  40012. }
  40013. imageArea = imageArea.getIntersection (getLocalBounds());
  40014. imageX = imageArea.getX();
  40015. imageY = imageArea.getY();
  40016. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  40017. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  40018. {
  40019. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  40020. if (rowComp != 0 && isRowSelected (firstRow + i))
  40021. {
  40022. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  40023. Graphics g (snapshot);
  40024. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  40025. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  40026. rowComp->paintEntireComponent (g);
  40027. }
  40028. }
  40029. return snapshot;
  40030. }
  40031. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  40032. {
  40033. DragAndDropContainer* const dragContainer
  40034. = DragAndDropContainer::findParentDragContainerFor (this);
  40035. if (dragContainer != 0)
  40036. {
  40037. int x, y;
  40038. Image dragImage (createSnapshotOfSelectedRows (x, y));
  40039. dragImage.multiplyAllAlphas (0.6f);
  40040. MouseEvent e2 (e.getEventRelativeTo (this));
  40041. const Point<int> p (x - e2.x, y - e2.y);
  40042. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  40043. }
  40044. else
  40045. {
  40046. // to be able to do a drag-and-drop operation, the listbox needs to
  40047. // be inside a component which is also a DragAndDropContainer.
  40048. jassertfalse;
  40049. }
  40050. }
  40051. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  40052. {
  40053. (void) existingComponentToUpdate;
  40054. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  40055. return 0;
  40056. }
  40057. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  40058. {
  40059. }
  40060. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  40061. {
  40062. }
  40063. void ListBoxModel::backgroundClicked()
  40064. {
  40065. }
  40066. void ListBoxModel::selectedRowsChanged (int)
  40067. {
  40068. }
  40069. void ListBoxModel::deleteKeyPressed (int)
  40070. {
  40071. }
  40072. void ListBoxModel::returnKeyPressed (int)
  40073. {
  40074. }
  40075. void ListBoxModel::listWasScrolled()
  40076. {
  40077. }
  40078. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  40079. {
  40080. return String::empty;
  40081. }
  40082. const String ListBoxModel::getTooltipForRow (int)
  40083. {
  40084. return String::empty;
  40085. }
  40086. END_JUCE_NAMESPACE
  40087. /*** End of inlined file: juce_ListBox.cpp ***/
  40088. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  40089. BEGIN_JUCE_NAMESPACE
  40090. ProgressBar::ProgressBar (double& progress_)
  40091. : progress (progress_),
  40092. displayPercentage (true),
  40093. lastCallbackTime (0)
  40094. {
  40095. currentValue = jlimit (0.0, 1.0, progress);
  40096. }
  40097. ProgressBar::~ProgressBar()
  40098. {
  40099. }
  40100. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  40101. {
  40102. displayPercentage = shouldDisplayPercentage;
  40103. repaint();
  40104. }
  40105. void ProgressBar::setTextToDisplay (const String& text)
  40106. {
  40107. displayPercentage = false;
  40108. displayedMessage = text;
  40109. }
  40110. void ProgressBar::lookAndFeelChanged()
  40111. {
  40112. setOpaque (findColour (backgroundColourId).isOpaque());
  40113. }
  40114. void ProgressBar::colourChanged()
  40115. {
  40116. lookAndFeelChanged();
  40117. }
  40118. void ProgressBar::paint (Graphics& g)
  40119. {
  40120. String text;
  40121. if (displayPercentage)
  40122. {
  40123. if (currentValue >= 0 && currentValue <= 1.0)
  40124. text << roundToInt (currentValue * 100.0) << '%';
  40125. }
  40126. else
  40127. {
  40128. text = displayedMessage;
  40129. }
  40130. getLookAndFeel().drawProgressBar (g, *this,
  40131. getWidth(), getHeight(),
  40132. currentValue, text);
  40133. }
  40134. void ProgressBar::visibilityChanged()
  40135. {
  40136. if (isVisible())
  40137. startTimer (30);
  40138. else
  40139. stopTimer();
  40140. }
  40141. void ProgressBar::timerCallback()
  40142. {
  40143. double newProgress = progress;
  40144. const uint32 now = Time::getMillisecondCounter();
  40145. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  40146. lastCallbackTime = now;
  40147. if (currentValue != newProgress
  40148. || newProgress < 0 || newProgress >= 1.0
  40149. || currentMessage != displayedMessage)
  40150. {
  40151. if (currentValue < newProgress
  40152. && newProgress >= 0 && newProgress < 1.0
  40153. && currentValue >= 0 && currentValue < 1.0)
  40154. {
  40155. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  40156. newProgress);
  40157. }
  40158. currentValue = newProgress;
  40159. currentMessage = displayedMessage;
  40160. repaint();
  40161. }
  40162. }
  40163. END_JUCE_NAMESPACE
  40164. /*** End of inlined file: juce_ProgressBar.cpp ***/
  40165. /*** Start of inlined file: juce_Slider.cpp ***/
  40166. BEGIN_JUCE_NAMESPACE
  40167. class SliderPopupDisplayComponent : public BubbleComponent
  40168. {
  40169. public:
  40170. SliderPopupDisplayComponent (Slider* const owner_)
  40171. : owner (owner_),
  40172. font (15.0f, Font::bold)
  40173. {
  40174. setAlwaysOnTop (true);
  40175. }
  40176. ~SliderPopupDisplayComponent()
  40177. {
  40178. }
  40179. void paintContent (Graphics& g, int w, int h)
  40180. {
  40181. g.setFont (font);
  40182. g.setColour (Colours::black);
  40183. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  40184. }
  40185. void getContentSize (int& w, int& h)
  40186. {
  40187. w = font.getStringWidth (text) + 18;
  40188. h = (int) (font.getHeight() * 1.6f);
  40189. }
  40190. void updatePosition (const String& newText)
  40191. {
  40192. if (text != newText)
  40193. {
  40194. text = newText;
  40195. repaint();
  40196. }
  40197. BubbleComponent::setPosition (owner);
  40198. }
  40199. juce_UseDebuggingNewOperator
  40200. private:
  40201. Slider* owner;
  40202. Font font;
  40203. String text;
  40204. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  40205. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  40206. };
  40207. Slider::Slider (const String& name)
  40208. : Component (name),
  40209. lastCurrentValue (0),
  40210. lastValueMin (0),
  40211. lastValueMax (0),
  40212. minimum (0),
  40213. maximum (10),
  40214. interval (0),
  40215. skewFactor (1.0),
  40216. velocityModeSensitivity (1.0),
  40217. velocityModeOffset (0.0),
  40218. velocityModeThreshold (1),
  40219. rotaryStart (float_Pi * 1.2f),
  40220. rotaryEnd (float_Pi * 2.8f),
  40221. numDecimalPlaces (7),
  40222. sliderRegionStart (0),
  40223. sliderRegionSize (1),
  40224. sliderBeingDragged (-1),
  40225. pixelsForFullDragExtent (250),
  40226. style (LinearHorizontal),
  40227. textBoxPos (TextBoxLeft),
  40228. textBoxWidth (80),
  40229. textBoxHeight (20),
  40230. incDecButtonMode (incDecButtonsNotDraggable),
  40231. editableText (true),
  40232. doubleClickToValue (false),
  40233. isVelocityBased (false),
  40234. userKeyOverridesVelocity (true),
  40235. rotaryStop (true),
  40236. incDecButtonsSideBySide (false),
  40237. sendChangeOnlyOnRelease (false),
  40238. popupDisplayEnabled (false),
  40239. menuEnabled (false),
  40240. menuShown (false),
  40241. scrollWheelEnabled (true),
  40242. snapsToMousePos (true),
  40243. valueBox (0),
  40244. incButton (0),
  40245. decButton (0),
  40246. popupDisplay (0),
  40247. parentForPopupDisplay (0)
  40248. {
  40249. setWantsKeyboardFocus (false);
  40250. setRepaintsOnMouseActivity (true);
  40251. lookAndFeelChanged();
  40252. updateText();
  40253. currentValue.addListener (this);
  40254. valueMin.addListener (this);
  40255. valueMax.addListener (this);
  40256. }
  40257. Slider::~Slider()
  40258. {
  40259. currentValue.removeListener (this);
  40260. valueMin.removeListener (this);
  40261. valueMax.removeListener (this);
  40262. popupDisplay = 0;
  40263. deleteAllChildren();
  40264. }
  40265. void Slider::handleAsyncUpdate()
  40266. {
  40267. cancelPendingUpdate();
  40268. Component::BailOutChecker checker (this);
  40269. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  40270. }
  40271. void Slider::sendDragStart()
  40272. {
  40273. startedDragging();
  40274. Component::BailOutChecker checker (this);
  40275. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  40276. }
  40277. void Slider::sendDragEnd()
  40278. {
  40279. stoppedDragging();
  40280. sliderBeingDragged = -1;
  40281. Component::BailOutChecker checker (this);
  40282. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  40283. }
  40284. void Slider::addListener (Listener* const listener)
  40285. {
  40286. listeners.add (listener);
  40287. }
  40288. void Slider::removeListener (Listener* const listener)
  40289. {
  40290. listeners.remove (listener);
  40291. }
  40292. void Slider::setSliderStyle (const SliderStyle newStyle)
  40293. {
  40294. if (style != newStyle)
  40295. {
  40296. style = newStyle;
  40297. repaint();
  40298. lookAndFeelChanged();
  40299. }
  40300. }
  40301. void Slider::setRotaryParameters (const float startAngleRadians,
  40302. const float endAngleRadians,
  40303. const bool stopAtEnd)
  40304. {
  40305. // make sure the values are sensible..
  40306. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  40307. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  40308. jassert (rotaryStart < rotaryEnd);
  40309. rotaryStart = startAngleRadians;
  40310. rotaryEnd = endAngleRadians;
  40311. rotaryStop = stopAtEnd;
  40312. }
  40313. void Slider::setVelocityBasedMode (const bool velBased)
  40314. {
  40315. isVelocityBased = velBased;
  40316. }
  40317. void Slider::setVelocityModeParameters (const double sensitivity,
  40318. const int threshold,
  40319. const double offset,
  40320. const bool userCanPressKeyToSwapMode)
  40321. {
  40322. jassert (threshold >= 0);
  40323. jassert (sensitivity > 0);
  40324. jassert (offset >= 0);
  40325. velocityModeSensitivity = sensitivity;
  40326. velocityModeOffset = offset;
  40327. velocityModeThreshold = threshold;
  40328. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  40329. }
  40330. void Slider::setSkewFactor (const double factor)
  40331. {
  40332. skewFactor = factor;
  40333. }
  40334. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40335. {
  40336. if (maximum > minimum)
  40337. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40338. / (maximum - minimum));
  40339. }
  40340. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40341. {
  40342. jassert (distanceForFullScaleDrag > 0);
  40343. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40344. }
  40345. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40346. {
  40347. if (incDecButtonMode != mode)
  40348. {
  40349. incDecButtonMode = mode;
  40350. lookAndFeelChanged();
  40351. }
  40352. }
  40353. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40354. const bool isReadOnly,
  40355. const int textEntryBoxWidth,
  40356. const int textEntryBoxHeight)
  40357. {
  40358. if (textBoxPos != newPosition
  40359. || editableText != (! isReadOnly)
  40360. || textBoxWidth != textEntryBoxWidth
  40361. || textBoxHeight != textEntryBoxHeight)
  40362. {
  40363. textBoxPos = newPosition;
  40364. editableText = ! isReadOnly;
  40365. textBoxWidth = textEntryBoxWidth;
  40366. textBoxHeight = textEntryBoxHeight;
  40367. repaint();
  40368. lookAndFeelChanged();
  40369. }
  40370. }
  40371. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40372. {
  40373. editableText = shouldBeEditable;
  40374. if (valueBox != 0)
  40375. valueBox->setEditable (shouldBeEditable && isEnabled());
  40376. }
  40377. void Slider::showTextBox()
  40378. {
  40379. jassert (editableText); // this should probably be avoided in read-only sliders.
  40380. if (valueBox != 0)
  40381. valueBox->showEditor();
  40382. }
  40383. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40384. {
  40385. if (valueBox != 0)
  40386. {
  40387. valueBox->hideEditor (discardCurrentEditorContents);
  40388. if (discardCurrentEditorContents)
  40389. updateText();
  40390. }
  40391. }
  40392. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40393. {
  40394. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40395. }
  40396. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40397. {
  40398. snapsToMousePos = shouldSnapToMouse;
  40399. }
  40400. void Slider::setPopupDisplayEnabled (const bool enabled,
  40401. Component* const parentComponentToUse)
  40402. {
  40403. popupDisplayEnabled = enabled;
  40404. parentForPopupDisplay = parentComponentToUse;
  40405. }
  40406. void Slider::colourChanged()
  40407. {
  40408. lookAndFeelChanged();
  40409. }
  40410. void Slider::lookAndFeelChanged()
  40411. {
  40412. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40413. : getTextFromValue (currentValue.getValue()));
  40414. deleteAllChildren();
  40415. valueBox = 0;
  40416. LookAndFeel& lf = getLookAndFeel();
  40417. if (textBoxPos != NoTextBox)
  40418. {
  40419. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40420. valueBox->setWantsKeyboardFocus (false);
  40421. valueBox->setText (previousTextBoxContent, false);
  40422. valueBox->setEditable (editableText && isEnabled());
  40423. valueBox->addListener (this);
  40424. if (style == LinearBar)
  40425. valueBox->addMouseListener (this, false);
  40426. valueBox->setTooltip (getTooltip());
  40427. }
  40428. if (style == IncDecButtons)
  40429. {
  40430. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40431. incButton->addButtonListener (this);
  40432. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40433. decButton->addButtonListener (this);
  40434. if (incDecButtonMode != incDecButtonsNotDraggable)
  40435. {
  40436. incButton->addMouseListener (this, false);
  40437. decButton->addMouseListener (this, false);
  40438. }
  40439. else
  40440. {
  40441. incButton->setRepeatSpeed (300, 100, 20);
  40442. incButton->addMouseListener (decButton, false);
  40443. decButton->setRepeatSpeed (300, 100, 20);
  40444. decButton->addMouseListener (incButton, false);
  40445. }
  40446. incButton->setTooltip (getTooltip());
  40447. decButton->setTooltip (getTooltip());
  40448. }
  40449. setComponentEffect (lf.getSliderEffect());
  40450. resized();
  40451. repaint();
  40452. }
  40453. void Slider::setRange (const double newMin,
  40454. const double newMax,
  40455. const double newInt)
  40456. {
  40457. if (minimum != newMin
  40458. || maximum != newMax
  40459. || interval != newInt)
  40460. {
  40461. minimum = newMin;
  40462. maximum = newMax;
  40463. interval = newInt;
  40464. // figure out the number of DPs needed to display all values at this
  40465. // interval setting.
  40466. numDecimalPlaces = 7;
  40467. if (newInt != 0)
  40468. {
  40469. int v = abs ((int) (newInt * 10000000));
  40470. while ((v % 10) == 0)
  40471. {
  40472. --numDecimalPlaces;
  40473. v /= 10;
  40474. }
  40475. }
  40476. // keep the current values inside the new range..
  40477. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40478. {
  40479. setValue (getValue(), false, false);
  40480. }
  40481. else
  40482. {
  40483. setMinValue (getMinValue(), false, false);
  40484. setMaxValue (getMaxValue(), false, false);
  40485. }
  40486. updateText();
  40487. }
  40488. }
  40489. void Slider::triggerChangeMessage (const bool synchronous)
  40490. {
  40491. if (synchronous)
  40492. handleAsyncUpdate();
  40493. else
  40494. triggerAsyncUpdate();
  40495. valueChanged();
  40496. }
  40497. void Slider::valueChanged (Value& value)
  40498. {
  40499. if (value.refersToSameSourceAs (currentValue))
  40500. {
  40501. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40502. setValue (currentValue.getValue(), false, false);
  40503. }
  40504. else if (value.refersToSameSourceAs (valueMin))
  40505. setMinValue (valueMin.getValue(), false, false, true);
  40506. else if (value.refersToSameSourceAs (valueMax))
  40507. setMaxValue (valueMax.getValue(), false, false, true);
  40508. }
  40509. double Slider::getValue() const
  40510. {
  40511. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40512. // methods to get the two values.
  40513. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40514. return currentValue.getValue();
  40515. }
  40516. void Slider::setValue (double newValue,
  40517. const bool sendUpdateMessage,
  40518. const bool sendMessageSynchronously)
  40519. {
  40520. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40521. // methods to set the two values.
  40522. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40523. newValue = constrainedValue (newValue);
  40524. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40525. {
  40526. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40527. newValue = jlimit ((double) valueMin.getValue(),
  40528. (double) valueMax.getValue(),
  40529. newValue);
  40530. }
  40531. if (newValue != lastCurrentValue)
  40532. {
  40533. if (valueBox != 0)
  40534. valueBox->hideEditor (true);
  40535. lastCurrentValue = newValue;
  40536. currentValue = newValue;
  40537. updateText();
  40538. repaint();
  40539. if (popupDisplay != 0)
  40540. {
  40541. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40542. ->updatePosition (getTextFromValue (newValue));
  40543. popupDisplay->repaint();
  40544. }
  40545. if (sendUpdateMessage)
  40546. triggerChangeMessage (sendMessageSynchronously);
  40547. }
  40548. }
  40549. double Slider::getMinValue() const
  40550. {
  40551. // The minimum value only applies to sliders that are in two- or three-value mode.
  40552. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40553. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40554. return valueMin.getValue();
  40555. }
  40556. double Slider::getMaxValue() const
  40557. {
  40558. // The maximum value only applies to sliders that are in two- or three-value mode.
  40559. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40560. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40561. return valueMax.getValue();
  40562. }
  40563. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40564. {
  40565. // The minimum value only applies to sliders that are in two- or three-value mode.
  40566. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40567. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40568. newValue = constrainedValue (newValue);
  40569. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40570. {
  40571. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40572. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40573. newValue = jmin ((double) valueMax.getValue(), newValue);
  40574. }
  40575. else
  40576. {
  40577. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40578. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40579. newValue = jmin (lastCurrentValue, newValue);
  40580. }
  40581. if (lastValueMin != newValue)
  40582. {
  40583. lastValueMin = newValue;
  40584. valueMin = newValue;
  40585. repaint();
  40586. if (popupDisplay != 0)
  40587. {
  40588. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40589. ->updatePosition (getTextFromValue (newValue));
  40590. popupDisplay->repaint();
  40591. }
  40592. if (sendUpdateMessage)
  40593. triggerChangeMessage (sendMessageSynchronously);
  40594. }
  40595. }
  40596. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40597. {
  40598. // The maximum value only applies to sliders that are in two- or three-value mode.
  40599. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40600. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40601. newValue = constrainedValue (newValue);
  40602. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40603. {
  40604. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40605. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40606. newValue = jmax ((double) valueMin.getValue(), newValue);
  40607. }
  40608. else
  40609. {
  40610. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40611. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40612. newValue = jmax (lastCurrentValue, newValue);
  40613. }
  40614. if (lastValueMax != newValue)
  40615. {
  40616. lastValueMax = newValue;
  40617. valueMax = newValue;
  40618. repaint();
  40619. if (popupDisplay != 0)
  40620. {
  40621. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40622. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40623. popupDisplay->repaint();
  40624. }
  40625. if (sendUpdateMessage)
  40626. triggerChangeMessage (sendMessageSynchronously);
  40627. }
  40628. }
  40629. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40630. const double valueToSetOnDoubleClick)
  40631. {
  40632. doubleClickToValue = isDoubleClickEnabled;
  40633. doubleClickReturnValue = valueToSetOnDoubleClick;
  40634. }
  40635. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40636. {
  40637. isEnabled_ = doubleClickToValue;
  40638. return doubleClickReturnValue;
  40639. }
  40640. void Slider::updateText()
  40641. {
  40642. if (valueBox != 0)
  40643. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40644. }
  40645. void Slider::setTextValueSuffix (const String& suffix)
  40646. {
  40647. if (textSuffix != suffix)
  40648. {
  40649. textSuffix = suffix;
  40650. updateText();
  40651. }
  40652. }
  40653. const String Slider::getTextValueSuffix() const
  40654. {
  40655. return textSuffix;
  40656. }
  40657. const String Slider::getTextFromValue (double v)
  40658. {
  40659. if (getNumDecimalPlacesToDisplay() > 0)
  40660. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40661. else
  40662. return String (roundToInt (v)) + getTextValueSuffix();
  40663. }
  40664. double Slider::getValueFromText (const String& text)
  40665. {
  40666. String t (text.trimStart());
  40667. if (t.endsWith (textSuffix))
  40668. t = t.substring (0, t.length() - textSuffix.length());
  40669. while (t.startsWithChar ('+'))
  40670. t = t.substring (1).trimStart();
  40671. return t.initialSectionContainingOnly ("0123456789.,-")
  40672. .getDoubleValue();
  40673. }
  40674. double Slider::proportionOfLengthToValue (double proportion)
  40675. {
  40676. if (skewFactor != 1.0 && proportion > 0.0)
  40677. proportion = exp (log (proportion) / skewFactor);
  40678. return minimum + (maximum - minimum) * proportion;
  40679. }
  40680. double Slider::valueToProportionOfLength (double value)
  40681. {
  40682. const double n = (value - minimum) / (maximum - minimum);
  40683. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40684. }
  40685. double Slider::snapValue (double attemptedValue, const bool)
  40686. {
  40687. return attemptedValue;
  40688. }
  40689. void Slider::startedDragging()
  40690. {
  40691. }
  40692. void Slider::stoppedDragging()
  40693. {
  40694. }
  40695. void Slider::valueChanged()
  40696. {
  40697. }
  40698. void Slider::enablementChanged()
  40699. {
  40700. repaint();
  40701. }
  40702. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40703. {
  40704. menuEnabled = menuEnabled_;
  40705. }
  40706. void Slider::setScrollWheelEnabled (const bool enabled)
  40707. {
  40708. scrollWheelEnabled = enabled;
  40709. }
  40710. void Slider::labelTextChanged (Label* label)
  40711. {
  40712. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40713. if (newValue != (double) currentValue.getValue())
  40714. {
  40715. sendDragStart();
  40716. setValue (newValue, true, true);
  40717. sendDragEnd();
  40718. }
  40719. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40720. }
  40721. void Slider::buttonClicked (Button* button)
  40722. {
  40723. if (style == IncDecButtons)
  40724. {
  40725. sendDragStart();
  40726. if (button == incButton)
  40727. setValue (snapValue (getValue() + interval, false), true, true);
  40728. else if (button == decButton)
  40729. setValue (snapValue (getValue() - interval, false), true, true);
  40730. sendDragEnd();
  40731. }
  40732. }
  40733. double Slider::constrainedValue (double value) const
  40734. {
  40735. if (interval > 0)
  40736. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40737. if (value <= minimum || maximum <= minimum)
  40738. value = minimum;
  40739. else if (value >= maximum)
  40740. value = maximum;
  40741. return value;
  40742. }
  40743. float Slider::getLinearSliderPos (const double value)
  40744. {
  40745. double sliderPosProportional;
  40746. if (maximum > minimum)
  40747. {
  40748. if (value < minimum)
  40749. {
  40750. sliderPosProportional = 0.0;
  40751. }
  40752. else if (value > maximum)
  40753. {
  40754. sliderPosProportional = 1.0;
  40755. }
  40756. else
  40757. {
  40758. sliderPosProportional = valueToProportionOfLength (value);
  40759. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40760. }
  40761. }
  40762. else
  40763. {
  40764. sliderPosProportional = 0.5;
  40765. }
  40766. if (isVertical() || style == IncDecButtons)
  40767. sliderPosProportional = 1.0 - sliderPosProportional;
  40768. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40769. }
  40770. bool Slider::isHorizontal() const
  40771. {
  40772. return style == LinearHorizontal
  40773. || style == LinearBar
  40774. || style == TwoValueHorizontal
  40775. || style == ThreeValueHorizontal;
  40776. }
  40777. bool Slider::isVertical() const
  40778. {
  40779. return style == LinearVertical
  40780. || style == TwoValueVertical
  40781. || style == ThreeValueVertical;
  40782. }
  40783. bool Slider::incDecDragDirectionIsHorizontal() const
  40784. {
  40785. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40786. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40787. }
  40788. float Slider::getPositionOfValue (const double value)
  40789. {
  40790. if (isHorizontal() || isVertical())
  40791. {
  40792. return getLinearSliderPos (value);
  40793. }
  40794. else
  40795. {
  40796. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40797. return 0.0f;
  40798. }
  40799. }
  40800. void Slider::paint (Graphics& g)
  40801. {
  40802. if (style != IncDecButtons)
  40803. {
  40804. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40805. {
  40806. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40807. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40808. getLookAndFeel().drawRotarySlider (g,
  40809. sliderRect.getX(),
  40810. sliderRect.getY(),
  40811. sliderRect.getWidth(),
  40812. sliderRect.getHeight(),
  40813. sliderPos,
  40814. rotaryStart, rotaryEnd,
  40815. *this);
  40816. }
  40817. else
  40818. {
  40819. getLookAndFeel().drawLinearSlider (g,
  40820. sliderRect.getX(),
  40821. sliderRect.getY(),
  40822. sliderRect.getWidth(),
  40823. sliderRect.getHeight(),
  40824. getLinearSliderPos (lastCurrentValue),
  40825. getLinearSliderPos (lastValueMin),
  40826. getLinearSliderPos (lastValueMax),
  40827. style,
  40828. *this);
  40829. }
  40830. if (style == LinearBar && valueBox == 0)
  40831. {
  40832. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40833. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40834. }
  40835. }
  40836. }
  40837. void Slider::resized()
  40838. {
  40839. int minXSpace = 0;
  40840. int minYSpace = 0;
  40841. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40842. minXSpace = 30;
  40843. else
  40844. minYSpace = 15;
  40845. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40846. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40847. if (style == LinearBar)
  40848. {
  40849. if (valueBox != 0)
  40850. valueBox->setBounds (getLocalBounds());
  40851. }
  40852. else
  40853. {
  40854. if (textBoxPos == NoTextBox)
  40855. {
  40856. sliderRect = getLocalBounds();
  40857. }
  40858. else if (textBoxPos == TextBoxLeft)
  40859. {
  40860. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40861. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40862. }
  40863. else if (textBoxPos == TextBoxRight)
  40864. {
  40865. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40866. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40867. }
  40868. else if (textBoxPos == TextBoxAbove)
  40869. {
  40870. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40871. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40872. }
  40873. else if (textBoxPos == TextBoxBelow)
  40874. {
  40875. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40876. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40877. }
  40878. }
  40879. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40880. if (style == LinearBar)
  40881. {
  40882. const int barIndent = 1;
  40883. sliderRegionStart = barIndent;
  40884. sliderRegionSize = getWidth() - barIndent * 2;
  40885. sliderRect.setBounds (sliderRegionStart, barIndent,
  40886. sliderRegionSize, getHeight() - barIndent * 2);
  40887. }
  40888. else if (isHorizontal())
  40889. {
  40890. sliderRegionStart = sliderRect.getX() + indent;
  40891. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40892. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40893. sliderRegionSize, sliderRect.getHeight());
  40894. }
  40895. else if (isVertical())
  40896. {
  40897. sliderRegionStart = sliderRect.getY() + indent;
  40898. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40899. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40900. sliderRect.getWidth(), sliderRegionSize);
  40901. }
  40902. else
  40903. {
  40904. sliderRegionStart = 0;
  40905. sliderRegionSize = 100;
  40906. }
  40907. if (style == IncDecButtons)
  40908. {
  40909. Rectangle<int> buttonRect (sliderRect);
  40910. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40911. buttonRect.expand (-2, 0);
  40912. else
  40913. buttonRect.expand (0, -2);
  40914. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40915. if (incDecButtonsSideBySide)
  40916. {
  40917. decButton->setBounds (buttonRect.getX(),
  40918. buttonRect.getY(),
  40919. buttonRect.getWidth() / 2,
  40920. buttonRect.getHeight());
  40921. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40922. incButton->setBounds (buttonRect.getCentreX(),
  40923. buttonRect.getY(),
  40924. buttonRect.getWidth() / 2,
  40925. buttonRect.getHeight());
  40926. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40927. }
  40928. else
  40929. {
  40930. incButton->setBounds (buttonRect.getX(),
  40931. buttonRect.getY(),
  40932. buttonRect.getWidth(),
  40933. buttonRect.getHeight() / 2);
  40934. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40935. decButton->setBounds (buttonRect.getX(),
  40936. buttonRect.getCentreY(),
  40937. buttonRect.getWidth(),
  40938. buttonRect.getHeight() / 2);
  40939. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40940. }
  40941. }
  40942. }
  40943. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40944. {
  40945. repaint();
  40946. }
  40947. void Slider::mouseDown (const MouseEvent& e)
  40948. {
  40949. mouseWasHidden = false;
  40950. incDecDragged = false;
  40951. mouseXWhenLastDragged = e.x;
  40952. mouseYWhenLastDragged = e.y;
  40953. mouseDragStartX = e.getMouseDownX();
  40954. mouseDragStartY = e.getMouseDownY();
  40955. if (isEnabled())
  40956. {
  40957. if (e.mods.isPopupMenu() && menuEnabled)
  40958. {
  40959. menuShown = true;
  40960. PopupMenu m;
  40961. m.setLookAndFeel (&getLookAndFeel());
  40962. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40963. m.addSeparator();
  40964. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40965. {
  40966. PopupMenu rotaryMenu;
  40967. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40968. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40969. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40970. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40971. }
  40972. const int r = m.show();
  40973. if (r == 1)
  40974. {
  40975. setVelocityBasedMode (! isVelocityBased);
  40976. }
  40977. else if (r == 2)
  40978. {
  40979. setSliderStyle (Rotary);
  40980. }
  40981. else if (r == 3)
  40982. {
  40983. setSliderStyle (RotaryHorizontalDrag);
  40984. }
  40985. else if (r == 4)
  40986. {
  40987. setSliderStyle (RotaryVerticalDrag);
  40988. }
  40989. }
  40990. else if (maximum > minimum)
  40991. {
  40992. menuShown = false;
  40993. if (valueBox != 0)
  40994. valueBox->hideEditor (true);
  40995. sliderBeingDragged = 0;
  40996. if (style == TwoValueHorizontal
  40997. || style == TwoValueVertical
  40998. || style == ThreeValueHorizontal
  40999. || style == ThreeValueVertical)
  41000. {
  41001. const float mousePos = (float) (isVertical() ? e.y : e.x);
  41002. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  41003. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  41004. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  41005. if (style == TwoValueHorizontal || style == TwoValueVertical)
  41006. {
  41007. if (maxPosDistance <= minPosDistance)
  41008. sliderBeingDragged = 2;
  41009. else
  41010. sliderBeingDragged = 1;
  41011. }
  41012. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  41013. {
  41014. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  41015. sliderBeingDragged = 1;
  41016. else if (normalPosDistance >= maxPosDistance)
  41017. sliderBeingDragged = 2;
  41018. }
  41019. }
  41020. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41021. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  41022. * valueToProportionOfLength (currentValue.getValue());
  41023. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  41024. : ((sliderBeingDragged == 1) ? valueMin
  41025. : currentValue)).getValue();
  41026. valueOnMouseDown = valueWhenLastDragged;
  41027. if (popupDisplayEnabled)
  41028. {
  41029. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  41030. popupDisplay = popup;
  41031. if (parentForPopupDisplay != 0)
  41032. {
  41033. parentForPopupDisplay->addChildComponent (popup);
  41034. }
  41035. else
  41036. {
  41037. popup->addToDesktop (0);
  41038. }
  41039. popup->setVisible (true);
  41040. }
  41041. sendDragStart();
  41042. mouseDrag (e);
  41043. }
  41044. }
  41045. }
  41046. void Slider::mouseUp (const MouseEvent&)
  41047. {
  41048. if (isEnabled()
  41049. && (! menuShown)
  41050. && (maximum > minimum)
  41051. && (style != IncDecButtons || incDecDragged))
  41052. {
  41053. restoreMouseIfHidden();
  41054. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  41055. triggerChangeMessage (false);
  41056. sendDragEnd();
  41057. popupDisplay = 0;
  41058. if (style == IncDecButtons)
  41059. {
  41060. incButton->setState (Button::buttonNormal);
  41061. decButton->setState (Button::buttonNormal);
  41062. }
  41063. }
  41064. }
  41065. void Slider::restoreMouseIfHidden()
  41066. {
  41067. if (mouseWasHidden)
  41068. {
  41069. mouseWasHidden = false;
  41070. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  41071. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  41072. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  41073. : ((sliderBeingDragged == 1) ? getMinValue()
  41074. : (double) currentValue.getValue());
  41075. Point<int> mousePos;
  41076. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  41077. {
  41078. mousePos = Desktop::getLastMouseDownPosition();
  41079. if (style == RotaryHorizontalDrag)
  41080. {
  41081. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  41082. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  41083. }
  41084. else
  41085. {
  41086. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  41087. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  41088. }
  41089. }
  41090. else
  41091. {
  41092. const int pixelPos = (int) getLinearSliderPos (pos);
  41093. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  41094. isVertical() ? pixelPos : (getHeight() / 2)));
  41095. }
  41096. Desktop::setMousePosition (mousePos);
  41097. }
  41098. }
  41099. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  41100. {
  41101. if (isEnabled()
  41102. && style != IncDecButtons
  41103. && style != Rotary
  41104. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  41105. {
  41106. restoreMouseIfHidden();
  41107. }
  41108. }
  41109. static double smallestAngleBetween (double a1, double a2)
  41110. {
  41111. return jmin (std::abs (a1 - a2),
  41112. std::abs (a1 + double_Pi * 2.0 - a2),
  41113. std::abs (a2 + double_Pi * 2.0 - a1));
  41114. }
  41115. void Slider::mouseDrag (const MouseEvent& e)
  41116. {
  41117. if (isEnabled()
  41118. && (! menuShown)
  41119. && (maximum > minimum))
  41120. {
  41121. if (style == Rotary)
  41122. {
  41123. int dx = e.x - sliderRect.getCentreX();
  41124. int dy = e.y - sliderRect.getCentreY();
  41125. if (dx * dx + dy * dy > 25)
  41126. {
  41127. double angle = std::atan2 ((double) dx, (double) -dy);
  41128. while (angle < 0.0)
  41129. angle += double_Pi * 2.0;
  41130. if (rotaryStop && ! e.mouseWasClicked())
  41131. {
  41132. if (std::abs (angle - lastAngle) > double_Pi)
  41133. {
  41134. if (angle >= lastAngle)
  41135. angle -= double_Pi * 2.0;
  41136. else
  41137. angle += double_Pi * 2.0;
  41138. }
  41139. if (angle >= lastAngle)
  41140. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  41141. else
  41142. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  41143. }
  41144. else
  41145. {
  41146. while (angle < rotaryStart)
  41147. angle += double_Pi * 2.0;
  41148. if (angle > rotaryEnd)
  41149. {
  41150. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  41151. angle = rotaryStart;
  41152. else
  41153. angle = rotaryEnd;
  41154. }
  41155. }
  41156. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  41157. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  41158. lastAngle = angle;
  41159. }
  41160. }
  41161. else
  41162. {
  41163. if (style == LinearBar && e.mouseWasClicked()
  41164. && valueBox != 0 && valueBox->isEditable())
  41165. return;
  41166. if (style == IncDecButtons && ! incDecDragged)
  41167. {
  41168. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  41169. return;
  41170. incDecDragged = true;
  41171. mouseDragStartX = e.x;
  41172. mouseDragStartY = e.y;
  41173. }
  41174. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  41175. : false))
  41176. || ((maximum - minimum) / sliderRegionSize < interval))
  41177. {
  41178. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  41179. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  41180. if (style == RotaryHorizontalDrag
  41181. || style == RotaryVerticalDrag
  41182. || style == IncDecButtons
  41183. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  41184. && ! snapsToMousePos))
  41185. {
  41186. const int mouseDiff = (style == RotaryHorizontalDrag
  41187. || style == LinearHorizontal
  41188. || style == LinearBar
  41189. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  41190. ? e.x - mouseDragStartX
  41191. : mouseDragStartY - e.y;
  41192. double newPos = valueToProportionOfLength (valueOnMouseDown)
  41193. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  41194. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  41195. if (style == IncDecButtons)
  41196. {
  41197. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  41198. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  41199. }
  41200. }
  41201. else
  41202. {
  41203. if (isVertical())
  41204. scaledMousePos = 1.0 - scaledMousePos;
  41205. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  41206. }
  41207. }
  41208. else
  41209. {
  41210. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  41211. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  41212. ? e.x - mouseXWhenLastDragged
  41213. : e.y - mouseYWhenLastDragged;
  41214. const double maxSpeed = jmax (200, sliderRegionSize);
  41215. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  41216. if (speed != 0)
  41217. {
  41218. speed = 0.2 * velocityModeSensitivity
  41219. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  41220. + jmax (0.0, (double) (speed - velocityModeThreshold))
  41221. / maxSpeed))));
  41222. if (mouseDiff < 0)
  41223. speed = -speed;
  41224. if (isVertical() || style == RotaryVerticalDrag
  41225. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  41226. speed = -speed;
  41227. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  41228. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  41229. e.source.enableUnboundedMouseMovement (true, false);
  41230. mouseWasHidden = true;
  41231. }
  41232. }
  41233. }
  41234. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  41235. if (sliderBeingDragged == 0)
  41236. {
  41237. setValue (snapValue (valueWhenLastDragged, true),
  41238. ! sendChangeOnlyOnRelease, true);
  41239. }
  41240. else if (sliderBeingDragged == 1)
  41241. {
  41242. setMinValue (snapValue (valueWhenLastDragged, true),
  41243. ! sendChangeOnlyOnRelease, false, true);
  41244. if (e.mods.isShiftDown())
  41245. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  41246. else
  41247. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41248. }
  41249. else
  41250. {
  41251. jassert (sliderBeingDragged == 2);
  41252. setMaxValue (snapValue (valueWhenLastDragged, true),
  41253. ! sendChangeOnlyOnRelease, false, true);
  41254. if (e.mods.isShiftDown())
  41255. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  41256. else
  41257. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41258. }
  41259. mouseXWhenLastDragged = e.x;
  41260. mouseYWhenLastDragged = e.y;
  41261. }
  41262. }
  41263. void Slider::mouseDoubleClick (const MouseEvent&)
  41264. {
  41265. if (doubleClickToValue
  41266. && isEnabled()
  41267. && style != IncDecButtons
  41268. && minimum <= doubleClickReturnValue
  41269. && maximum >= doubleClickReturnValue)
  41270. {
  41271. sendDragStart();
  41272. setValue (doubleClickReturnValue, true, true);
  41273. sendDragEnd();
  41274. }
  41275. }
  41276. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  41277. {
  41278. if (scrollWheelEnabled && isEnabled()
  41279. && style != TwoValueHorizontal
  41280. && style != TwoValueVertical)
  41281. {
  41282. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  41283. {
  41284. if (valueBox != 0)
  41285. valueBox->hideEditor (false);
  41286. const double value = (double) currentValue.getValue();
  41287. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  41288. const double currentPos = valueToProportionOfLength (value);
  41289. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  41290. double delta = (newValue != value)
  41291. ? jmax (std::abs (newValue - value), interval) : 0;
  41292. if (value > newValue)
  41293. delta = -delta;
  41294. sendDragStart();
  41295. setValue (snapValue (value + delta, false), true, true);
  41296. sendDragEnd();
  41297. }
  41298. }
  41299. else
  41300. {
  41301. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  41302. }
  41303. }
  41304. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  41305. {
  41306. }
  41307. void SliderListener::sliderDragEnded (Slider*)
  41308. {
  41309. }
  41310. END_JUCE_NAMESPACE
  41311. /*** End of inlined file: juce_Slider.cpp ***/
  41312. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  41313. BEGIN_JUCE_NAMESPACE
  41314. class DragOverlayComp : public Component
  41315. {
  41316. public:
  41317. DragOverlayComp (const Image& image_)
  41318. : image (image_)
  41319. {
  41320. image.duplicateIfShared();
  41321. image.multiplyAllAlphas (0.8f);
  41322. setAlwaysOnTop (true);
  41323. }
  41324. ~DragOverlayComp()
  41325. {
  41326. }
  41327. void paint (Graphics& g)
  41328. {
  41329. g.drawImageAt (image, 0, 0);
  41330. }
  41331. private:
  41332. Image image;
  41333. DragOverlayComp (const DragOverlayComp&);
  41334. DragOverlayComp& operator= (const DragOverlayComp&);
  41335. };
  41336. TableHeaderComponent::TableHeaderComponent()
  41337. : columnsChanged (false),
  41338. columnsResized (false),
  41339. sortChanged (false),
  41340. menuActive (true),
  41341. stretchToFit (false),
  41342. columnIdBeingResized (0),
  41343. columnIdBeingDragged (0),
  41344. columnIdUnderMouse (0),
  41345. lastDeliberateWidth (0)
  41346. {
  41347. }
  41348. TableHeaderComponent::~TableHeaderComponent()
  41349. {
  41350. dragOverlayComp = 0;
  41351. }
  41352. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41353. {
  41354. menuActive = hasMenu;
  41355. }
  41356. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41357. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41358. {
  41359. if (onlyCountVisibleColumns)
  41360. {
  41361. int num = 0;
  41362. for (int i = columns.size(); --i >= 0;)
  41363. if (columns.getUnchecked(i)->isVisible())
  41364. ++num;
  41365. return num;
  41366. }
  41367. else
  41368. {
  41369. return columns.size();
  41370. }
  41371. }
  41372. const String TableHeaderComponent::getColumnName (const int columnId) const
  41373. {
  41374. const ColumnInfo* const ci = getInfoForId (columnId);
  41375. return ci != 0 ? ci->name : String::empty;
  41376. }
  41377. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41378. {
  41379. ColumnInfo* const ci = getInfoForId (columnId);
  41380. if (ci != 0 && ci->name != newName)
  41381. {
  41382. ci->name = newName;
  41383. sendColumnsChanged();
  41384. }
  41385. }
  41386. void TableHeaderComponent::addColumn (const String& columnName,
  41387. const int columnId,
  41388. const int width,
  41389. const int minimumWidth,
  41390. const int maximumWidth,
  41391. const int propertyFlags,
  41392. const int insertIndex)
  41393. {
  41394. // can't have a duplicate or null ID!
  41395. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41396. jassert (width > 0);
  41397. ColumnInfo* const ci = new ColumnInfo();
  41398. ci->name = columnName;
  41399. ci->id = columnId;
  41400. ci->width = width;
  41401. ci->lastDeliberateWidth = width;
  41402. ci->minimumWidth = minimumWidth;
  41403. ci->maximumWidth = maximumWidth;
  41404. if (ci->maximumWidth < 0)
  41405. ci->maximumWidth = std::numeric_limits<int>::max();
  41406. jassert (ci->maximumWidth >= ci->minimumWidth);
  41407. ci->propertyFlags = propertyFlags;
  41408. columns.insert (insertIndex, ci);
  41409. sendColumnsChanged();
  41410. }
  41411. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41412. {
  41413. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41414. if (index >= 0)
  41415. {
  41416. columns.remove (index);
  41417. sortChanged = true;
  41418. sendColumnsChanged();
  41419. }
  41420. }
  41421. void TableHeaderComponent::removeAllColumns()
  41422. {
  41423. if (columns.size() > 0)
  41424. {
  41425. columns.clear();
  41426. sendColumnsChanged();
  41427. }
  41428. }
  41429. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41430. {
  41431. const int currentIndex = getIndexOfColumnId (columnId, false);
  41432. newIndex = visibleIndexToTotalIndex (newIndex);
  41433. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41434. {
  41435. columns.move (currentIndex, newIndex);
  41436. sendColumnsChanged();
  41437. }
  41438. }
  41439. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41440. {
  41441. const ColumnInfo* const ci = getInfoForId (columnId);
  41442. return ci != 0 ? ci->width : 0;
  41443. }
  41444. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41445. {
  41446. ColumnInfo* const ci = getInfoForId (columnId);
  41447. if (ci != 0 && ci->width != newWidth)
  41448. {
  41449. const int numColumns = getNumColumns (true);
  41450. ci->lastDeliberateWidth = ci->width
  41451. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41452. if (stretchToFit)
  41453. {
  41454. const int index = getIndexOfColumnId (columnId, true) + 1;
  41455. if (((unsigned int) index) < (unsigned int) numColumns)
  41456. {
  41457. const int x = getColumnPosition (index).getX();
  41458. if (lastDeliberateWidth == 0)
  41459. lastDeliberateWidth = getTotalWidth();
  41460. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41461. }
  41462. }
  41463. repaint();
  41464. columnsResized = true;
  41465. triggerAsyncUpdate();
  41466. }
  41467. }
  41468. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41469. {
  41470. int n = 0;
  41471. for (int i = 0; i < columns.size(); ++i)
  41472. {
  41473. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41474. {
  41475. if (columns.getUnchecked(i)->id == columnId)
  41476. return n;
  41477. ++n;
  41478. }
  41479. }
  41480. return -1;
  41481. }
  41482. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41483. {
  41484. if (onlyCountVisibleColumns)
  41485. index = visibleIndexToTotalIndex (index);
  41486. const ColumnInfo* const ci = columns [index];
  41487. return (ci != 0) ? ci->id : 0;
  41488. }
  41489. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41490. {
  41491. int x = 0, width = 0, n = 0;
  41492. for (int i = 0; i < columns.size(); ++i)
  41493. {
  41494. x += width;
  41495. if (columns.getUnchecked(i)->isVisible())
  41496. {
  41497. width = columns.getUnchecked(i)->width;
  41498. if (n++ == index)
  41499. break;
  41500. }
  41501. else
  41502. {
  41503. width = 0;
  41504. }
  41505. }
  41506. return Rectangle<int> (x, 0, width, getHeight());
  41507. }
  41508. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41509. {
  41510. if (xToFind >= 0)
  41511. {
  41512. int x = 0;
  41513. for (int i = 0; i < columns.size(); ++i)
  41514. {
  41515. const ColumnInfo* const ci = columns.getUnchecked(i);
  41516. if (ci->isVisible())
  41517. {
  41518. x += ci->width;
  41519. if (xToFind < x)
  41520. return ci->id;
  41521. }
  41522. }
  41523. }
  41524. return 0;
  41525. }
  41526. int TableHeaderComponent::getTotalWidth() const
  41527. {
  41528. int w = 0;
  41529. for (int i = columns.size(); --i >= 0;)
  41530. if (columns.getUnchecked(i)->isVisible())
  41531. w += columns.getUnchecked(i)->width;
  41532. return w;
  41533. }
  41534. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41535. {
  41536. stretchToFit = shouldStretchToFit;
  41537. lastDeliberateWidth = getTotalWidth();
  41538. resized();
  41539. }
  41540. bool TableHeaderComponent::isStretchToFitActive() const
  41541. {
  41542. return stretchToFit;
  41543. }
  41544. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41545. {
  41546. if (stretchToFit && getWidth() > 0
  41547. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41548. {
  41549. lastDeliberateWidth = targetTotalWidth;
  41550. resizeColumnsToFit (0, targetTotalWidth);
  41551. }
  41552. }
  41553. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41554. {
  41555. targetTotalWidth = jmax (targetTotalWidth, 0);
  41556. StretchableObjectResizer sor;
  41557. int i;
  41558. for (i = firstColumnIndex; i < columns.size(); ++i)
  41559. {
  41560. ColumnInfo* const ci = columns.getUnchecked(i);
  41561. if (ci->isVisible())
  41562. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41563. }
  41564. sor.resizeToFit (targetTotalWidth);
  41565. int visIndex = 0;
  41566. for (i = firstColumnIndex; i < columns.size(); ++i)
  41567. {
  41568. ColumnInfo* const ci = columns.getUnchecked(i);
  41569. if (ci->isVisible())
  41570. {
  41571. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41572. (int) std::floor (sor.getItemSize (visIndex++)));
  41573. if (newWidth != ci->width)
  41574. {
  41575. ci->width = newWidth;
  41576. repaint();
  41577. columnsResized = true;
  41578. triggerAsyncUpdate();
  41579. }
  41580. }
  41581. }
  41582. }
  41583. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41584. {
  41585. ColumnInfo* const ci = getInfoForId (columnId);
  41586. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41587. {
  41588. if (shouldBeVisible)
  41589. ci->propertyFlags |= visible;
  41590. else
  41591. ci->propertyFlags &= ~visible;
  41592. sendColumnsChanged();
  41593. resized();
  41594. }
  41595. }
  41596. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41597. {
  41598. const ColumnInfo* const ci = getInfoForId (columnId);
  41599. return ci != 0 && ci->isVisible();
  41600. }
  41601. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41602. {
  41603. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41604. {
  41605. for (int i = columns.size(); --i >= 0;)
  41606. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41607. ColumnInfo* const ci = getInfoForId (columnId);
  41608. if (ci != 0)
  41609. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41610. reSortTable();
  41611. }
  41612. }
  41613. int TableHeaderComponent::getSortColumnId() const
  41614. {
  41615. for (int i = columns.size(); --i >= 0;)
  41616. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41617. return columns.getUnchecked(i)->id;
  41618. return 0;
  41619. }
  41620. bool TableHeaderComponent::isSortedForwards() const
  41621. {
  41622. for (int i = columns.size(); --i >= 0;)
  41623. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41624. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41625. return true;
  41626. }
  41627. void TableHeaderComponent::reSortTable()
  41628. {
  41629. sortChanged = true;
  41630. repaint();
  41631. triggerAsyncUpdate();
  41632. }
  41633. const String TableHeaderComponent::toString() const
  41634. {
  41635. String s;
  41636. XmlElement doc ("TABLELAYOUT");
  41637. doc.setAttribute ("sortedCol", getSortColumnId());
  41638. doc.setAttribute ("sortForwards", isSortedForwards());
  41639. for (int i = 0; i < columns.size(); ++i)
  41640. {
  41641. const ColumnInfo* const ci = columns.getUnchecked (i);
  41642. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41643. e->setAttribute ("id", ci->id);
  41644. e->setAttribute ("visible", ci->isVisible());
  41645. e->setAttribute ("width", ci->width);
  41646. }
  41647. return doc.createDocument (String::empty, true, false);
  41648. }
  41649. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41650. {
  41651. XmlDocument doc (storedVersion);
  41652. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41653. int index = 0;
  41654. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41655. {
  41656. forEachXmlChildElement (*storedXml, col)
  41657. {
  41658. const int tabId = col->getIntAttribute ("id");
  41659. ColumnInfo* const ci = getInfoForId (tabId);
  41660. if (ci != 0)
  41661. {
  41662. columns.move (columns.indexOf (ci), index);
  41663. ci->width = col->getIntAttribute ("width");
  41664. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41665. }
  41666. ++index;
  41667. }
  41668. columnsResized = true;
  41669. sendColumnsChanged();
  41670. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41671. storedXml->getBoolAttribute ("sortForwards", true));
  41672. }
  41673. }
  41674. void TableHeaderComponent::addListener (Listener* const newListener)
  41675. {
  41676. listeners.addIfNotAlreadyThere (newListener);
  41677. }
  41678. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41679. {
  41680. listeners.removeValue (listenerToRemove);
  41681. }
  41682. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41683. {
  41684. const ColumnInfo* const ci = getInfoForId (columnId);
  41685. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41686. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41687. }
  41688. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41689. {
  41690. for (int i = 0; i < columns.size(); ++i)
  41691. {
  41692. const ColumnInfo* const ci = columns.getUnchecked(i);
  41693. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41694. menu.addItem (ci->id, ci->name,
  41695. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41696. isColumnVisible (ci->id));
  41697. }
  41698. }
  41699. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41700. {
  41701. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41702. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41703. }
  41704. void TableHeaderComponent::paint (Graphics& g)
  41705. {
  41706. LookAndFeel& lf = getLookAndFeel();
  41707. lf.drawTableHeaderBackground (g, *this);
  41708. const Rectangle<int> clip (g.getClipBounds());
  41709. int x = 0;
  41710. for (int i = 0; i < columns.size(); ++i)
  41711. {
  41712. const ColumnInfo* const ci = columns.getUnchecked(i);
  41713. if (ci->isVisible())
  41714. {
  41715. if (x + ci->width > clip.getX()
  41716. && (ci->id != columnIdBeingDragged
  41717. || dragOverlayComp == 0
  41718. || ! dragOverlayComp->isVisible()))
  41719. {
  41720. g.saveState();
  41721. g.setOrigin (x, 0);
  41722. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41723. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41724. ci->id == columnIdUnderMouse,
  41725. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41726. ci->propertyFlags);
  41727. g.restoreState();
  41728. }
  41729. x += ci->width;
  41730. if (x >= clip.getRight())
  41731. break;
  41732. }
  41733. }
  41734. }
  41735. void TableHeaderComponent::resized()
  41736. {
  41737. }
  41738. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41739. {
  41740. updateColumnUnderMouse (e.x, e.y);
  41741. }
  41742. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41743. {
  41744. updateColumnUnderMouse (e.x, e.y);
  41745. }
  41746. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41747. {
  41748. updateColumnUnderMouse (e.x, e.y);
  41749. }
  41750. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41751. {
  41752. repaint();
  41753. columnIdBeingResized = 0;
  41754. columnIdBeingDragged = 0;
  41755. if (columnIdUnderMouse != 0)
  41756. {
  41757. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41758. if (e.mods.isPopupMenu())
  41759. columnClicked (columnIdUnderMouse, e.mods);
  41760. }
  41761. if (menuActive && e.mods.isPopupMenu())
  41762. showColumnChooserMenu (columnIdUnderMouse);
  41763. }
  41764. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41765. {
  41766. if (columnIdBeingResized == 0
  41767. && columnIdBeingDragged == 0
  41768. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41769. {
  41770. dragOverlayComp = 0;
  41771. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41772. if (columnIdBeingResized != 0)
  41773. {
  41774. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41775. initialColumnWidth = ci->width;
  41776. }
  41777. else
  41778. {
  41779. beginDrag (e);
  41780. }
  41781. }
  41782. if (columnIdBeingResized != 0)
  41783. {
  41784. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41785. if (ci != 0)
  41786. {
  41787. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41788. initialColumnWidth + e.getDistanceFromDragStartX());
  41789. if (stretchToFit)
  41790. {
  41791. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41792. int minWidthOnRight = 0;
  41793. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41794. if (columns.getUnchecked (i)->isVisible())
  41795. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41796. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41797. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41798. }
  41799. setColumnWidth (columnIdBeingResized, w);
  41800. }
  41801. }
  41802. else if (columnIdBeingDragged != 0)
  41803. {
  41804. if (e.y >= -50 && e.y < getHeight() + 50)
  41805. {
  41806. if (dragOverlayComp != 0)
  41807. {
  41808. dragOverlayComp->setVisible (true);
  41809. dragOverlayComp->setBounds (jlimit (0,
  41810. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41811. e.x - draggingColumnOffset),
  41812. 0,
  41813. dragOverlayComp->getWidth(),
  41814. getHeight());
  41815. for (int i = columns.size(); --i >= 0;)
  41816. {
  41817. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41818. int newIndex = currentIndex;
  41819. if (newIndex > 0)
  41820. {
  41821. // if the previous column isn't draggable, we can't move our column
  41822. // past it, because that'd change the undraggable column's position..
  41823. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41824. if ((previous->propertyFlags & draggable) != 0)
  41825. {
  41826. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41827. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41828. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41829. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41830. {
  41831. --newIndex;
  41832. }
  41833. }
  41834. }
  41835. if (newIndex < columns.size() - 1)
  41836. {
  41837. // if the next column isn't draggable, we can't move our column
  41838. // past it, because that'd change the undraggable column's position..
  41839. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41840. if ((nextCol->propertyFlags & draggable) != 0)
  41841. {
  41842. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41843. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41844. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41845. > abs (dragOverlayComp->getRight() - rightOfNext))
  41846. {
  41847. ++newIndex;
  41848. }
  41849. }
  41850. }
  41851. if (newIndex != currentIndex)
  41852. moveColumn (columnIdBeingDragged, newIndex);
  41853. else
  41854. break;
  41855. }
  41856. }
  41857. }
  41858. else
  41859. {
  41860. endDrag (draggingColumnOriginalIndex);
  41861. }
  41862. }
  41863. }
  41864. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41865. {
  41866. if (columnIdBeingDragged == 0)
  41867. {
  41868. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41869. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41870. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41871. {
  41872. columnIdBeingDragged = 0;
  41873. }
  41874. else
  41875. {
  41876. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41877. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41878. const int temp = columnIdBeingDragged;
  41879. columnIdBeingDragged = 0;
  41880. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41881. columnIdBeingDragged = temp;
  41882. dragOverlayComp->setBounds (columnRect);
  41883. for (int i = listeners.size(); --i >= 0;)
  41884. {
  41885. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41886. i = jmin (i, listeners.size() - 1);
  41887. }
  41888. }
  41889. }
  41890. }
  41891. void TableHeaderComponent::endDrag (const int finalIndex)
  41892. {
  41893. if (columnIdBeingDragged != 0)
  41894. {
  41895. moveColumn (columnIdBeingDragged, finalIndex);
  41896. columnIdBeingDragged = 0;
  41897. repaint();
  41898. for (int i = listeners.size(); --i >= 0;)
  41899. {
  41900. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41901. i = jmin (i, listeners.size() - 1);
  41902. }
  41903. }
  41904. }
  41905. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41906. {
  41907. mouseDrag (e);
  41908. for (int i = columns.size(); --i >= 0;)
  41909. if (columns.getUnchecked (i)->isVisible())
  41910. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41911. columnIdBeingResized = 0;
  41912. repaint();
  41913. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41914. updateColumnUnderMouse (e.x, e.y);
  41915. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41916. columnClicked (columnIdUnderMouse, e.mods);
  41917. dragOverlayComp = 0;
  41918. }
  41919. const MouseCursor TableHeaderComponent::getMouseCursor()
  41920. {
  41921. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41922. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41923. return Component::getMouseCursor();
  41924. }
  41925. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41926. {
  41927. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41928. }
  41929. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41930. {
  41931. for (int i = columns.size(); --i >= 0;)
  41932. if (columns.getUnchecked(i)->id == id)
  41933. return columns.getUnchecked(i);
  41934. return 0;
  41935. }
  41936. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41937. {
  41938. int n = 0;
  41939. for (int i = 0; i < columns.size(); ++i)
  41940. {
  41941. if (columns.getUnchecked(i)->isVisible())
  41942. {
  41943. if (n == visibleIndex)
  41944. return i;
  41945. ++n;
  41946. }
  41947. }
  41948. return -1;
  41949. }
  41950. void TableHeaderComponent::sendColumnsChanged()
  41951. {
  41952. if (stretchToFit && lastDeliberateWidth > 0)
  41953. resizeAllColumnsToFit (lastDeliberateWidth);
  41954. repaint();
  41955. columnsChanged = true;
  41956. triggerAsyncUpdate();
  41957. }
  41958. void TableHeaderComponent::handleAsyncUpdate()
  41959. {
  41960. const bool changed = columnsChanged || sortChanged;
  41961. const bool sized = columnsResized || changed;
  41962. const bool sorted = sortChanged;
  41963. columnsChanged = false;
  41964. columnsResized = false;
  41965. sortChanged = false;
  41966. if (sorted)
  41967. {
  41968. for (int i = listeners.size(); --i >= 0;)
  41969. {
  41970. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41971. i = jmin (i, listeners.size() - 1);
  41972. }
  41973. }
  41974. if (changed)
  41975. {
  41976. for (int i = listeners.size(); --i >= 0;)
  41977. {
  41978. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41979. i = jmin (i, listeners.size() - 1);
  41980. }
  41981. }
  41982. if (sized)
  41983. {
  41984. for (int i = listeners.size(); --i >= 0;)
  41985. {
  41986. listeners.getUnchecked(i)->tableColumnsResized (this);
  41987. i = jmin (i, listeners.size() - 1);
  41988. }
  41989. }
  41990. }
  41991. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41992. {
  41993. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41994. {
  41995. const int draggableDistance = 3;
  41996. int x = 0;
  41997. for (int i = 0; i < columns.size(); ++i)
  41998. {
  41999. const ColumnInfo* const ci = columns.getUnchecked(i);
  42000. if (ci->isVisible())
  42001. {
  42002. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  42003. && (ci->propertyFlags & resizable) != 0)
  42004. return ci->id;
  42005. x += ci->width;
  42006. }
  42007. }
  42008. }
  42009. return 0;
  42010. }
  42011. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  42012. {
  42013. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  42014. ? getColumnIdAtX (x) : 0;
  42015. if (newCol != columnIdUnderMouse)
  42016. {
  42017. columnIdUnderMouse = newCol;
  42018. repaint();
  42019. }
  42020. }
  42021. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  42022. {
  42023. PopupMenu m;
  42024. addMenuItems (m, columnIdClicked);
  42025. if (m.getNumItems() > 0)
  42026. {
  42027. m.setLookAndFeel (&getLookAndFeel());
  42028. const int result = m.show();
  42029. if (result != 0)
  42030. reactToMenuItem (result, columnIdClicked);
  42031. }
  42032. }
  42033. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  42034. {
  42035. }
  42036. END_JUCE_NAMESPACE
  42037. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  42038. /*** Start of inlined file: juce_TableListBox.cpp ***/
  42039. BEGIN_JUCE_NAMESPACE
  42040. static const char* const tableColumnPropertyTag = "_tableColumnID";
  42041. class TableListRowComp : public Component,
  42042. public TooltipClient
  42043. {
  42044. public:
  42045. TableListRowComp (TableListBox& owner_)
  42046. : owner (owner_),
  42047. row (-1),
  42048. isSelected (false)
  42049. {
  42050. }
  42051. ~TableListRowComp()
  42052. {
  42053. deleteAllChildren();
  42054. }
  42055. void paint (Graphics& g)
  42056. {
  42057. TableListBoxModel* const model = owner.getModel();
  42058. if (model != 0)
  42059. {
  42060. const TableHeaderComponent* const header = owner.getHeader();
  42061. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  42062. const int numColumns = header->getNumColumns (true);
  42063. for (int i = 0; i < numColumns; ++i)
  42064. {
  42065. if (! columnsWithComponents [i])
  42066. {
  42067. const int columnId = header->getColumnIdOfIndex (i, true);
  42068. Rectangle<int> columnRect (header->getColumnPosition (i));
  42069. columnRect.setSize (columnRect.getWidth(), getHeight());
  42070. g.saveState();
  42071. g.reduceClipRegion (columnRect);
  42072. g.setOrigin (columnRect.getX(), 0);
  42073. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  42074. g.restoreState();
  42075. }
  42076. }
  42077. }
  42078. }
  42079. void update (const int newRow, const bool isNowSelected)
  42080. {
  42081. if (newRow != row || isNowSelected != isSelected)
  42082. {
  42083. row = newRow;
  42084. isSelected = isNowSelected;
  42085. repaint();
  42086. deleteAllChildren();
  42087. }
  42088. if (row < owner.getNumRows())
  42089. {
  42090. jassert (row >= 0);
  42091. const Identifier tagPropertyName ("_tableLastUseNum");
  42092. const int newTag = Random::getSystemRandom().nextInt();
  42093. const TableHeaderComponent* const header = owner.getHeader();
  42094. const int numColumns = header->getNumColumns (true);
  42095. columnsWithComponents.clear();
  42096. if (owner.getModel() != 0)
  42097. {
  42098. for (int i = 0; i < numColumns; ++i)
  42099. {
  42100. const int columnId = header->getColumnIdOfIndex (i, true);
  42101. Component* const newComp
  42102. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  42103. findChildComponentForColumn (columnId));
  42104. if (newComp != 0)
  42105. {
  42106. addAndMakeVisible (newComp);
  42107. newComp->getProperties().set (tagPropertyName, newTag);
  42108. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  42109. const Rectangle<int> columnRect (header->getColumnPosition (i));
  42110. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  42111. columnsWithComponents.setBit (i);
  42112. }
  42113. }
  42114. }
  42115. for (int i = getNumChildComponents(); --i >= 0;)
  42116. {
  42117. Component* const c = getChildComponent (i);
  42118. if ((int) c->getProperties() [tagPropertyName] != newTag)
  42119. delete c;
  42120. }
  42121. }
  42122. else
  42123. {
  42124. columnsWithComponents.clear();
  42125. deleteAllChildren();
  42126. }
  42127. }
  42128. void resized()
  42129. {
  42130. for (int i = getNumChildComponents(); --i >= 0;)
  42131. {
  42132. Component* const c = getChildComponent (i);
  42133. const int columnId = c->getProperties() [tableColumnPropertyTag];
  42134. if (columnId != 0)
  42135. {
  42136. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  42137. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  42138. }
  42139. }
  42140. }
  42141. void mouseDown (const MouseEvent& e)
  42142. {
  42143. isDragging = false;
  42144. selectRowOnMouseUp = false;
  42145. if (isEnabled())
  42146. {
  42147. if (! isSelected)
  42148. {
  42149. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  42150. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  42151. if (columnId != 0 && owner.getModel() != 0)
  42152. owner.getModel()->cellClicked (row, columnId, e);
  42153. }
  42154. else
  42155. {
  42156. selectRowOnMouseUp = true;
  42157. }
  42158. }
  42159. }
  42160. void mouseDrag (const MouseEvent& e)
  42161. {
  42162. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  42163. {
  42164. const SparseSet<int> selectedRows (owner.getSelectedRows());
  42165. if (selectedRows.size() > 0)
  42166. {
  42167. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  42168. if (dragDescription.isNotEmpty())
  42169. {
  42170. isDragging = true;
  42171. owner.startDragAndDrop (e, dragDescription);
  42172. }
  42173. }
  42174. }
  42175. }
  42176. void mouseUp (const MouseEvent& e)
  42177. {
  42178. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  42179. {
  42180. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  42181. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  42182. if (columnId != 0 && owner.getModel() != 0)
  42183. owner.getModel()->cellClicked (row, columnId, e);
  42184. }
  42185. }
  42186. void mouseDoubleClick (const MouseEvent& e)
  42187. {
  42188. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  42189. if (columnId != 0 && owner.getModel() != 0)
  42190. owner.getModel()->cellDoubleClicked (row, columnId, e);
  42191. }
  42192. const String getTooltip()
  42193. {
  42194. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  42195. if (columnId != 0 && owner.getModel() != 0)
  42196. return owner.getModel()->getCellTooltip (row, columnId);
  42197. return String::empty;
  42198. }
  42199. Component* findChildComponentForColumn (const int columnId) const
  42200. {
  42201. for (int i = getNumChildComponents(); --i >= 0;)
  42202. {
  42203. Component* const c = getChildComponent (i);
  42204. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  42205. return c;
  42206. }
  42207. return 0;
  42208. }
  42209. juce_UseDebuggingNewOperator
  42210. private:
  42211. TableListBox& owner;
  42212. int row;
  42213. bool isSelected, isDragging, selectRowOnMouseUp;
  42214. BigInteger columnsWithComponents;
  42215. TableListRowComp (const TableListRowComp&);
  42216. TableListRowComp& operator= (const TableListRowComp&);
  42217. };
  42218. class TableListBoxHeader : public TableHeaderComponent
  42219. {
  42220. public:
  42221. TableListBoxHeader (TableListBox& owner_)
  42222. : owner (owner_)
  42223. {
  42224. }
  42225. ~TableListBoxHeader()
  42226. {
  42227. }
  42228. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  42229. {
  42230. if (owner.isAutoSizeMenuOptionShown())
  42231. {
  42232. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  42233. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  42234. menu.addSeparator();
  42235. }
  42236. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  42237. }
  42238. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  42239. {
  42240. if (menuReturnId == 0xf836743)
  42241. {
  42242. owner.autoSizeColumn (columnIdClicked);
  42243. }
  42244. else if (menuReturnId == 0xf836744)
  42245. {
  42246. owner.autoSizeAllColumns();
  42247. }
  42248. else
  42249. {
  42250. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  42251. }
  42252. }
  42253. juce_UseDebuggingNewOperator
  42254. private:
  42255. TableListBox& owner;
  42256. TableListBoxHeader (const TableListBoxHeader&);
  42257. TableListBoxHeader& operator= (const TableListBoxHeader&);
  42258. };
  42259. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  42260. : ListBox (name, 0),
  42261. model (model_),
  42262. autoSizeOptionsShown (true)
  42263. {
  42264. ListBox::model = this;
  42265. header = new TableListBoxHeader (*this);
  42266. header->setSize (100, 28);
  42267. header->addListener (this);
  42268. setHeaderComponent (header);
  42269. }
  42270. TableListBox::~TableListBox()
  42271. {
  42272. header = 0;
  42273. }
  42274. void TableListBox::setModel (TableListBoxModel* const newModel)
  42275. {
  42276. if (model != newModel)
  42277. {
  42278. model = newModel;
  42279. updateContent();
  42280. }
  42281. }
  42282. int TableListBox::getHeaderHeight() const
  42283. {
  42284. return header->getHeight();
  42285. }
  42286. void TableListBox::setHeaderHeight (const int newHeight)
  42287. {
  42288. header->setSize (header->getWidth(), newHeight);
  42289. resized();
  42290. }
  42291. void TableListBox::autoSizeColumn (const int columnId)
  42292. {
  42293. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  42294. if (width > 0)
  42295. header->setColumnWidth (columnId, width);
  42296. }
  42297. void TableListBox::autoSizeAllColumns()
  42298. {
  42299. for (int i = 0; i < header->getNumColumns (true); ++i)
  42300. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  42301. }
  42302. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  42303. {
  42304. autoSizeOptionsShown = shouldBeShown;
  42305. }
  42306. bool TableListBox::isAutoSizeMenuOptionShown() const
  42307. {
  42308. return autoSizeOptionsShown;
  42309. }
  42310. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  42311. const int rowNumber,
  42312. const bool relativeToComponentTopLeft) const
  42313. {
  42314. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42315. if (relativeToComponentTopLeft)
  42316. headerCell.translate (header->getX(), 0);
  42317. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  42318. return Rectangle<int> (headerCell.getX(), row.getY(),
  42319. headerCell.getWidth(), row.getHeight());
  42320. }
  42321. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  42322. {
  42323. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  42324. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  42325. }
  42326. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  42327. {
  42328. ScrollBar* const scrollbar = getHorizontalScrollBar();
  42329. if (scrollbar != 0)
  42330. {
  42331. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42332. double x = scrollbar->getCurrentRangeStart();
  42333. const double w = scrollbar->getCurrentRangeSize();
  42334. if (pos.getX() < x)
  42335. x = pos.getX();
  42336. else if (pos.getRight() > x + w)
  42337. x += jmax (0.0, pos.getRight() - (x + w));
  42338. scrollbar->setCurrentRangeStart (x);
  42339. }
  42340. }
  42341. int TableListBox::getNumRows()
  42342. {
  42343. return model != 0 ? model->getNumRows() : 0;
  42344. }
  42345. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  42346. {
  42347. }
  42348. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  42349. {
  42350. if (existingComponentToUpdate == 0)
  42351. existingComponentToUpdate = new TableListRowComp (*this);
  42352. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42353. return existingComponentToUpdate;
  42354. }
  42355. void TableListBox::selectedRowsChanged (int row)
  42356. {
  42357. if (model != 0)
  42358. model->selectedRowsChanged (row);
  42359. }
  42360. void TableListBox::deleteKeyPressed (int row)
  42361. {
  42362. if (model != 0)
  42363. model->deleteKeyPressed (row);
  42364. }
  42365. void TableListBox::returnKeyPressed (int row)
  42366. {
  42367. if (model != 0)
  42368. model->returnKeyPressed (row);
  42369. }
  42370. void TableListBox::backgroundClicked()
  42371. {
  42372. if (model != 0)
  42373. model->backgroundClicked();
  42374. }
  42375. void TableListBox::listWasScrolled()
  42376. {
  42377. if (model != 0)
  42378. model->listWasScrolled();
  42379. }
  42380. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42381. {
  42382. setMinimumContentWidth (header->getTotalWidth());
  42383. repaint();
  42384. updateColumnComponents();
  42385. }
  42386. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42387. {
  42388. setMinimumContentWidth (header->getTotalWidth());
  42389. repaint();
  42390. updateColumnComponents();
  42391. }
  42392. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42393. {
  42394. if (model != 0)
  42395. model->sortOrderChanged (header->getSortColumnId(),
  42396. header->isSortedForwards());
  42397. }
  42398. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42399. {
  42400. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42401. repaint();
  42402. }
  42403. void TableListBox::resized()
  42404. {
  42405. ListBox::resized();
  42406. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42407. setMinimumContentWidth (header->getTotalWidth());
  42408. }
  42409. void TableListBox::updateColumnComponents() const
  42410. {
  42411. const int firstRow = getRowContainingPosition (0, 0);
  42412. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42413. {
  42414. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42415. if (rowComp != 0)
  42416. rowComp->resized();
  42417. }
  42418. }
  42419. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42420. {
  42421. }
  42422. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42423. {
  42424. }
  42425. void TableListBoxModel::backgroundClicked()
  42426. {
  42427. }
  42428. void TableListBoxModel::sortOrderChanged (int, const bool)
  42429. {
  42430. }
  42431. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42432. {
  42433. return 0;
  42434. }
  42435. void TableListBoxModel::selectedRowsChanged (int)
  42436. {
  42437. }
  42438. void TableListBoxModel::deleteKeyPressed (int)
  42439. {
  42440. }
  42441. void TableListBoxModel::returnKeyPressed (int)
  42442. {
  42443. }
  42444. void TableListBoxModel::listWasScrolled()
  42445. {
  42446. }
  42447. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42448. {
  42449. return String::empty;
  42450. }
  42451. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42452. {
  42453. return String::empty;
  42454. }
  42455. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42456. {
  42457. (void) existingComponentToUpdate;
  42458. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42459. return 0;
  42460. }
  42461. END_JUCE_NAMESPACE
  42462. /*** End of inlined file: juce_TableListBox.cpp ***/
  42463. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42464. BEGIN_JUCE_NAMESPACE
  42465. // a word or space that can't be broken down any further
  42466. struct TextAtom
  42467. {
  42468. String atomText;
  42469. float width;
  42470. uint16 numChars;
  42471. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42472. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42473. const String getText (const juce_wchar passwordCharacter) const
  42474. {
  42475. if (passwordCharacter == 0)
  42476. return atomText;
  42477. else
  42478. return String::repeatedString (String::charToString (passwordCharacter),
  42479. atomText.length());
  42480. }
  42481. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42482. {
  42483. if (passwordCharacter == 0)
  42484. return atomText.substring (0, numChars);
  42485. else if (isNewLine())
  42486. return String::empty;
  42487. else
  42488. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42489. }
  42490. };
  42491. // a run of text with a single font and colour
  42492. class TextEditor::UniformTextSection
  42493. {
  42494. public:
  42495. UniformTextSection (const String& text,
  42496. const Font& font_,
  42497. const Colour& colour_,
  42498. const juce_wchar passwordCharacter)
  42499. : font (font_),
  42500. colour (colour_)
  42501. {
  42502. initialiseAtoms (text, passwordCharacter);
  42503. }
  42504. UniformTextSection (const UniformTextSection& other)
  42505. : font (other.font),
  42506. colour (other.colour)
  42507. {
  42508. atoms.ensureStorageAllocated (other.atoms.size());
  42509. for (int i = 0; i < other.atoms.size(); ++i)
  42510. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42511. }
  42512. ~UniformTextSection()
  42513. {
  42514. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42515. }
  42516. void clear()
  42517. {
  42518. for (int i = atoms.size(); --i >= 0;)
  42519. delete getAtom(i);
  42520. atoms.clear();
  42521. }
  42522. int getNumAtoms() const
  42523. {
  42524. return atoms.size();
  42525. }
  42526. TextAtom* getAtom (const int index) const throw()
  42527. {
  42528. return atoms.getUnchecked (index);
  42529. }
  42530. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42531. {
  42532. if (other.atoms.size() > 0)
  42533. {
  42534. TextAtom* const lastAtom = atoms.getLast();
  42535. int i = 0;
  42536. if (lastAtom != 0)
  42537. {
  42538. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42539. {
  42540. TextAtom* const first = other.getAtom(0);
  42541. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42542. {
  42543. lastAtom->atomText += first->atomText;
  42544. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42545. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42546. delete first;
  42547. ++i;
  42548. }
  42549. }
  42550. }
  42551. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42552. while (i < other.atoms.size())
  42553. {
  42554. atoms.add (other.getAtom(i));
  42555. ++i;
  42556. }
  42557. }
  42558. }
  42559. UniformTextSection* split (const int indexToBreakAt,
  42560. const juce_wchar passwordCharacter)
  42561. {
  42562. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42563. font, colour,
  42564. passwordCharacter);
  42565. int index = 0;
  42566. for (int i = 0; i < atoms.size(); ++i)
  42567. {
  42568. TextAtom* const atom = getAtom(i);
  42569. const int nextIndex = index + atom->numChars;
  42570. if (index == indexToBreakAt)
  42571. {
  42572. int j;
  42573. for (j = i; j < atoms.size(); ++j)
  42574. section2->atoms.add (getAtom (j));
  42575. for (j = atoms.size(); --j >= i;)
  42576. atoms.remove (j);
  42577. break;
  42578. }
  42579. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42580. {
  42581. TextAtom* const secondAtom = new TextAtom();
  42582. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42583. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42584. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42585. section2->atoms.add (secondAtom);
  42586. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42587. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42588. atom->numChars = (uint16) (indexToBreakAt - index);
  42589. int j;
  42590. for (j = i + 1; j < atoms.size(); ++j)
  42591. section2->atoms.add (getAtom (j));
  42592. for (j = atoms.size(); --j > i;)
  42593. atoms.remove (j);
  42594. break;
  42595. }
  42596. index = nextIndex;
  42597. }
  42598. return section2;
  42599. }
  42600. void appendAllText (String::Concatenator& concatenator) const
  42601. {
  42602. for (int i = 0; i < atoms.size(); ++i)
  42603. concatenator.append (getAtom(i)->atomText);
  42604. }
  42605. void appendSubstring (String::Concatenator& concatenator,
  42606. const Range<int>& range) const
  42607. {
  42608. int index = 0;
  42609. for (int i = 0; i < atoms.size(); ++i)
  42610. {
  42611. const TextAtom* const atom = getAtom (i);
  42612. const int nextIndex = index + atom->numChars;
  42613. if (range.getStart() < nextIndex)
  42614. {
  42615. if (range.getEnd() <= index)
  42616. break;
  42617. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42618. if (! r.isEmpty())
  42619. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42620. }
  42621. index = nextIndex;
  42622. }
  42623. }
  42624. int getTotalLength() const
  42625. {
  42626. int total = 0;
  42627. for (int i = atoms.size(); --i >= 0;)
  42628. total += getAtom(i)->numChars;
  42629. return total;
  42630. }
  42631. void setFont (const Font& newFont,
  42632. const juce_wchar passwordCharacter)
  42633. {
  42634. if (font != newFont)
  42635. {
  42636. font = newFont;
  42637. for (int i = atoms.size(); --i >= 0;)
  42638. {
  42639. TextAtom* const atom = atoms.getUnchecked(i);
  42640. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42641. }
  42642. }
  42643. }
  42644. juce_UseDebuggingNewOperator
  42645. Font font;
  42646. Colour colour;
  42647. private:
  42648. Array <TextAtom*> atoms;
  42649. void initialiseAtoms (const String& textToParse,
  42650. const juce_wchar passwordCharacter)
  42651. {
  42652. int i = 0;
  42653. const int len = textToParse.length();
  42654. const juce_wchar* const text = textToParse;
  42655. while (i < len)
  42656. {
  42657. int start = i;
  42658. // create a whitespace atom unless it starts with non-ws
  42659. if (CharacterFunctions::isWhitespace (text[i])
  42660. && text[i] != '\r'
  42661. && text[i] != '\n')
  42662. {
  42663. while (i < len
  42664. && CharacterFunctions::isWhitespace (text[i])
  42665. && text[i] != '\r'
  42666. && text[i] != '\n')
  42667. {
  42668. ++i;
  42669. }
  42670. }
  42671. else
  42672. {
  42673. if (text[i] == '\r')
  42674. {
  42675. ++i;
  42676. if ((i < len) && (text[i] == '\n'))
  42677. {
  42678. ++start;
  42679. ++i;
  42680. }
  42681. }
  42682. else if (text[i] == '\n')
  42683. {
  42684. ++i;
  42685. }
  42686. else
  42687. {
  42688. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42689. ++i;
  42690. }
  42691. }
  42692. TextAtom* const atom = new TextAtom();
  42693. atom->atomText = String (text + start, i - start);
  42694. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42695. atom->numChars = (uint16) (i - start);
  42696. atoms.add (atom);
  42697. }
  42698. }
  42699. UniformTextSection& operator= (const UniformTextSection& other);
  42700. };
  42701. class TextEditor::Iterator
  42702. {
  42703. public:
  42704. Iterator (const Array <UniformTextSection*>& sections_,
  42705. const float wordWrapWidth_,
  42706. const juce_wchar passwordCharacter_)
  42707. : indexInText (0),
  42708. lineY (0),
  42709. lineHeight (0),
  42710. maxDescent (0),
  42711. atomX (0),
  42712. atomRight (0),
  42713. atom (0),
  42714. currentSection (0),
  42715. sections (sections_),
  42716. sectionIndex (0),
  42717. atomIndex (0),
  42718. wordWrapWidth (wordWrapWidth_),
  42719. passwordCharacter (passwordCharacter_)
  42720. {
  42721. jassert (wordWrapWidth_ > 0);
  42722. if (sections.size() > 0)
  42723. {
  42724. currentSection = sections.getUnchecked (sectionIndex);
  42725. if (currentSection != 0)
  42726. beginNewLine();
  42727. }
  42728. }
  42729. Iterator (const Iterator& other)
  42730. : indexInText (other.indexInText),
  42731. lineY (other.lineY),
  42732. lineHeight (other.lineHeight),
  42733. maxDescent (other.maxDescent),
  42734. atomX (other.atomX),
  42735. atomRight (other.atomRight),
  42736. atom (other.atom),
  42737. currentSection (other.currentSection),
  42738. sections (other.sections),
  42739. sectionIndex (other.sectionIndex),
  42740. atomIndex (other.atomIndex),
  42741. wordWrapWidth (other.wordWrapWidth),
  42742. passwordCharacter (other.passwordCharacter),
  42743. tempAtom (other.tempAtom)
  42744. {
  42745. }
  42746. ~Iterator()
  42747. {
  42748. }
  42749. bool next()
  42750. {
  42751. if (atom == &tempAtom)
  42752. {
  42753. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42754. if (numRemaining > 0)
  42755. {
  42756. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42757. atomX = 0;
  42758. if (tempAtom.numChars > 0)
  42759. lineY += lineHeight;
  42760. indexInText += tempAtom.numChars;
  42761. GlyphArrangement g;
  42762. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42763. int split;
  42764. for (split = 0; split < g.getNumGlyphs(); ++split)
  42765. if (shouldWrap (g.getGlyph (split).getRight()))
  42766. break;
  42767. if (split > 0 && split <= numRemaining)
  42768. {
  42769. tempAtom.numChars = (uint16) split;
  42770. tempAtom.width = g.getGlyph (split - 1).getRight();
  42771. atomRight = atomX + tempAtom.width;
  42772. return true;
  42773. }
  42774. }
  42775. }
  42776. bool forceNewLine = false;
  42777. if (sectionIndex >= sections.size())
  42778. {
  42779. moveToEndOfLastAtom();
  42780. return false;
  42781. }
  42782. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42783. {
  42784. if (atomIndex >= currentSection->getNumAtoms())
  42785. {
  42786. if (++sectionIndex >= sections.size())
  42787. {
  42788. moveToEndOfLastAtom();
  42789. return false;
  42790. }
  42791. atomIndex = 0;
  42792. currentSection = sections.getUnchecked (sectionIndex);
  42793. }
  42794. else
  42795. {
  42796. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42797. if (! lastAtom->isWhitespace())
  42798. {
  42799. // handle the case where the last atom in a section is actually part of the same
  42800. // word as the first atom of the next section...
  42801. float right = atomRight + lastAtom->width;
  42802. float lineHeight2 = lineHeight;
  42803. float maxDescent2 = maxDescent;
  42804. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42805. {
  42806. const UniformTextSection* const s = sections.getUnchecked (section);
  42807. if (s->getNumAtoms() == 0)
  42808. break;
  42809. const TextAtom* const nextAtom = s->getAtom (0);
  42810. if (nextAtom->isWhitespace())
  42811. break;
  42812. right += nextAtom->width;
  42813. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42814. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42815. if (shouldWrap (right))
  42816. {
  42817. lineHeight = lineHeight2;
  42818. maxDescent = maxDescent2;
  42819. forceNewLine = true;
  42820. break;
  42821. }
  42822. if (s->getNumAtoms() > 1)
  42823. break;
  42824. }
  42825. }
  42826. }
  42827. }
  42828. if (atom != 0)
  42829. {
  42830. atomX = atomRight;
  42831. indexInText += atom->numChars;
  42832. if (atom->isNewLine())
  42833. beginNewLine();
  42834. }
  42835. atom = currentSection->getAtom (atomIndex);
  42836. atomRight = atomX + atom->width;
  42837. ++atomIndex;
  42838. if (shouldWrap (atomRight) || forceNewLine)
  42839. {
  42840. if (atom->isWhitespace())
  42841. {
  42842. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42843. atomRight = jmin (atomRight, wordWrapWidth);
  42844. }
  42845. else
  42846. {
  42847. atomRight = atom->width;
  42848. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42849. {
  42850. tempAtom = *atom;
  42851. tempAtom.width = 0;
  42852. tempAtom.numChars = 0;
  42853. atom = &tempAtom;
  42854. if (atomX > 0)
  42855. beginNewLine();
  42856. return next();
  42857. }
  42858. beginNewLine();
  42859. return true;
  42860. }
  42861. }
  42862. return true;
  42863. }
  42864. void beginNewLine()
  42865. {
  42866. atomX = 0;
  42867. lineY += lineHeight;
  42868. int tempSectionIndex = sectionIndex;
  42869. int tempAtomIndex = atomIndex;
  42870. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42871. lineHeight = section->font.getHeight();
  42872. maxDescent = section->font.getDescent();
  42873. float x = (atom != 0) ? atom->width : 0;
  42874. while (! shouldWrap (x))
  42875. {
  42876. if (tempSectionIndex >= sections.size())
  42877. break;
  42878. bool checkSize = false;
  42879. if (tempAtomIndex >= section->getNumAtoms())
  42880. {
  42881. if (++tempSectionIndex >= sections.size())
  42882. break;
  42883. tempAtomIndex = 0;
  42884. section = sections.getUnchecked (tempSectionIndex);
  42885. checkSize = true;
  42886. }
  42887. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42888. if (nextAtom == 0)
  42889. break;
  42890. x += nextAtom->width;
  42891. if (shouldWrap (x) || nextAtom->isNewLine())
  42892. break;
  42893. if (checkSize)
  42894. {
  42895. lineHeight = jmax (lineHeight, section->font.getHeight());
  42896. maxDescent = jmax (maxDescent, section->font.getDescent());
  42897. }
  42898. ++tempAtomIndex;
  42899. }
  42900. }
  42901. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42902. {
  42903. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42904. {
  42905. if (lastSection != currentSection)
  42906. {
  42907. lastSection = currentSection;
  42908. g.setColour (currentSection->colour);
  42909. g.setFont (currentSection->font);
  42910. }
  42911. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42912. GlyphArrangement ga;
  42913. ga.addLineOfText (currentSection->font,
  42914. atom->getTrimmedText (passwordCharacter),
  42915. atomX,
  42916. (float) roundToInt (lineY + lineHeight - maxDescent));
  42917. ga.draw (g);
  42918. }
  42919. }
  42920. void drawSelection (Graphics& g,
  42921. const Range<int>& selection) const
  42922. {
  42923. const int startX = roundToInt (indexToX (selection.getStart()));
  42924. const int endX = roundToInt (indexToX (selection.getEnd()));
  42925. const int y = roundToInt (lineY);
  42926. const int nextY = roundToInt (lineY + lineHeight);
  42927. g.fillRect (startX, y, endX - startX, nextY - y);
  42928. }
  42929. void drawSelectedText (Graphics& g,
  42930. const Range<int>& selection,
  42931. const Colour& selectedTextColour) const
  42932. {
  42933. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42934. {
  42935. GlyphArrangement ga;
  42936. ga.addLineOfText (currentSection->font,
  42937. atom->getTrimmedText (passwordCharacter),
  42938. atomX,
  42939. (float) roundToInt (lineY + lineHeight - maxDescent));
  42940. if (selection.getEnd() < indexInText + atom->numChars)
  42941. {
  42942. GlyphArrangement ga2 (ga);
  42943. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42944. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42945. g.setColour (currentSection->colour);
  42946. ga2.draw (g);
  42947. }
  42948. if (selection.getStart() > indexInText)
  42949. {
  42950. GlyphArrangement ga2 (ga);
  42951. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42952. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42953. g.setColour (currentSection->colour);
  42954. ga2.draw (g);
  42955. }
  42956. g.setColour (selectedTextColour);
  42957. ga.draw (g);
  42958. }
  42959. }
  42960. float indexToX (const int indexToFind) const
  42961. {
  42962. if (indexToFind <= indexInText)
  42963. return atomX;
  42964. if (indexToFind >= indexInText + atom->numChars)
  42965. return atomRight;
  42966. GlyphArrangement g;
  42967. g.addLineOfText (currentSection->font,
  42968. atom->getText (passwordCharacter),
  42969. atomX, 0.0f);
  42970. if (indexToFind - indexInText >= g.getNumGlyphs())
  42971. return atomRight;
  42972. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42973. }
  42974. int xToIndex (const float xToFind) const
  42975. {
  42976. if (xToFind <= atomX || atom->isNewLine())
  42977. return indexInText;
  42978. if (xToFind >= atomRight)
  42979. return indexInText + atom->numChars;
  42980. GlyphArrangement g;
  42981. g.addLineOfText (currentSection->font,
  42982. atom->getText (passwordCharacter),
  42983. atomX, 0.0f);
  42984. int j;
  42985. for (j = 0; j < g.getNumGlyphs(); ++j)
  42986. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42987. break;
  42988. return indexInText + j;
  42989. }
  42990. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42991. {
  42992. while (next())
  42993. {
  42994. if (indexInText + atom->numChars > index)
  42995. {
  42996. cx = indexToX (index);
  42997. cy = lineY;
  42998. lineHeight_ = lineHeight;
  42999. return true;
  43000. }
  43001. }
  43002. cx = atomX;
  43003. cy = lineY;
  43004. lineHeight_ = lineHeight;
  43005. return false;
  43006. }
  43007. juce_UseDebuggingNewOperator
  43008. int indexInText;
  43009. float lineY, lineHeight, maxDescent;
  43010. float atomX, atomRight;
  43011. const TextAtom* atom;
  43012. const UniformTextSection* currentSection;
  43013. private:
  43014. const Array <UniformTextSection*>& sections;
  43015. int sectionIndex, atomIndex;
  43016. const float wordWrapWidth;
  43017. const juce_wchar passwordCharacter;
  43018. TextAtom tempAtom;
  43019. Iterator& operator= (const Iterator&);
  43020. void moveToEndOfLastAtom()
  43021. {
  43022. if (atom != 0)
  43023. {
  43024. atomX = atomRight;
  43025. if (atom->isNewLine())
  43026. {
  43027. atomX = 0.0f;
  43028. lineY += lineHeight;
  43029. }
  43030. }
  43031. }
  43032. bool shouldWrap (const float x) const
  43033. {
  43034. return (x - 0.0001f) >= wordWrapWidth;
  43035. }
  43036. };
  43037. class TextEditor::InsertAction : public UndoableAction
  43038. {
  43039. TextEditor& owner;
  43040. const String text;
  43041. const int insertIndex, oldCaretPos, newCaretPos;
  43042. const Font font;
  43043. const Colour colour;
  43044. InsertAction (const InsertAction&);
  43045. InsertAction& operator= (const InsertAction&);
  43046. public:
  43047. InsertAction (TextEditor& owner_,
  43048. const String& text_,
  43049. const int insertIndex_,
  43050. const Font& font_,
  43051. const Colour& colour_,
  43052. const int oldCaretPos_,
  43053. const int newCaretPos_)
  43054. : owner (owner_),
  43055. text (text_),
  43056. insertIndex (insertIndex_),
  43057. oldCaretPos (oldCaretPos_),
  43058. newCaretPos (newCaretPos_),
  43059. font (font_),
  43060. colour (colour_)
  43061. {
  43062. }
  43063. ~InsertAction()
  43064. {
  43065. }
  43066. bool perform()
  43067. {
  43068. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  43069. return true;
  43070. }
  43071. bool undo()
  43072. {
  43073. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  43074. return true;
  43075. }
  43076. int getSizeInUnits()
  43077. {
  43078. return text.length() + 16;
  43079. }
  43080. };
  43081. class TextEditor::RemoveAction : public UndoableAction
  43082. {
  43083. TextEditor& owner;
  43084. const Range<int> range;
  43085. const int oldCaretPos, newCaretPos;
  43086. Array <UniformTextSection*> removedSections;
  43087. RemoveAction (const RemoveAction&);
  43088. RemoveAction& operator= (const RemoveAction&);
  43089. public:
  43090. RemoveAction (TextEditor& owner_,
  43091. const Range<int> range_,
  43092. const int oldCaretPos_,
  43093. const int newCaretPos_,
  43094. const Array <UniformTextSection*>& removedSections_)
  43095. : owner (owner_),
  43096. range (range_),
  43097. oldCaretPos (oldCaretPos_),
  43098. newCaretPos (newCaretPos_),
  43099. removedSections (removedSections_)
  43100. {
  43101. }
  43102. ~RemoveAction()
  43103. {
  43104. for (int i = removedSections.size(); --i >= 0;)
  43105. {
  43106. UniformTextSection* const section = removedSections.getUnchecked (i);
  43107. section->clear();
  43108. delete section;
  43109. }
  43110. }
  43111. bool perform()
  43112. {
  43113. owner.remove (range, 0, newCaretPos);
  43114. return true;
  43115. }
  43116. bool undo()
  43117. {
  43118. owner.reinsert (range.getStart(), removedSections);
  43119. owner.moveCursorTo (oldCaretPos, false);
  43120. return true;
  43121. }
  43122. int getSizeInUnits()
  43123. {
  43124. int n = 0;
  43125. for (int i = removedSections.size(); --i >= 0;)
  43126. n += removedSections.getUnchecked (i)->getTotalLength();
  43127. return n + 16;
  43128. }
  43129. };
  43130. class TextEditor::TextHolderComponent : public Component,
  43131. public Timer,
  43132. public Value::Listener
  43133. {
  43134. public:
  43135. TextHolderComponent (TextEditor& owner_)
  43136. : owner (owner_)
  43137. {
  43138. setWantsKeyboardFocus (false);
  43139. setInterceptsMouseClicks (false, true);
  43140. owner.getTextValue().addListener (this);
  43141. }
  43142. ~TextHolderComponent()
  43143. {
  43144. owner.getTextValue().removeListener (this);
  43145. }
  43146. void paint (Graphics& g)
  43147. {
  43148. owner.drawContent (g);
  43149. }
  43150. void timerCallback()
  43151. {
  43152. owner.timerCallbackInt();
  43153. }
  43154. const MouseCursor getMouseCursor()
  43155. {
  43156. return owner.getMouseCursor();
  43157. }
  43158. void valueChanged (Value&)
  43159. {
  43160. owner.textWasChangedByValue();
  43161. }
  43162. private:
  43163. TextEditor& owner;
  43164. TextHolderComponent (const TextHolderComponent&);
  43165. TextHolderComponent& operator= (const TextHolderComponent&);
  43166. };
  43167. class TextEditorViewport : public Viewport
  43168. {
  43169. public:
  43170. TextEditorViewport (TextEditor* const owner_)
  43171. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  43172. {
  43173. }
  43174. ~TextEditorViewport()
  43175. {
  43176. }
  43177. void visibleAreaChanged (int, int, int, int)
  43178. {
  43179. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  43180. // appear and disappear, causing the wrap width to change.
  43181. {
  43182. const float wordWrapWidth = owner->getWordWrapWidth();
  43183. if (wordWrapWidth != lastWordWrapWidth)
  43184. {
  43185. lastWordWrapWidth = wordWrapWidth;
  43186. rentrant = true;
  43187. owner->updateTextHolderSize();
  43188. rentrant = false;
  43189. }
  43190. }
  43191. }
  43192. private:
  43193. TextEditor* const owner;
  43194. float lastWordWrapWidth;
  43195. bool rentrant;
  43196. TextEditorViewport (const TextEditorViewport&);
  43197. TextEditorViewport& operator= (const TextEditorViewport&);
  43198. };
  43199. namespace TextEditorDefs
  43200. {
  43201. const int flashSpeedIntervalMs = 380;
  43202. const int textChangeMessageId = 0x10003001;
  43203. const int returnKeyMessageId = 0x10003002;
  43204. const int escapeKeyMessageId = 0x10003003;
  43205. const int focusLossMessageId = 0x10003004;
  43206. const int maxActionsPerTransaction = 100;
  43207. static int getCharacterCategory (const juce_wchar character)
  43208. {
  43209. return CharacterFunctions::isLetterOrDigit (character)
  43210. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43211. }
  43212. }
  43213. TextEditor::TextEditor (const String& name,
  43214. const juce_wchar passwordCharacter_)
  43215. : Component (name),
  43216. borderSize (1, 1, 1, 3),
  43217. readOnly (false),
  43218. multiline (false),
  43219. wordWrap (false),
  43220. returnKeyStartsNewLine (false),
  43221. caretVisible (true),
  43222. popupMenuEnabled (true),
  43223. selectAllTextWhenFocused (false),
  43224. scrollbarVisible (true),
  43225. wasFocused (false),
  43226. caretFlashState (true),
  43227. keepCursorOnScreen (true),
  43228. tabKeyUsed (false),
  43229. menuActive (false),
  43230. valueTextNeedsUpdating (false),
  43231. cursorX (0),
  43232. cursorY (0),
  43233. cursorHeight (0),
  43234. maxTextLength (0),
  43235. leftIndent (4),
  43236. topIndent (4),
  43237. lastTransactionTime (0),
  43238. currentFont (14.0f),
  43239. totalNumChars (0),
  43240. caretPosition (0),
  43241. passwordCharacter (passwordCharacter_),
  43242. dragType (notDragging)
  43243. {
  43244. setOpaque (true);
  43245. addAndMakeVisible (viewport = new TextEditorViewport (this));
  43246. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  43247. viewport->setWantsKeyboardFocus (false);
  43248. viewport->setScrollBarsShown (false, false);
  43249. setMouseCursor (MouseCursor::IBeamCursor);
  43250. setWantsKeyboardFocus (true);
  43251. }
  43252. TextEditor::~TextEditor()
  43253. {
  43254. textValue.referTo (Value());
  43255. clearInternal (0);
  43256. viewport = 0;
  43257. textHolder = 0;
  43258. }
  43259. void TextEditor::newTransaction()
  43260. {
  43261. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43262. undoManager.beginNewTransaction();
  43263. }
  43264. void TextEditor::doUndoRedo (const bool isRedo)
  43265. {
  43266. if (! isReadOnly())
  43267. {
  43268. if (isRedo ? undoManager.redo()
  43269. : undoManager.undo())
  43270. {
  43271. scrollToMakeSureCursorIsVisible();
  43272. repaint();
  43273. textChanged();
  43274. }
  43275. }
  43276. }
  43277. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  43278. const bool shouldWordWrap)
  43279. {
  43280. if (multiline != shouldBeMultiLine
  43281. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  43282. {
  43283. multiline = shouldBeMultiLine;
  43284. wordWrap = shouldWordWrap && shouldBeMultiLine;
  43285. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  43286. scrollbarVisible && multiline);
  43287. viewport->setViewPosition (0, 0);
  43288. resized();
  43289. scrollToMakeSureCursorIsVisible();
  43290. }
  43291. }
  43292. bool TextEditor::isMultiLine() const
  43293. {
  43294. return multiline;
  43295. }
  43296. void TextEditor::setScrollbarsShown (bool shown)
  43297. {
  43298. if (scrollbarVisible != shown)
  43299. {
  43300. scrollbarVisible = shown;
  43301. shown = shown && isMultiLine();
  43302. viewport->setScrollBarsShown (shown, shown);
  43303. }
  43304. }
  43305. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  43306. {
  43307. if (readOnly != shouldBeReadOnly)
  43308. {
  43309. readOnly = shouldBeReadOnly;
  43310. enablementChanged();
  43311. }
  43312. }
  43313. bool TextEditor::isReadOnly() const
  43314. {
  43315. return readOnly || ! isEnabled();
  43316. }
  43317. bool TextEditor::isTextInputActive() const
  43318. {
  43319. return ! isReadOnly();
  43320. }
  43321. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  43322. {
  43323. returnKeyStartsNewLine = shouldStartNewLine;
  43324. }
  43325. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  43326. {
  43327. tabKeyUsed = shouldTabKeyBeUsed;
  43328. }
  43329. void TextEditor::setPopupMenuEnabled (const bool b)
  43330. {
  43331. popupMenuEnabled = b;
  43332. }
  43333. void TextEditor::setSelectAllWhenFocused (const bool b)
  43334. {
  43335. selectAllTextWhenFocused = b;
  43336. }
  43337. const Font TextEditor::getFont() const
  43338. {
  43339. return currentFont;
  43340. }
  43341. void TextEditor::setFont (const Font& newFont)
  43342. {
  43343. currentFont = newFont;
  43344. scrollToMakeSureCursorIsVisible();
  43345. }
  43346. void TextEditor::applyFontToAllText (const Font& newFont)
  43347. {
  43348. currentFont = newFont;
  43349. const Colour overallColour (findColour (textColourId));
  43350. for (int i = sections.size(); --i >= 0;)
  43351. {
  43352. UniformTextSection* const uts = sections.getUnchecked (i);
  43353. uts->setFont (newFont, passwordCharacter);
  43354. uts->colour = overallColour;
  43355. }
  43356. coalesceSimilarSections();
  43357. updateTextHolderSize();
  43358. scrollToMakeSureCursorIsVisible();
  43359. repaint();
  43360. }
  43361. void TextEditor::colourChanged()
  43362. {
  43363. setOpaque (findColour (backgroundColourId).isOpaque());
  43364. repaint();
  43365. }
  43366. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43367. {
  43368. caretVisible = shouldCaretBeVisible;
  43369. if (shouldCaretBeVisible)
  43370. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43371. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43372. : MouseCursor::NormalCursor);
  43373. }
  43374. void TextEditor::setInputRestrictions (const int maxLen,
  43375. const String& chars)
  43376. {
  43377. maxTextLength = jmax (0, maxLen);
  43378. allowedCharacters = chars;
  43379. }
  43380. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43381. {
  43382. textToShowWhenEmpty = text;
  43383. colourForTextWhenEmpty = colourToUse;
  43384. }
  43385. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43386. {
  43387. if (passwordCharacter != newPasswordCharacter)
  43388. {
  43389. passwordCharacter = newPasswordCharacter;
  43390. resized();
  43391. repaint();
  43392. }
  43393. }
  43394. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43395. {
  43396. viewport->setScrollBarThickness (newThicknessPixels);
  43397. }
  43398. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43399. {
  43400. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43401. }
  43402. void TextEditor::clear()
  43403. {
  43404. clearInternal (0);
  43405. updateTextHolderSize();
  43406. undoManager.clearUndoHistory();
  43407. }
  43408. void TextEditor::setText (const String& newText,
  43409. const bool sendTextChangeMessage)
  43410. {
  43411. const int newLength = newText.length();
  43412. if (newLength != getTotalNumChars() || getText() != newText)
  43413. {
  43414. const int oldCursorPos = caretPosition;
  43415. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43416. clearInternal (0);
  43417. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43418. // if you're adding text with line-feeds to a single-line text editor, it
  43419. // ain't gonna look right!
  43420. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43421. if (cursorWasAtEnd && ! isMultiLine())
  43422. moveCursorTo (getTotalNumChars(), false);
  43423. else
  43424. moveCursorTo (oldCursorPos, false);
  43425. if (sendTextChangeMessage)
  43426. textChanged();
  43427. updateTextHolderSize();
  43428. scrollToMakeSureCursorIsVisible();
  43429. undoManager.clearUndoHistory();
  43430. repaint();
  43431. }
  43432. }
  43433. Value& TextEditor::getTextValue()
  43434. {
  43435. if (valueTextNeedsUpdating)
  43436. {
  43437. valueTextNeedsUpdating = false;
  43438. textValue = getText();
  43439. }
  43440. return textValue;
  43441. }
  43442. void TextEditor::textWasChangedByValue()
  43443. {
  43444. if (textValue.getValueSource().getReferenceCount() > 1)
  43445. setText (textValue.getValue());
  43446. }
  43447. void TextEditor::textChanged()
  43448. {
  43449. updateTextHolderSize();
  43450. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43451. if (textValue.getValueSource().getReferenceCount() > 1)
  43452. {
  43453. valueTextNeedsUpdating = false;
  43454. textValue = getText();
  43455. }
  43456. }
  43457. void TextEditor::returnPressed()
  43458. {
  43459. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43460. }
  43461. void TextEditor::escapePressed()
  43462. {
  43463. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43464. }
  43465. void TextEditor::addListener (Listener* const newListener)
  43466. {
  43467. listeners.add (newListener);
  43468. }
  43469. void TextEditor::removeListener (Listener* const listenerToRemove)
  43470. {
  43471. listeners.remove (listenerToRemove);
  43472. }
  43473. void TextEditor::timerCallbackInt()
  43474. {
  43475. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43476. if (caretFlashState != newState)
  43477. {
  43478. caretFlashState = newState;
  43479. if (caretFlashState)
  43480. wasFocused = true;
  43481. if (caretVisible
  43482. && hasKeyboardFocus (false)
  43483. && ! isReadOnly())
  43484. {
  43485. repaintCaret();
  43486. }
  43487. }
  43488. const unsigned int now = Time::getApproximateMillisecondCounter();
  43489. if (now > lastTransactionTime + 200)
  43490. newTransaction();
  43491. }
  43492. void TextEditor::repaintCaret()
  43493. {
  43494. if (! findColour (caretColourId).isTransparent())
  43495. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43496. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43497. 4,
  43498. roundToInt (cursorHeight) + 2);
  43499. }
  43500. void TextEditor::repaintText (const Range<int>& range)
  43501. {
  43502. if (! range.isEmpty())
  43503. {
  43504. float x = 0, y = 0, lh = currentFont.getHeight();
  43505. const float wordWrapWidth = getWordWrapWidth();
  43506. if (wordWrapWidth > 0)
  43507. {
  43508. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43509. i.getCharPosition (range.getStart(), x, y, lh);
  43510. const int y1 = (int) y;
  43511. int y2;
  43512. if (range.getEnd() >= getTotalNumChars())
  43513. {
  43514. y2 = textHolder->getHeight();
  43515. }
  43516. else
  43517. {
  43518. i.getCharPosition (range.getEnd(), x, y, lh);
  43519. y2 = (int) (y + lh * 2.0f);
  43520. }
  43521. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43522. }
  43523. }
  43524. }
  43525. void TextEditor::moveCaret (int newCaretPos)
  43526. {
  43527. if (newCaretPos < 0)
  43528. newCaretPos = 0;
  43529. else if (newCaretPos > getTotalNumChars())
  43530. newCaretPos = getTotalNumChars();
  43531. if (newCaretPos != getCaretPosition())
  43532. {
  43533. repaintCaret();
  43534. caretFlashState = true;
  43535. caretPosition = newCaretPos;
  43536. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43537. scrollToMakeSureCursorIsVisible();
  43538. repaintCaret();
  43539. }
  43540. }
  43541. void TextEditor::setCaretPosition (const int newIndex)
  43542. {
  43543. moveCursorTo (newIndex, false);
  43544. }
  43545. int TextEditor::getCaretPosition() const
  43546. {
  43547. return caretPosition;
  43548. }
  43549. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43550. const int desiredCaretY)
  43551. {
  43552. updateCaretPosition();
  43553. int vx = roundToInt (cursorX) - desiredCaretX;
  43554. int vy = roundToInt (cursorY) - desiredCaretY;
  43555. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43556. {
  43557. vx += desiredCaretX - proportionOfWidth (0.2f);
  43558. }
  43559. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43560. {
  43561. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43562. }
  43563. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43564. if (! isMultiLine())
  43565. {
  43566. vy = viewport->getViewPositionY();
  43567. }
  43568. else
  43569. {
  43570. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43571. const int curH = roundToInt (cursorHeight);
  43572. if (desiredCaretY < 0)
  43573. {
  43574. vy = jmax (0, desiredCaretY + vy);
  43575. }
  43576. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43577. {
  43578. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43579. }
  43580. }
  43581. viewport->setViewPosition (vx, vy);
  43582. }
  43583. const Rectangle<int> TextEditor::getCaretRectangle()
  43584. {
  43585. updateCaretPosition();
  43586. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43587. roundToInt (cursorY) - viewport->getY(),
  43588. 1, roundToInt (cursorHeight));
  43589. }
  43590. float TextEditor::getWordWrapWidth() const
  43591. {
  43592. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43593. : 1.0e10f;
  43594. }
  43595. void TextEditor::updateTextHolderSize()
  43596. {
  43597. const float wordWrapWidth = getWordWrapWidth();
  43598. if (wordWrapWidth > 0)
  43599. {
  43600. float maxWidth = 0.0f;
  43601. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43602. while (i.next())
  43603. maxWidth = jmax (maxWidth, i.atomRight);
  43604. const int w = leftIndent + roundToInt (maxWidth);
  43605. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43606. currentFont.getHeight()));
  43607. textHolder->setSize (w + 1, h + 1);
  43608. }
  43609. }
  43610. int TextEditor::getTextWidth() const
  43611. {
  43612. return textHolder->getWidth();
  43613. }
  43614. int TextEditor::getTextHeight() const
  43615. {
  43616. return textHolder->getHeight();
  43617. }
  43618. void TextEditor::setIndents (const int newLeftIndent,
  43619. const int newTopIndent)
  43620. {
  43621. leftIndent = newLeftIndent;
  43622. topIndent = newTopIndent;
  43623. }
  43624. void TextEditor::setBorder (const BorderSize& border)
  43625. {
  43626. borderSize = border;
  43627. resized();
  43628. }
  43629. const BorderSize TextEditor::getBorder() const
  43630. {
  43631. return borderSize;
  43632. }
  43633. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43634. {
  43635. keepCursorOnScreen = shouldScrollToShowCursor;
  43636. }
  43637. void TextEditor::updateCaretPosition()
  43638. {
  43639. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43640. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43641. }
  43642. void TextEditor::scrollToMakeSureCursorIsVisible()
  43643. {
  43644. updateCaretPosition();
  43645. if (keepCursorOnScreen)
  43646. {
  43647. int x = viewport->getViewPositionX();
  43648. int y = viewport->getViewPositionY();
  43649. const int relativeCursorX = roundToInt (cursorX) - x;
  43650. const int relativeCursorY = roundToInt (cursorY) - y;
  43651. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43652. {
  43653. x += relativeCursorX - proportionOfWidth (0.2f);
  43654. }
  43655. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43656. {
  43657. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43658. }
  43659. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43660. if (! isMultiLine())
  43661. {
  43662. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43663. }
  43664. else
  43665. {
  43666. const int curH = roundToInt (cursorHeight);
  43667. if (relativeCursorY < 0)
  43668. {
  43669. y = jmax (0, relativeCursorY + y);
  43670. }
  43671. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43672. {
  43673. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43674. }
  43675. }
  43676. viewport->setViewPosition (x, y);
  43677. }
  43678. }
  43679. void TextEditor::moveCursorTo (const int newPosition,
  43680. const bool isSelecting)
  43681. {
  43682. if (isSelecting)
  43683. {
  43684. moveCaret (newPosition);
  43685. const Range<int> oldSelection (selection);
  43686. if (dragType == notDragging)
  43687. {
  43688. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43689. dragType = draggingSelectionStart;
  43690. else
  43691. dragType = draggingSelectionEnd;
  43692. }
  43693. if (dragType == draggingSelectionStart)
  43694. {
  43695. if (getCaretPosition() >= selection.getEnd())
  43696. dragType = draggingSelectionEnd;
  43697. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43698. }
  43699. else
  43700. {
  43701. if (getCaretPosition() < selection.getStart())
  43702. dragType = draggingSelectionStart;
  43703. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43704. }
  43705. repaintText (selection.getUnionWith (oldSelection));
  43706. }
  43707. else
  43708. {
  43709. dragType = notDragging;
  43710. repaintText (selection);
  43711. moveCaret (newPosition);
  43712. selection = Range<int>::emptyRange (getCaretPosition());
  43713. }
  43714. }
  43715. int TextEditor::getTextIndexAt (const int x,
  43716. const int y)
  43717. {
  43718. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43719. (float) (y + viewport->getViewPositionY() - topIndent));
  43720. }
  43721. void TextEditor::insertTextAtCaret (const String& newText_)
  43722. {
  43723. String newText (newText_);
  43724. if (allowedCharacters.isNotEmpty())
  43725. newText = newText.retainCharacters (allowedCharacters);
  43726. if ((! returnKeyStartsNewLine) && newText == "\n")
  43727. {
  43728. returnPressed();
  43729. return;
  43730. }
  43731. if (! isMultiLine())
  43732. newText = newText.replaceCharacters ("\r\n", " ");
  43733. else
  43734. newText = newText.replace ("\r\n", "\n");
  43735. const int newCaretPos = selection.getStart() + newText.length();
  43736. const int insertIndex = selection.getStart();
  43737. remove (selection, getUndoManager(),
  43738. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43739. if (maxTextLength > 0)
  43740. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43741. if (newText.isNotEmpty())
  43742. insert (newText,
  43743. insertIndex,
  43744. currentFont,
  43745. findColour (textColourId),
  43746. getUndoManager(),
  43747. newCaretPos);
  43748. textChanged();
  43749. }
  43750. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43751. {
  43752. moveCursorTo (newSelection.getStart(), false);
  43753. moveCursorTo (newSelection.getEnd(), true);
  43754. }
  43755. void TextEditor::copy()
  43756. {
  43757. if (passwordCharacter == 0)
  43758. {
  43759. const String selectedText (getHighlightedText());
  43760. if (selectedText.isNotEmpty())
  43761. SystemClipboard::copyTextToClipboard (selectedText);
  43762. }
  43763. }
  43764. void TextEditor::paste()
  43765. {
  43766. if (! isReadOnly())
  43767. {
  43768. const String clip (SystemClipboard::getTextFromClipboard());
  43769. if (clip.isNotEmpty())
  43770. insertTextAtCaret (clip);
  43771. }
  43772. }
  43773. void TextEditor::cut()
  43774. {
  43775. if (! isReadOnly())
  43776. {
  43777. moveCaret (selection.getEnd());
  43778. insertTextAtCaret (String::empty);
  43779. }
  43780. }
  43781. void TextEditor::drawContent (Graphics& g)
  43782. {
  43783. const float wordWrapWidth = getWordWrapWidth();
  43784. if (wordWrapWidth > 0)
  43785. {
  43786. g.setOrigin (leftIndent, topIndent);
  43787. const Rectangle<int> clip (g.getClipBounds());
  43788. Colour selectedTextColour;
  43789. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43790. while (i.lineY + 200.0 < clip.getY() && i.next())
  43791. {}
  43792. if (! selection.isEmpty())
  43793. {
  43794. g.setColour (findColour (highlightColourId)
  43795. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43796. selectedTextColour = findColour (highlightedTextColourId);
  43797. Iterator i2 (i);
  43798. while (i2.next() && i2.lineY < clip.getBottom())
  43799. {
  43800. if (i2.lineY + i2.lineHeight >= clip.getY()
  43801. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43802. {
  43803. i2.drawSelection (g, selection);
  43804. }
  43805. }
  43806. }
  43807. const UniformTextSection* lastSection = 0;
  43808. while (i.next() && i.lineY < clip.getBottom())
  43809. {
  43810. if (i.lineY + i.lineHeight >= clip.getY())
  43811. {
  43812. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43813. {
  43814. i.drawSelectedText (g, selection, selectedTextColour);
  43815. lastSection = 0;
  43816. }
  43817. else
  43818. {
  43819. i.draw (g, lastSection);
  43820. }
  43821. }
  43822. }
  43823. }
  43824. }
  43825. void TextEditor::paint (Graphics& g)
  43826. {
  43827. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43828. }
  43829. void TextEditor::paintOverChildren (Graphics& g)
  43830. {
  43831. if (caretFlashState
  43832. && hasKeyboardFocus (false)
  43833. && caretVisible
  43834. && ! isReadOnly())
  43835. {
  43836. g.setColour (findColour (caretColourId));
  43837. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43838. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43839. 2.0f, cursorHeight);
  43840. }
  43841. if (textToShowWhenEmpty.isNotEmpty()
  43842. && (! hasKeyboardFocus (false))
  43843. && getTotalNumChars() == 0)
  43844. {
  43845. g.setColour (colourForTextWhenEmpty);
  43846. g.setFont (getFont());
  43847. if (isMultiLine())
  43848. {
  43849. g.drawText (textToShowWhenEmpty,
  43850. 0, 0, getWidth(), getHeight(),
  43851. Justification::centred, true);
  43852. }
  43853. else
  43854. {
  43855. g.drawText (textToShowWhenEmpty,
  43856. leftIndent, topIndent,
  43857. viewport->getWidth() - leftIndent,
  43858. viewport->getHeight() - topIndent,
  43859. Justification::centredLeft, true);
  43860. }
  43861. }
  43862. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43863. }
  43864. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43865. {
  43866. public:
  43867. TextEditorMenuPerformer (TextEditor* const editor_)
  43868. : editor (editor_)
  43869. {
  43870. }
  43871. void modalStateFinished (int returnValue)
  43872. {
  43873. if (editor != 0 && returnValue != 0)
  43874. editor->performPopupMenuAction (returnValue);
  43875. }
  43876. private:
  43877. Component::SafePointer<TextEditor> editor;
  43878. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43879. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43880. };
  43881. void TextEditor::mouseDown (const MouseEvent& e)
  43882. {
  43883. beginDragAutoRepeat (100);
  43884. newTransaction();
  43885. if (wasFocused || ! selectAllTextWhenFocused)
  43886. {
  43887. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43888. {
  43889. moveCursorTo (getTextIndexAt (e.x, e.y),
  43890. e.mods.isShiftDown());
  43891. }
  43892. else
  43893. {
  43894. PopupMenu m;
  43895. m.setLookAndFeel (&getLookAndFeel());
  43896. addPopupMenuItems (m, &e);
  43897. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43898. }
  43899. }
  43900. }
  43901. void TextEditor::mouseDrag (const MouseEvent& e)
  43902. {
  43903. if (wasFocused || ! selectAllTextWhenFocused)
  43904. {
  43905. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43906. {
  43907. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43908. }
  43909. }
  43910. }
  43911. void TextEditor::mouseUp (const MouseEvent& e)
  43912. {
  43913. newTransaction();
  43914. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43915. if (wasFocused || ! selectAllTextWhenFocused)
  43916. {
  43917. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43918. {
  43919. moveCaret (getTextIndexAt (e.x, e.y));
  43920. }
  43921. }
  43922. wasFocused = true;
  43923. }
  43924. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43925. {
  43926. int tokenEnd = getTextIndexAt (e.x, e.y);
  43927. int tokenStart = tokenEnd;
  43928. if (e.getNumberOfClicks() > 3)
  43929. {
  43930. tokenStart = 0;
  43931. tokenEnd = getTotalNumChars();
  43932. }
  43933. else
  43934. {
  43935. const String t (getText());
  43936. const int totalLength = getTotalNumChars();
  43937. while (tokenEnd < totalLength)
  43938. {
  43939. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43940. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43941. ++tokenEnd;
  43942. else
  43943. break;
  43944. }
  43945. tokenStart = tokenEnd;
  43946. while (tokenStart > 0)
  43947. {
  43948. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43949. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43950. --tokenStart;
  43951. else
  43952. break;
  43953. }
  43954. if (e.getNumberOfClicks() > 2)
  43955. {
  43956. while (tokenEnd < totalLength)
  43957. {
  43958. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43959. ++tokenEnd;
  43960. else
  43961. break;
  43962. }
  43963. while (tokenStart > 0)
  43964. {
  43965. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43966. --tokenStart;
  43967. else
  43968. break;
  43969. }
  43970. }
  43971. }
  43972. moveCursorTo (tokenEnd, false);
  43973. moveCursorTo (tokenStart, true);
  43974. }
  43975. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43976. {
  43977. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43978. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43979. }
  43980. bool TextEditor::keyPressed (const KeyPress& key)
  43981. {
  43982. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43983. return false;
  43984. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43985. if (key.isKeyCode (KeyPress::leftKey)
  43986. || key.isKeyCode (KeyPress::upKey))
  43987. {
  43988. newTransaction();
  43989. int newPos;
  43990. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43991. newPos = indexAtPosition (cursorX, cursorY - 1);
  43992. else if (moveInWholeWordSteps)
  43993. newPos = findWordBreakBefore (getCaretPosition());
  43994. else
  43995. newPos = getCaretPosition() - 1;
  43996. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43997. }
  43998. else if (key.isKeyCode (KeyPress::rightKey)
  43999. || key.isKeyCode (KeyPress::downKey))
  44000. {
  44001. newTransaction();
  44002. int newPos;
  44003. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  44004. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  44005. else if (moveInWholeWordSteps)
  44006. newPos = findWordBreakAfter (getCaretPosition());
  44007. else
  44008. newPos = getCaretPosition() + 1;
  44009. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  44010. }
  44011. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  44012. {
  44013. newTransaction();
  44014. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  44015. key.getModifiers().isShiftDown());
  44016. }
  44017. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  44018. {
  44019. newTransaction();
  44020. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  44021. key.getModifiers().isShiftDown());
  44022. }
  44023. else if (key.isKeyCode (KeyPress::homeKey))
  44024. {
  44025. newTransaction();
  44026. if (isMultiLine() && ! moveInWholeWordSteps)
  44027. moveCursorTo (indexAtPosition (0.0f, cursorY),
  44028. key.getModifiers().isShiftDown());
  44029. else
  44030. moveCursorTo (0, key.getModifiers().isShiftDown());
  44031. }
  44032. else if (key.isKeyCode (KeyPress::endKey))
  44033. {
  44034. newTransaction();
  44035. if (isMultiLine() && ! moveInWholeWordSteps)
  44036. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  44037. key.getModifiers().isShiftDown());
  44038. else
  44039. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  44040. }
  44041. else if (key.isKeyCode (KeyPress::backspaceKey))
  44042. {
  44043. if (moveInWholeWordSteps)
  44044. {
  44045. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  44046. }
  44047. else
  44048. {
  44049. if (selection.isEmpty() && selection.getStart() > 0)
  44050. selection.setStart (selection.getEnd() - 1);
  44051. }
  44052. cut();
  44053. }
  44054. else if (key.isKeyCode (KeyPress::deleteKey))
  44055. {
  44056. if (key.getModifiers().isShiftDown())
  44057. copy();
  44058. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  44059. selection.setEnd (selection.getStart() + 1);
  44060. cut();
  44061. }
  44062. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  44063. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  44064. {
  44065. newTransaction();
  44066. copy();
  44067. }
  44068. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  44069. {
  44070. newTransaction();
  44071. copy();
  44072. cut();
  44073. }
  44074. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  44075. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  44076. {
  44077. newTransaction();
  44078. paste();
  44079. }
  44080. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  44081. {
  44082. newTransaction();
  44083. doUndoRedo (false);
  44084. }
  44085. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  44086. {
  44087. newTransaction();
  44088. doUndoRedo (true);
  44089. }
  44090. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  44091. {
  44092. newTransaction();
  44093. moveCursorTo (getTotalNumChars(), false);
  44094. moveCursorTo (0, true);
  44095. }
  44096. else if (key == KeyPress::returnKey)
  44097. {
  44098. newTransaction();
  44099. insertTextAtCaret ("\n");
  44100. }
  44101. else if (key.isKeyCode (KeyPress::escapeKey))
  44102. {
  44103. newTransaction();
  44104. moveCursorTo (getCaretPosition(), false);
  44105. escapePressed();
  44106. }
  44107. else if (key.getTextCharacter() >= ' '
  44108. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  44109. {
  44110. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  44111. lastTransactionTime = Time::getApproximateMillisecondCounter();
  44112. }
  44113. else
  44114. {
  44115. return false;
  44116. }
  44117. return true;
  44118. }
  44119. bool TextEditor::keyStateChanged (const bool isKeyDown)
  44120. {
  44121. if (! isKeyDown)
  44122. return false;
  44123. #if JUCE_WINDOWS
  44124. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  44125. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  44126. #endif
  44127. // (overridden to avoid forwarding key events to the parent)
  44128. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  44129. }
  44130. const int baseMenuItemID = 0x7fff0000;
  44131. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  44132. {
  44133. const bool writable = ! isReadOnly();
  44134. if (passwordCharacter == 0)
  44135. {
  44136. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  44137. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  44138. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  44139. }
  44140. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  44141. m.addSeparator();
  44142. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  44143. m.addSeparator();
  44144. if (getUndoManager() != 0)
  44145. {
  44146. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  44147. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  44148. }
  44149. }
  44150. void TextEditor::performPopupMenuAction (const int menuItemID)
  44151. {
  44152. switch (menuItemID)
  44153. {
  44154. case baseMenuItemID + 1:
  44155. copy();
  44156. cut();
  44157. break;
  44158. case baseMenuItemID + 2:
  44159. copy();
  44160. break;
  44161. case baseMenuItemID + 3:
  44162. paste();
  44163. break;
  44164. case baseMenuItemID + 4:
  44165. cut();
  44166. break;
  44167. case baseMenuItemID + 5:
  44168. moveCursorTo (getTotalNumChars(), false);
  44169. moveCursorTo (0, true);
  44170. break;
  44171. case baseMenuItemID + 6:
  44172. doUndoRedo (false);
  44173. break;
  44174. case baseMenuItemID + 7:
  44175. doUndoRedo (true);
  44176. break;
  44177. default:
  44178. break;
  44179. }
  44180. }
  44181. void TextEditor::focusGained (FocusChangeType)
  44182. {
  44183. newTransaction();
  44184. caretFlashState = true;
  44185. if (selectAllTextWhenFocused)
  44186. {
  44187. moveCursorTo (0, false);
  44188. moveCursorTo (getTotalNumChars(), true);
  44189. }
  44190. repaint();
  44191. if (caretVisible)
  44192. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  44193. ComponentPeer* const peer = getPeer();
  44194. if (peer != 0 && ! isReadOnly())
  44195. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  44196. }
  44197. void TextEditor::focusLost (FocusChangeType)
  44198. {
  44199. newTransaction();
  44200. wasFocused = false;
  44201. textHolder->stopTimer();
  44202. caretFlashState = false;
  44203. postCommandMessage (TextEditorDefs::focusLossMessageId);
  44204. repaint();
  44205. }
  44206. void TextEditor::resized()
  44207. {
  44208. viewport->setBoundsInset (borderSize);
  44209. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  44210. updateTextHolderSize();
  44211. if (! isMultiLine())
  44212. {
  44213. scrollToMakeSureCursorIsVisible();
  44214. }
  44215. else
  44216. {
  44217. updateCaretPosition();
  44218. }
  44219. }
  44220. void TextEditor::handleCommandMessage (const int commandId)
  44221. {
  44222. Component::BailOutChecker checker (this);
  44223. switch (commandId)
  44224. {
  44225. case TextEditorDefs::textChangeMessageId:
  44226. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  44227. break;
  44228. case TextEditorDefs::returnKeyMessageId:
  44229. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  44230. break;
  44231. case TextEditorDefs::escapeKeyMessageId:
  44232. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  44233. break;
  44234. case TextEditorDefs::focusLossMessageId:
  44235. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  44236. break;
  44237. default:
  44238. jassertfalse;
  44239. break;
  44240. }
  44241. }
  44242. void TextEditor::enablementChanged()
  44243. {
  44244. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  44245. : MouseCursor::IBeamCursor);
  44246. repaint();
  44247. }
  44248. UndoManager* TextEditor::getUndoManager() throw()
  44249. {
  44250. return isReadOnly() ? 0 : &undoManager;
  44251. }
  44252. void TextEditor::clearInternal (UndoManager* const um)
  44253. {
  44254. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  44255. }
  44256. void TextEditor::insert (const String& text,
  44257. const int insertIndex,
  44258. const Font& font,
  44259. const Colour& colour,
  44260. UndoManager* const um,
  44261. const int caretPositionToMoveTo)
  44262. {
  44263. if (text.isNotEmpty())
  44264. {
  44265. if (um != 0)
  44266. {
  44267. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44268. newTransaction();
  44269. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  44270. caretPosition, caretPositionToMoveTo));
  44271. }
  44272. else
  44273. {
  44274. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  44275. // a line gets moved due to word wrap
  44276. int index = 0;
  44277. int nextIndex = 0;
  44278. for (int i = 0; i < sections.size(); ++i)
  44279. {
  44280. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44281. if (insertIndex == index)
  44282. {
  44283. sections.insert (i, new UniformTextSection (text,
  44284. font, colour,
  44285. passwordCharacter));
  44286. break;
  44287. }
  44288. else if (insertIndex > index && insertIndex < nextIndex)
  44289. {
  44290. splitSection (i, insertIndex - index);
  44291. sections.insert (i + 1, new UniformTextSection (text,
  44292. font, colour,
  44293. passwordCharacter));
  44294. break;
  44295. }
  44296. index = nextIndex;
  44297. }
  44298. if (nextIndex == insertIndex)
  44299. sections.add (new UniformTextSection (text,
  44300. font, colour,
  44301. passwordCharacter));
  44302. coalesceSimilarSections();
  44303. totalNumChars = -1;
  44304. valueTextNeedsUpdating = true;
  44305. moveCursorTo (caretPositionToMoveTo, false);
  44306. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  44307. }
  44308. }
  44309. }
  44310. void TextEditor::reinsert (const int insertIndex,
  44311. const Array <UniformTextSection*>& sectionsToInsert)
  44312. {
  44313. int index = 0;
  44314. int nextIndex = 0;
  44315. for (int i = 0; i < sections.size(); ++i)
  44316. {
  44317. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44318. if (insertIndex == index)
  44319. {
  44320. for (int j = sectionsToInsert.size(); --j >= 0;)
  44321. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44322. break;
  44323. }
  44324. else if (insertIndex > index && insertIndex < nextIndex)
  44325. {
  44326. splitSection (i, insertIndex - index);
  44327. for (int j = sectionsToInsert.size(); --j >= 0;)
  44328. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44329. break;
  44330. }
  44331. index = nextIndex;
  44332. }
  44333. if (nextIndex == insertIndex)
  44334. {
  44335. for (int j = 0; j < sectionsToInsert.size(); ++j)
  44336. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44337. }
  44338. coalesceSimilarSections();
  44339. totalNumChars = -1;
  44340. valueTextNeedsUpdating = true;
  44341. }
  44342. void TextEditor::remove (const Range<int>& range,
  44343. UndoManager* const um,
  44344. const int caretPositionToMoveTo)
  44345. {
  44346. if (! range.isEmpty())
  44347. {
  44348. int index = 0;
  44349. for (int i = 0; i < sections.size(); ++i)
  44350. {
  44351. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  44352. if (range.getStart() > index && range.getStart() < nextIndex)
  44353. {
  44354. splitSection (i, range.getStart() - index);
  44355. --i;
  44356. }
  44357. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44358. {
  44359. splitSection (i, range.getEnd() - index);
  44360. --i;
  44361. }
  44362. else
  44363. {
  44364. index = nextIndex;
  44365. if (index > range.getEnd())
  44366. break;
  44367. }
  44368. }
  44369. index = 0;
  44370. if (um != 0)
  44371. {
  44372. Array <UniformTextSection*> removedSections;
  44373. for (int i = 0; i < sections.size(); ++i)
  44374. {
  44375. if (range.getEnd() <= range.getStart())
  44376. break;
  44377. UniformTextSection* const section = sections.getUnchecked (i);
  44378. const int nextIndex = index + section->getTotalLength();
  44379. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44380. removedSections.add (new UniformTextSection (*section));
  44381. index = nextIndex;
  44382. }
  44383. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44384. newTransaction();
  44385. um->perform (new RemoveAction (*this, range, caretPosition,
  44386. caretPositionToMoveTo, removedSections));
  44387. }
  44388. else
  44389. {
  44390. Range<int> remainingRange (range);
  44391. for (int i = 0; i < sections.size(); ++i)
  44392. {
  44393. UniformTextSection* const section = sections.getUnchecked (i);
  44394. const int nextIndex = index + section->getTotalLength();
  44395. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44396. {
  44397. sections.remove(i);
  44398. section->clear();
  44399. delete section;
  44400. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44401. if (remainingRange.isEmpty())
  44402. break;
  44403. --i;
  44404. }
  44405. else
  44406. {
  44407. index = nextIndex;
  44408. }
  44409. }
  44410. coalesceSimilarSections();
  44411. totalNumChars = -1;
  44412. valueTextNeedsUpdating = true;
  44413. moveCursorTo (caretPositionToMoveTo, false);
  44414. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44415. }
  44416. }
  44417. }
  44418. const String TextEditor::getText() const
  44419. {
  44420. String t;
  44421. t.preallocateStorage (getTotalNumChars());
  44422. String::Concatenator concatenator (t);
  44423. for (int i = 0; i < sections.size(); ++i)
  44424. sections.getUnchecked (i)->appendAllText (concatenator);
  44425. return t;
  44426. }
  44427. const String TextEditor::getTextInRange (const Range<int>& range) const
  44428. {
  44429. String t;
  44430. if (! range.isEmpty())
  44431. {
  44432. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44433. String::Concatenator concatenator (t);
  44434. int index = 0;
  44435. for (int i = 0; i < sections.size(); ++i)
  44436. {
  44437. const UniformTextSection* const s = sections.getUnchecked (i);
  44438. const int nextIndex = index + s->getTotalLength();
  44439. if (range.getStart() < nextIndex)
  44440. {
  44441. if (range.getEnd() <= index)
  44442. break;
  44443. s->appendSubstring (concatenator, range - index);
  44444. }
  44445. index = nextIndex;
  44446. }
  44447. }
  44448. return t;
  44449. }
  44450. const String TextEditor::getHighlightedText() const
  44451. {
  44452. return getTextInRange (selection);
  44453. }
  44454. int TextEditor::getTotalNumChars() const
  44455. {
  44456. if (totalNumChars < 0)
  44457. {
  44458. totalNumChars = 0;
  44459. for (int i = sections.size(); --i >= 0;)
  44460. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44461. }
  44462. return totalNumChars;
  44463. }
  44464. bool TextEditor::isEmpty() const
  44465. {
  44466. return getTotalNumChars() == 0;
  44467. }
  44468. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44469. {
  44470. const float wordWrapWidth = getWordWrapWidth();
  44471. if (wordWrapWidth > 0 && sections.size() > 0)
  44472. {
  44473. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44474. i.getCharPosition (index, cx, cy, lineHeight);
  44475. }
  44476. else
  44477. {
  44478. cx = cy = 0;
  44479. lineHeight = currentFont.getHeight();
  44480. }
  44481. }
  44482. int TextEditor::indexAtPosition (const float x, const float y)
  44483. {
  44484. const float wordWrapWidth = getWordWrapWidth();
  44485. if (wordWrapWidth > 0)
  44486. {
  44487. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44488. while (i.next())
  44489. {
  44490. if (i.lineY + i.lineHeight > y)
  44491. {
  44492. if (i.lineY > y)
  44493. return jmax (0, i.indexInText - 1);
  44494. if (i.atomX >= x)
  44495. return i.indexInText;
  44496. if (x < i.atomRight)
  44497. return i.xToIndex (x);
  44498. }
  44499. }
  44500. }
  44501. return getTotalNumChars();
  44502. }
  44503. int TextEditor::findWordBreakAfter (const int position) const
  44504. {
  44505. const String t (getTextInRange (Range<int> (position, position + 512)));
  44506. const int totalLength = t.length();
  44507. int i = 0;
  44508. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44509. ++i;
  44510. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44511. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44512. ++i;
  44513. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44514. ++i;
  44515. return position + i;
  44516. }
  44517. int TextEditor::findWordBreakBefore (const int position) const
  44518. {
  44519. if (position <= 0)
  44520. return 0;
  44521. const int startOfBuffer = jmax (0, position - 512);
  44522. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44523. int i = position - startOfBuffer;
  44524. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44525. --i;
  44526. if (i > 0)
  44527. {
  44528. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44529. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44530. --i;
  44531. }
  44532. jassert (startOfBuffer + i >= 0);
  44533. return startOfBuffer + i;
  44534. }
  44535. void TextEditor::splitSection (const int sectionIndex,
  44536. const int charToSplitAt)
  44537. {
  44538. jassert (sections[sectionIndex] != 0);
  44539. sections.insert (sectionIndex + 1,
  44540. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44541. }
  44542. void TextEditor::coalesceSimilarSections()
  44543. {
  44544. for (int i = 0; i < sections.size() - 1; ++i)
  44545. {
  44546. UniformTextSection* const s1 = sections.getUnchecked (i);
  44547. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44548. if (s1->font == s2->font
  44549. && s1->colour == s2->colour)
  44550. {
  44551. s1->append (*s2, passwordCharacter);
  44552. sections.remove (i + 1);
  44553. delete s2;
  44554. --i;
  44555. }
  44556. }
  44557. }
  44558. END_JUCE_NAMESPACE
  44559. /*** End of inlined file: juce_TextEditor.cpp ***/
  44560. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44561. BEGIN_JUCE_NAMESPACE
  44562. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44563. class ToolbarSpacerComp : public ToolbarItemComponent
  44564. {
  44565. public:
  44566. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44567. : ToolbarItemComponent (itemId_, String::empty, false),
  44568. fixedSize (fixedSize_),
  44569. drawBar (drawBar_)
  44570. {
  44571. }
  44572. ~ToolbarSpacerComp()
  44573. {
  44574. }
  44575. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44576. int& preferredSize, int& minSize, int& maxSize)
  44577. {
  44578. if (fixedSize <= 0)
  44579. {
  44580. preferredSize = toolbarThickness * 2;
  44581. minSize = 4;
  44582. maxSize = 32768;
  44583. }
  44584. else
  44585. {
  44586. maxSize = roundToInt (toolbarThickness * fixedSize);
  44587. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44588. preferredSize = maxSize;
  44589. if (getEditingMode() == editableOnPalette)
  44590. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44591. }
  44592. return true;
  44593. }
  44594. void paintButtonArea (Graphics&, int, int, bool, bool)
  44595. {
  44596. }
  44597. void contentAreaChanged (const Rectangle<int>&)
  44598. {
  44599. }
  44600. int getResizeOrder() const throw()
  44601. {
  44602. return fixedSize <= 0 ? 0 : 1;
  44603. }
  44604. void paint (Graphics& g)
  44605. {
  44606. const int w = getWidth();
  44607. const int h = getHeight();
  44608. if (drawBar)
  44609. {
  44610. g.setColour (findColour (Toolbar::separatorColourId, true));
  44611. const float thickness = 0.2f;
  44612. if (isToolbarVertical())
  44613. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44614. else
  44615. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44616. }
  44617. if (getEditingMode() != normalMode && ! drawBar)
  44618. {
  44619. g.setColour (findColour (Toolbar::separatorColourId, true));
  44620. const int indentX = jmin (2, (w - 3) / 2);
  44621. const int indentY = jmin (2, (h - 3) / 2);
  44622. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44623. if (fixedSize <= 0)
  44624. {
  44625. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44626. if (isToolbarVertical())
  44627. {
  44628. x1 = w * 0.5f;
  44629. y1 = h * 0.4f;
  44630. x2 = x1;
  44631. y2 = indentX * 2.0f;
  44632. x3 = x1;
  44633. y3 = h * 0.6f;
  44634. x4 = x1;
  44635. y4 = h - y2;
  44636. hw = w * 0.15f;
  44637. hl = w * 0.2f;
  44638. }
  44639. else
  44640. {
  44641. x1 = w * 0.4f;
  44642. y1 = h * 0.5f;
  44643. x2 = indentX * 2.0f;
  44644. y2 = y1;
  44645. x3 = w * 0.6f;
  44646. y3 = y1;
  44647. x4 = w - x2;
  44648. y4 = y1;
  44649. hw = h * 0.15f;
  44650. hl = h * 0.2f;
  44651. }
  44652. Path p;
  44653. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44654. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44655. g.fillPath (p);
  44656. }
  44657. }
  44658. }
  44659. juce_UseDebuggingNewOperator
  44660. private:
  44661. const float fixedSize;
  44662. const bool drawBar;
  44663. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44664. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44665. };
  44666. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44667. {
  44668. public:
  44669. MissingItemsComponent (Toolbar& owner_, const int height_)
  44670. : PopupMenuCustomComponent (true),
  44671. owner (owner_),
  44672. height (height_)
  44673. {
  44674. for (int i = owner_.items.size(); --i >= 0;)
  44675. {
  44676. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44677. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44678. {
  44679. oldIndexes.insert (0, i);
  44680. addAndMakeVisible (tc, 0);
  44681. }
  44682. }
  44683. layout (400);
  44684. }
  44685. ~MissingItemsComponent()
  44686. {
  44687. // deleting the toolbar while its menu it open??
  44688. jassert (owner.isValidComponent());
  44689. for (int i = 0; i < getNumChildComponents(); ++i)
  44690. {
  44691. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44692. if (tc != 0)
  44693. {
  44694. tc->setVisible (false);
  44695. const int index = oldIndexes.remove (i);
  44696. owner.addChildComponent (tc, index);
  44697. --i;
  44698. }
  44699. }
  44700. owner.resized();
  44701. }
  44702. void layout (const int preferredWidth)
  44703. {
  44704. const int indent = 8;
  44705. int x = indent;
  44706. int y = indent;
  44707. int maxX = 0;
  44708. for (int i = 0; i < getNumChildComponents(); ++i)
  44709. {
  44710. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44711. if (tc != 0)
  44712. {
  44713. int preferredSize = 1, minSize = 1, maxSize = 1;
  44714. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44715. {
  44716. if (x + preferredSize > preferredWidth && x > indent)
  44717. {
  44718. x = indent;
  44719. y += height;
  44720. }
  44721. tc->setBounds (x, y, preferredSize, height);
  44722. x += preferredSize;
  44723. maxX = jmax (maxX, x);
  44724. }
  44725. }
  44726. }
  44727. setSize (maxX + 8, y + height + 8);
  44728. }
  44729. void getIdealSize (int& idealWidth, int& idealHeight)
  44730. {
  44731. idealWidth = getWidth();
  44732. idealHeight = getHeight();
  44733. }
  44734. juce_UseDebuggingNewOperator
  44735. private:
  44736. Toolbar& owner;
  44737. const int height;
  44738. Array <int> oldIndexes;
  44739. MissingItemsComponent (const MissingItemsComponent&);
  44740. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44741. };
  44742. Toolbar::Toolbar()
  44743. : vertical (false),
  44744. isEditingActive (false),
  44745. toolbarStyle (Toolbar::iconsOnly)
  44746. {
  44747. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44748. missingItemsButton->setAlwaysOnTop (true);
  44749. missingItemsButton->addButtonListener (this);
  44750. }
  44751. Toolbar::~Toolbar()
  44752. {
  44753. animator.cancelAllAnimations (true);
  44754. deleteAllChildren();
  44755. }
  44756. void Toolbar::setVertical (const bool shouldBeVertical)
  44757. {
  44758. if (vertical != shouldBeVertical)
  44759. {
  44760. vertical = shouldBeVertical;
  44761. resized();
  44762. }
  44763. }
  44764. void Toolbar::clear()
  44765. {
  44766. for (int i = items.size(); --i >= 0;)
  44767. {
  44768. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44769. items.remove (i);
  44770. delete tc;
  44771. }
  44772. resized();
  44773. }
  44774. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44775. {
  44776. if (itemId == ToolbarItemFactory::separatorBarId)
  44777. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44778. else if (itemId == ToolbarItemFactory::spacerId)
  44779. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44780. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44781. return new ToolbarSpacerComp (itemId, 0, false);
  44782. return factory.createItem (itemId);
  44783. }
  44784. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44785. const int itemId,
  44786. const int insertIndex)
  44787. {
  44788. // An ID can't be zero - this might indicate a mistake somewhere?
  44789. jassert (itemId != 0);
  44790. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44791. if (tc != 0)
  44792. {
  44793. #if JUCE_DEBUG
  44794. Array <int> allowedIds;
  44795. factory.getAllToolbarItemIds (allowedIds);
  44796. // If your factory can create an item for a given ID, it must also return
  44797. // that ID from its getAllToolbarItemIds() method!
  44798. jassert (allowedIds.contains (itemId));
  44799. #endif
  44800. items.insert (insertIndex, tc);
  44801. addAndMakeVisible (tc, insertIndex);
  44802. }
  44803. }
  44804. void Toolbar::addItem (ToolbarItemFactory& factory,
  44805. const int itemId,
  44806. const int insertIndex)
  44807. {
  44808. addItemInternal (factory, itemId, insertIndex);
  44809. resized();
  44810. }
  44811. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44812. {
  44813. Array <int> ids;
  44814. factoryToUse.getDefaultItemSet (ids);
  44815. clear();
  44816. for (int i = 0; i < ids.size(); ++i)
  44817. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44818. resized();
  44819. }
  44820. void Toolbar::removeToolbarItem (const int itemIndex)
  44821. {
  44822. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44823. if (tc != 0)
  44824. {
  44825. items.removeValue (tc);
  44826. delete tc;
  44827. resized();
  44828. }
  44829. }
  44830. int Toolbar::getNumItems() const throw()
  44831. {
  44832. return items.size();
  44833. }
  44834. int Toolbar::getItemId (const int itemIndex) const throw()
  44835. {
  44836. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44837. return tc != 0 ? tc->getItemId() : 0;
  44838. }
  44839. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44840. {
  44841. return items [itemIndex];
  44842. }
  44843. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44844. {
  44845. for (;;)
  44846. {
  44847. index += delta;
  44848. ToolbarItemComponent* const tc = getItemComponent (index);
  44849. if (tc == 0)
  44850. break;
  44851. if (tc->isActive)
  44852. return tc;
  44853. }
  44854. return 0;
  44855. }
  44856. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44857. {
  44858. if (toolbarStyle != newStyle)
  44859. {
  44860. toolbarStyle = newStyle;
  44861. updateAllItemPositions (false);
  44862. }
  44863. }
  44864. const String Toolbar::toString() const
  44865. {
  44866. String s ("TB:");
  44867. for (int i = 0; i < getNumItems(); ++i)
  44868. s << getItemId(i) << ' ';
  44869. return s.trimEnd();
  44870. }
  44871. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44872. const String& savedVersion)
  44873. {
  44874. if (! savedVersion.startsWith ("TB:"))
  44875. return false;
  44876. StringArray tokens;
  44877. tokens.addTokens (savedVersion.substring (3), false);
  44878. clear();
  44879. for (int i = 0; i < tokens.size(); ++i)
  44880. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44881. resized();
  44882. return true;
  44883. }
  44884. void Toolbar::paint (Graphics& g)
  44885. {
  44886. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44887. }
  44888. int Toolbar::getThickness() const throw()
  44889. {
  44890. return vertical ? getWidth() : getHeight();
  44891. }
  44892. int Toolbar::getLength() const throw()
  44893. {
  44894. return vertical ? getHeight() : getWidth();
  44895. }
  44896. void Toolbar::setEditingActive (const bool active)
  44897. {
  44898. if (isEditingActive != active)
  44899. {
  44900. isEditingActive = active;
  44901. updateAllItemPositions (false);
  44902. }
  44903. }
  44904. void Toolbar::resized()
  44905. {
  44906. updateAllItemPositions (false);
  44907. }
  44908. void Toolbar::updateAllItemPositions (const bool animate)
  44909. {
  44910. if (getWidth() > 0 && getHeight() > 0)
  44911. {
  44912. StretchableObjectResizer resizer;
  44913. int i;
  44914. for (i = 0; i < items.size(); ++i)
  44915. {
  44916. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44917. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44918. : ToolbarItemComponent::normalMode);
  44919. tc->setStyle (toolbarStyle);
  44920. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44921. int preferredSize = 1, minSize = 1, maxSize = 1;
  44922. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44923. preferredSize, minSize, maxSize))
  44924. {
  44925. tc->isActive = true;
  44926. resizer.addItem (preferredSize, minSize, maxSize,
  44927. spacer != 0 ? spacer->getResizeOrder() : 2);
  44928. }
  44929. else
  44930. {
  44931. tc->isActive = false;
  44932. tc->setVisible (false);
  44933. }
  44934. }
  44935. resizer.resizeToFit (getLength());
  44936. int totalLength = 0;
  44937. for (i = 0; i < resizer.getNumItems(); ++i)
  44938. totalLength += (int) resizer.getItemSize (i);
  44939. const bool itemsOffTheEnd = totalLength > getLength();
  44940. const int extrasButtonSize = getThickness() / 2;
  44941. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44942. missingItemsButton->setVisible (itemsOffTheEnd);
  44943. missingItemsButton->setEnabled (! isEditingActive);
  44944. if (vertical)
  44945. missingItemsButton->setCentrePosition (getWidth() / 2,
  44946. getHeight() - 4 - extrasButtonSize / 2);
  44947. else
  44948. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44949. getHeight() / 2);
  44950. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44951. : missingItemsButton->getX()) - 4
  44952. : getLength();
  44953. int pos = 0, activeIndex = 0;
  44954. for (i = 0; i < items.size(); ++i)
  44955. {
  44956. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44957. if (tc->isActive)
  44958. {
  44959. const int size = (int) resizer.getItemSize (activeIndex++);
  44960. Rectangle<int> newBounds;
  44961. if (vertical)
  44962. newBounds.setBounds (0, pos, getWidth(), size);
  44963. else
  44964. newBounds.setBounds (pos, 0, size, getHeight());
  44965. if (animate)
  44966. {
  44967. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44968. }
  44969. else
  44970. {
  44971. animator.cancelAnimation (tc, false);
  44972. tc->setBounds (newBounds);
  44973. }
  44974. pos += size;
  44975. tc->setVisible (pos <= maxLength
  44976. && ((! tc->isBeingDragged)
  44977. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44978. }
  44979. }
  44980. }
  44981. }
  44982. void Toolbar::buttonClicked (Button*)
  44983. {
  44984. jassert (missingItemsButton->isShowing());
  44985. if (missingItemsButton->isShowing())
  44986. {
  44987. PopupMenu m;
  44988. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44989. m.showAt (missingItemsButton);
  44990. }
  44991. }
  44992. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44993. Component* /*sourceComponent*/)
  44994. {
  44995. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44996. }
  44997. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44998. {
  44999. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  45000. if (tc != 0)
  45001. {
  45002. if (getNumItems() == 0)
  45003. {
  45004. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  45005. {
  45006. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  45007. if (palette != 0)
  45008. palette->replaceComponent (tc);
  45009. }
  45010. else
  45011. {
  45012. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  45013. }
  45014. items.add (tc);
  45015. addChildComponent (tc);
  45016. updateAllItemPositions (false);
  45017. }
  45018. else
  45019. {
  45020. for (int i = getNumItems(); --i >= 0;)
  45021. {
  45022. int currentIndex = getIndexOfChildComponent (tc);
  45023. if (currentIndex < 0)
  45024. {
  45025. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  45026. {
  45027. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  45028. if (palette != 0)
  45029. palette->replaceComponent (tc);
  45030. }
  45031. else
  45032. {
  45033. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  45034. }
  45035. items.add (tc);
  45036. addChildComponent (tc);
  45037. currentIndex = getIndexOfChildComponent (tc);
  45038. updateAllItemPositions (true);
  45039. }
  45040. int newIndex = currentIndex;
  45041. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  45042. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  45043. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  45044. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  45045. if (prev != 0)
  45046. {
  45047. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  45048. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  45049. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  45050. {
  45051. newIndex = getIndexOfChildComponent (prev);
  45052. }
  45053. }
  45054. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  45055. if (next != 0)
  45056. {
  45057. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  45058. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  45059. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  45060. {
  45061. newIndex = getIndexOfChildComponent (next) + 1;
  45062. }
  45063. }
  45064. if (newIndex != currentIndex)
  45065. {
  45066. items.removeValue (tc);
  45067. removeChildComponent (tc);
  45068. addChildComponent (tc, newIndex);
  45069. items.insert (newIndex, tc);
  45070. updateAllItemPositions (true);
  45071. }
  45072. else
  45073. {
  45074. break;
  45075. }
  45076. }
  45077. }
  45078. }
  45079. }
  45080. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  45081. {
  45082. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  45083. if (tc != 0)
  45084. {
  45085. if (isParentOf (tc))
  45086. {
  45087. items.removeValue (tc);
  45088. removeChildComponent (tc);
  45089. updateAllItemPositions (true);
  45090. }
  45091. }
  45092. }
  45093. void Toolbar::itemDropped (const String&, Component*, int, int)
  45094. {
  45095. }
  45096. void Toolbar::mouseDown (const MouseEvent& e)
  45097. {
  45098. if (e.mods.isPopupMenu())
  45099. {
  45100. }
  45101. }
  45102. class ToolbarCustomisationDialog : public DialogWindow
  45103. {
  45104. public:
  45105. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  45106. Toolbar* const toolbar_,
  45107. const int optionFlags)
  45108. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  45109. toolbar (toolbar_)
  45110. {
  45111. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  45112. setResizable (true, true);
  45113. setResizeLimits (400, 300, 1500, 1000);
  45114. positionNearBar();
  45115. }
  45116. ~ToolbarCustomisationDialog()
  45117. {
  45118. setContentComponent (0, true);
  45119. }
  45120. void closeButtonPressed()
  45121. {
  45122. setVisible (false);
  45123. }
  45124. bool canModalEventBeSentToComponent (const Component* comp)
  45125. {
  45126. return toolbar->isParentOf (comp);
  45127. }
  45128. void positionNearBar()
  45129. {
  45130. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  45131. const int tbx = toolbar->getScreenX();
  45132. const int tby = toolbar->getScreenY();
  45133. const int gap = 8;
  45134. int x, y;
  45135. if (toolbar->isVertical())
  45136. {
  45137. y = tby;
  45138. if (tbx > screenSize.getCentreX())
  45139. x = tbx - getWidth() - gap;
  45140. else
  45141. x = tbx + toolbar->getWidth() + gap;
  45142. }
  45143. else
  45144. {
  45145. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  45146. if (tby > screenSize.getCentreY())
  45147. y = tby - getHeight() - gap;
  45148. else
  45149. y = tby + toolbar->getHeight() + gap;
  45150. }
  45151. setTopLeftPosition (x, y);
  45152. }
  45153. private:
  45154. Toolbar* const toolbar;
  45155. class CustomiserPanel : public Component,
  45156. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  45157. private ButtonListener
  45158. {
  45159. public:
  45160. CustomiserPanel (ToolbarItemFactory& factory_,
  45161. Toolbar* const toolbar_,
  45162. const int optionFlags)
  45163. : factory (factory_),
  45164. toolbar (toolbar_),
  45165. styleBox (0),
  45166. defaultButton (0)
  45167. {
  45168. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  45169. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  45170. | Toolbar::allowIconsWithTextChoice
  45171. | Toolbar::allowTextOnlyChoice)) != 0)
  45172. {
  45173. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  45174. styleBox->setEditableText (false);
  45175. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  45176. styleBox->addItem (TRANS("Show icons only"), 1);
  45177. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  45178. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  45179. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  45180. styleBox->addItem (TRANS("Show descriptions only"), 3);
  45181. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  45182. styleBox->setSelectedId (1);
  45183. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  45184. styleBox->setSelectedId (2);
  45185. else if (toolbar_->getStyle() == Toolbar::textOnly)
  45186. styleBox->setSelectedId (3);
  45187. styleBox->addListener (this);
  45188. }
  45189. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  45190. {
  45191. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  45192. defaultButton->addButtonListener (this);
  45193. }
  45194. addAndMakeVisible (instructions = new Label (String::empty,
  45195. 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.")));
  45196. instructions->setFont (Font (13.0f));
  45197. setSize (500, 300);
  45198. }
  45199. ~CustomiserPanel()
  45200. {
  45201. deleteAllChildren();
  45202. }
  45203. void comboBoxChanged (ComboBox*)
  45204. {
  45205. if (styleBox->getSelectedId() == 1)
  45206. toolbar->setStyle (Toolbar::iconsOnly);
  45207. else if (styleBox->getSelectedId() == 2)
  45208. toolbar->setStyle (Toolbar::iconsWithText);
  45209. else if (styleBox->getSelectedId() == 3)
  45210. toolbar->setStyle (Toolbar::textOnly);
  45211. palette->resized(); // to make it update the styles
  45212. }
  45213. void buttonClicked (Button*)
  45214. {
  45215. toolbar->addDefaultItems (factory);
  45216. }
  45217. void paint (Graphics& g)
  45218. {
  45219. Colour background;
  45220. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  45221. if (dw != 0)
  45222. background = dw->getBackgroundColour();
  45223. g.setColour (background.contrasting().withAlpha (0.3f));
  45224. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  45225. }
  45226. void resized()
  45227. {
  45228. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  45229. if (styleBox != 0)
  45230. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  45231. if (defaultButton != 0)
  45232. {
  45233. defaultButton->changeWidthToFitText (22);
  45234. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  45235. }
  45236. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  45237. }
  45238. private:
  45239. ToolbarItemFactory& factory;
  45240. Toolbar* const toolbar;
  45241. Label* instructions;
  45242. ToolbarItemPalette* palette;
  45243. ComboBox* styleBox;
  45244. TextButton* defaultButton;
  45245. };
  45246. };
  45247. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  45248. {
  45249. setEditingActive (true);
  45250. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  45251. dw.runModalLoop();
  45252. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  45253. setEditingActive (false);
  45254. }
  45255. END_JUCE_NAMESPACE
  45256. /*** End of inlined file: juce_Toolbar.cpp ***/
  45257. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  45258. BEGIN_JUCE_NAMESPACE
  45259. ToolbarItemFactory::ToolbarItemFactory()
  45260. {
  45261. }
  45262. ToolbarItemFactory::~ToolbarItemFactory()
  45263. {
  45264. }
  45265. class ItemDragAndDropOverlayComponent : public Component
  45266. {
  45267. public:
  45268. ItemDragAndDropOverlayComponent()
  45269. : isDragging (false)
  45270. {
  45271. setAlwaysOnTop (true);
  45272. setRepaintsOnMouseActivity (true);
  45273. setMouseCursor (MouseCursor::DraggingHandCursor);
  45274. }
  45275. ~ItemDragAndDropOverlayComponent()
  45276. {
  45277. }
  45278. void paint (Graphics& g)
  45279. {
  45280. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45281. if (isMouseOverOrDragging()
  45282. && tc != 0
  45283. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45284. {
  45285. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  45286. g.drawRect (0, 0, getWidth(), getHeight(),
  45287. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  45288. }
  45289. }
  45290. void mouseDown (const MouseEvent& e)
  45291. {
  45292. isDragging = false;
  45293. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45294. if (tc != 0)
  45295. {
  45296. tc->dragOffsetX = e.x;
  45297. tc->dragOffsetY = e.y;
  45298. }
  45299. }
  45300. void mouseDrag (const MouseEvent& e)
  45301. {
  45302. if (! (isDragging || e.mouseWasClicked()))
  45303. {
  45304. isDragging = true;
  45305. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  45306. if (dnd != 0)
  45307. {
  45308. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  45309. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45310. if (tc != 0)
  45311. {
  45312. tc->isBeingDragged = true;
  45313. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45314. tc->setVisible (false);
  45315. }
  45316. }
  45317. }
  45318. }
  45319. void mouseUp (const MouseEvent&)
  45320. {
  45321. isDragging = false;
  45322. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45323. if (tc != 0)
  45324. {
  45325. tc->isBeingDragged = false;
  45326. Toolbar* const tb = tc->getToolbar();
  45327. if (tb != 0)
  45328. tb->updateAllItemPositions (true);
  45329. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45330. delete tc;
  45331. }
  45332. }
  45333. void parentSizeChanged()
  45334. {
  45335. setBounds (0, 0, getParentWidth(), getParentHeight());
  45336. }
  45337. juce_UseDebuggingNewOperator
  45338. private:
  45339. bool isDragging;
  45340. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  45341. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  45342. };
  45343. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  45344. const String& labelText,
  45345. const bool isBeingUsedAsAButton_)
  45346. : Button (labelText),
  45347. itemId (itemId_),
  45348. mode (normalMode),
  45349. toolbarStyle (Toolbar::iconsOnly),
  45350. dragOffsetX (0),
  45351. dragOffsetY (0),
  45352. isActive (true),
  45353. isBeingDragged (false),
  45354. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  45355. {
  45356. // Your item ID can't be 0!
  45357. jassert (itemId_ != 0);
  45358. }
  45359. ToolbarItemComponent::~ToolbarItemComponent()
  45360. {
  45361. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45362. overlayComp = 0;
  45363. }
  45364. Toolbar* ToolbarItemComponent::getToolbar() const
  45365. {
  45366. return dynamic_cast <Toolbar*> (getParentComponent());
  45367. }
  45368. bool ToolbarItemComponent::isToolbarVertical() const
  45369. {
  45370. const Toolbar* const t = getToolbar();
  45371. return t != 0 && t->isVertical();
  45372. }
  45373. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45374. {
  45375. if (toolbarStyle != newStyle)
  45376. {
  45377. toolbarStyle = newStyle;
  45378. repaint();
  45379. resized();
  45380. }
  45381. }
  45382. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45383. {
  45384. if (isBeingUsedAsAButton)
  45385. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45386. over, down, *this);
  45387. if (toolbarStyle != Toolbar::iconsOnly)
  45388. {
  45389. const int indent = contentArea.getX();
  45390. int y = indent;
  45391. int h = getHeight() - indent * 2;
  45392. if (toolbarStyle == Toolbar::iconsWithText)
  45393. {
  45394. y = contentArea.getBottom() + indent / 2;
  45395. h -= contentArea.getHeight();
  45396. }
  45397. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45398. getButtonText(), *this);
  45399. }
  45400. if (! contentArea.isEmpty())
  45401. {
  45402. g.saveState();
  45403. g.setOrigin (contentArea.getX(), contentArea.getY());
  45404. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45405. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45406. g.restoreState();
  45407. }
  45408. }
  45409. void ToolbarItemComponent::resized()
  45410. {
  45411. if (toolbarStyle != Toolbar::textOnly)
  45412. {
  45413. const int indent = jmin (proportionOfWidth (0.08f),
  45414. proportionOfHeight (0.08f));
  45415. contentArea = Rectangle<int> (indent, indent,
  45416. getWidth() - indent * 2,
  45417. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45418. : (getHeight() - indent * 2));
  45419. }
  45420. else
  45421. {
  45422. contentArea = Rectangle<int>();
  45423. }
  45424. contentAreaChanged (contentArea);
  45425. }
  45426. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45427. {
  45428. if (mode != newMode)
  45429. {
  45430. mode = newMode;
  45431. repaint();
  45432. if (mode == normalMode)
  45433. {
  45434. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45435. overlayComp = 0;
  45436. }
  45437. else if (overlayComp == 0)
  45438. {
  45439. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45440. overlayComp->parentSizeChanged();
  45441. }
  45442. resized();
  45443. }
  45444. }
  45445. END_JUCE_NAMESPACE
  45446. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45447. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45448. BEGIN_JUCE_NAMESPACE
  45449. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45450. Toolbar* const toolbar_)
  45451. : factory (factory_),
  45452. toolbar (toolbar_)
  45453. {
  45454. Component* const itemHolder = new Component();
  45455. Array <int> allIds;
  45456. factory_.getAllToolbarItemIds (allIds);
  45457. for (int i = 0; i < allIds.size(); ++i)
  45458. {
  45459. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45460. jassert (tc != 0);
  45461. if (tc != 0)
  45462. {
  45463. itemHolder->addAndMakeVisible (tc);
  45464. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45465. }
  45466. }
  45467. viewport = new Viewport();
  45468. viewport->setViewedComponent (itemHolder);
  45469. addAndMakeVisible (viewport);
  45470. }
  45471. ToolbarItemPalette::~ToolbarItemPalette()
  45472. {
  45473. viewport->getViewedComponent()->deleteAllChildren();
  45474. deleteAllChildren();
  45475. }
  45476. void ToolbarItemPalette::resized()
  45477. {
  45478. viewport->setBoundsInset (BorderSize (1));
  45479. Component* const itemHolder = viewport->getViewedComponent();
  45480. const int indent = 8;
  45481. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45482. const int height = toolbar->getThickness();
  45483. int x = indent;
  45484. int y = indent;
  45485. int maxX = 0;
  45486. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45487. {
  45488. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45489. if (tc != 0)
  45490. {
  45491. tc->setStyle (toolbar->getStyle());
  45492. int preferredSize = 1, minSize = 1, maxSize = 1;
  45493. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45494. {
  45495. if (x + preferredSize > preferredWidth && x > indent)
  45496. {
  45497. x = indent;
  45498. y += height;
  45499. }
  45500. tc->setBounds (x, y, preferredSize, height);
  45501. x += preferredSize + 8;
  45502. maxX = jmax (maxX, x);
  45503. }
  45504. }
  45505. }
  45506. itemHolder->setSize (maxX, y + height + 8);
  45507. }
  45508. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45509. {
  45510. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45511. jassert (tc != 0);
  45512. if (tc != 0)
  45513. {
  45514. tc->setBounds (comp->getBounds());
  45515. tc->setStyle (toolbar->getStyle());
  45516. tc->setEditingMode (comp->getEditingMode());
  45517. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45518. }
  45519. }
  45520. END_JUCE_NAMESPACE
  45521. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45522. /*** Start of inlined file: juce_TreeView.cpp ***/
  45523. BEGIN_JUCE_NAMESPACE
  45524. class TreeViewContentComponent : public Component,
  45525. public TooltipClient
  45526. {
  45527. public:
  45528. TreeViewContentComponent (TreeView& owner_)
  45529. : owner (owner_),
  45530. buttonUnderMouse (0),
  45531. isDragging (false)
  45532. {
  45533. }
  45534. ~TreeViewContentComponent()
  45535. {
  45536. deleteAllChildren();
  45537. }
  45538. void mouseDown (const MouseEvent& e)
  45539. {
  45540. updateButtonUnderMouse (e);
  45541. isDragging = false;
  45542. needSelectionOnMouseUp = false;
  45543. Rectangle<int> pos;
  45544. TreeViewItem* const item = findItemAt (e.y, pos);
  45545. if (item == 0)
  45546. return;
  45547. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45548. // as selection clicks)
  45549. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45550. {
  45551. if (e.x >= pos.getX() - owner.getIndentSize())
  45552. item->setOpen (! item->isOpen());
  45553. // (clicks to the left of an open/close button are ignored)
  45554. }
  45555. else
  45556. {
  45557. // mouse-down inside the body of the item..
  45558. if (! owner.isMultiSelectEnabled())
  45559. item->setSelected (true, true);
  45560. else if (item->isSelected())
  45561. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45562. else
  45563. selectBasedOnModifiers (item, e.mods);
  45564. if (e.x >= pos.getX())
  45565. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45566. }
  45567. }
  45568. void mouseUp (const MouseEvent& e)
  45569. {
  45570. updateButtonUnderMouse (e);
  45571. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45572. {
  45573. Rectangle<int> pos;
  45574. TreeViewItem* const item = findItemAt (e.y, pos);
  45575. if (item != 0)
  45576. selectBasedOnModifiers (item, e.mods);
  45577. }
  45578. }
  45579. void mouseDoubleClick (const MouseEvent& e)
  45580. {
  45581. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45582. {
  45583. Rectangle<int> pos;
  45584. TreeViewItem* const item = findItemAt (e.y, pos);
  45585. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45586. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45587. }
  45588. }
  45589. void mouseDrag (const MouseEvent& e)
  45590. {
  45591. if (isEnabled()
  45592. && ! (isDragging || e.mouseWasClicked()
  45593. || e.getDistanceFromDragStart() < 5
  45594. || e.mods.isPopupMenu()))
  45595. {
  45596. isDragging = true;
  45597. Rectangle<int> pos;
  45598. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45599. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45600. {
  45601. const String dragDescription (item->getDragSourceDescription());
  45602. if (dragDescription.isNotEmpty())
  45603. {
  45604. DragAndDropContainer* const dragContainer
  45605. = DragAndDropContainer::findParentDragContainerFor (this);
  45606. if (dragContainer != 0)
  45607. {
  45608. pos.setSize (pos.getWidth(), item->itemHeight);
  45609. Image dragImage (Component::createComponentSnapshot (pos, true));
  45610. dragImage.multiplyAllAlphas (0.6f);
  45611. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45612. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45613. }
  45614. else
  45615. {
  45616. // to be able to do a drag-and-drop operation, the treeview needs to
  45617. // be inside a component which is also a DragAndDropContainer.
  45618. jassertfalse;
  45619. }
  45620. }
  45621. }
  45622. }
  45623. }
  45624. void mouseMove (const MouseEvent& e)
  45625. {
  45626. updateButtonUnderMouse (e);
  45627. }
  45628. void mouseExit (const MouseEvent& e)
  45629. {
  45630. updateButtonUnderMouse (e);
  45631. }
  45632. void paint (Graphics& g)
  45633. {
  45634. if (owner.rootItem != 0)
  45635. {
  45636. owner.handleAsyncUpdate();
  45637. if (! owner.rootItemVisible)
  45638. g.setOrigin (0, -owner.rootItem->itemHeight);
  45639. owner.rootItem->paintRecursively (g, getWidth());
  45640. }
  45641. }
  45642. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45643. {
  45644. if (owner.rootItem != 0)
  45645. {
  45646. owner.handleAsyncUpdate();
  45647. if (! owner.rootItemVisible)
  45648. y += owner.rootItem->itemHeight;
  45649. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45650. if (ti != 0)
  45651. itemPosition = ti->getItemPosition (false);
  45652. return ti;
  45653. }
  45654. return 0;
  45655. }
  45656. void updateComponents()
  45657. {
  45658. const int visibleTop = -getY();
  45659. const int visibleBottom = visibleTop + getParentHeight();
  45660. BigInteger itemsToKeep;
  45661. {
  45662. TreeViewItem* item = owner.rootItem;
  45663. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45664. while (item != 0 && y < visibleBottom)
  45665. {
  45666. y += item->itemHeight;
  45667. if (y >= visibleTop)
  45668. {
  45669. const int index = rowComponentIds.indexOf (item->uid);
  45670. if (index < 0)
  45671. {
  45672. Component* const comp = item->createItemComponent();
  45673. if (comp != 0)
  45674. {
  45675. addAndMakeVisible (comp);
  45676. itemsToKeep.setBit (rowComponentItems.size());
  45677. rowComponentItems.add (item);
  45678. rowComponentIds.add (item->uid);
  45679. rowComponents.add (comp);
  45680. }
  45681. }
  45682. else
  45683. {
  45684. itemsToKeep.setBit (index);
  45685. }
  45686. }
  45687. item = item->getNextVisibleItem (true);
  45688. }
  45689. }
  45690. for (int i = rowComponentItems.size(); --i >= 0;)
  45691. {
  45692. Component* const comp = rowComponents.getUnchecked(i);
  45693. bool keep = false;
  45694. if (isParentOf (comp))
  45695. {
  45696. if (itemsToKeep[i])
  45697. {
  45698. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45699. Rectangle<int> pos (item->getItemPosition (false));
  45700. pos.setSize (pos.getWidth(), item->itemHeight);
  45701. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45702. {
  45703. keep = true;
  45704. comp->setBounds (pos);
  45705. }
  45706. }
  45707. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45708. {
  45709. keep = true;
  45710. comp->setSize (0, 0);
  45711. }
  45712. }
  45713. if (! keep)
  45714. {
  45715. delete comp;
  45716. rowComponents.remove (i);
  45717. rowComponentIds.remove (i);
  45718. rowComponentItems.remove (i);
  45719. }
  45720. }
  45721. }
  45722. void updateButtonUnderMouse (const MouseEvent& e)
  45723. {
  45724. TreeViewItem* newItem = 0;
  45725. if (owner.openCloseButtonsVisible)
  45726. {
  45727. Rectangle<int> pos;
  45728. TreeViewItem* item = findItemAt (e.y, pos);
  45729. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45730. {
  45731. newItem = item;
  45732. if (! newItem->mightContainSubItems())
  45733. newItem = 0;
  45734. }
  45735. }
  45736. if (buttonUnderMouse != newItem)
  45737. {
  45738. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45739. {
  45740. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45741. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45742. }
  45743. buttonUnderMouse = newItem;
  45744. if (buttonUnderMouse != 0)
  45745. {
  45746. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45747. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45748. }
  45749. }
  45750. }
  45751. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45752. {
  45753. return item == buttonUnderMouse;
  45754. }
  45755. void resized()
  45756. {
  45757. owner.itemsChanged();
  45758. }
  45759. const String getTooltip()
  45760. {
  45761. Rectangle<int> pos;
  45762. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45763. if (item != 0)
  45764. return item->getTooltip();
  45765. return owner.getTooltip();
  45766. }
  45767. juce_UseDebuggingNewOperator
  45768. private:
  45769. TreeView& owner;
  45770. Array <TreeViewItem*> rowComponentItems;
  45771. Array <int> rowComponentIds;
  45772. Array <Component*> rowComponents;
  45773. TreeViewItem* buttonUnderMouse;
  45774. bool isDragging, needSelectionOnMouseUp;
  45775. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45776. {
  45777. TreeViewItem* firstSelected = 0;
  45778. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45779. {
  45780. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45781. jassert (lastSelected != 0);
  45782. int rowStart = firstSelected->getRowNumberInTree();
  45783. int rowEnd = lastSelected->getRowNumberInTree();
  45784. if (rowStart > rowEnd)
  45785. swapVariables (rowStart, rowEnd);
  45786. int ourRow = item->getRowNumberInTree();
  45787. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45788. if (ourRow > otherEnd)
  45789. swapVariables (ourRow, otherEnd);
  45790. for (int i = ourRow; i <= otherEnd; ++i)
  45791. owner.getItemOnRow (i)->setSelected (true, false);
  45792. }
  45793. else
  45794. {
  45795. const bool cmd = modifiers.isCommandDown();
  45796. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45797. }
  45798. }
  45799. bool containsItem (TreeViewItem* const item) const
  45800. {
  45801. for (int i = rowComponentItems.size(); --i >= 0;)
  45802. if (rowComponentItems.getUnchecked(i) == item)
  45803. return true;
  45804. return false;
  45805. }
  45806. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45807. {
  45808. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45809. {
  45810. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45811. if (source->isDragging())
  45812. {
  45813. Component* const underMouse = source->getComponentUnderMouse();
  45814. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45815. return true;
  45816. }
  45817. }
  45818. return false;
  45819. }
  45820. TreeViewContentComponent (const TreeViewContentComponent&);
  45821. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45822. };
  45823. class TreeView::TreeViewport : public Viewport
  45824. {
  45825. public:
  45826. TreeViewport() throw() : lastX (-1) {}
  45827. ~TreeViewport() throw() {}
  45828. void updateComponents (const bool triggerResize = false)
  45829. {
  45830. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45831. if (tvc != 0)
  45832. {
  45833. if (triggerResize)
  45834. tvc->resized();
  45835. else
  45836. tvc->updateComponents();
  45837. }
  45838. repaint();
  45839. }
  45840. void visibleAreaChanged (int x, int, int, int)
  45841. {
  45842. const bool hasScrolledSideways = (x != lastX);
  45843. lastX = x;
  45844. updateComponents (hasScrolledSideways);
  45845. }
  45846. juce_UseDebuggingNewOperator
  45847. private:
  45848. int lastX;
  45849. TreeViewport (const TreeViewport&);
  45850. TreeViewport& operator= (const TreeViewport&);
  45851. };
  45852. TreeView::TreeView (const String& componentName)
  45853. : Component (componentName),
  45854. rootItem (0),
  45855. indentSize (24),
  45856. defaultOpenness (false),
  45857. needsRecalculating (true),
  45858. rootItemVisible (true),
  45859. multiSelectEnabled (false),
  45860. openCloseButtonsVisible (true)
  45861. {
  45862. addAndMakeVisible (viewport = new TreeViewport());
  45863. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45864. viewport->setWantsKeyboardFocus (false);
  45865. setWantsKeyboardFocus (true);
  45866. }
  45867. TreeView::~TreeView()
  45868. {
  45869. if (rootItem != 0)
  45870. rootItem->setOwnerView (0);
  45871. }
  45872. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45873. {
  45874. if (rootItem != newRootItem)
  45875. {
  45876. if (newRootItem != 0)
  45877. {
  45878. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45879. if (newRootItem->ownerView != 0)
  45880. newRootItem->ownerView->setRootItem (0);
  45881. }
  45882. if (rootItem != 0)
  45883. rootItem->setOwnerView (0);
  45884. rootItem = newRootItem;
  45885. if (newRootItem != 0)
  45886. newRootItem->setOwnerView (this);
  45887. needsRecalculating = true;
  45888. handleAsyncUpdate();
  45889. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45890. {
  45891. rootItem->setOpen (false); // force a re-open
  45892. rootItem->setOpen (true);
  45893. }
  45894. }
  45895. }
  45896. void TreeView::deleteRootItem()
  45897. {
  45898. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45899. setRootItem (0);
  45900. }
  45901. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45902. {
  45903. rootItemVisible = shouldBeVisible;
  45904. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45905. {
  45906. rootItem->setOpen (false); // force a re-open
  45907. rootItem->setOpen (true);
  45908. }
  45909. itemsChanged();
  45910. }
  45911. void TreeView::colourChanged()
  45912. {
  45913. setOpaque (findColour (backgroundColourId).isOpaque());
  45914. repaint();
  45915. }
  45916. void TreeView::setIndentSize (const int newIndentSize)
  45917. {
  45918. if (indentSize != newIndentSize)
  45919. {
  45920. indentSize = newIndentSize;
  45921. resized();
  45922. }
  45923. }
  45924. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45925. {
  45926. if (defaultOpenness != isOpenByDefault)
  45927. {
  45928. defaultOpenness = isOpenByDefault;
  45929. itemsChanged();
  45930. }
  45931. }
  45932. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45933. {
  45934. multiSelectEnabled = canMultiSelect;
  45935. }
  45936. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45937. {
  45938. if (openCloseButtonsVisible != shouldBeVisible)
  45939. {
  45940. openCloseButtonsVisible = shouldBeVisible;
  45941. itemsChanged();
  45942. }
  45943. }
  45944. Viewport* TreeView::getViewport() const throw()
  45945. {
  45946. return viewport;
  45947. }
  45948. void TreeView::clearSelectedItems()
  45949. {
  45950. if (rootItem != 0)
  45951. rootItem->deselectAllRecursively();
  45952. }
  45953. int TreeView::getNumSelectedItems() const throw()
  45954. {
  45955. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45956. }
  45957. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45958. {
  45959. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45960. }
  45961. int TreeView::getNumRowsInTree() const
  45962. {
  45963. if (rootItem != 0)
  45964. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45965. return 0;
  45966. }
  45967. TreeViewItem* TreeView::getItemOnRow (int index) const
  45968. {
  45969. if (! rootItemVisible)
  45970. ++index;
  45971. if (rootItem != 0 && index >= 0)
  45972. return rootItem->getItemOnRow (index);
  45973. return 0;
  45974. }
  45975. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45976. {
  45977. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45978. Rectangle<int> pos;
  45979. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45980. }
  45981. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45982. {
  45983. if (rootItem == 0)
  45984. return 0;
  45985. return rootItem->findItemFromIdentifierString (identifierString);
  45986. }
  45987. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45988. {
  45989. XmlElement* e = 0;
  45990. if (rootItem != 0)
  45991. {
  45992. e = rootItem->getOpennessState();
  45993. if (e != 0 && alsoIncludeScrollPosition)
  45994. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45995. }
  45996. return e;
  45997. }
  45998. void TreeView::restoreOpennessState (const XmlElement& newState)
  45999. {
  46000. if (rootItem != 0)
  46001. {
  46002. rootItem->restoreOpennessState (newState);
  46003. if (newState.hasAttribute ("scrollPos"))
  46004. viewport->setViewPosition (viewport->getViewPositionX(),
  46005. newState.getIntAttribute ("scrollPos"));
  46006. }
  46007. }
  46008. void TreeView::paint (Graphics& g)
  46009. {
  46010. g.fillAll (findColour (backgroundColourId));
  46011. }
  46012. void TreeView::resized()
  46013. {
  46014. viewport->setBounds (getLocalBounds());
  46015. itemsChanged();
  46016. handleAsyncUpdate();
  46017. }
  46018. void TreeView::enablementChanged()
  46019. {
  46020. repaint();
  46021. }
  46022. void TreeView::moveSelectedRow (int delta)
  46023. {
  46024. if (delta == 0)
  46025. return;
  46026. int rowSelected = 0;
  46027. TreeViewItem* const firstSelected = getSelectedItem (0);
  46028. if (firstSelected != 0)
  46029. rowSelected = firstSelected->getRowNumberInTree();
  46030. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  46031. for (;;)
  46032. {
  46033. TreeViewItem* item = getItemOnRow (rowSelected);
  46034. if (item != 0)
  46035. {
  46036. if (! item->canBeSelected())
  46037. {
  46038. // if the row we want to highlight doesn't allow it, try skipping
  46039. // to the next item..
  46040. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  46041. rowSelected + (delta < 0 ? -1 : 1));
  46042. if (rowSelected != nextRowToTry)
  46043. {
  46044. rowSelected = nextRowToTry;
  46045. continue;
  46046. }
  46047. else
  46048. {
  46049. break;
  46050. }
  46051. }
  46052. item->setSelected (true, true);
  46053. scrollToKeepItemVisible (item);
  46054. }
  46055. break;
  46056. }
  46057. }
  46058. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  46059. {
  46060. if (item != 0 && item->ownerView == this)
  46061. {
  46062. handleAsyncUpdate();
  46063. item = item->getDeepestOpenParentItem();
  46064. int y = item->y;
  46065. int viewTop = viewport->getViewPositionY();
  46066. if (y < viewTop)
  46067. {
  46068. viewport->setViewPosition (viewport->getViewPositionX(), y);
  46069. }
  46070. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  46071. {
  46072. viewport->setViewPosition (viewport->getViewPositionX(),
  46073. (y + item->itemHeight) - viewport->getViewHeight());
  46074. }
  46075. }
  46076. }
  46077. bool TreeView::keyPressed (const KeyPress& key)
  46078. {
  46079. if (key.isKeyCode (KeyPress::upKey))
  46080. {
  46081. moveSelectedRow (-1);
  46082. }
  46083. else if (key.isKeyCode (KeyPress::downKey))
  46084. {
  46085. moveSelectedRow (1);
  46086. }
  46087. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  46088. {
  46089. if (rootItem != 0)
  46090. {
  46091. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  46092. if (key.isKeyCode (KeyPress::pageUpKey))
  46093. rowsOnScreen = -rowsOnScreen;
  46094. moveSelectedRow (rowsOnScreen);
  46095. }
  46096. }
  46097. else if (key.isKeyCode (KeyPress::homeKey))
  46098. {
  46099. moveSelectedRow (-0x3fffffff);
  46100. }
  46101. else if (key.isKeyCode (KeyPress::endKey))
  46102. {
  46103. moveSelectedRow (0x3fffffff);
  46104. }
  46105. else if (key.isKeyCode (KeyPress::returnKey))
  46106. {
  46107. TreeViewItem* const firstSelected = getSelectedItem (0);
  46108. if (firstSelected != 0)
  46109. firstSelected->setOpen (! firstSelected->isOpen());
  46110. }
  46111. else if (key.isKeyCode (KeyPress::leftKey))
  46112. {
  46113. TreeViewItem* const firstSelected = getSelectedItem (0);
  46114. if (firstSelected != 0)
  46115. {
  46116. if (firstSelected->isOpen())
  46117. {
  46118. firstSelected->setOpen (false);
  46119. }
  46120. else
  46121. {
  46122. TreeViewItem* parent = firstSelected->parentItem;
  46123. if ((! rootItemVisible) && parent == rootItem)
  46124. parent = 0;
  46125. if (parent != 0)
  46126. {
  46127. parent->setSelected (true, true);
  46128. scrollToKeepItemVisible (parent);
  46129. }
  46130. }
  46131. }
  46132. }
  46133. else if (key.isKeyCode (KeyPress::rightKey))
  46134. {
  46135. TreeViewItem* const firstSelected = getSelectedItem (0);
  46136. if (firstSelected != 0)
  46137. {
  46138. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  46139. moveSelectedRow (1);
  46140. else
  46141. firstSelected->setOpen (true);
  46142. }
  46143. }
  46144. else
  46145. {
  46146. return false;
  46147. }
  46148. return true;
  46149. }
  46150. void TreeView::itemsChanged() throw()
  46151. {
  46152. needsRecalculating = true;
  46153. repaint();
  46154. triggerAsyncUpdate();
  46155. }
  46156. void TreeView::handleAsyncUpdate()
  46157. {
  46158. if (needsRecalculating)
  46159. {
  46160. needsRecalculating = false;
  46161. const ScopedLock sl (nodeAlterationLock);
  46162. if (rootItem != 0)
  46163. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  46164. viewport->updateComponents();
  46165. if (rootItem != 0)
  46166. {
  46167. viewport->getViewedComponent()
  46168. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  46169. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  46170. }
  46171. else
  46172. {
  46173. viewport->getViewedComponent()->setSize (0, 0);
  46174. }
  46175. }
  46176. }
  46177. class TreeView::InsertPointHighlight : public Component
  46178. {
  46179. public:
  46180. InsertPointHighlight()
  46181. : lastItem (0)
  46182. {
  46183. setSize (100, 12);
  46184. setAlwaysOnTop (true);
  46185. setInterceptsMouseClicks (false, false);
  46186. }
  46187. ~InsertPointHighlight() {}
  46188. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  46189. {
  46190. lastItem = item;
  46191. lastIndex = insertIndex;
  46192. const int offset = getHeight() / 2;
  46193. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  46194. }
  46195. void paint (Graphics& g)
  46196. {
  46197. Path p;
  46198. const float h = (float) getHeight();
  46199. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  46200. p.startNewSubPath (h - 2.0f, h / 2.0f);
  46201. p.lineTo ((float) getWidth(), h / 2.0f);
  46202. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  46203. g.strokePath (p, PathStrokeType (2.0f));
  46204. }
  46205. TreeViewItem* lastItem;
  46206. int lastIndex;
  46207. private:
  46208. InsertPointHighlight (const InsertPointHighlight&);
  46209. InsertPointHighlight& operator= (const InsertPointHighlight&);
  46210. };
  46211. class TreeView::TargetGroupHighlight : public Component
  46212. {
  46213. public:
  46214. TargetGroupHighlight()
  46215. {
  46216. setAlwaysOnTop (true);
  46217. setInterceptsMouseClicks (false, false);
  46218. }
  46219. ~TargetGroupHighlight() {}
  46220. void setTargetPosition (TreeViewItem* const item) throw()
  46221. {
  46222. Rectangle<int> r (item->getItemPosition (true));
  46223. r.setHeight (item->getItemHeight());
  46224. setBounds (r);
  46225. }
  46226. void paint (Graphics& g)
  46227. {
  46228. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  46229. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  46230. }
  46231. private:
  46232. TargetGroupHighlight (const TargetGroupHighlight&);
  46233. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  46234. };
  46235. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  46236. {
  46237. beginDragAutoRepeat (100);
  46238. if (dragInsertPointHighlight == 0)
  46239. {
  46240. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  46241. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  46242. }
  46243. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  46244. dragTargetGroupHighlight->setTargetPosition (item);
  46245. }
  46246. void TreeView::hideDragHighlight() throw()
  46247. {
  46248. dragInsertPointHighlight = 0;
  46249. dragTargetGroupHighlight = 0;
  46250. }
  46251. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  46252. const StringArray& files, const String& sourceDescription,
  46253. Component* sourceComponent) const throw()
  46254. {
  46255. insertIndex = 0;
  46256. TreeViewItem* item = getItemAt (y);
  46257. if (item == 0)
  46258. return 0;
  46259. Rectangle<int> itemPos (item->getItemPosition (true));
  46260. insertIndex = item->getIndexInParent();
  46261. const int oldY = y;
  46262. y = itemPos.getY();
  46263. if (item->getNumSubItems() == 0 || ! item->isOpen())
  46264. {
  46265. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46266. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46267. {
  46268. // Check if we're trying to drag into an empty group item..
  46269. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  46270. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  46271. {
  46272. insertIndex = 0;
  46273. x = itemPos.getX() + getIndentSize();
  46274. y = itemPos.getBottom();
  46275. return item;
  46276. }
  46277. }
  46278. }
  46279. if (oldY > itemPos.getCentreY())
  46280. {
  46281. y += item->getItemHeight();
  46282. while (item->isLastOfSiblings() && item->parentItem != 0
  46283. && item->parentItem->parentItem != 0)
  46284. {
  46285. if (x > itemPos.getX())
  46286. break;
  46287. item = item->parentItem;
  46288. itemPos = item->getItemPosition (true);
  46289. insertIndex = item->getIndexInParent();
  46290. }
  46291. ++insertIndex;
  46292. }
  46293. x = itemPos.getX();
  46294. return item->parentItem;
  46295. }
  46296. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46297. {
  46298. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  46299. int insertIndex;
  46300. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46301. if (item != 0)
  46302. {
  46303. if (scrolled || dragInsertPointHighlight == 0
  46304. || dragInsertPointHighlight->lastItem != item
  46305. || dragInsertPointHighlight->lastIndex != insertIndex)
  46306. {
  46307. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46308. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46309. showDragHighlight (item, insertIndex, x, y);
  46310. else
  46311. hideDragHighlight();
  46312. }
  46313. }
  46314. else
  46315. {
  46316. hideDragHighlight();
  46317. }
  46318. }
  46319. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46320. {
  46321. hideDragHighlight();
  46322. int insertIndex;
  46323. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46324. if (item != 0)
  46325. {
  46326. if (files.size() > 0)
  46327. {
  46328. if (item->isInterestedInFileDrag (files))
  46329. item->filesDropped (files, insertIndex);
  46330. }
  46331. else
  46332. {
  46333. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46334. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  46335. }
  46336. }
  46337. }
  46338. bool TreeView::isInterestedInFileDrag (const StringArray&)
  46339. {
  46340. return true;
  46341. }
  46342. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  46343. {
  46344. fileDragMove (files, x, y);
  46345. }
  46346. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  46347. {
  46348. handleDrag (files, String::empty, 0, x, y);
  46349. }
  46350. void TreeView::fileDragExit (const StringArray&)
  46351. {
  46352. hideDragHighlight();
  46353. }
  46354. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46355. {
  46356. handleDrop (files, String::empty, 0, x, y);
  46357. }
  46358. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46359. {
  46360. return true;
  46361. }
  46362. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46363. {
  46364. itemDragMove (sourceDescription, sourceComponent, x, y);
  46365. }
  46366. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46367. {
  46368. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46369. }
  46370. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46371. {
  46372. hideDragHighlight();
  46373. }
  46374. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46375. {
  46376. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46377. }
  46378. enum TreeViewOpenness
  46379. {
  46380. opennessDefault = 0,
  46381. opennessClosed = 1,
  46382. opennessOpen = 2
  46383. };
  46384. TreeViewItem::TreeViewItem()
  46385. : ownerView (0),
  46386. parentItem (0),
  46387. y (0),
  46388. itemHeight (0),
  46389. totalHeight (0),
  46390. selected (false),
  46391. redrawNeeded (true),
  46392. drawLinesInside (true),
  46393. drawsInLeftMargin (false),
  46394. openness (opennessDefault)
  46395. {
  46396. static int nextUID = 0;
  46397. uid = nextUID++;
  46398. }
  46399. TreeViewItem::~TreeViewItem()
  46400. {
  46401. }
  46402. const String TreeViewItem::getUniqueName() const
  46403. {
  46404. return String::empty;
  46405. }
  46406. void TreeViewItem::itemOpennessChanged (bool)
  46407. {
  46408. }
  46409. int TreeViewItem::getNumSubItems() const throw()
  46410. {
  46411. return subItems.size();
  46412. }
  46413. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46414. {
  46415. return subItems [index];
  46416. }
  46417. void TreeViewItem::clearSubItems()
  46418. {
  46419. if (subItems.size() > 0)
  46420. {
  46421. if (ownerView != 0)
  46422. {
  46423. const ScopedLock sl (ownerView->nodeAlterationLock);
  46424. subItems.clear();
  46425. treeHasChanged();
  46426. }
  46427. else
  46428. {
  46429. subItems.clear();
  46430. }
  46431. }
  46432. }
  46433. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46434. {
  46435. if (newItem != 0)
  46436. {
  46437. newItem->parentItem = this;
  46438. newItem->setOwnerView (ownerView);
  46439. newItem->y = 0;
  46440. newItem->itemHeight = newItem->getItemHeight();
  46441. newItem->totalHeight = 0;
  46442. newItem->itemWidth = newItem->getItemWidth();
  46443. newItem->totalWidth = 0;
  46444. if (ownerView != 0)
  46445. {
  46446. const ScopedLock sl (ownerView->nodeAlterationLock);
  46447. subItems.insert (insertPosition, newItem);
  46448. treeHasChanged();
  46449. if (newItem->isOpen())
  46450. newItem->itemOpennessChanged (true);
  46451. }
  46452. else
  46453. {
  46454. subItems.insert (insertPosition, newItem);
  46455. if (newItem->isOpen())
  46456. newItem->itemOpennessChanged (true);
  46457. }
  46458. }
  46459. }
  46460. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46461. {
  46462. if (ownerView != 0)
  46463. {
  46464. const ScopedLock sl (ownerView->nodeAlterationLock);
  46465. if (((unsigned int) index) < (unsigned int) subItems.size())
  46466. {
  46467. subItems.remove (index, deleteItem);
  46468. treeHasChanged();
  46469. }
  46470. }
  46471. else
  46472. {
  46473. subItems.remove (index, deleteItem);
  46474. }
  46475. }
  46476. bool TreeViewItem::isOpen() const throw()
  46477. {
  46478. if (openness == opennessDefault)
  46479. return ownerView != 0 && ownerView->defaultOpenness;
  46480. else
  46481. return openness == opennessOpen;
  46482. }
  46483. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46484. {
  46485. if (isOpen() != shouldBeOpen)
  46486. {
  46487. openness = shouldBeOpen ? opennessOpen
  46488. : opennessClosed;
  46489. treeHasChanged();
  46490. itemOpennessChanged (isOpen());
  46491. }
  46492. }
  46493. bool TreeViewItem::isSelected() const throw()
  46494. {
  46495. return selected;
  46496. }
  46497. void TreeViewItem::deselectAllRecursively()
  46498. {
  46499. setSelected (false, false);
  46500. for (int i = 0; i < subItems.size(); ++i)
  46501. subItems.getUnchecked(i)->deselectAllRecursively();
  46502. }
  46503. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46504. const bool deselectOtherItemsFirst)
  46505. {
  46506. if (shouldBeSelected && ! canBeSelected())
  46507. return;
  46508. if (deselectOtherItemsFirst)
  46509. getTopLevelItem()->deselectAllRecursively();
  46510. if (shouldBeSelected != selected)
  46511. {
  46512. selected = shouldBeSelected;
  46513. if (ownerView != 0)
  46514. ownerView->repaint();
  46515. itemSelectionChanged (shouldBeSelected);
  46516. }
  46517. }
  46518. void TreeViewItem::paintItem (Graphics&, int, int)
  46519. {
  46520. }
  46521. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46522. {
  46523. ownerView->getLookAndFeel()
  46524. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46525. }
  46526. void TreeViewItem::itemClicked (const MouseEvent&)
  46527. {
  46528. }
  46529. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46530. {
  46531. if (mightContainSubItems())
  46532. setOpen (! isOpen());
  46533. }
  46534. void TreeViewItem::itemSelectionChanged (bool)
  46535. {
  46536. }
  46537. const String TreeViewItem::getTooltip()
  46538. {
  46539. return String::empty;
  46540. }
  46541. const String TreeViewItem::getDragSourceDescription()
  46542. {
  46543. return String::empty;
  46544. }
  46545. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46546. {
  46547. return false;
  46548. }
  46549. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46550. {
  46551. }
  46552. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46553. {
  46554. return false;
  46555. }
  46556. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46557. {
  46558. }
  46559. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46560. {
  46561. const int indentX = getIndentX();
  46562. int width = itemWidth;
  46563. if (ownerView != 0 && width < 0)
  46564. width = ownerView->viewport->getViewWidth() - indentX;
  46565. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46566. if (relativeToTreeViewTopLeft)
  46567. r -= ownerView->viewport->getViewPosition();
  46568. return r;
  46569. }
  46570. void TreeViewItem::treeHasChanged() const throw()
  46571. {
  46572. if (ownerView != 0)
  46573. ownerView->itemsChanged();
  46574. }
  46575. void TreeViewItem::repaintItem() const
  46576. {
  46577. if (ownerView != 0 && areAllParentsOpen())
  46578. {
  46579. Rectangle<int> r (getItemPosition (true));
  46580. r.setLeft (0);
  46581. ownerView->viewport->repaint (r);
  46582. }
  46583. }
  46584. bool TreeViewItem::areAllParentsOpen() const throw()
  46585. {
  46586. return parentItem == 0
  46587. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46588. }
  46589. void TreeViewItem::updatePositions (int newY)
  46590. {
  46591. y = newY;
  46592. itemHeight = getItemHeight();
  46593. totalHeight = itemHeight;
  46594. itemWidth = getItemWidth();
  46595. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46596. if (isOpen())
  46597. {
  46598. newY += totalHeight;
  46599. for (int i = 0; i < subItems.size(); ++i)
  46600. {
  46601. TreeViewItem* const ti = subItems.getUnchecked(i);
  46602. ti->updatePositions (newY);
  46603. newY += ti->totalHeight;
  46604. totalHeight += ti->totalHeight;
  46605. totalWidth = jmax (totalWidth, ti->totalWidth);
  46606. }
  46607. }
  46608. }
  46609. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46610. {
  46611. TreeViewItem* result = this;
  46612. TreeViewItem* item = this;
  46613. while (item->parentItem != 0)
  46614. {
  46615. item = item->parentItem;
  46616. if (! item->isOpen())
  46617. result = item;
  46618. }
  46619. return result;
  46620. }
  46621. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46622. {
  46623. ownerView = newOwner;
  46624. for (int i = subItems.size(); --i >= 0;)
  46625. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46626. }
  46627. int TreeViewItem::getIndentX() const throw()
  46628. {
  46629. const int indentWidth = ownerView->getIndentSize();
  46630. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46631. if (! ownerView->openCloseButtonsVisible)
  46632. x -= indentWidth;
  46633. TreeViewItem* p = parentItem;
  46634. while (p != 0)
  46635. {
  46636. x += indentWidth;
  46637. p = p->parentItem;
  46638. }
  46639. return x;
  46640. }
  46641. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46642. {
  46643. drawsInLeftMargin = canDrawInLeftMargin;
  46644. }
  46645. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46646. {
  46647. jassert (ownerView != 0);
  46648. if (ownerView == 0)
  46649. return;
  46650. const int indent = getIndentX();
  46651. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46652. {
  46653. g.saveState();
  46654. g.setOrigin (indent, 0);
  46655. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46656. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46657. paintItem (g, itemW, itemHeight);
  46658. g.restoreState();
  46659. }
  46660. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46661. const float halfH = itemHeight * 0.5f;
  46662. int depth = 0;
  46663. TreeViewItem* p = parentItem;
  46664. while (p != 0)
  46665. {
  46666. ++depth;
  46667. p = p->parentItem;
  46668. }
  46669. if (! ownerView->rootItemVisible)
  46670. --depth;
  46671. const int indentWidth = ownerView->getIndentSize();
  46672. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46673. {
  46674. float x = (depth + 0.5f) * indentWidth;
  46675. if (depth >= 0)
  46676. {
  46677. if (parentItem != 0 && parentItem->drawLinesInside)
  46678. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46679. if ((parentItem != 0 && parentItem->drawLinesInside)
  46680. || (parentItem == 0 && drawLinesInside))
  46681. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46682. }
  46683. p = parentItem;
  46684. int d = depth;
  46685. while (p != 0 && --d >= 0)
  46686. {
  46687. x -= (float) indentWidth;
  46688. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46689. && ! p->isLastOfSiblings())
  46690. {
  46691. g.drawLine (x, 0, x, (float) itemHeight);
  46692. }
  46693. p = p->parentItem;
  46694. }
  46695. if (mightContainSubItems())
  46696. {
  46697. g.saveState();
  46698. g.setOrigin (depth * indentWidth, 0);
  46699. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46700. paintOpenCloseButton (g, indentWidth, itemHeight,
  46701. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46702. ->isMouseOverButton (this));
  46703. g.restoreState();
  46704. }
  46705. }
  46706. if (isOpen())
  46707. {
  46708. const Rectangle<int> clip (g.getClipBounds());
  46709. for (int i = 0; i < subItems.size(); ++i)
  46710. {
  46711. TreeViewItem* const ti = subItems.getUnchecked(i);
  46712. const int relY = ti->y - y;
  46713. if (relY >= clip.getBottom())
  46714. break;
  46715. if (relY + ti->totalHeight >= clip.getY())
  46716. {
  46717. g.saveState();
  46718. g.setOrigin (0, relY);
  46719. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46720. ti->paintRecursively (g, width);
  46721. g.restoreState();
  46722. }
  46723. }
  46724. }
  46725. }
  46726. bool TreeViewItem::isLastOfSiblings() const throw()
  46727. {
  46728. return parentItem == 0
  46729. || parentItem->subItems.getLast() == this;
  46730. }
  46731. int TreeViewItem::getIndexInParent() const throw()
  46732. {
  46733. if (parentItem == 0)
  46734. return 0;
  46735. return parentItem->subItems.indexOf (this);
  46736. }
  46737. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46738. {
  46739. return (parentItem == 0) ? this
  46740. : parentItem->getTopLevelItem();
  46741. }
  46742. int TreeViewItem::getNumRows() const throw()
  46743. {
  46744. int num = 1;
  46745. if (isOpen())
  46746. {
  46747. for (int i = subItems.size(); --i >= 0;)
  46748. num += subItems.getUnchecked(i)->getNumRows();
  46749. }
  46750. return num;
  46751. }
  46752. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46753. {
  46754. if (index == 0)
  46755. return this;
  46756. if (index > 0 && isOpen())
  46757. {
  46758. --index;
  46759. for (int i = 0; i < subItems.size(); ++i)
  46760. {
  46761. TreeViewItem* const item = subItems.getUnchecked(i);
  46762. if (index == 0)
  46763. return item;
  46764. const int numRows = item->getNumRows();
  46765. if (numRows > index)
  46766. return item->getItemOnRow (index);
  46767. index -= numRows;
  46768. }
  46769. }
  46770. return 0;
  46771. }
  46772. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46773. {
  46774. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46775. {
  46776. const int h = itemHeight;
  46777. if (targetY < h)
  46778. return this;
  46779. if (isOpen())
  46780. {
  46781. targetY -= h;
  46782. for (int i = 0; i < subItems.size(); ++i)
  46783. {
  46784. TreeViewItem* const ti = subItems.getUnchecked(i);
  46785. if (targetY < ti->totalHeight)
  46786. return ti->findItemRecursively (targetY);
  46787. targetY -= ti->totalHeight;
  46788. }
  46789. }
  46790. }
  46791. return 0;
  46792. }
  46793. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46794. {
  46795. int total = 0;
  46796. if (isSelected())
  46797. ++total;
  46798. for (int i = subItems.size(); --i >= 0;)
  46799. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46800. return total;
  46801. }
  46802. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46803. {
  46804. if (isSelected())
  46805. {
  46806. if (index == 0)
  46807. return this;
  46808. --index;
  46809. }
  46810. if (index >= 0)
  46811. {
  46812. for (int i = 0; i < subItems.size(); ++i)
  46813. {
  46814. TreeViewItem* const item = subItems.getUnchecked(i);
  46815. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46816. if (found != 0)
  46817. return found;
  46818. index -= item->countSelectedItemsRecursively();
  46819. }
  46820. }
  46821. return 0;
  46822. }
  46823. int TreeViewItem::getRowNumberInTree() const throw()
  46824. {
  46825. if (parentItem != 0 && ownerView != 0)
  46826. {
  46827. int n = 1 + parentItem->getRowNumberInTree();
  46828. int ourIndex = parentItem->subItems.indexOf (this);
  46829. jassert (ourIndex >= 0);
  46830. while (--ourIndex >= 0)
  46831. n += parentItem->subItems [ourIndex]->getNumRows();
  46832. if (parentItem->parentItem == 0
  46833. && ! ownerView->rootItemVisible)
  46834. --n;
  46835. return n;
  46836. }
  46837. else
  46838. {
  46839. return 0;
  46840. }
  46841. }
  46842. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46843. {
  46844. drawLinesInside = drawLines;
  46845. }
  46846. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46847. {
  46848. if (recurse && isOpen() && subItems.size() > 0)
  46849. return subItems [0];
  46850. if (parentItem != 0)
  46851. {
  46852. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46853. if (nextIndex >= parentItem->subItems.size())
  46854. return parentItem->getNextVisibleItem (false);
  46855. return parentItem->subItems [nextIndex];
  46856. }
  46857. return 0;
  46858. }
  46859. const String TreeViewItem::getItemIdentifierString() const
  46860. {
  46861. String s;
  46862. if (parentItem != 0)
  46863. s = parentItem->getItemIdentifierString();
  46864. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46865. }
  46866. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46867. {
  46868. const String thisId (getUniqueName());
  46869. if (thisId == identifierString)
  46870. return this;
  46871. if (identifierString.startsWith (thisId + "/"))
  46872. {
  46873. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46874. bool wasOpen = isOpen();
  46875. setOpen (true);
  46876. for (int i = subItems.size(); --i >= 0;)
  46877. {
  46878. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46879. if (item != 0)
  46880. return item;
  46881. }
  46882. setOpen (wasOpen);
  46883. }
  46884. return 0;
  46885. }
  46886. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46887. {
  46888. if (e.hasTagName ("CLOSED"))
  46889. {
  46890. setOpen (false);
  46891. }
  46892. else if (e.hasTagName ("OPEN"))
  46893. {
  46894. setOpen (true);
  46895. forEachXmlChildElement (e, n)
  46896. {
  46897. const String id (n->getStringAttribute ("id"));
  46898. for (int i = 0; i < subItems.size(); ++i)
  46899. {
  46900. TreeViewItem* const ti = subItems.getUnchecked(i);
  46901. if (ti->getUniqueName() == id)
  46902. {
  46903. ti->restoreOpennessState (*n);
  46904. break;
  46905. }
  46906. }
  46907. }
  46908. }
  46909. }
  46910. XmlElement* TreeViewItem::getOpennessState() const throw()
  46911. {
  46912. const String name (getUniqueName());
  46913. if (name.isNotEmpty())
  46914. {
  46915. XmlElement* e;
  46916. if (isOpen())
  46917. {
  46918. e = new XmlElement ("OPEN");
  46919. for (int i = 0; i < subItems.size(); ++i)
  46920. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46921. }
  46922. else
  46923. {
  46924. e = new XmlElement ("CLOSED");
  46925. }
  46926. e->setAttribute ("id", name);
  46927. return e;
  46928. }
  46929. else
  46930. {
  46931. // trying to save the openness for an element that has no name - this won't
  46932. // work because it needs the names to identify what to open.
  46933. jassertfalse;
  46934. }
  46935. return 0;
  46936. }
  46937. END_JUCE_NAMESPACE
  46938. /*** End of inlined file: juce_TreeView.cpp ***/
  46939. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46940. BEGIN_JUCE_NAMESPACE
  46941. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46942. : fileList (listToShow)
  46943. {
  46944. }
  46945. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46946. {
  46947. }
  46948. FileBrowserListener::~FileBrowserListener()
  46949. {
  46950. }
  46951. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46952. {
  46953. listeners.add (listener);
  46954. }
  46955. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46956. {
  46957. listeners.remove (listener);
  46958. }
  46959. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46960. {
  46961. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46962. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46963. }
  46964. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46965. {
  46966. if (fileList.getDirectory().exists())
  46967. {
  46968. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46969. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46970. }
  46971. }
  46972. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46973. {
  46974. if (fileList.getDirectory().exists())
  46975. {
  46976. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46977. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46978. }
  46979. }
  46980. END_JUCE_NAMESPACE
  46981. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46982. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46983. BEGIN_JUCE_NAMESPACE
  46984. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46985. TimeSliceThread& thread_)
  46986. : fileFilter (fileFilter_),
  46987. thread (thread_),
  46988. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46989. fileFindHandle (0),
  46990. shouldStop (true)
  46991. {
  46992. }
  46993. DirectoryContentsList::~DirectoryContentsList()
  46994. {
  46995. clear();
  46996. }
  46997. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46998. {
  46999. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  47000. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  47001. }
  47002. bool DirectoryContentsList::ignoresHiddenFiles() const
  47003. {
  47004. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  47005. }
  47006. const File& DirectoryContentsList::getDirectory() const
  47007. {
  47008. return root;
  47009. }
  47010. void DirectoryContentsList::setDirectory (const File& directory,
  47011. const bool includeDirectories,
  47012. const bool includeFiles)
  47013. {
  47014. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  47015. if (directory != root)
  47016. {
  47017. clear();
  47018. root = directory;
  47019. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  47020. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  47021. }
  47022. int newFlags = fileTypeFlags;
  47023. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  47024. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  47025. setTypeFlags (newFlags);
  47026. }
  47027. void DirectoryContentsList::setTypeFlags (const int newFlags)
  47028. {
  47029. if (fileTypeFlags != newFlags)
  47030. {
  47031. fileTypeFlags = newFlags;
  47032. refresh();
  47033. }
  47034. }
  47035. void DirectoryContentsList::clear()
  47036. {
  47037. shouldStop = true;
  47038. thread.removeTimeSliceClient (this);
  47039. fileFindHandle = 0;
  47040. if (files.size() > 0)
  47041. {
  47042. files.clear();
  47043. changed();
  47044. }
  47045. }
  47046. void DirectoryContentsList::refresh()
  47047. {
  47048. clear();
  47049. if (root.isDirectory())
  47050. {
  47051. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  47052. shouldStop = false;
  47053. thread.addTimeSliceClient (this);
  47054. }
  47055. }
  47056. int DirectoryContentsList::getNumFiles() const
  47057. {
  47058. return files.size();
  47059. }
  47060. bool DirectoryContentsList::getFileInfo (const int index,
  47061. FileInfo& result) const
  47062. {
  47063. const ScopedLock sl (fileListLock);
  47064. const FileInfo* const info = files [index];
  47065. if (info != 0)
  47066. {
  47067. result = *info;
  47068. return true;
  47069. }
  47070. return false;
  47071. }
  47072. const File DirectoryContentsList::getFile (const int index) const
  47073. {
  47074. const ScopedLock sl (fileListLock);
  47075. const FileInfo* const info = files [index];
  47076. if (info != 0)
  47077. return root.getChildFile (info->filename);
  47078. return File::nonexistent;
  47079. }
  47080. bool DirectoryContentsList::isStillLoading() const
  47081. {
  47082. return fileFindHandle != 0;
  47083. }
  47084. void DirectoryContentsList::changed()
  47085. {
  47086. sendChangeMessage (this);
  47087. }
  47088. bool DirectoryContentsList::useTimeSlice()
  47089. {
  47090. const uint32 startTime = Time::getApproximateMillisecondCounter();
  47091. bool hasChanged = false;
  47092. for (int i = 100; --i >= 0;)
  47093. {
  47094. if (! checkNextFile (hasChanged))
  47095. {
  47096. if (hasChanged)
  47097. changed();
  47098. return false;
  47099. }
  47100. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  47101. break;
  47102. }
  47103. if (hasChanged)
  47104. changed();
  47105. return true;
  47106. }
  47107. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  47108. {
  47109. if (fileFindHandle != 0)
  47110. {
  47111. bool fileFoundIsDir, isHidden, isReadOnly;
  47112. int64 fileSize;
  47113. Time modTime, creationTime;
  47114. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  47115. &modTime, &creationTime, &isReadOnly))
  47116. {
  47117. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  47118. fileSize, modTime, creationTime, isReadOnly))
  47119. {
  47120. hasChanged = true;
  47121. }
  47122. return true;
  47123. }
  47124. else
  47125. {
  47126. fileFindHandle = 0;
  47127. }
  47128. }
  47129. return false;
  47130. }
  47131. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  47132. const DirectoryContentsList::FileInfo* const second)
  47133. {
  47134. #if JUCE_WINDOWS
  47135. if (first->isDirectory != second->isDirectory)
  47136. return first->isDirectory ? -1 : 1;
  47137. #endif
  47138. return first->filename.compareIgnoreCase (second->filename);
  47139. }
  47140. bool DirectoryContentsList::addFile (const File& file,
  47141. const bool isDir,
  47142. const int64 fileSize,
  47143. const Time& modTime,
  47144. const Time& creationTime,
  47145. const bool isReadOnly)
  47146. {
  47147. if (fileFilter == 0
  47148. || ((! isDir) && fileFilter->isFileSuitable (file))
  47149. || (isDir && fileFilter->isDirectorySuitable (file)))
  47150. {
  47151. ScopedPointer <FileInfo> info (new FileInfo());
  47152. info->filename = file.getFileName();
  47153. info->fileSize = fileSize;
  47154. info->modificationTime = modTime;
  47155. info->creationTime = creationTime;
  47156. info->isDirectory = isDir;
  47157. info->isReadOnly = isReadOnly;
  47158. const ScopedLock sl (fileListLock);
  47159. for (int i = files.size(); --i >= 0;)
  47160. if (files.getUnchecked(i)->filename == info->filename)
  47161. return false;
  47162. files.addSorted (*this, info.release());
  47163. return true;
  47164. }
  47165. return false;
  47166. }
  47167. END_JUCE_NAMESPACE
  47168. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  47169. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  47170. BEGIN_JUCE_NAMESPACE
  47171. FileBrowserComponent::FileBrowserComponent (int flags_,
  47172. const File& initialFileOrDirectory,
  47173. const FileFilter* fileFilter_,
  47174. FilePreviewComponent* previewComp_)
  47175. : FileFilter (String::empty),
  47176. fileFilter (fileFilter_),
  47177. flags (flags_),
  47178. previewComp (previewComp_),
  47179. thread ("Juce FileBrowser")
  47180. {
  47181. // You need to specify one or other of the open/save flags..
  47182. jassert ((flags & (saveMode | openMode)) != 0);
  47183. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  47184. // You need to specify at least one of these flags..
  47185. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  47186. String filename;
  47187. if (initialFileOrDirectory == File::nonexistent)
  47188. {
  47189. currentRoot = File::getCurrentWorkingDirectory();
  47190. }
  47191. else if (initialFileOrDirectory.isDirectory())
  47192. {
  47193. currentRoot = initialFileOrDirectory;
  47194. }
  47195. else
  47196. {
  47197. chosenFiles.add (initialFileOrDirectory);
  47198. currentRoot = initialFileOrDirectory.getParentDirectory();
  47199. filename = initialFileOrDirectory.getFileName();
  47200. }
  47201. fileList = new DirectoryContentsList (this, thread);
  47202. if ((flags & useTreeView) != 0)
  47203. {
  47204. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  47205. if ((flags & canSelectMultipleItems) != 0)
  47206. tree->setMultiSelectEnabled (true);
  47207. addAndMakeVisible (tree);
  47208. fileListComponent = tree;
  47209. }
  47210. else
  47211. {
  47212. FileListComponent* const list = new FileListComponent (*fileList);
  47213. list->setOutlineThickness (1);
  47214. if ((flags & canSelectMultipleItems) != 0)
  47215. list->setMultipleSelectionEnabled (true);
  47216. addAndMakeVisible (list);
  47217. fileListComponent = list;
  47218. }
  47219. fileListComponent->addListener (this);
  47220. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  47221. currentPathBox->setEditableText (true);
  47222. StringArray rootNames, rootPaths;
  47223. const BigInteger separators (getRoots (rootNames, rootPaths));
  47224. for (int i = 0; i < rootNames.size(); ++i)
  47225. {
  47226. if (separators [i])
  47227. currentPathBox->addSeparator();
  47228. currentPathBox->addItem (rootNames[i], i + 1);
  47229. }
  47230. currentPathBox->addSeparator();
  47231. currentPathBox->addListener (this);
  47232. addAndMakeVisible (filenameBox = new TextEditor());
  47233. filenameBox->setMultiLine (false);
  47234. filenameBox->setSelectAllWhenFocused (true);
  47235. filenameBox->setText (filename, false);
  47236. filenameBox->addListener (this);
  47237. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  47238. Label* label = new Label ("f", TRANS("file:"));
  47239. addAndMakeVisible (label);
  47240. label->attachToComponent (filenameBox, true);
  47241. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  47242. goUpButton->addButtonListener (this);
  47243. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  47244. if (previewComp != 0)
  47245. addAndMakeVisible (previewComp);
  47246. setRoot (currentRoot);
  47247. thread.startThread (4);
  47248. }
  47249. FileBrowserComponent::~FileBrowserComponent()
  47250. {
  47251. if (previewComp != 0)
  47252. removeChildComponent (previewComp);
  47253. deleteAllChildren();
  47254. fileList = 0;
  47255. thread.stopThread (10000);
  47256. }
  47257. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  47258. {
  47259. listeners.add (newListener);
  47260. }
  47261. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  47262. {
  47263. listeners.remove (listener);
  47264. }
  47265. bool FileBrowserComponent::isSaveMode() const throw()
  47266. {
  47267. return (flags & saveMode) != 0;
  47268. }
  47269. int FileBrowserComponent::getNumSelectedFiles() const throw()
  47270. {
  47271. if (chosenFiles.size() == 0 && currentFileIsValid())
  47272. return 1;
  47273. return chosenFiles.size();
  47274. }
  47275. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  47276. {
  47277. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  47278. return currentRoot;
  47279. if (! filenameBox->isReadOnly())
  47280. return currentRoot.getChildFile (filenameBox->getText());
  47281. return chosenFiles[index];
  47282. }
  47283. bool FileBrowserComponent::currentFileIsValid() const
  47284. {
  47285. if (isSaveMode())
  47286. return ! getSelectedFile (0).isDirectory();
  47287. else
  47288. return getSelectedFile (0).exists();
  47289. }
  47290. const File FileBrowserComponent::getHighlightedFile() const throw()
  47291. {
  47292. return fileListComponent->getSelectedFile (0);
  47293. }
  47294. void FileBrowserComponent::deselectAllFiles()
  47295. {
  47296. fileListComponent->deselectAllFiles();
  47297. }
  47298. bool FileBrowserComponent::isFileSuitable (const File& file) const
  47299. {
  47300. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  47301. : false;
  47302. }
  47303. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  47304. {
  47305. return true;
  47306. }
  47307. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  47308. {
  47309. if (f.isDirectory())
  47310. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  47311. return (flags & canSelectFiles) != 0 && f.exists()
  47312. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  47313. }
  47314. const File FileBrowserComponent::getRoot() const
  47315. {
  47316. return currentRoot;
  47317. }
  47318. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  47319. {
  47320. if (currentRoot != newRootDirectory)
  47321. {
  47322. fileListComponent->scrollToTop();
  47323. String path (newRootDirectory.getFullPathName());
  47324. if (path.isEmpty())
  47325. path = File::separatorString;
  47326. StringArray rootNames, rootPaths;
  47327. getRoots (rootNames, rootPaths);
  47328. if (! rootPaths.contains (path, true))
  47329. {
  47330. bool alreadyListed = false;
  47331. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  47332. {
  47333. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  47334. {
  47335. alreadyListed = true;
  47336. break;
  47337. }
  47338. }
  47339. if (! alreadyListed)
  47340. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  47341. }
  47342. }
  47343. currentRoot = newRootDirectory;
  47344. fileList->setDirectory (currentRoot, true, true);
  47345. String currentRootName (currentRoot.getFullPathName());
  47346. if (currentRootName.isEmpty())
  47347. currentRootName = File::separatorString;
  47348. currentPathBox->setText (currentRootName, true);
  47349. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  47350. && currentRoot.getParentDirectory() != currentRoot);
  47351. }
  47352. void FileBrowserComponent::goUp()
  47353. {
  47354. setRoot (getRoot().getParentDirectory());
  47355. }
  47356. void FileBrowserComponent::refresh()
  47357. {
  47358. fileList->refresh();
  47359. }
  47360. const String FileBrowserComponent::getActionVerb() const
  47361. {
  47362. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47363. }
  47364. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47365. {
  47366. return previewComp;
  47367. }
  47368. void FileBrowserComponent::resized()
  47369. {
  47370. getLookAndFeel()
  47371. .layoutFileBrowserComponent (*this, fileListComponent,
  47372. previewComp, currentPathBox,
  47373. filenameBox, goUpButton);
  47374. }
  47375. void FileBrowserComponent::sendListenerChangeMessage()
  47376. {
  47377. Component::BailOutChecker checker (this);
  47378. if (previewComp != 0)
  47379. previewComp->selectedFileChanged (getSelectedFile (0));
  47380. // You shouldn't delete the browser when the file gets changed!
  47381. jassert (! checker.shouldBailOut());
  47382. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47383. }
  47384. void FileBrowserComponent::selectionChanged()
  47385. {
  47386. StringArray newFilenames;
  47387. bool resetChosenFiles = true;
  47388. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47389. {
  47390. const File f (fileListComponent->getSelectedFile (i));
  47391. if (isFileOrDirSuitable (f))
  47392. {
  47393. if (resetChosenFiles)
  47394. {
  47395. chosenFiles.clear();
  47396. resetChosenFiles = false;
  47397. }
  47398. chosenFiles.add (f);
  47399. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47400. }
  47401. }
  47402. if (newFilenames.size() > 0)
  47403. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47404. sendListenerChangeMessage();
  47405. }
  47406. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47407. {
  47408. Component::BailOutChecker checker (this);
  47409. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47410. }
  47411. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47412. {
  47413. if (f.isDirectory())
  47414. {
  47415. setRoot (f);
  47416. if ((flags & canSelectDirectories) != 0)
  47417. filenameBox->setText (String::empty);
  47418. }
  47419. else
  47420. {
  47421. Component::BailOutChecker checker (this);
  47422. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47423. }
  47424. }
  47425. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47426. {
  47427. (void) key;
  47428. #if JUCE_LINUX || JUCE_WINDOWS
  47429. if (key.getModifiers().isCommandDown()
  47430. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47431. {
  47432. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47433. fileList->refresh();
  47434. return true;
  47435. }
  47436. #endif
  47437. return false;
  47438. }
  47439. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47440. {
  47441. sendListenerChangeMessage();
  47442. }
  47443. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47444. {
  47445. if (filenameBox->getText().containsChar (File::separator))
  47446. {
  47447. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47448. if (f.isDirectory())
  47449. {
  47450. setRoot (f);
  47451. chosenFiles.clear();
  47452. filenameBox->setText (String::empty);
  47453. }
  47454. else
  47455. {
  47456. setRoot (f.getParentDirectory());
  47457. chosenFiles.clear();
  47458. chosenFiles.add (f);
  47459. filenameBox->setText (f.getFileName());
  47460. }
  47461. }
  47462. else
  47463. {
  47464. fileDoubleClicked (getSelectedFile (0));
  47465. }
  47466. }
  47467. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47468. {
  47469. }
  47470. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47471. {
  47472. if (! isSaveMode())
  47473. selectionChanged();
  47474. }
  47475. void FileBrowserComponent::buttonClicked (Button*)
  47476. {
  47477. goUp();
  47478. }
  47479. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47480. {
  47481. const String newText (currentPathBox->getText().trim().unquoted());
  47482. if (newText.isNotEmpty())
  47483. {
  47484. const int index = currentPathBox->getSelectedId() - 1;
  47485. StringArray rootNames, rootPaths;
  47486. getRoots (rootNames, rootPaths);
  47487. if (rootPaths [index].isNotEmpty())
  47488. {
  47489. setRoot (File (rootPaths [index]));
  47490. }
  47491. else
  47492. {
  47493. File f (newText);
  47494. for (;;)
  47495. {
  47496. if (f.isDirectory())
  47497. {
  47498. setRoot (f);
  47499. break;
  47500. }
  47501. if (f.getParentDirectory() == f)
  47502. break;
  47503. f = f.getParentDirectory();
  47504. }
  47505. }
  47506. }
  47507. }
  47508. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47509. {
  47510. BigInteger separators;
  47511. #if JUCE_WINDOWS
  47512. Array<File> roots;
  47513. File::findFileSystemRoots (roots);
  47514. rootPaths.clear();
  47515. for (int i = 0; i < roots.size(); ++i)
  47516. {
  47517. const File& drive = roots.getReference(i);
  47518. String name (drive.getFullPathName());
  47519. rootPaths.add (name);
  47520. if (drive.isOnHardDisk())
  47521. {
  47522. String volume (drive.getVolumeLabel());
  47523. if (volume.isEmpty())
  47524. volume = TRANS("Hard Drive");
  47525. name << " [" << drive.getVolumeLabel() << ']';
  47526. }
  47527. else if (drive.isOnCDRomDrive())
  47528. {
  47529. name << TRANS(" [CD/DVD drive]");
  47530. }
  47531. rootNames.add (name);
  47532. }
  47533. separators.setBit (rootPaths.size());
  47534. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47535. rootNames.add ("Documents");
  47536. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47537. rootNames.add ("Desktop");
  47538. #endif
  47539. #if JUCE_MAC
  47540. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47541. rootNames.add ("Home folder");
  47542. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47543. rootNames.add ("Documents");
  47544. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47545. rootNames.add ("Desktop");
  47546. separators.setBit (rootPaths.size());
  47547. Array <File> volumes;
  47548. File vol ("/Volumes");
  47549. vol.findChildFiles (volumes, File::findDirectories, false);
  47550. for (int i = 0; i < volumes.size(); ++i)
  47551. {
  47552. const File& volume = volumes.getReference(i);
  47553. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47554. {
  47555. rootPaths.add (volume.getFullPathName());
  47556. rootNames.add (volume.getFileName());
  47557. }
  47558. }
  47559. #endif
  47560. #if JUCE_LINUX
  47561. rootPaths.add ("/");
  47562. rootNames.add ("/");
  47563. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47564. rootNames.add ("Home folder");
  47565. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47566. rootNames.add ("Desktop");
  47567. #endif
  47568. return separators;
  47569. }
  47570. END_JUCE_NAMESPACE
  47571. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47572. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47573. BEGIN_JUCE_NAMESPACE
  47574. FileChooser::FileChooser (const String& chooserBoxTitle,
  47575. const File& currentFileOrDirectory,
  47576. const String& fileFilters,
  47577. const bool useNativeDialogBox_)
  47578. : title (chooserBoxTitle),
  47579. filters (fileFilters),
  47580. startingFile (currentFileOrDirectory),
  47581. useNativeDialogBox (useNativeDialogBox_)
  47582. {
  47583. #if JUCE_LINUX
  47584. useNativeDialogBox = false;
  47585. #endif
  47586. if (! fileFilters.containsNonWhitespaceChars())
  47587. filters = "*";
  47588. }
  47589. FileChooser::~FileChooser()
  47590. {
  47591. }
  47592. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47593. {
  47594. return showDialog (false, true, false, false, false, previewComponent);
  47595. }
  47596. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47597. {
  47598. return showDialog (false, true, false, false, true, previewComponent);
  47599. }
  47600. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47601. {
  47602. return showDialog (true, true, false, false, true, previewComponent);
  47603. }
  47604. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47605. {
  47606. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47607. }
  47608. bool FileChooser::browseForDirectory()
  47609. {
  47610. return showDialog (true, false, false, false, false, 0);
  47611. }
  47612. const File FileChooser::getResult() const
  47613. {
  47614. // if you've used a multiple-file select, you should use the getResults() method
  47615. // to retrieve all the files that were chosen.
  47616. jassert (results.size() <= 1);
  47617. return results.getFirst();
  47618. }
  47619. const Array<File>& FileChooser::getResults() const
  47620. {
  47621. return results;
  47622. }
  47623. bool FileChooser::showDialog (const bool selectsDirectories,
  47624. const bool selectsFiles,
  47625. const bool isSave,
  47626. const bool warnAboutOverwritingExistingFiles,
  47627. const bool selectMultipleFiles,
  47628. FilePreviewComponent* const previewComponent)
  47629. {
  47630. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47631. results.clear();
  47632. // the preview component needs to be the right size before you pass it in here..
  47633. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47634. && previewComponent->getHeight() > 10));
  47635. #if JUCE_WINDOWS
  47636. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47637. #elif JUCE_MAC
  47638. if (useNativeDialogBox && (previewComponent == 0))
  47639. #else
  47640. if (false)
  47641. #endif
  47642. {
  47643. showPlatformDialog (results, title, startingFile, filters,
  47644. selectsDirectories, selectsFiles, isSave,
  47645. warnAboutOverwritingExistingFiles,
  47646. selectMultipleFiles,
  47647. previewComponent);
  47648. }
  47649. else
  47650. {
  47651. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47652. selectsDirectories ? "*" : String::empty,
  47653. String::empty);
  47654. int flags = isSave ? FileBrowserComponent::saveMode
  47655. : FileBrowserComponent::openMode;
  47656. if (selectsFiles)
  47657. flags |= FileBrowserComponent::canSelectFiles;
  47658. if (selectsDirectories)
  47659. {
  47660. flags |= FileBrowserComponent::canSelectDirectories;
  47661. if (! isSave)
  47662. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47663. }
  47664. if (selectMultipleFiles)
  47665. flags |= FileBrowserComponent::canSelectMultipleItems;
  47666. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47667. FileChooserDialogBox box (title, String::empty,
  47668. browserComponent,
  47669. warnAboutOverwritingExistingFiles,
  47670. browserComponent.findColour (AlertWindow::backgroundColourId));
  47671. if (box.show())
  47672. {
  47673. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47674. results.add (browserComponent.getSelectedFile (i));
  47675. }
  47676. }
  47677. if (previouslyFocused != 0)
  47678. previouslyFocused->grabKeyboardFocus();
  47679. return results.size() > 0;
  47680. }
  47681. FilePreviewComponent::FilePreviewComponent()
  47682. {
  47683. }
  47684. FilePreviewComponent::~FilePreviewComponent()
  47685. {
  47686. }
  47687. END_JUCE_NAMESPACE
  47688. /*** End of inlined file: juce_FileChooser.cpp ***/
  47689. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47690. BEGIN_JUCE_NAMESPACE
  47691. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47692. const String& instructions,
  47693. FileBrowserComponent& chooserComponent,
  47694. const bool warnAboutOverwritingExistingFiles_,
  47695. const Colour& backgroundColour)
  47696. : ResizableWindow (name, backgroundColour, true),
  47697. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47698. {
  47699. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47700. setResizable (true, true);
  47701. setResizeLimits (300, 300, 1200, 1000);
  47702. content->okButton.addButtonListener (this);
  47703. content->cancelButton.addButtonListener (this);
  47704. content->chooserComponent.addListener (this);
  47705. }
  47706. FileChooserDialogBox::~FileChooserDialogBox()
  47707. {
  47708. content->chooserComponent.removeListener (this);
  47709. }
  47710. bool FileChooserDialogBox::show (int w, int h)
  47711. {
  47712. return showAt (-1, -1, w, h);
  47713. }
  47714. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47715. {
  47716. if (w <= 0)
  47717. {
  47718. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47719. if (previewComp != 0)
  47720. w = 400 + previewComp->getWidth();
  47721. else
  47722. w = 600;
  47723. }
  47724. if (h <= 0)
  47725. h = 500;
  47726. if (x < 0 || y < 0)
  47727. centreWithSize (w, h);
  47728. else
  47729. setBounds (x, y, w, h);
  47730. const bool ok = (runModalLoop() != 0);
  47731. setVisible (false);
  47732. return ok;
  47733. }
  47734. void FileChooserDialogBox::buttonClicked (Button* button)
  47735. {
  47736. if (button == &(content->okButton))
  47737. {
  47738. if (warnAboutOverwritingExistingFiles
  47739. && content->chooserComponent.isSaveMode()
  47740. && content->chooserComponent.getSelectedFile(0).exists())
  47741. {
  47742. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47743. TRANS("File already exists"),
  47744. TRANS("There's already a file called:")
  47745. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47746. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47747. TRANS("overwrite"),
  47748. TRANS("cancel")))
  47749. {
  47750. return;
  47751. }
  47752. }
  47753. exitModalState (1);
  47754. }
  47755. else if (button == &(content->cancelButton))
  47756. {
  47757. closeButtonPressed();
  47758. }
  47759. }
  47760. void FileChooserDialogBox::closeButtonPressed()
  47761. {
  47762. setVisible (false);
  47763. }
  47764. void FileChooserDialogBox::selectionChanged()
  47765. {
  47766. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47767. }
  47768. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47769. {
  47770. }
  47771. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47772. {
  47773. selectionChanged();
  47774. content->okButton.triggerClick();
  47775. }
  47776. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47777. : Component (name), instructions (instructions_),
  47778. chooserComponent (chooserComponent_),
  47779. okButton (chooserComponent_.getActionVerb()),
  47780. cancelButton (TRANS ("Cancel"))
  47781. {
  47782. addAndMakeVisible (&chooserComponent);
  47783. addAndMakeVisible (&okButton);
  47784. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47785. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47786. addAndMakeVisible (&cancelButton);
  47787. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47788. setInterceptsMouseClicks (false, true);
  47789. }
  47790. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47791. {
  47792. }
  47793. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47794. {
  47795. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47796. text.draw (g);
  47797. }
  47798. void FileChooserDialogBox::ContentComponent::resized()
  47799. {
  47800. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47801. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47802. const int y = roundToInt (bb.getBottom()) + 10;
  47803. const int buttonHeight = 26;
  47804. const int buttonY = getHeight() - buttonHeight - 8;
  47805. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47806. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47807. proportionOfWidth (0.2f), buttonHeight);
  47808. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47809. proportionOfWidth (0.2f), buttonHeight);
  47810. }
  47811. END_JUCE_NAMESPACE
  47812. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47813. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47814. BEGIN_JUCE_NAMESPACE
  47815. FileFilter::FileFilter (const String& filterDescription)
  47816. : description (filterDescription)
  47817. {
  47818. }
  47819. FileFilter::~FileFilter()
  47820. {
  47821. }
  47822. const String& FileFilter::getDescription() const throw()
  47823. {
  47824. return description;
  47825. }
  47826. END_JUCE_NAMESPACE
  47827. /*** End of inlined file: juce_FileFilter.cpp ***/
  47828. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47829. BEGIN_JUCE_NAMESPACE
  47830. const Image juce_createIconForFile (const File& file);
  47831. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47832. : ListBox (String::empty, 0),
  47833. DirectoryContentsDisplayComponent (listToShow)
  47834. {
  47835. setModel (this);
  47836. fileList.addChangeListener (this);
  47837. }
  47838. FileListComponent::~FileListComponent()
  47839. {
  47840. fileList.removeChangeListener (this);
  47841. }
  47842. int FileListComponent::getNumSelectedFiles() const
  47843. {
  47844. return getNumSelectedRows();
  47845. }
  47846. const File FileListComponent::getSelectedFile (int index) const
  47847. {
  47848. return fileList.getFile (getSelectedRow (index));
  47849. }
  47850. void FileListComponent::deselectAllFiles()
  47851. {
  47852. deselectAllRows();
  47853. }
  47854. void FileListComponent::scrollToTop()
  47855. {
  47856. getVerticalScrollBar()->setCurrentRangeStart (0);
  47857. }
  47858. void FileListComponent::changeListenerCallback (void*)
  47859. {
  47860. updateContent();
  47861. if (lastDirectory != fileList.getDirectory())
  47862. {
  47863. lastDirectory = fileList.getDirectory();
  47864. deselectAllRows();
  47865. }
  47866. }
  47867. class FileListItemComponent : public Component,
  47868. public TimeSliceClient,
  47869. public AsyncUpdater
  47870. {
  47871. public:
  47872. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47873. : owner (owner_), thread (thread_),
  47874. highlighted (false), index (0), icon (0)
  47875. {
  47876. }
  47877. ~FileListItemComponent()
  47878. {
  47879. thread.removeTimeSliceClient (this);
  47880. clearIcon();
  47881. }
  47882. void paint (Graphics& g)
  47883. {
  47884. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47885. file.getFileName(),
  47886. &icon,
  47887. fileSize, modTime,
  47888. isDirectory, highlighted,
  47889. index);
  47890. }
  47891. void mouseDown (const MouseEvent& e)
  47892. {
  47893. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47894. owner.sendMouseClickMessage (file, e);
  47895. }
  47896. void mouseDoubleClick (const MouseEvent&)
  47897. {
  47898. owner.sendDoubleClickMessage (file);
  47899. }
  47900. void update (const File& root,
  47901. const DirectoryContentsList::FileInfo* const fileInfo,
  47902. const int index_,
  47903. const bool highlighted_)
  47904. {
  47905. thread.removeTimeSliceClient (this);
  47906. if (highlighted_ != highlighted
  47907. || index_ != index)
  47908. {
  47909. index = index_;
  47910. highlighted = highlighted_;
  47911. repaint();
  47912. }
  47913. File newFile;
  47914. String newFileSize;
  47915. String newModTime;
  47916. if (fileInfo != 0)
  47917. {
  47918. newFile = root.getChildFile (fileInfo->filename);
  47919. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47920. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47921. }
  47922. if (newFile != file
  47923. || fileSize != newFileSize
  47924. || modTime != newModTime)
  47925. {
  47926. file = newFile;
  47927. fileSize = newFileSize;
  47928. modTime = newModTime;
  47929. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47930. repaint();
  47931. clearIcon();
  47932. }
  47933. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47934. {
  47935. updateIcon (true);
  47936. if (! icon.isValid())
  47937. thread.addTimeSliceClient (this);
  47938. }
  47939. }
  47940. bool useTimeSlice()
  47941. {
  47942. updateIcon (false);
  47943. return false;
  47944. }
  47945. void handleAsyncUpdate()
  47946. {
  47947. repaint();
  47948. }
  47949. juce_UseDebuggingNewOperator
  47950. private:
  47951. FileListComponent& owner;
  47952. TimeSliceThread& thread;
  47953. bool highlighted;
  47954. int index;
  47955. File file;
  47956. String fileSize;
  47957. String modTime;
  47958. Image icon;
  47959. bool isDirectory;
  47960. void clearIcon()
  47961. {
  47962. icon = Image::null;
  47963. }
  47964. void updateIcon (const bool onlyUpdateIfCached)
  47965. {
  47966. if (icon.isNull())
  47967. {
  47968. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47969. Image im (ImageCache::getFromHashCode (hashCode));
  47970. if (im.isNull() && ! onlyUpdateIfCached)
  47971. {
  47972. im = juce_createIconForFile (file);
  47973. if (im.isValid())
  47974. ImageCache::addImageToCache (im, hashCode);
  47975. }
  47976. if (im.isValid())
  47977. {
  47978. icon = im;
  47979. triggerAsyncUpdate();
  47980. }
  47981. }
  47982. }
  47983. };
  47984. int FileListComponent::getNumRows()
  47985. {
  47986. return fileList.getNumFiles();
  47987. }
  47988. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47989. {
  47990. }
  47991. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47992. {
  47993. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47994. if (comp == 0)
  47995. {
  47996. delete existingComponentToUpdate;
  47997. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47998. }
  47999. DirectoryContentsList::FileInfo fileInfo;
  48000. if (fileList.getFileInfo (row, fileInfo))
  48001. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  48002. else
  48003. comp->update (fileList.getDirectory(), 0, row, isSelected);
  48004. return comp;
  48005. }
  48006. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  48007. {
  48008. sendSelectionChangeMessage();
  48009. }
  48010. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  48011. {
  48012. }
  48013. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  48014. {
  48015. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  48016. }
  48017. END_JUCE_NAMESPACE
  48018. /*** End of inlined file: juce_FileListComponent.cpp ***/
  48019. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  48020. BEGIN_JUCE_NAMESPACE
  48021. FilenameComponent::FilenameComponent (const String& name,
  48022. const File& currentFile,
  48023. const bool canEditFilename,
  48024. const bool isDirectory,
  48025. const bool isForSaving,
  48026. const String& fileBrowserWildcard,
  48027. const String& enforcedSuffix_,
  48028. const String& textWhenNothingSelected)
  48029. : Component (name),
  48030. maxRecentFiles (30),
  48031. isDir (isDirectory),
  48032. isSaving (isForSaving),
  48033. isFileDragOver (false),
  48034. wildcard (fileBrowserWildcard),
  48035. enforcedSuffix (enforcedSuffix_)
  48036. {
  48037. addAndMakeVisible (&filenameBox);
  48038. filenameBox.setEditableText (canEditFilename);
  48039. filenameBox.addListener (this);
  48040. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  48041. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  48042. setBrowseButtonText ("...");
  48043. setCurrentFile (currentFile, true);
  48044. }
  48045. FilenameComponent::~FilenameComponent()
  48046. {
  48047. }
  48048. void FilenameComponent::paintOverChildren (Graphics& g)
  48049. {
  48050. if (isFileDragOver)
  48051. {
  48052. g.setColour (Colours::red.withAlpha (0.2f));
  48053. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  48054. }
  48055. }
  48056. void FilenameComponent::resized()
  48057. {
  48058. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  48059. }
  48060. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  48061. {
  48062. browseButtonText = newBrowseButtonText;
  48063. lookAndFeelChanged();
  48064. }
  48065. void FilenameComponent::lookAndFeelChanged()
  48066. {
  48067. browseButton = 0;
  48068. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  48069. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  48070. resized();
  48071. browseButton->addButtonListener (this);
  48072. }
  48073. void FilenameComponent::setTooltip (const String& newTooltip)
  48074. {
  48075. SettableTooltipClient::setTooltip (newTooltip);
  48076. filenameBox.setTooltip (newTooltip);
  48077. }
  48078. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  48079. {
  48080. defaultBrowseFile = newDefaultDirectory;
  48081. }
  48082. void FilenameComponent::buttonClicked (Button*)
  48083. {
  48084. FileChooser fc (TRANS("Choose a new file"),
  48085. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  48086. : getCurrentFile(),
  48087. wildcard);
  48088. if (isDir ? fc.browseForDirectory()
  48089. : (isSaving ? fc.browseForFileToSave (false)
  48090. : fc.browseForFileToOpen()))
  48091. {
  48092. setCurrentFile (fc.getResult(), true);
  48093. }
  48094. }
  48095. void FilenameComponent::comboBoxChanged (ComboBox*)
  48096. {
  48097. setCurrentFile (getCurrentFile(), true);
  48098. }
  48099. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  48100. {
  48101. return true;
  48102. }
  48103. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  48104. {
  48105. isFileDragOver = false;
  48106. repaint();
  48107. const File f (filenames[0]);
  48108. if (f.exists() && (f.isDirectory() == isDir))
  48109. setCurrentFile (f, true);
  48110. }
  48111. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  48112. {
  48113. isFileDragOver = true;
  48114. repaint();
  48115. }
  48116. void FilenameComponent::fileDragExit (const StringArray&)
  48117. {
  48118. isFileDragOver = false;
  48119. repaint();
  48120. }
  48121. const File FilenameComponent::getCurrentFile() const
  48122. {
  48123. File f (filenameBox.getText());
  48124. if (enforcedSuffix.isNotEmpty())
  48125. f = f.withFileExtension (enforcedSuffix);
  48126. return f;
  48127. }
  48128. void FilenameComponent::setCurrentFile (File newFile,
  48129. const bool addToRecentlyUsedList,
  48130. const bool sendChangeNotification)
  48131. {
  48132. if (enforcedSuffix.isNotEmpty())
  48133. newFile = newFile.withFileExtension (enforcedSuffix);
  48134. if (newFile.getFullPathName() != lastFilename)
  48135. {
  48136. lastFilename = newFile.getFullPathName();
  48137. if (addToRecentlyUsedList)
  48138. addRecentlyUsedFile (newFile);
  48139. filenameBox.setText (lastFilename, true);
  48140. if (sendChangeNotification)
  48141. triggerAsyncUpdate();
  48142. }
  48143. }
  48144. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  48145. {
  48146. filenameBox.setEditableText (shouldBeEditable);
  48147. }
  48148. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  48149. {
  48150. StringArray names;
  48151. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  48152. names.add (filenameBox.getItemText (i));
  48153. return names;
  48154. }
  48155. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  48156. {
  48157. if (filenames != getRecentlyUsedFilenames())
  48158. {
  48159. filenameBox.clear();
  48160. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  48161. filenameBox.addItem (filenames[i], i + 1);
  48162. }
  48163. }
  48164. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  48165. {
  48166. maxRecentFiles = jmax (1, newMaximum);
  48167. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  48168. }
  48169. void FilenameComponent::addRecentlyUsedFile (const File& file)
  48170. {
  48171. StringArray files (getRecentlyUsedFilenames());
  48172. if (file.getFullPathName().isNotEmpty())
  48173. {
  48174. files.removeString (file.getFullPathName(), true);
  48175. files.insert (0, file.getFullPathName());
  48176. setRecentlyUsedFilenames (files);
  48177. }
  48178. }
  48179. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  48180. {
  48181. listeners.add (listener);
  48182. }
  48183. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  48184. {
  48185. listeners.remove (listener);
  48186. }
  48187. void FilenameComponent::handleAsyncUpdate()
  48188. {
  48189. Component::BailOutChecker checker (this);
  48190. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  48191. }
  48192. END_JUCE_NAMESPACE
  48193. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  48194. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48195. BEGIN_JUCE_NAMESPACE
  48196. FileSearchPathListComponent::FileSearchPathListComponent()
  48197. {
  48198. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  48199. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  48200. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  48201. listBox->setOutlineThickness (1);
  48202. addAndMakeVisible (addButton = new TextButton ("+"));
  48203. addButton->addButtonListener (this);
  48204. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  48205. addAndMakeVisible (removeButton = new TextButton ("-"));
  48206. removeButton->addButtonListener (this);
  48207. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  48208. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  48209. changeButton->addButtonListener (this);
  48210. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  48211. upButton->addButtonListener (this);
  48212. {
  48213. Path arrowPath;
  48214. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  48215. DrawablePath arrowImage;
  48216. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  48217. arrowImage.setPath (arrowPath);
  48218. upButton->setImages (&arrowImage);
  48219. }
  48220. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  48221. downButton->addButtonListener (this);
  48222. {
  48223. Path arrowPath;
  48224. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  48225. DrawablePath arrowImage;
  48226. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  48227. arrowImage.setPath (arrowPath);
  48228. downButton->setImages (&arrowImage);
  48229. }
  48230. updateButtons();
  48231. }
  48232. FileSearchPathListComponent::~FileSearchPathListComponent()
  48233. {
  48234. deleteAllChildren();
  48235. }
  48236. void FileSearchPathListComponent::updateButtons()
  48237. {
  48238. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  48239. removeButton->setEnabled (anythingSelected);
  48240. changeButton->setEnabled (anythingSelected);
  48241. upButton->setEnabled (anythingSelected);
  48242. downButton->setEnabled (anythingSelected);
  48243. }
  48244. void FileSearchPathListComponent::changed()
  48245. {
  48246. listBox->updateContent();
  48247. listBox->repaint();
  48248. updateButtons();
  48249. }
  48250. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  48251. {
  48252. if (newPath.toString() != path.toString())
  48253. {
  48254. path = newPath;
  48255. changed();
  48256. }
  48257. }
  48258. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  48259. {
  48260. defaultBrowseTarget = newDefaultDirectory;
  48261. }
  48262. int FileSearchPathListComponent::getNumRows()
  48263. {
  48264. return path.getNumPaths();
  48265. }
  48266. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  48267. {
  48268. if (rowIsSelected)
  48269. g.fillAll (findColour (TextEditor::highlightColourId));
  48270. g.setColour (findColour (ListBox::textColourId));
  48271. Font f (height * 0.7f);
  48272. f.setHorizontalScale (0.9f);
  48273. g.setFont (f);
  48274. g.drawText (path [rowNumber].getFullPathName(),
  48275. 4, 0, width - 6, height,
  48276. Justification::centredLeft, true);
  48277. }
  48278. void FileSearchPathListComponent::deleteKeyPressed (int row)
  48279. {
  48280. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  48281. {
  48282. path.remove (row);
  48283. changed();
  48284. }
  48285. }
  48286. void FileSearchPathListComponent::returnKeyPressed (int row)
  48287. {
  48288. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  48289. if (chooser.browseForDirectory())
  48290. {
  48291. path.remove (row);
  48292. path.add (chooser.getResult(), row);
  48293. changed();
  48294. }
  48295. }
  48296. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  48297. {
  48298. returnKeyPressed (row);
  48299. }
  48300. void FileSearchPathListComponent::selectedRowsChanged (int)
  48301. {
  48302. updateButtons();
  48303. }
  48304. void FileSearchPathListComponent::paint (Graphics& g)
  48305. {
  48306. g.fillAll (findColour (backgroundColourId));
  48307. }
  48308. void FileSearchPathListComponent::resized()
  48309. {
  48310. const int buttonH = 22;
  48311. const int buttonY = getHeight() - buttonH - 4;
  48312. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  48313. addButton->setBounds (2, buttonY, buttonH, buttonH);
  48314. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  48315. changeButton->changeWidthToFitText (buttonH);
  48316. downButton->setSize (buttonH * 2, buttonH);
  48317. upButton->setSize (buttonH * 2, buttonH);
  48318. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  48319. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  48320. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  48321. }
  48322. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  48323. {
  48324. return true;
  48325. }
  48326. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  48327. {
  48328. for (int i = filenames.size(); --i >= 0;)
  48329. {
  48330. const File f (filenames[i]);
  48331. if (f.isDirectory())
  48332. {
  48333. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  48334. path.add (f, row);
  48335. changed();
  48336. }
  48337. }
  48338. }
  48339. void FileSearchPathListComponent::buttonClicked (Button* button)
  48340. {
  48341. const int currentRow = listBox->getSelectedRow();
  48342. if (button == removeButton)
  48343. {
  48344. deleteKeyPressed (currentRow);
  48345. }
  48346. else if (button == addButton)
  48347. {
  48348. File start (defaultBrowseTarget);
  48349. if (start == File::nonexistent)
  48350. start = path [0];
  48351. if (start == File::nonexistent)
  48352. start = File::getCurrentWorkingDirectory();
  48353. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48354. if (chooser.browseForDirectory())
  48355. {
  48356. path.add (chooser.getResult(), currentRow);
  48357. }
  48358. }
  48359. else if (button == changeButton)
  48360. {
  48361. returnKeyPressed (currentRow);
  48362. }
  48363. else if (button == upButton)
  48364. {
  48365. if (currentRow > 0 && currentRow < path.getNumPaths())
  48366. {
  48367. const File f (path[currentRow]);
  48368. path.remove (currentRow);
  48369. path.add (f, currentRow - 1);
  48370. listBox->selectRow (currentRow - 1);
  48371. }
  48372. }
  48373. else if (button == downButton)
  48374. {
  48375. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48376. {
  48377. const File f (path[currentRow]);
  48378. path.remove (currentRow);
  48379. path.add (f, currentRow + 1);
  48380. listBox->selectRow (currentRow + 1);
  48381. }
  48382. }
  48383. changed();
  48384. }
  48385. END_JUCE_NAMESPACE
  48386. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48387. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48388. BEGIN_JUCE_NAMESPACE
  48389. const Image juce_createIconForFile (const File& file);
  48390. class FileListTreeItem : public TreeViewItem,
  48391. public TimeSliceClient,
  48392. public AsyncUpdater,
  48393. public ChangeListener
  48394. {
  48395. public:
  48396. FileListTreeItem (FileTreeComponent& owner_,
  48397. DirectoryContentsList* const parentContentsList_,
  48398. const int indexInContentsList_,
  48399. const File& file_,
  48400. TimeSliceThread& thread_)
  48401. : file (file_),
  48402. owner (owner_),
  48403. parentContentsList (parentContentsList_),
  48404. indexInContentsList (indexInContentsList_),
  48405. subContentsList (0),
  48406. canDeleteSubContentsList (false),
  48407. thread (thread_),
  48408. icon (0)
  48409. {
  48410. DirectoryContentsList::FileInfo fileInfo;
  48411. if (parentContentsList_ != 0
  48412. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48413. {
  48414. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48415. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48416. isDirectory = fileInfo.isDirectory;
  48417. }
  48418. else
  48419. {
  48420. isDirectory = true;
  48421. }
  48422. }
  48423. ~FileListTreeItem()
  48424. {
  48425. thread.removeTimeSliceClient (this);
  48426. clearSubItems();
  48427. if (canDeleteSubContentsList)
  48428. delete subContentsList;
  48429. }
  48430. bool mightContainSubItems() { return isDirectory; }
  48431. const String getUniqueName() const { return file.getFullPathName(); }
  48432. int getItemHeight() const { return 22; }
  48433. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48434. void itemOpennessChanged (bool isNowOpen)
  48435. {
  48436. if (isNowOpen)
  48437. {
  48438. clearSubItems();
  48439. isDirectory = file.isDirectory();
  48440. if (isDirectory)
  48441. {
  48442. if (subContentsList == 0)
  48443. {
  48444. jassert (parentContentsList != 0);
  48445. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48446. l->setDirectory (file, true, true);
  48447. setSubContentsList (l);
  48448. canDeleteSubContentsList = true;
  48449. }
  48450. changeListenerCallback (0);
  48451. }
  48452. }
  48453. }
  48454. void setSubContentsList (DirectoryContentsList* newList)
  48455. {
  48456. jassert (subContentsList == 0);
  48457. subContentsList = newList;
  48458. newList->addChangeListener (this);
  48459. }
  48460. void changeListenerCallback (void*)
  48461. {
  48462. clearSubItems();
  48463. if (isOpen() && subContentsList != 0)
  48464. {
  48465. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48466. {
  48467. FileListTreeItem* const item
  48468. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48469. addSubItem (item);
  48470. }
  48471. }
  48472. }
  48473. void paintItem (Graphics& g, int width, int height)
  48474. {
  48475. if (file != File::nonexistent)
  48476. {
  48477. updateIcon (true);
  48478. if (icon.isNull())
  48479. thread.addTimeSliceClient (this);
  48480. }
  48481. owner.getLookAndFeel()
  48482. .drawFileBrowserRow (g, width, height,
  48483. file.getFileName(),
  48484. &icon, fileSize, modTime,
  48485. isDirectory, isSelected(),
  48486. indexInContentsList);
  48487. }
  48488. void itemClicked (const MouseEvent& e)
  48489. {
  48490. owner.sendMouseClickMessage (file, e);
  48491. }
  48492. void itemDoubleClicked (const MouseEvent& e)
  48493. {
  48494. TreeViewItem::itemDoubleClicked (e);
  48495. owner.sendDoubleClickMessage (file);
  48496. }
  48497. void itemSelectionChanged (bool)
  48498. {
  48499. owner.sendSelectionChangeMessage();
  48500. }
  48501. bool useTimeSlice()
  48502. {
  48503. updateIcon (false);
  48504. thread.removeTimeSliceClient (this);
  48505. return false;
  48506. }
  48507. void handleAsyncUpdate()
  48508. {
  48509. owner.repaint();
  48510. }
  48511. const File file;
  48512. juce_UseDebuggingNewOperator
  48513. private:
  48514. FileTreeComponent& owner;
  48515. DirectoryContentsList* parentContentsList;
  48516. int indexInContentsList;
  48517. DirectoryContentsList* subContentsList;
  48518. bool isDirectory, canDeleteSubContentsList;
  48519. TimeSliceThread& thread;
  48520. Image icon;
  48521. String fileSize;
  48522. String modTime;
  48523. void updateIcon (const bool onlyUpdateIfCached)
  48524. {
  48525. if (icon.isNull())
  48526. {
  48527. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48528. Image im (ImageCache::getFromHashCode (hashCode));
  48529. if (im.isNull() && ! onlyUpdateIfCached)
  48530. {
  48531. im = juce_createIconForFile (file);
  48532. if (im.isValid())
  48533. ImageCache::addImageToCache (im, hashCode);
  48534. }
  48535. if (im.isValid())
  48536. {
  48537. icon = im;
  48538. triggerAsyncUpdate();
  48539. }
  48540. }
  48541. }
  48542. };
  48543. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48544. : DirectoryContentsDisplayComponent (listToShow)
  48545. {
  48546. FileListTreeItem* const root
  48547. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48548. listToShow.getTimeSliceThread());
  48549. root->setSubContentsList (&listToShow);
  48550. setRootItemVisible (false);
  48551. setRootItem (root);
  48552. }
  48553. FileTreeComponent::~FileTreeComponent()
  48554. {
  48555. deleteRootItem();
  48556. }
  48557. const File FileTreeComponent::getSelectedFile (const int index) const
  48558. {
  48559. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48560. return item != 0 ? item->file
  48561. : File::nonexistent;
  48562. }
  48563. void FileTreeComponent::deselectAllFiles()
  48564. {
  48565. clearSelectedItems();
  48566. }
  48567. void FileTreeComponent::scrollToTop()
  48568. {
  48569. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48570. }
  48571. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48572. {
  48573. dragAndDropDescription = description;
  48574. }
  48575. END_JUCE_NAMESPACE
  48576. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48577. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48578. BEGIN_JUCE_NAMESPACE
  48579. ImagePreviewComponent::ImagePreviewComponent()
  48580. {
  48581. }
  48582. ImagePreviewComponent::~ImagePreviewComponent()
  48583. {
  48584. }
  48585. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48586. {
  48587. const int availableW = proportionOfWidth (0.97f);
  48588. const int availableH = getHeight() - 13 * 4;
  48589. const double scale = jmin (1.0,
  48590. availableW / (double) w,
  48591. availableH / (double) h);
  48592. w = roundToInt (scale * w);
  48593. h = roundToInt (scale * h);
  48594. }
  48595. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48596. {
  48597. if (fileToLoad != file)
  48598. {
  48599. fileToLoad = file;
  48600. startTimer (100);
  48601. }
  48602. }
  48603. void ImagePreviewComponent::timerCallback()
  48604. {
  48605. stopTimer();
  48606. currentThumbnail = Image::null;
  48607. currentDetails = String::empty;
  48608. repaint();
  48609. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48610. if (in != 0)
  48611. {
  48612. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48613. if (format != 0)
  48614. {
  48615. currentThumbnail = format->decodeImage (*in);
  48616. if (currentThumbnail.isValid())
  48617. {
  48618. int w = currentThumbnail.getWidth();
  48619. int h = currentThumbnail.getHeight();
  48620. currentDetails
  48621. << fileToLoad.getFileName() << "\n"
  48622. << format->getFormatName() << "\n"
  48623. << w << " x " << h << " pixels\n"
  48624. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48625. getThumbSize (w, h);
  48626. currentThumbnail = currentThumbnail.rescaled (w, h);
  48627. }
  48628. }
  48629. }
  48630. }
  48631. void ImagePreviewComponent::paint (Graphics& g)
  48632. {
  48633. if (currentThumbnail.isValid())
  48634. {
  48635. g.setFont (13.0f);
  48636. int w = currentThumbnail.getWidth();
  48637. int h = currentThumbnail.getHeight();
  48638. getThumbSize (w, h);
  48639. const int numLines = 4;
  48640. const int totalH = 13 * numLines + h + 4;
  48641. const int y = (getHeight() - totalH) / 2;
  48642. g.drawImageWithin (currentThumbnail,
  48643. (getWidth() - w) / 2, y, w, h,
  48644. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48645. false);
  48646. g.drawFittedText (currentDetails,
  48647. 0, y + h + 4, getWidth(), 100,
  48648. Justification::centredTop, numLines);
  48649. }
  48650. }
  48651. END_JUCE_NAMESPACE
  48652. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48653. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48654. BEGIN_JUCE_NAMESPACE
  48655. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48656. const String& directoryWildcardPatterns,
  48657. const String& description_)
  48658. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48659. : (description_ + " (" + fileWildcardPatterns + ")"))
  48660. {
  48661. parse (fileWildcardPatterns, fileWildcards);
  48662. parse (directoryWildcardPatterns, directoryWildcards);
  48663. }
  48664. WildcardFileFilter::~WildcardFileFilter()
  48665. {
  48666. }
  48667. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48668. {
  48669. return match (file, fileWildcards);
  48670. }
  48671. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48672. {
  48673. return match (file, directoryWildcards);
  48674. }
  48675. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48676. {
  48677. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48678. result.trim();
  48679. result.removeEmptyStrings();
  48680. // special case for *.*, because people use it to mean "any file", but it
  48681. // would actually ignore files with no extension.
  48682. for (int i = result.size(); --i >= 0;)
  48683. if (result[i] == "*.*")
  48684. result.set (i, "*");
  48685. }
  48686. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48687. {
  48688. const String filename (file.getFileName());
  48689. for (int i = wildcards.size(); --i >= 0;)
  48690. if (filename.matchesWildcard (wildcards[i], true))
  48691. return true;
  48692. return false;
  48693. }
  48694. END_JUCE_NAMESPACE
  48695. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48696. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48697. BEGIN_JUCE_NAMESPACE
  48698. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48699. {
  48700. }
  48701. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48702. {
  48703. }
  48704. namespace KeyboardFocusHelpers
  48705. {
  48706. // This will sort a set of components, so that they are ordered in terms of
  48707. // left-to-right and then top-to-bottom.
  48708. class ScreenPositionComparator
  48709. {
  48710. public:
  48711. ScreenPositionComparator() {}
  48712. static int compareElements (const Component* const first, const Component* const second)
  48713. {
  48714. int explicitOrder1 = first->getExplicitFocusOrder();
  48715. if (explicitOrder1 <= 0)
  48716. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48717. int explicitOrder2 = second->getExplicitFocusOrder();
  48718. if (explicitOrder2 <= 0)
  48719. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48720. if (explicitOrder1 != explicitOrder2)
  48721. return explicitOrder1 - explicitOrder2;
  48722. const int diff = first->getY() - second->getY();
  48723. return (diff == 0) ? first->getX() - second->getX()
  48724. : diff;
  48725. }
  48726. };
  48727. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48728. {
  48729. if (parent->getNumChildComponents() > 0)
  48730. {
  48731. Array <Component*> localComps;
  48732. ScreenPositionComparator comparator;
  48733. int i;
  48734. for (i = parent->getNumChildComponents(); --i >= 0;)
  48735. {
  48736. Component* const c = parent->getChildComponent (i);
  48737. if (c->isVisible() && c->isEnabled())
  48738. localComps.addSorted (comparator, c);
  48739. }
  48740. for (i = 0; i < localComps.size(); ++i)
  48741. {
  48742. Component* const c = localComps.getUnchecked (i);
  48743. if (c->getWantsKeyboardFocus())
  48744. comps.add (c);
  48745. if (! c->isFocusContainer())
  48746. findAllFocusableComponents (c, comps);
  48747. }
  48748. }
  48749. }
  48750. }
  48751. static Component* getIncrementedComponent (Component* const current, const int delta)
  48752. {
  48753. Component* focusContainer = current->getParentComponent();
  48754. if (focusContainer != 0)
  48755. {
  48756. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48757. focusContainer = focusContainer->getParentComponent();
  48758. if (focusContainer != 0)
  48759. {
  48760. Array <Component*> comps;
  48761. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48762. if (comps.size() > 0)
  48763. {
  48764. const int index = comps.indexOf (current);
  48765. return comps [(index + comps.size() + delta) % comps.size()];
  48766. }
  48767. }
  48768. }
  48769. return 0;
  48770. }
  48771. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48772. {
  48773. return getIncrementedComponent (current, 1);
  48774. }
  48775. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48776. {
  48777. return getIncrementedComponent (current, -1);
  48778. }
  48779. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48780. {
  48781. Array <Component*> comps;
  48782. if (parentComponent != 0)
  48783. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48784. return comps.getFirst();
  48785. }
  48786. END_JUCE_NAMESPACE
  48787. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48788. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48789. BEGIN_JUCE_NAMESPACE
  48790. bool KeyListener::keyStateChanged (const bool, Component*)
  48791. {
  48792. return false;
  48793. }
  48794. END_JUCE_NAMESPACE
  48795. /*** End of inlined file: juce_KeyListener.cpp ***/
  48796. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48797. BEGIN_JUCE_NAMESPACE
  48798. // N.B. these two includes are put here deliberately to avoid problems with
  48799. // old GCCs failing on long include paths
  48800. const int maxKeys = 3;
  48801. class KeyMappingChangeButton : public Button
  48802. {
  48803. public:
  48804. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48805. const CommandID commandID_,
  48806. const String& keyName,
  48807. const int keyNum_)
  48808. : Button (keyName),
  48809. owner (owner_),
  48810. commandID (commandID_),
  48811. keyNum (keyNum_)
  48812. {
  48813. setWantsKeyboardFocus (false);
  48814. setTriggeredOnMouseDown (keyNum >= 0);
  48815. if (keyNum_ < 0)
  48816. setTooltip (TRANS("adds a new key-mapping"));
  48817. else
  48818. setTooltip (TRANS("click to change this key-mapping"));
  48819. }
  48820. ~KeyMappingChangeButton()
  48821. {
  48822. }
  48823. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48824. {
  48825. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48826. keyNum >= 0 ? getName() : String::empty);
  48827. }
  48828. void clicked()
  48829. {
  48830. if (keyNum >= 0)
  48831. {
  48832. // existing key clicked..
  48833. PopupMenu m;
  48834. m.addItem (1, TRANS("change this key-mapping"));
  48835. m.addSeparator();
  48836. m.addItem (2, TRANS("remove this key-mapping"));
  48837. const int res = m.show();
  48838. if (res == 1)
  48839. {
  48840. owner->assignNewKey (commandID, keyNum);
  48841. }
  48842. else if (res == 2)
  48843. {
  48844. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48845. }
  48846. }
  48847. else
  48848. {
  48849. // + button pressed..
  48850. owner->assignNewKey (commandID, -1);
  48851. }
  48852. }
  48853. void fitToContent (const int h) throw()
  48854. {
  48855. if (keyNum < 0)
  48856. {
  48857. setSize (h, h);
  48858. }
  48859. else
  48860. {
  48861. Font f (h * 0.6f);
  48862. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48863. }
  48864. }
  48865. juce_UseDebuggingNewOperator
  48866. private:
  48867. KeyMappingEditorComponent* const owner;
  48868. const CommandID commandID;
  48869. const int keyNum;
  48870. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48871. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48872. };
  48873. class KeyMappingItemComponent : public Component
  48874. {
  48875. public:
  48876. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48877. const CommandID commandID_)
  48878. : owner (owner_),
  48879. commandID (commandID_)
  48880. {
  48881. setInterceptsMouseClicks (false, true);
  48882. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48883. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48884. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48885. {
  48886. KeyMappingChangeButton* const kb
  48887. = new KeyMappingChangeButton (owner_, commandID,
  48888. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48889. kb->setEnabled (! isReadOnly);
  48890. addAndMakeVisible (kb);
  48891. }
  48892. KeyMappingChangeButton* const kb
  48893. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48894. addChildComponent (kb);
  48895. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48896. }
  48897. ~KeyMappingItemComponent()
  48898. {
  48899. deleteAllChildren();
  48900. }
  48901. void paint (Graphics& g)
  48902. {
  48903. g.setFont (getHeight() * 0.7f);
  48904. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48905. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48906. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48907. Justification::centredLeft, true);
  48908. }
  48909. void resized()
  48910. {
  48911. int x = getWidth() - 4;
  48912. for (int i = getNumChildComponents(); --i >= 0;)
  48913. {
  48914. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48915. kb->fitToContent (getHeight() - 2);
  48916. kb->setTopRightPosition (x, 1);
  48917. x -= kb->getWidth() + 5;
  48918. }
  48919. }
  48920. juce_UseDebuggingNewOperator
  48921. private:
  48922. KeyMappingEditorComponent* const owner;
  48923. const CommandID commandID;
  48924. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48925. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48926. };
  48927. class KeyMappingTreeViewItem : public TreeViewItem
  48928. {
  48929. public:
  48930. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48931. const CommandID commandID_)
  48932. : owner (owner_),
  48933. commandID (commandID_)
  48934. {
  48935. }
  48936. ~KeyMappingTreeViewItem()
  48937. {
  48938. }
  48939. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48940. bool mightContainSubItems() { return false; }
  48941. int getItemHeight() const { return 20; }
  48942. Component* createItemComponent()
  48943. {
  48944. return new KeyMappingItemComponent (owner, commandID);
  48945. }
  48946. juce_UseDebuggingNewOperator
  48947. private:
  48948. KeyMappingEditorComponent* const owner;
  48949. const CommandID commandID;
  48950. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48951. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48952. };
  48953. class KeyCategoryTreeViewItem : public TreeViewItem
  48954. {
  48955. public:
  48956. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48957. const String& name)
  48958. : owner (owner_),
  48959. categoryName (name)
  48960. {
  48961. }
  48962. ~KeyCategoryTreeViewItem()
  48963. {
  48964. }
  48965. const String getUniqueName() const { return categoryName + "_cat"; }
  48966. bool mightContainSubItems() { return true; }
  48967. int getItemHeight() const { return 28; }
  48968. void paintItem (Graphics& g, int width, int height)
  48969. {
  48970. g.setFont (height * 0.6f, Font::bold);
  48971. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48972. g.drawText (categoryName,
  48973. 2, 0, width - 2, height,
  48974. Justification::centredLeft, true);
  48975. }
  48976. void itemOpennessChanged (bool isNowOpen)
  48977. {
  48978. if (isNowOpen)
  48979. {
  48980. if (getNumSubItems() == 0)
  48981. {
  48982. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48983. for (int i = 0; i < commands.size(); ++i)
  48984. {
  48985. if (owner->shouldCommandBeIncluded (commands[i]))
  48986. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48987. }
  48988. }
  48989. }
  48990. else
  48991. {
  48992. clearSubItems();
  48993. }
  48994. }
  48995. juce_UseDebuggingNewOperator
  48996. private:
  48997. KeyMappingEditorComponent* owner;
  48998. String categoryName;
  48999. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  49000. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  49001. };
  49002. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  49003. const bool showResetToDefaultButton)
  49004. : mappings (mappingManager)
  49005. {
  49006. jassert (mappingManager != 0); // can't be null!
  49007. mappingManager->addChangeListener (this);
  49008. setLinesDrawnForSubItems (false);
  49009. resetButton = 0;
  49010. if (showResetToDefaultButton)
  49011. {
  49012. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  49013. resetButton->addButtonListener (this);
  49014. }
  49015. addAndMakeVisible (tree = new TreeView());
  49016. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  49017. tree->setRootItemVisible (false);
  49018. tree->setDefaultOpenness (true);
  49019. tree->setRootItem (this);
  49020. }
  49021. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  49022. {
  49023. mappings->removeChangeListener (this);
  49024. deleteAllChildren();
  49025. }
  49026. bool KeyMappingEditorComponent::mightContainSubItems()
  49027. {
  49028. return true;
  49029. }
  49030. const String KeyMappingEditorComponent::getUniqueName() const
  49031. {
  49032. return "keys";
  49033. }
  49034. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  49035. const Colour& textColour)
  49036. {
  49037. setColour (backgroundColourId, mainBackground);
  49038. setColour (textColourId, textColour);
  49039. tree->setColour (TreeView::backgroundColourId, mainBackground);
  49040. }
  49041. void KeyMappingEditorComponent::parentHierarchyChanged()
  49042. {
  49043. changeListenerCallback (0);
  49044. }
  49045. void KeyMappingEditorComponent::resized()
  49046. {
  49047. int h = getHeight();
  49048. if (resetButton != 0)
  49049. {
  49050. const int buttonHeight = 20;
  49051. h -= buttonHeight + 8;
  49052. int x = getWidth() - 8;
  49053. resetButton->changeWidthToFitText (buttonHeight);
  49054. resetButton->setTopRightPosition (x, h + 6);
  49055. }
  49056. tree->setBounds (0, 0, getWidth(), h);
  49057. }
  49058. void KeyMappingEditorComponent::buttonClicked (Button* button)
  49059. {
  49060. if (button == resetButton)
  49061. {
  49062. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  49063. TRANS("Reset to defaults"),
  49064. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  49065. TRANS("Reset")))
  49066. {
  49067. mappings->resetToDefaultMappings();
  49068. }
  49069. }
  49070. }
  49071. void KeyMappingEditorComponent::changeListenerCallback (void*)
  49072. {
  49073. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  49074. clearSubItems();
  49075. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  49076. for (int i = 0; i < categories.size(); ++i)
  49077. {
  49078. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  49079. int count = 0;
  49080. for (int j = 0; j < commands.size(); ++j)
  49081. if (shouldCommandBeIncluded (commands[j]))
  49082. ++count;
  49083. if (count > 0)
  49084. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  49085. }
  49086. if (oldOpenness != 0)
  49087. tree->restoreOpennessState (*oldOpenness);
  49088. }
  49089. class KeyEntryWindow : public AlertWindow
  49090. {
  49091. public:
  49092. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  49093. : AlertWindow (TRANS("New key-mapping"),
  49094. TRANS("Please press a key combination now..."),
  49095. AlertWindow::NoIcon),
  49096. owner (owner_)
  49097. {
  49098. addButton (TRANS("ok"), 1);
  49099. addButton (TRANS("cancel"), 0);
  49100. // (avoid return + escape keys getting processed by the buttons..)
  49101. for (int i = getNumChildComponents(); --i >= 0;)
  49102. getChildComponent (i)->setWantsKeyboardFocus (false);
  49103. setWantsKeyboardFocus (true);
  49104. grabKeyboardFocus();
  49105. }
  49106. ~KeyEntryWindow()
  49107. {
  49108. }
  49109. bool keyPressed (const KeyPress& key)
  49110. {
  49111. lastPress = key;
  49112. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  49113. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  49114. if (previousCommand != 0)
  49115. {
  49116. message << "\n\n"
  49117. << TRANS("(Currently assigned to \"")
  49118. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  49119. << "\")";
  49120. }
  49121. setMessage (message);
  49122. return true;
  49123. }
  49124. bool keyStateChanged (bool)
  49125. {
  49126. return true;
  49127. }
  49128. KeyPress lastPress;
  49129. juce_UseDebuggingNewOperator
  49130. private:
  49131. KeyMappingEditorComponent* owner;
  49132. KeyEntryWindow (const KeyEntryWindow&);
  49133. KeyEntryWindow& operator= (const KeyEntryWindow&);
  49134. };
  49135. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  49136. {
  49137. KeyEntryWindow entryWindow (this);
  49138. if (entryWindow.runModalLoop() != 0)
  49139. {
  49140. entryWindow.setVisible (false);
  49141. if (entryWindow.lastPress.isValid())
  49142. {
  49143. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  49144. if (previousCommand != 0)
  49145. {
  49146. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  49147. TRANS("Change key-mapping"),
  49148. TRANS("This key is already assigned to the command \"")
  49149. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  49150. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  49151. TRANS("re-assign"),
  49152. TRANS("cancel")))
  49153. {
  49154. return;
  49155. }
  49156. }
  49157. mappings->removeKeyPress (entryWindow.lastPress);
  49158. if (index >= 0)
  49159. mappings->removeKeyPress (commandID, index);
  49160. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  49161. }
  49162. }
  49163. }
  49164. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  49165. {
  49166. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  49167. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  49168. }
  49169. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  49170. {
  49171. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  49172. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  49173. }
  49174. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  49175. {
  49176. return key.getTextDescription();
  49177. }
  49178. END_JUCE_NAMESPACE
  49179. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  49180. /*** Start of inlined file: juce_KeyPress.cpp ***/
  49181. BEGIN_JUCE_NAMESPACE
  49182. KeyPress::KeyPress() throw()
  49183. : keyCode (0),
  49184. mods (0),
  49185. textCharacter (0)
  49186. {
  49187. }
  49188. KeyPress::KeyPress (const int keyCode_,
  49189. const ModifierKeys& mods_,
  49190. const juce_wchar textCharacter_) throw()
  49191. : keyCode (keyCode_),
  49192. mods (mods_),
  49193. textCharacter (textCharacter_)
  49194. {
  49195. }
  49196. KeyPress::KeyPress (const int keyCode_) throw()
  49197. : keyCode (keyCode_),
  49198. textCharacter (0)
  49199. {
  49200. }
  49201. KeyPress::KeyPress (const KeyPress& other) throw()
  49202. : keyCode (other.keyCode),
  49203. mods (other.mods),
  49204. textCharacter (other.textCharacter)
  49205. {
  49206. }
  49207. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  49208. {
  49209. keyCode = other.keyCode;
  49210. mods = other.mods;
  49211. textCharacter = other.textCharacter;
  49212. return *this;
  49213. }
  49214. bool KeyPress::operator== (const KeyPress& other) const throw()
  49215. {
  49216. return mods.getRawFlags() == other.mods.getRawFlags()
  49217. && (textCharacter == other.textCharacter
  49218. || textCharacter == 0
  49219. || other.textCharacter == 0)
  49220. && (keyCode == other.keyCode
  49221. || (keyCode < 256
  49222. && other.keyCode < 256
  49223. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  49224. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  49225. }
  49226. bool KeyPress::operator!= (const KeyPress& other) const throw()
  49227. {
  49228. return ! operator== (other);
  49229. }
  49230. bool KeyPress::isCurrentlyDown() const
  49231. {
  49232. return isKeyCurrentlyDown (keyCode)
  49233. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  49234. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  49235. }
  49236. namespace KeyPressHelpers
  49237. {
  49238. struct KeyNameAndCode
  49239. {
  49240. const char* name;
  49241. int code;
  49242. };
  49243. static const KeyNameAndCode translations[] =
  49244. {
  49245. { "spacebar", KeyPress::spaceKey },
  49246. { "return", KeyPress::returnKey },
  49247. { "escape", KeyPress::escapeKey },
  49248. { "backspace", KeyPress::backspaceKey },
  49249. { "cursor left", KeyPress::leftKey },
  49250. { "cursor right", KeyPress::rightKey },
  49251. { "cursor up", KeyPress::upKey },
  49252. { "cursor down", KeyPress::downKey },
  49253. { "page up", KeyPress::pageUpKey },
  49254. { "page down", KeyPress::pageDownKey },
  49255. { "home", KeyPress::homeKey },
  49256. { "end", KeyPress::endKey },
  49257. { "delete", KeyPress::deleteKey },
  49258. { "insert", KeyPress::insertKey },
  49259. { "tab", KeyPress::tabKey },
  49260. { "play", KeyPress::playKey },
  49261. { "stop", KeyPress::stopKey },
  49262. { "fast forward", KeyPress::fastForwardKey },
  49263. { "rewind", KeyPress::rewindKey }
  49264. };
  49265. static const String numberPadPrefix() { return "numpad "; }
  49266. }
  49267. const KeyPress KeyPress::createFromDescription (const String& desc)
  49268. {
  49269. int modifiers = 0;
  49270. if (desc.containsWholeWordIgnoreCase ("ctrl")
  49271. || desc.containsWholeWordIgnoreCase ("control")
  49272. || desc.containsWholeWordIgnoreCase ("ctl"))
  49273. modifiers |= ModifierKeys::ctrlModifier;
  49274. if (desc.containsWholeWordIgnoreCase ("shift")
  49275. || desc.containsWholeWordIgnoreCase ("shft"))
  49276. modifiers |= ModifierKeys::shiftModifier;
  49277. if (desc.containsWholeWordIgnoreCase ("alt")
  49278. || desc.containsWholeWordIgnoreCase ("option"))
  49279. modifiers |= ModifierKeys::altModifier;
  49280. if (desc.containsWholeWordIgnoreCase ("command")
  49281. || desc.containsWholeWordIgnoreCase ("cmd"))
  49282. modifiers |= ModifierKeys::commandModifier;
  49283. int key = 0;
  49284. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49285. {
  49286. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  49287. {
  49288. key = KeyPressHelpers::translations[i].code;
  49289. break;
  49290. }
  49291. }
  49292. if (key == 0)
  49293. {
  49294. // see if it's a numpad key..
  49295. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  49296. {
  49297. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  49298. if (lastChar >= '0' && lastChar <= '9')
  49299. key = numberPad0 + lastChar - '0';
  49300. else if (lastChar == '+')
  49301. key = numberPadAdd;
  49302. else if (lastChar == '-')
  49303. key = numberPadSubtract;
  49304. else if (lastChar == '*')
  49305. key = numberPadMultiply;
  49306. else if (lastChar == '/')
  49307. key = numberPadDivide;
  49308. else if (lastChar == '.')
  49309. key = numberPadDecimalPoint;
  49310. else if (lastChar == '=')
  49311. key = numberPadEquals;
  49312. else if (desc.endsWith ("separator"))
  49313. key = numberPadSeparator;
  49314. else if (desc.endsWith ("delete"))
  49315. key = numberPadDelete;
  49316. }
  49317. if (key == 0)
  49318. {
  49319. // see if it's a function key..
  49320. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  49321. for (int i = 1; i <= 12; ++i)
  49322. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  49323. key = F1Key + i - 1;
  49324. if (key == 0)
  49325. {
  49326. // give up and use the hex code..
  49327. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  49328. .toLowerCase()
  49329. .retainCharacters ("0123456789abcdef")
  49330. .getHexValue32();
  49331. if (hexCode > 0)
  49332. key = hexCode;
  49333. else
  49334. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  49335. }
  49336. }
  49337. }
  49338. return KeyPress (key, ModifierKeys (modifiers), 0);
  49339. }
  49340. const String KeyPress::getTextDescription() const
  49341. {
  49342. String desc;
  49343. if (keyCode > 0)
  49344. {
  49345. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  49346. // want to store it as being a slash, not shift+whatever.
  49347. if (textCharacter == '/')
  49348. return "/";
  49349. if (mods.isCtrlDown())
  49350. desc << "ctrl + ";
  49351. if (mods.isShiftDown())
  49352. desc << "shift + ";
  49353. #if JUCE_MAC
  49354. // only do this on the mac, because on Windows ctrl and command are the same,
  49355. // and this would get confusing
  49356. if (mods.isCommandDown())
  49357. desc << "command + ";
  49358. if (mods.isAltDown())
  49359. desc << "option + ";
  49360. #else
  49361. if (mods.isAltDown())
  49362. desc << "alt + ";
  49363. #endif
  49364. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49365. if (keyCode == KeyPressHelpers::translations[i].code)
  49366. return desc + KeyPressHelpers::translations[i].name;
  49367. if (keyCode >= F1Key && keyCode <= F16Key)
  49368. desc << 'F' << (1 + keyCode - F1Key);
  49369. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49370. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49371. else if (keyCode >= 33 && keyCode < 176)
  49372. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49373. else if (keyCode == numberPadAdd)
  49374. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49375. else if (keyCode == numberPadSubtract)
  49376. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49377. else if (keyCode == numberPadMultiply)
  49378. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49379. else if (keyCode == numberPadDivide)
  49380. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49381. else if (keyCode == numberPadSeparator)
  49382. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49383. else if (keyCode == numberPadDecimalPoint)
  49384. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49385. else if (keyCode == numberPadDelete)
  49386. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49387. else
  49388. desc << '#' << String::toHexString (keyCode);
  49389. }
  49390. return desc;
  49391. }
  49392. END_JUCE_NAMESPACE
  49393. /*** End of inlined file: juce_KeyPress.cpp ***/
  49394. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49395. BEGIN_JUCE_NAMESPACE
  49396. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49397. : commandManager (commandManager_)
  49398. {
  49399. // A manager is needed to get the descriptions of commands, and will be called when
  49400. // a command is invoked. So you can't leave this null..
  49401. jassert (commandManager_ != 0);
  49402. Desktop::getInstance().addFocusChangeListener (this);
  49403. }
  49404. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49405. : commandManager (other.commandManager)
  49406. {
  49407. Desktop::getInstance().addFocusChangeListener (this);
  49408. }
  49409. KeyPressMappingSet::~KeyPressMappingSet()
  49410. {
  49411. Desktop::getInstance().removeFocusChangeListener (this);
  49412. }
  49413. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49414. {
  49415. for (int i = 0; i < mappings.size(); ++i)
  49416. if (mappings.getUnchecked(i)->commandID == commandID)
  49417. return mappings.getUnchecked (i)->keypresses;
  49418. return Array <KeyPress> ();
  49419. }
  49420. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49421. const KeyPress& newKeyPress,
  49422. int insertIndex)
  49423. {
  49424. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49425. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49426. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49427. && ! newKeyPress.getModifiers().isShiftDown()));
  49428. if (findCommandForKeyPress (newKeyPress) != commandID)
  49429. {
  49430. removeKeyPress (newKeyPress);
  49431. if (newKeyPress.isValid())
  49432. {
  49433. for (int i = mappings.size(); --i >= 0;)
  49434. {
  49435. if (mappings.getUnchecked(i)->commandID == commandID)
  49436. {
  49437. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49438. sendChangeMessage (this);
  49439. return;
  49440. }
  49441. }
  49442. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49443. if (ci != 0)
  49444. {
  49445. CommandMapping* const cm = new CommandMapping();
  49446. cm->commandID = commandID;
  49447. cm->keypresses.add (newKeyPress);
  49448. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49449. mappings.add (cm);
  49450. sendChangeMessage (this);
  49451. }
  49452. }
  49453. }
  49454. }
  49455. void KeyPressMappingSet::resetToDefaultMappings()
  49456. {
  49457. mappings.clear();
  49458. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49459. {
  49460. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49461. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49462. {
  49463. addKeyPress (ci->commandID,
  49464. ci->defaultKeypresses.getReference (j));
  49465. }
  49466. }
  49467. sendChangeMessage (this);
  49468. }
  49469. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49470. {
  49471. clearAllKeyPresses (commandID);
  49472. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49473. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49474. {
  49475. addKeyPress (ci->commandID,
  49476. ci->defaultKeypresses.getReference (j));
  49477. }
  49478. }
  49479. void KeyPressMappingSet::clearAllKeyPresses()
  49480. {
  49481. if (mappings.size() > 0)
  49482. {
  49483. sendChangeMessage (this);
  49484. mappings.clear();
  49485. }
  49486. }
  49487. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49488. {
  49489. for (int i = mappings.size(); --i >= 0;)
  49490. {
  49491. if (mappings.getUnchecked(i)->commandID == commandID)
  49492. {
  49493. mappings.remove (i);
  49494. sendChangeMessage (this);
  49495. }
  49496. }
  49497. }
  49498. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49499. {
  49500. if (keypress.isValid())
  49501. {
  49502. for (int i = mappings.size(); --i >= 0;)
  49503. {
  49504. CommandMapping* const cm = mappings.getUnchecked(i);
  49505. for (int j = cm->keypresses.size(); --j >= 0;)
  49506. {
  49507. if (keypress == cm->keypresses [j])
  49508. {
  49509. cm->keypresses.remove (j);
  49510. sendChangeMessage (this);
  49511. }
  49512. }
  49513. }
  49514. }
  49515. }
  49516. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49517. {
  49518. for (int i = mappings.size(); --i >= 0;)
  49519. {
  49520. if (mappings.getUnchecked(i)->commandID == commandID)
  49521. {
  49522. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49523. sendChangeMessage (this);
  49524. break;
  49525. }
  49526. }
  49527. }
  49528. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49529. {
  49530. for (int i = 0; i < mappings.size(); ++i)
  49531. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49532. return mappings.getUnchecked(i)->commandID;
  49533. return 0;
  49534. }
  49535. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49536. {
  49537. for (int i = mappings.size(); --i >= 0;)
  49538. if (mappings.getUnchecked(i)->commandID == commandID)
  49539. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49540. return false;
  49541. }
  49542. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49543. const KeyPress& key,
  49544. const bool isKeyDown,
  49545. const int millisecsSinceKeyPressed,
  49546. Component* const originatingComponent) const
  49547. {
  49548. ApplicationCommandTarget::InvocationInfo info (commandID);
  49549. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49550. info.isKeyDown = isKeyDown;
  49551. info.keyPress = key;
  49552. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49553. info.originatingComponent = originatingComponent;
  49554. commandManager->invoke (info, false);
  49555. }
  49556. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49557. {
  49558. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49559. {
  49560. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49561. {
  49562. // if the XML was created as a set of differences from the default mappings,
  49563. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49564. resetToDefaultMappings();
  49565. }
  49566. else
  49567. {
  49568. // if the XML was created calling createXml (false), then we need to clear all
  49569. // the keys and treat the xml as describing the entire set of mappings.
  49570. clearAllKeyPresses();
  49571. }
  49572. forEachXmlChildElement (xmlVersion, map)
  49573. {
  49574. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49575. if (commandId != 0)
  49576. {
  49577. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49578. if (map->hasTagName ("MAPPING"))
  49579. {
  49580. addKeyPress (commandId, key);
  49581. }
  49582. else if (map->hasTagName ("UNMAPPING"))
  49583. {
  49584. if (containsMapping (commandId, key))
  49585. removeKeyPress (key);
  49586. }
  49587. }
  49588. }
  49589. return true;
  49590. }
  49591. return false;
  49592. }
  49593. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49594. {
  49595. ScopedPointer <KeyPressMappingSet> defaultSet;
  49596. if (saveDifferencesFromDefaultSet)
  49597. {
  49598. defaultSet = new KeyPressMappingSet (commandManager);
  49599. defaultSet->resetToDefaultMappings();
  49600. }
  49601. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49602. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49603. int i;
  49604. for (i = 0; i < mappings.size(); ++i)
  49605. {
  49606. const CommandMapping* const cm = mappings.getUnchecked(i);
  49607. for (int j = 0; j < cm->keypresses.size(); ++j)
  49608. {
  49609. if (defaultSet == 0
  49610. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49611. {
  49612. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49613. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49614. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49615. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49616. }
  49617. }
  49618. }
  49619. if (defaultSet != 0)
  49620. {
  49621. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49622. {
  49623. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49624. for (int j = 0; j < cm->keypresses.size(); ++j)
  49625. {
  49626. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49627. {
  49628. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49629. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49630. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49631. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49632. }
  49633. }
  49634. }
  49635. }
  49636. return doc;
  49637. }
  49638. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49639. Component* originatingComponent)
  49640. {
  49641. bool used = false;
  49642. const CommandID commandID = findCommandForKeyPress (key);
  49643. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49644. if (ci != 0
  49645. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49646. {
  49647. ApplicationCommandInfo info (0);
  49648. if (commandManager->getTargetForCommand (commandID, info) != 0
  49649. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49650. {
  49651. invokeCommand (commandID, key, true, 0, originatingComponent);
  49652. used = true;
  49653. }
  49654. else
  49655. {
  49656. if (originatingComponent != 0)
  49657. originatingComponent->getLookAndFeel().playAlertSound();
  49658. }
  49659. }
  49660. return used;
  49661. }
  49662. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49663. {
  49664. bool used = false;
  49665. const uint32 now = Time::getMillisecondCounter();
  49666. for (int i = mappings.size(); --i >= 0;)
  49667. {
  49668. CommandMapping* const cm = mappings.getUnchecked(i);
  49669. if (cm->wantsKeyUpDownCallbacks)
  49670. {
  49671. for (int j = cm->keypresses.size(); --j >= 0;)
  49672. {
  49673. const KeyPress key (cm->keypresses.getReference (j));
  49674. const bool isDown = key.isCurrentlyDown();
  49675. int keyPressEntryIndex = 0;
  49676. bool wasDown = false;
  49677. for (int k = keysDown.size(); --k >= 0;)
  49678. {
  49679. if (key == keysDown.getUnchecked(k)->key)
  49680. {
  49681. keyPressEntryIndex = k;
  49682. wasDown = true;
  49683. used = true;
  49684. break;
  49685. }
  49686. }
  49687. if (isDown != wasDown)
  49688. {
  49689. int millisecs = 0;
  49690. if (isDown)
  49691. {
  49692. KeyPressTime* const k = new KeyPressTime();
  49693. k->key = key;
  49694. k->timeWhenPressed = now;
  49695. keysDown.add (k);
  49696. }
  49697. else
  49698. {
  49699. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49700. if (now > pressTime)
  49701. millisecs = now - pressTime;
  49702. keysDown.remove (keyPressEntryIndex);
  49703. }
  49704. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49705. used = true;
  49706. }
  49707. }
  49708. }
  49709. }
  49710. return used;
  49711. }
  49712. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49713. {
  49714. if (focusedComponent != 0)
  49715. focusedComponent->keyStateChanged (false);
  49716. }
  49717. END_JUCE_NAMESPACE
  49718. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49719. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49720. BEGIN_JUCE_NAMESPACE
  49721. ModifierKeys::ModifierKeys (const int flags_) throw()
  49722. : flags (flags_)
  49723. {
  49724. }
  49725. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49726. : flags (other.flags)
  49727. {
  49728. }
  49729. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49730. {
  49731. flags = other.flags;
  49732. return *this;
  49733. }
  49734. ModifierKeys ModifierKeys::currentModifiers;
  49735. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49736. {
  49737. return currentModifiers;
  49738. }
  49739. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49740. {
  49741. int num = 0;
  49742. if (isLeftButtonDown()) ++num;
  49743. if (isRightButtonDown()) ++num;
  49744. if (isMiddleButtonDown()) ++num;
  49745. return num;
  49746. }
  49747. END_JUCE_NAMESPACE
  49748. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49749. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49750. BEGIN_JUCE_NAMESPACE
  49751. class ComponentAnimator::AnimationTask
  49752. {
  49753. public:
  49754. AnimationTask (Component* const comp)
  49755. : component (comp)
  49756. {
  49757. }
  49758. Component::SafePointer<Component> component;
  49759. Rectangle<int> destination;
  49760. int msElapsed, msTotal;
  49761. double startSpeed, midSpeed, endSpeed, lastProgress;
  49762. double left, top, right, bottom;
  49763. bool useTimeslice (const int elapsed)
  49764. {
  49765. if (component == 0)
  49766. return false;
  49767. msElapsed += elapsed;
  49768. double newProgress = msElapsed / (double) msTotal;
  49769. if (newProgress >= 0 && newProgress < 1.0)
  49770. {
  49771. newProgress = timeToDistance (newProgress);
  49772. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49773. jassert (newProgress >= lastProgress);
  49774. lastProgress = newProgress;
  49775. left += (destination.getX() - left) * delta;
  49776. top += (destination.getY() - top) * delta;
  49777. right += (destination.getRight() - right) * delta;
  49778. bottom += (destination.getBottom() - bottom) * delta;
  49779. if (delta < 1.0)
  49780. {
  49781. const Rectangle<int> newBounds (roundToInt (left),
  49782. roundToInt (top),
  49783. roundToInt (right - left),
  49784. roundToInt (bottom - top));
  49785. if (newBounds != destination)
  49786. {
  49787. component->setBounds (newBounds);
  49788. return true;
  49789. }
  49790. }
  49791. }
  49792. component->setBounds (destination);
  49793. return false;
  49794. }
  49795. void moveToFinalDestination()
  49796. {
  49797. if (component != 0)
  49798. component->setBounds (destination);
  49799. }
  49800. private:
  49801. inline double timeToDistance (const double time) const
  49802. {
  49803. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49804. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49805. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49806. }
  49807. };
  49808. ComponentAnimator::ComponentAnimator()
  49809. : lastTime (0)
  49810. {
  49811. }
  49812. ComponentAnimator::~ComponentAnimator()
  49813. {
  49814. cancelAllAnimations (false);
  49815. jassert (tasks.size() == 0);
  49816. }
  49817. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49818. {
  49819. for (int i = tasks.size(); --i >= 0;)
  49820. if (component == tasks.getUnchecked(i)->component.getComponent())
  49821. return tasks.getUnchecked(i);
  49822. return 0;
  49823. }
  49824. void ComponentAnimator::animateComponent (Component* const component,
  49825. const Rectangle<int>& finalPosition,
  49826. const int millisecondsToSpendMoving,
  49827. const double startSpeed,
  49828. const double endSpeed)
  49829. {
  49830. if (component != 0)
  49831. {
  49832. AnimationTask* at = findTaskFor (component);
  49833. if (at == 0)
  49834. {
  49835. at = new AnimationTask (component);
  49836. tasks.add (at);
  49837. sendChangeMessage (this);
  49838. }
  49839. at->msElapsed = 0;
  49840. at->lastProgress = 0;
  49841. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49842. at->destination = finalPosition;
  49843. // the speeds must be 0 or greater!
  49844. jassert (startSpeed >= 0 && endSpeed >= 0)
  49845. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49846. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49847. at->midSpeed = invTotalDistance;
  49848. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49849. at->left = component->getX();
  49850. at->top = component->getY();
  49851. at->right = component->getRight();
  49852. at->bottom = component->getBottom();
  49853. if (! isTimerRunning())
  49854. {
  49855. lastTime = Time::getMillisecondCounter();
  49856. startTimer (1000 / 50);
  49857. }
  49858. }
  49859. }
  49860. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49861. {
  49862. for (int i = tasks.size(); --i >= 0;)
  49863. {
  49864. AnimationTask* const at = tasks.getUnchecked(i);
  49865. if (moveComponentsToTheirFinalPositions)
  49866. at->moveToFinalDestination();
  49867. delete at;
  49868. tasks.remove (i);
  49869. sendChangeMessage (this);
  49870. }
  49871. }
  49872. void ComponentAnimator::cancelAnimation (Component* const component,
  49873. const bool moveComponentToItsFinalPosition)
  49874. {
  49875. AnimationTask* const at = findTaskFor (component);
  49876. if (at != 0)
  49877. {
  49878. if (moveComponentToItsFinalPosition)
  49879. at->moveToFinalDestination();
  49880. tasks.removeValue (at);
  49881. delete at;
  49882. sendChangeMessage (this);
  49883. }
  49884. }
  49885. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49886. {
  49887. AnimationTask* const at = findTaskFor (component);
  49888. if (at != 0)
  49889. return at->destination;
  49890. else if (component != 0)
  49891. return component->getBounds();
  49892. return Rectangle<int>();
  49893. }
  49894. bool ComponentAnimator::isAnimating (Component* component) const
  49895. {
  49896. return findTaskFor (component) != 0;
  49897. }
  49898. void ComponentAnimator::timerCallback()
  49899. {
  49900. const uint32 timeNow = Time::getMillisecondCounter();
  49901. if (lastTime == 0 || lastTime == timeNow)
  49902. lastTime = timeNow;
  49903. const int elapsed = timeNow - lastTime;
  49904. for (int i = tasks.size(); --i >= 0;)
  49905. {
  49906. AnimationTask* const at = tasks.getUnchecked(i);
  49907. if (! at->useTimeslice (elapsed))
  49908. {
  49909. tasks.remove (i);
  49910. delete at;
  49911. sendChangeMessage (this);
  49912. }
  49913. }
  49914. lastTime = timeNow;
  49915. if (tasks.size() == 0)
  49916. stopTimer();
  49917. }
  49918. END_JUCE_NAMESPACE
  49919. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49920. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49921. BEGIN_JUCE_NAMESPACE
  49922. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49923. : minW (0),
  49924. maxW (0x3fffffff),
  49925. minH (0),
  49926. maxH (0x3fffffff),
  49927. minOffTop (0),
  49928. minOffLeft (0),
  49929. minOffBottom (0),
  49930. minOffRight (0),
  49931. aspectRatio (0.0)
  49932. {
  49933. }
  49934. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49935. {
  49936. }
  49937. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49938. {
  49939. minW = minimumWidth;
  49940. }
  49941. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49942. {
  49943. maxW = maximumWidth;
  49944. }
  49945. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49946. {
  49947. minH = minimumHeight;
  49948. }
  49949. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49950. {
  49951. maxH = maximumHeight;
  49952. }
  49953. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49954. {
  49955. jassert (maxW >= minimumWidth);
  49956. jassert (maxH >= minimumHeight);
  49957. jassert (minimumWidth > 0 && minimumHeight > 0);
  49958. minW = minimumWidth;
  49959. minH = minimumHeight;
  49960. if (minW > maxW)
  49961. maxW = minW;
  49962. if (minH > maxH)
  49963. maxH = minH;
  49964. }
  49965. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49966. {
  49967. jassert (maximumWidth >= minW);
  49968. jassert (maximumHeight >= minH);
  49969. jassert (maximumWidth > 0 && maximumHeight > 0);
  49970. maxW = jmax (minW, maximumWidth);
  49971. maxH = jmax (minH, maximumHeight);
  49972. }
  49973. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49974. const int minimumHeight,
  49975. const int maximumWidth,
  49976. const int maximumHeight) throw()
  49977. {
  49978. jassert (maximumWidth >= minimumWidth);
  49979. jassert (maximumHeight >= minimumHeight);
  49980. jassert (maximumWidth > 0 && maximumHeight > 0);
  49981. jassert (minimumWidth > 0 && minimumHeight > 0);
  49982. minW = jmax (0, minimumWidth);
  49983. minH = jmax (0, minimumHeight);
  49984. maxW = jmax (minW, maximumWidth);
  49985. maxH = jmax (minH, maximumHeight);
  49986. }
  49987. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49988. const int minimumWhenOffTheLeft,
  49989. const int minimumWhenOffTheBottom,
  49990. const int minimumWhenOffTheRight) throw()
  49991. {
  49992. minOffTop = minimumWhenOffTheTop;
  49993. minOffLeft = minimumWhenOffTheLeft;
  49994. minOffBottom = minimumWhenOffTheBottom;
  49995. minOffRight = minimumWhenOffTheRight;
  49996. }
  49997. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49998. {
  49999. aspectRatio = jmax (0.0, widthOverHeight);
  50000. }
  50001. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  50002. {
  50003. return aspectRatio;
  50004. }
  50005. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  50006. const Rectangle<int>& targetBounds,
  50007. const bool isStretchingTop,
  50008. const bool isStretchingLeft,
  50009. const bool isStretchingBottom,
  50010. const bool isStretchingRight)
  50011. {
  50012. jassert (component != 0);
  50013. Rectangle<int> limits, bounds (targetBounds);
  50014. BorderSize border;
  50015. Component* const parent = component->getParentComponent();
  50016. if (parent == 0)
  50017. {
  50018. ComponentPeer* peer = component->getPeer();
  50019. if (peer != 0)
  50020. border = peer->getFrameSize();
  50021. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  50022. }
  50023. else
  50024. {
  50025. limits.setSize (parent->getWidth(), parent->getHeight());
  50026. }
  50027. border.addTo (bounds);
  50028. checkBounds (bounds,
  50029. border.addedTo (component->getBounds()), limits,
  50030. isStretchingTop, isStretchingLeft,
  50031. isStretchingBottom, isStretchingRight);
  50032. border.subtractFrom (bounds);
  50033. applyBoundsToComponent (component, bounds);
  50034. }
  50035. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  50036. {
  50037. setBoundsForComponent (component, component->getBounds(),
  50038. false, false, false, false);
  50039. }
  50040. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  50041. const Rectangle<int>& bounds)
  50042. {
  50043. component->setBounds (bounds);
  50044. }
  50045. void ComponentBoundsConstrainer::resizeStart()
  50046. {
  50047. }
  50048. void ComponentBoundsConstrainer::resizeEnd()
  50049. {
  50050. }
  50051. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  50052. const Rectangle<int>& old,
  50053. const Rectangle<int>& limits,
  50054. const bool isStretchingTop,
  50055. const bool isStretchingLeft,
  50056. const bool isStretchingBottom,
  50057. const bool isStretchingRight)
  50058. {
  50059. int x = bounds.getX();
  50060. int y = bounds.getY();
  50061. int w = bounds.getWidth();
  50062. int h = bounds.getHeight();
  50063. // constrain the size if it's being stretched..
  50064. if (isStretchingLeft)
  50065. {
  50066. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  50067. w = old.getRight() - x;
  50068. }
  50069. if (isStretchingRight)
  50070. {
  50071. w = jlimit (minW, maxW, w);
  50072. }
  50073. if (isStretchingTop)
  50074. {
  50075. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  50076. h = old.getBottom() - y;
  50077. }
  50078. if (isStretchingBottom)
  50079. {
  50080. h = jlimit (minH, maxH, h);
  50081. }
  50082. // constrain the aspect ratio if one has been specified..
  50083. if (aspectRatio > 0.0 && w > 0 && h > 0)
  50084. {
  50085. bool adjustWidth;
  50086. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  50087. {
  50088. adjustWidth = true;
  50089. }
  50090. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  50091. {
  50092. adjustWidth = false;
  50093. }
  50094. else
  50095. {
  50096. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  50097. const double newRatio = std::abs (w / (double) h);
  50098. adjustWidth = (oldRatio > newRatio);
  50099. }
  50100. if (adjustWidth)
  50101. {
  50102. w = roundToInt (h * aspectRatio);
  50103. if (w > maxW || w < minW)
  50104. {
  50105. w = jlimit (minW, maxW, w);
  50106. h = roundToInt (w / aspectRatio);
  50107. }
  50108. }
  50109. else
  50110. {
  50111. h = roundToInt (w / aspectRatio);
  50112. if (h > maxH || h < minH)
  50113. {
  50114. h = jlimit (minH, maxH, h);
  50115. w = roundToInt (h * aspectRatio);
  50116. }
  50117. }
  50118. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  50119. {
  50120. x = old.getX() + (old.getWidth() - w) / 2;
  50121. }
  50122. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  50123. {
  50124. y = old.getY() + (old.getHeight() - h) / 2;
  50125. }
  50126. else
  50127. {
  50128. if (isStretchingLeft)
  50129. x = old.getRight() - w;
  50130. if (isStretchingTop)
  50131. y = old.getBottom() - h;
  50132. }
  50133. }
  50134. // ...and constrain the position if limits have been set for that.
  50135. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  50136. {
  50137. if (minOffTop > 0)
  50138. {
  50139. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  50140. if (y < limit)
  50141. {
  50142. if (isStretchingTop)
  50143. h -= (limit - y);
  50144. y = limit;
  50145. }
  50146. }
  50147. if (minOffLeft > 0)
  50148. {
  50149. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  50150. if (x < limit)
  50151. {
  50152. if (isStretchingLeft)
  50153. w -= (limit - x);
  50154. x = limit;
  50155. }
  50156. }
  50157. if (minOffBottom > 0)
  50158. {
  50159. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  50160. if (y > limit)
  50161. {
  50162. if (isStretchingBottom)
  50163. h += (limit - y);
  50164. else
  50165. y = limit;
  50166. }
  50167. }
  50168. if (minOffRight > 0)
  50169. {
  50170. const int limit = limits.getRight() - jmin (minOffRight, w);
  50171. if (x > limit)
  50172. {
  50173. if (isStretchingRight)
  50174. w += (limit - x);
  50175. else
  50176. x = limit;
  50177. }
  50178. }
  50179. }
  50180. jassert (w >= 0 && h >= 0);
  50181. bounds = Rectangle<int> (x, y, w, h);
  50182. }
  50183. END_JUCE_NAMESPACE
  50184. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  50185. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50186. BEGIN_JUCE_NAMESPACE
  50187. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  50188. : component (component_),
  50189. lastPeer (0),
  50190. reentrant (false)
  50191. {
  50192. jassert (component != 0); // can't use this with a null pointer..
  50193. component->addComponentListener (this);
  50194. registerWithParentComps();
  50195. }
  50196. ComponentMovementWatcher::~ComponentMovementWatcher()
  50197. {
  50198. component->removeComponentListener (this);
  50199. unregister();
  50200. }
  50201. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  50202. {
  50203. // agh! don't delete the target component without deleting this object first!
  50204. jassert (component != 0);
  50205. if (! reentrant)
  50206. {
  50207. reentrant = true;
  50208. ComponentPeer* const peer = component->getPeer();
  50209. if (peer != lastPeer)
  50210. {
  50211. componentPeerChanged();
  50212. if (component == 0)
  50213. return;
  50214. lastPeer = peer;
  50215. }
  50216. unregister();
  50217. registerWithParentComps();
  50218. reentrant = false;
  50219. componentMovedOrResized (*component, true, true);
  50220. }
  50221. }
  50222. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  50223. {
  50224. // agh! don't delete the target component without deleting this object first!
  50225. jassert (component != 0);
  50226. if (wasMoved)
  50227. {
  50228. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  50229. wasMoved = lastBounds.getPosition() != pos;
  50230. lastBounds.setPosition (pos);
  50231. }
  50232. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  50233. lastBounds.setSize (component->getWidth(), component->getHeight());
  50234. if (wasMoved || wasResized)
  50235. componentMovedOrResized (wasMoved, wasResized);
  50236. }
  50237. void ComponentMovementWatcher::registerWithParentComps()
  50238. {
  50239. Component* p = component->getParentComponent();
  50240. while (p != 0)
  50241. {
  50242. p->addComponentListener (this);
  50243. registeredParentComps.add (p);
  50244. p = p->getParentComponent();
  50245. }
  50246. }
  50247. void ComponentMovementWatcher::unregister()
  50248. {
  50249. for (int i = registeredParentComps.size(); --i >= 0;)
  50250. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  50251. registeredParentComps.clear();
  50252. }
  50253. END_JUCE_NAMESPACE
  50254. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50255. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  50256. BEGIN_JUCE_NAMESPACE
  50257. GroupComponent::GroupComponent (const String& componentName,
  50258. const String& labelText)
  50259. : Component (componentName),
  50260. text (labelText),
  50261. justification (Justification::left)
  50262. {
  50263. setInterceptsMouseClicks (false, true);
  50264. }
  50265. GroupComponent::~GroupComponent()
  50266. {
  50267. }
  50268. void GroupComponent::setText (const String& newText)
  50269. {
  50270. if (text != newText)
  50271. {
  50272. text = newText;
  50273. repaint();
  50274. }
  50275. }
  50276. const String GroupComponent::getText() const
  50277. {
  50278. return text;
  50279. }
  50280. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  50281. {
  50282. if (justification != newJustification)
  50283. {
  50284. justification = newJustification;
  50285. repaint();
  50286. }
  50287. }
  50288. void GroupComponent::paint (Graphics& g)
  50289. {
  50290. getLookAndFeel()
  50291. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  50292. text, justification,
  50293. *this);
  50294. }
  50295. void GroupComponent::enablementChanged()
  50296. {
  50297. repaint();
  50298. }
  50299. void GroupComponent::colourChanged()
  50300. {
  50301. repaint();
  50302. }
  50303. END_JUCE_NAMESPACE
  50304. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50305. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50306. BEGIN_JUCE_NAMESPACE
  50307. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50308. : DocumentWindow (String::empty, backgroundColour,
  50309. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50310. {
  50311. }
  50312. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50313. {
  50314. }
  50315. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50316. {
  50317. MultiDocumentPanel* const owner = getOwner();
  50318. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50319. if (owner != 0)
  50320. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50321. }
  50322. void MultiDocumentPanelWindow::closeButtonPressed()
  50323. {
  50324. MultiDocumentPanel* const owner = getOwner();
  50325. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50326. if (owner != 0)
  50327. owner->closeDocument (getContentComponent(), true);
  50328. }
  50329. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50330. {
  50331. DocumentWindow::activeWindowStatusChanged();
  50332. updateOrder();
  50333. }
  50334. void MultiDocumentPanelWindow::broughtToFront()
  50335. {
  50336. DocumentWindow::broughtToFront();
  50337. updateOrder();
  50338. }
  50339. void MultiDocumentPanelWindow::updateOrder()
  50340. {
  50341. MultiDocumentPanel* const owner = getOwner();
  50342. if (owner != 0)
  50343. owner->updateOrder();
  50344. }
  50345. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50346. {
  50347. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50348. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50349. }
  50350. class MDITabbedComponentInternal : public TabbedComponent
  50351. {
  50352. public:
  50353. MDITabbedComponentInternal()
  50354. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50355. {
  50356. }
  50357. ~MDITabbedComponentInternal()
  50358. {
  50359. }
  50360. void currentTabChanged (int, const String&)
  50361. {
  50362. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50363. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50364. if (owner != 0)
  50365. owner->updateOrder();
  50366. }
  50367. };
  50368. MultiDocumentPanel::MultiDocumentPanel()
  50369. : mode (MaximisedWindowsWithTabs),
  50370. backgroundColour (Colours::lightblue),
  50371. maximumNumDocuments (0),
  50372. numDocsBeforeTabsUsed (0)
  50373. {
  50374. setOpaque (true);
  50375. }
  50376. MultiDocumentPanel::~MultiDocumentPanel()
  50377. {
  50378. closeAllDocuments (false);
  50379. }
  50380. static bool shouldDeleteComp (Component* const c)
  50381. {
  50382. return c->getProperties() ["mdiDocumentDelete_"];
  50383. }
  50384. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50385. {
  50386. while (components.size() > 0)
  50387. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50388. return false;
  50389. return true;
  50390. }
  50391. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50392. {
  50393. return new MultiDocumentPanelWindow (backgroundColour);
  50394. }
  50395. void MultiDocumentPanel::addWindow (Component* component)
  50396. {
  50397. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50398. dw->setResizable (true, false);
  50399. dw->setContentComponent (component, false, true);
  50400. dw->setName (component->getName());
  50401. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50402. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50403. int x = 4;
  50404. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50405. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50406. x += 16;
  50407. dw->setTopLeftPosition (x, x);
  50408. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50409. if (pos.toString().isNotEmpty())
  50410. dw->restoreWindowStateFromString (pos.toString());
  50411. addAndMakeVisible (dw);
  50412. dw->toFront (true);
  50413. }
  50414. bool MultiDocumentPanel::addDocument (Component* const component,
  50415. const Colour& docColour,
  50416. const bool deleteWhenRemoved)
  50417. {
  50418. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50419. // with a frame-within-a-frame! Just pass in the bare content component.
  50420. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50421. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50422. return false;
  50423. components.add (component);
  50424. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50425. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50426. component->addComponentListener (this);
  50427. if (mode == FloatingWindows)
  50428. {
  50429. if (isFullscreenWhenOneDocument())
  50430. {
  50431. if (components.size() == 1)
  50432. {
  50433. addAndMakeVisible (component);
  50434. }
  50435. else
  50436. {
  50437. if (components.size() == 2)
  50438. addWindow (components.getFirst());
  50439. addWindow (component);
  50440. }
  50441. }
  50442. else
  50443. {
  50444. addWindow (component);
  50445. }
  50446. }
  50447. else
  50448. {
  50449. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50450. {
  50451. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50452. Array <Component*> temp (components);
  50453. for (int i = 0; i < temp.size(); ++i)
  50454. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50455. resized();
  50456. }
  50457. else
  50458. {
  50459. if (tabComponent != 0)
  50460. tabComponent->addTab (component->getName(), docColour, component, false);
  50461. else
  50462. addAndMakeVisible (component);
  50463. }
  50464. setActiveDocument (component);
  50465. }
  50466. resized();
  50467. activeDocumentChanged();
  50468. return true;
  50469. }
  50470. bool MultiDocumentPanel::closeDocument (Component* component,
  50471. const bool checkItsOkToCloseFirst)
  50472. {
  50473. if (components.contains (component))
  50474. {
  50475. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50476. return false;
  50477. component->removeComponentListener (this);
  50478. const bool shouldDelete = shouldDeleteComp (component);
  50479. component->getProperties().remove ("mdiDocumentDelete_");
  50480. component->getProperties().remove ("mdiDocumentBkg_");
  50481. if (mode == FloatingWindows)
  50482. {
  50483. for (int i = getNumChildComponents(); --i >= 0;)
  50484. {
  50485. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50486. if (dw != 0 && dw->getContentComponent() == component)
  50487. {
  50488. dw->setContentComponent (0, false);
  50489. delete dw;
  50490. break;
  50491. }
  50492. }
  50493. if (shouldDelete)
  50494. delete component;
  50495. components.removeValue (component);
  50496. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50497. {
  50498. for (int i = getNumChildComponents(); --i >= 0;)
  50499. {
  50500. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50501. if (dw != 0)
  50502. {
  50503. dw->setContentComponent (0, false);
  50504. delete dw;
  50505. }
  50506. }
  50507. addAndMakeVisible (components.getFirst());
  50508. }
  50509. }
  50510. else
  50511. {
  50512. jassert (components.indexOf (component) >= 0);
  50513. if (tabComponent != 0)
  50514. {
  50515. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50516. if (tabComponent->getTabContentComponent (i) == component)
  50517. tabComponent->removeTab (i);
  50518. }
  50519. else
  50520. {
  50521. removeChildComponent (component);
  50522. }
  50523. if (shouldDelete)
  50524. delete component;
  50525. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50526. tabComponent = 0;
  50527. components.removeValue (component);
  50528. if (components.size() > 0 && tabComponent == 0)
  50529. addAndMakeVisible (components.getFirst());
  50530. }
  50531. resized();
  50532. activeDocumentChanged();
  50533. }
  50534. else
  50535. {
  50536. jassertfalse;
  50537. }
  50538. return true;
  50539. }
  50540. int MultiDocumentPanel::getNumDocuments() const throw()
  50541. {
  50542. return components.size();
  50543. }
  50544. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50545. {
  50546. return components [index];
  50547. }
  50548. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50549. {
  50550. if (mode == FloatingWindows)
  50551. {
  50552. for (int i = getNumChildComponents(); --i >= 0;)
  50553. {
  50554. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50555. if (dw != 0 && dw->isActiveWindow())
  50556. return dw->getContentComponent();
  50557. }
  50558. }
  50559. return components.getLast();
  50560. }
  50561. void MultiDocumentPanel::setActiveDocument (Component* component)
  50562. {
  50563. if (mode == FloatingWindows)
  50564. {
  50565. component = getContainerComp (component);
  50566. if (component != 0)
  50567. component->toFront (true);
  50568. }
  50569. else if (tabComponent != 0)
  50570. {
  50571. jassert (components.indexOf (component) >= 0);
  50572. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50573. {
  50574. if (tabComponent->getTabContentComponent (i) == component)
  50575. {
  50576. tabComponent->setCurrentTabIndex (i);
  50577. break;
  50578. }
  50579. }
  50580. }
  50581. else
  50582. {
  50583. component->grabKeyboardFocus();
  50584. }
  50585. }
  50586. void MultiDocumentPanel::activeDocumentChanged()
  50587. {
  50588. }
  50589. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50590. {
  50591. maximumNumDocuments = newNumber;
  50592. }
  50593. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50594. {
  50595. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50596. }
  50597. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50598. {
  50599. return numDocsBeforeTabsUsed != 0;
  50600. }
  50601. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50602. {
  50603. if (mode != newLayoutMode)
  50604. {
  50605. mode = newLayoutMode;
  50606. if (mode == FloatingWindows)
  50607. {
  50608. tabComponent = 0;
  50609. }
  50610. else
  50611. {
  50612. for (int i = getNumChildComponents(); --i >= 0;)
  50613. {
  50614. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50615. if (dw != 0)
  50616. {
  50617. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50618. dw->setContentComponent (0, false);
  50619. delete dw;
  50620. }
  50621. }
  50622. }
  50623. resized();
  50624. const Array <Component*> tempComps (components);
  50625. components.clear();
  50626. for (int i = 0; i < tempComps.size(); ++i)
  50627. {
  50628. Component* const c = tempComps.getUnchecked(i);
  50629. addDocument (c,
  50630. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50631. shouldDeleteComp (c));
  50632. }
  50633. }
  50634. }
  50635. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50636. {
  50637. if (backgroundColour != newBackgroundColour)
  50638. {
  50639. backgroundColour = newBackgroundColour;
  50640. setOpaque (newBackgroundColour.isOpaque());
  50641. repaint();
  50642. }
  50643. }
  50644. void MultiDocumentPanel::paint (Graphics& g)
  50645. {
  50646. g.fillAll (backgroundColour);
  50647. }
  50648. void MultiDocumentPanel::resized()
  50649. {
  50650. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50651. {
  50652. for (int i = getNumChildComponents(); --i >= 0;)
  50653. getChildComponent (i)->setBounds (getLocalBounds());
  50654. }
  50655. setWantsKeyboardFocus (components.size() == 0);
  50656. }
  50657. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50658. {
  50659. if (mode == FloatingWindows)
  50660. {
  50661. for (int i = 0; i < getNumChildComponents(); ++i)
  50662. {
  50663. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50664. if (dw != 0 && dw->getContentComponent() == c)
  50665. {
  50666. c = dw;
  50667. break;
  50668. }
  50669. }
  50670. }
  50671. return c;
  50672. }
  50673. void MultiDocumentPanel::componentNameChanged (Component&)
  50674. {
  50675. if (mode == FloatingWindows)
  50676. {
  50677. for (int i = 0; i < getNumChildComponents(); ++i)
  50678. {
  50679. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50680. if (dw != 0)
  50681. dw->setName (dw->getContentComponent()->getName());
  50682. }
  50683. }
  50684. else if (tabComponent != 0)
  50685. {
  50686. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50687. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50688. }
  50689. }
  50690. void MultiDocumentPanel::updateOrder()
  50691. {
  50692. const Array <Component*> oldList (components);
  50693. if (mode == FloatingWindows)
  50694. {
  50695. components.clear();
  50696. for (int i = 0; i < getNumChildComponents(); ++i)
  50697. {
  50698. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50699. if (dw != 0)
  50700. components.add (dw->getContentComponent());
  50701. }
  50702. }
  50703. else
  50704. {
  50705. if (tabComponent != 0)
  50706. {
  50707. Component* const current = tabComponent->getCurrentContentComponent();
  50708. if (current != 0)
  50709. {
  50710. components.removeValue (current);
  50711. components.add (current);
  50712. }
  50713. }
  50714. }
  50715. if (components != oldList)
  50716. activeDocumentChanged();
  50717. }
  50718. END_JUCE_NAMESPACE
  50719. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50720. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50721. BEGIN_JUCE_NAMESPACE
  50722. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50723. : zone (zoneFlags)
  50724. {
  50725. }
  50726. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50727. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50728. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50729. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50730. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50731. const BorderSize& border,
  50732. const Point<int>& position)
  50733. {
  50734. int z = 0;
  50735. if (totalSize.contains (position)
  50736. && ! border.subtractedFrom (totalSize).contains (position))
  50737. {
  50738. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50739. if (position.getX() < jmax (border.getLeft(), minW))
  50740. z |= left;
  50741. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50742. z |= right;
  50743. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50744. if (position.getY() < jmax (border.getTop(), minH))
  50745. z |= top;
  50746. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50747. z |= bottom;
  50748. }
  50749. return Zone (z);
  50750. }
  50751. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50752. {
  50753. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50754. switch (zone)
  50755. {
  50756. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50757. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50758. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50759. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50760. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50761. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50762. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50763. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50764. default: break;
  50765. }
  50766. return mc;
  50767. }
  50768. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50769. {
  50770. if (isDraggingWholeObject())
  50771. return b + offset;
  50772. if (isDraggingLeftEdge())
  50773. b.setLeft (b.getX() + offset.getX());
  50774. if (isDraggingRightEdge())
  50775. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50776. if (isDraggingTopEdge())
  50777. b.setTop (b.getY() + offset.getY());
  50778. if (isDraggingBottomEdge())
  50779. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50780. return b;
  50781. }
  50782. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50783. {
  50784. if (isDraggingWholeObject())
  50785. return b + offset;
  50786. if (isDraggingLeftEdge())
  50787. b.setLeft (b.getX() + offset.getX());
  50788. if (isDraggingRightEdge())
  50789. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50790. if (isDraggingTopEdge())
  50791. b.setTop (b.getY() + offset.getY());
  50792. if (isDraggingBottomEdge())
  50793. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50794. return b;
  50795. }
  50796. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50797. ComponentBoundsConstrainer* const constrainer_)
  50798. : component (componentToResize),
  50799. constrainer (constrainer_),
  50800. borderSize (5),
  50801. mouseZone (0)
  50802. {
  50803. }
  50804. ResizableBorderComponent::~ResizableBorderComponent()
  50805. {
  50806. }
  50807. void ResizableBorderComponent::paint (Graphics& g)
  50808. {
  50809. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50810. }
  50811. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50812. {
  50813. updateMouseZone (e);
  50814. }
  50815. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50816. {
  50817. updateMouseZone (e);
  50818. }
  50819. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50820. {
  50821. if (component == 0)
  50822. {
  50823. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50824. return;
  50825. }
  50826. updateMouseZone (e);
  50827. originalBounds = component->getBounds();
  50828. if (constrainer != 0)
  50829. constrainer->resizeStart();
  50830. }
  50831. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50832. {
  50833. if (component == 0)
  50834. {
  50835. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50836. return;
  50837. }
  50838. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50839. if (constrainer != 0)
  50840. constrainer->setBoundsForComponent (component, bounds,
  50841. mouseZone.isDraggingTopEdge(),
  50842. mouseZone.isDraggingLeftEdge(),
  50843. mouseZone.isDraggingBottomEdge(),
  50844. mouseZone.isDraggingRightEdge());
  50845. else
  50846. component->setBounds (bounds);
  50847. }
  50848. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50849. {
  50850. if (constrainer != 0)
  50851. constrainer->resizeEnd();
  50852. }
  50853. bool ResizableBorderComponent::hitTest (int x, int y)
  50854. {
  50855. return x < borderSize.getLeft()
  50856. || x >= getWidth() - borderSize.getRight()
  50857. || y < borderSize.getTop()
  50858. || y >= getHeight() - borderSize.getBottom();
  50859. }
  50860. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50861. {
  50862. if (borderSize != newBorderSize)
  50863. {
  50864. borderSize = newBorderSize;
  50865. repaint();
  50866. }
  50867. }
  50868. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50869. {
  50870. return borderSize;
  50871. }
  50872. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50873. {
  50874. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50875. if (mouseZone != newZone)
  50876. {
  50877. mouseZone = newZone;
  50878. setMouseCursor (newZone.getMouseCursor());
  50879. }
  50880. }
  50881. END_JUCE_NAMESPACE
  50882. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50883. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50884. BEGIN_JUCE_NAMESPACE
  50885. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50886. ComponentBoundsConstrainer* const constrainer_)
  50887. : component (componentToResize),
  50888. constrainer (constrainer_)
  50889. {
  50890. setRepaintsOnMouseActivity (true);
  50891. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50892. }
  50893. ResizableCornerComponent::~ResizableCornerComponent()
  50894. {
  50895. }
  50896. void ResizableCornerComponent::paint (Graphics& g)
  50897. {
  50898. getLookAndFeel()
  50899. .drawCornerResizer (g, getWidth(), getHeight(),
  50900. isMouseOverOrDragging(),
  50901. isMouseButtonDown());
  50902. }
  50903. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50904. {
  50905. if (component == 0)
  50906. {
  50907. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50908. return;
  50909. }
  50910. originalBounds = component->getBounds();
  50911. if (constrainer != 0)
  50912. constrainer->resizeStart();
  50913. }
  50914. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50915. {
  50916. if (component == 0)
  50917. {
  50918. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50919. return;
  50920. }
  50921. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50922. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50923. if (constrainer != 0)
  50924. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50925. else
  50926. component->setBounds (r);
  50927. }
  50928. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50929. {
  50930. if (constrainer != 0)
  50931. constrainer->resizeStart();
  50932. }
  50933. bool ResizableCornerComponent::hitTest (int x, int y)
  50934. {
  50935. if (getWidth() <= 0)
  50936. return false;
  50937. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50938. return y >= yAtX - getHeight() / 4;
  50939. }
  50940. END_JUCE_NAMESPACE
  50941. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50942. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50943. BEGIN_JUCE_NAMESPACE
  50944. class ScrollBar::ScrollbarButton : public Button
  50945. {
  50946. public:
  50947. int direction;
  50948. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50949. : Button (String::empty),
  50950. direction (direction_),
  50951. owner (owner_)
  50952. {
  50953. setWantsKeyboardFocus (false);
  50954. }
  50955. ~ScrollbarButton()
  50956. {
  50957. }
  50958. void paintButton (Graphics& g, bool over, bool down)
  50959. {
  50960. getLookAndFeel()
  50961. .drawScrollbarButton (g, owner,
  50962. getWidth(), getHeight(),
  50963. direction,
  50964. owner.isVertical(),
  50965. over, down);
  50966. }
  50967. void clicked()
  50968. {
  50969. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50970. }
  50971. juce_UseDebuggingNewOperator
  50972. private:
  50973. ScrollBar& owner;
  50974. ScrollbarButton (const ScrollbarButton&);
  50975. ScrollbarButton& operator= (const ScrollbarButton&);
  50976. };
  50977. ScrollBar::ScrollBar (const bool vertical_,
  50978. const bool buttonsAreVisible)
  50979. : totalRange (0.0, 1.0),
  50980. visibleRange (0.0, 0.1),
  50981. singleStepSize (0.1),
  50982. thumbAreaStart (0),
  50983. thumbAreaSize (0),
  50984. thumbStart (0),
  50985. thumbSize (0),
  50986. initialDelayInMillisecs (100),
  50987. repeatDelayInMillisecs (50),
  50988. minimumDelayInMillisecs (10),
  50989. vertical (vertical_),
  50990. isDraggingThumb (false),
  50991. autohides (true)
  50992. {
  50993. setButtonVisibility (buttonsAreVisible);
  50994. setRepaintsOnMouseActivity (true);
  50995. setFocusContainer (true);
  50996. }
  50997. ScrollBar::~ScrollBar()
  50998. {
  50999. upButton = 0;
  51000. downButton = 0;
  51001. }
  51002. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  51003. {
  51004. if (totalRange != newRangeLimit)
  51005. {
  51006. totalRange = newRangeLimit;
  51007. setCurrentRange (visibleRange);
  51008. updateThumbPosition();
  51009. }
  51010. }
  51011. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  51012. {
  51013. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  51014. setRangeLimits (Range<double> (newMinimum, newMaximum));
  51015. }
  51016. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  51017. {
  51018. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  51019. if (visibleRange != constrainedRange)
  51020. {
  51021. visibleRange = constrainedRange;
  51022. updateThumbPosition();
  51023. triggerAsyncUpdate();
  51024. }
  51025. }
  51026. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  51027. {
  51028. setCurrentRange (Range<double> (newStart, newStart + newSize));
  51029. }
  51030. void ScrollBar::setCurrentRangeStart (const double newStart)
  51031. {
  51032. setCurrentRange (visibleRange.movedToStartAt (newStart));
  51033. }
  51034. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  51035. {
  51036. singleStepSize = newSingleStepSize;
  51037. }
  51038. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  51039. {
  51040. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  51041. }
  51042. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  51043. {
  51044. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  51045. }
  51046. void ScrollBar::scrollToTop()
  51047. {
  51048. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  51049. }
  51050. void ScrollBar::scrollToBottom()
  51051. {
  51052. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  51053. }
  51054. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  51055. const int repeatDelayInMillisecs_,
  51056. const int minimumDelayInMillisecs_)
  51057. {
  51058. initialDelayInMillisecs = initialDelayInMillisecs_;
  51059. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  51060. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  51061. if (upButton != 0)
  51062. {
  51063. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  51064. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  51065. }
  51066. }
  51067. void ScrollBar::addListener (Listener* const listener)
  51068. {
  51069. listeners.add (listener);
  51070. }
  51071. void ScrollBar::removeListener (Listener* const listener)
  51072. {
  51073. listeners.remove (listener);
  51074. }
  51075. void ScrollBar::handleAsyncUpdate()
  51076. {
  51077. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  51078. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  51079. }
  51080. void ScrollBar::updateThumbPosition()
  51081. {
  51082. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  51083. : thumbAreaSize);
  51084. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51085. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  51086. if (newThumbSize > thumbAreaSize)
  51087. newThumbSize = thumbAreaSize;
  51088. int newThumbStart = thumbAreaStart;
  51089. if (totalRange.getLength() > visibleRange.getLength())
  51090. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  51091. / (totalRange.getLength() - visibleRange.getLength()));
  51092. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  51093. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  51094. {
  51095. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  51096. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  51097. if (vertical)
  51098. repaint (0, repaintStart, getWidth(), repaintSize);
  51099. else
  51100. repaint (repaintStart, 0, repaintSize, getHeight());
  51101. thumbStart = newThumbStart;
  51102. thumbSize = newThumbSize;
  51103. }
  51104. }
  51105. void ScrollBar::setOrientation (const bool shouldBeVertical)
  51106. {
  51107. if (vertical != shouldBeVertical)
  51108. {
  51109. vertical = shouldBeVertical;
  51110. if (upButton != 0)
  51111. {
  51112. upButton->direction = vertical ? 0 : 3;
  51113. downButton->direction = vertical ? 2 : 1;
  51114. }
  51115. updateThumbPosition();
  51116. }
  51117. }
  51118. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  51119. {
  51120. upButton = 0;
  51121. downButton = 0;
  51122. if (buttonsAreVisible)
  51123. {
  51124. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  51125. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  51126. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  51127. }
  51128. updateThumbPosition();
  51129. }
  51130. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  51131. {
  51132. autohides = shouldHideWhenFullRange;
  51133. updateThumbPosition();
  51134. }
  51135. bool ScrollBar::autoHides() const throw()
  51136. {
  51137. return autohides;
  51138. }
  51139. void ScrollBar::paint (Graphics& g)
  51140. {
  51141. if (thumbAreaSize > 0)
  51142. {
  51143. LookAndFeel& lf = getLookAndFeel();
  51144. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  51145. ? thumbSize : 0;
  51146. if (vertical)
  51147. {
  51148. lf.drawScrollbar (g, *this,
  51149. 0, thumbAreaStart,
  51150. getWidth(), thumbAreaSize,
  51151. vertical,
  51152. thumbStart, thumb,
  51153. isMouseOver(), isMouseButtonDown());
  51154. }
  51155. else
  51156. {
  51157. lf.drawScrollbar (g, *this,
  51158. thumbAreaStart, 0,
  51159. thumbAreaSize, getHeight(),
  51160. vertical,
  51161. thumbStart, thumb,
  51162. isMouseOver(), isMouseButtonDown());
  51163. }
  51164. }
  51165. }
  51166. void ScrollBar::lookAndFeelChanged()
  51167. {
  51168. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  51169. }
  51170. void ScrollBar::resized()
  51171. {
  51172. const int length = ((vertical) ? getHeight() : getWidth());
  51173. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  51174. : 0;
  51175. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51176. {
  51177. thumbAreaStart = length >> 1;
  51178. thumbAreaSize = 0;
  51179. }
  51180. else
  51181. {
  51182. thumbAreaStart = buttonSize;
  51183. thumbAreaSize = length - (buttonSize << 1);
  51184. }
  51185. if (upButton != 0)
  51186. {
  51187. if (vertical)
  51188. {
  51189. upButton->setBounds (0, 0, getWidth(), buttonSize);
  51190. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  51191. }
  51192. else
  51193. {
  51194. upButton->setBounds (0, 0, buttonSize, getHeight());
  51195. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  51196. }
  51197. }
  51198. updateThumbPosition();
  51199. }
  51200. void ScrollBar::mouseDown (const MouseEvent& e)
  51201. {
  51202. isDraggingThumb = false;
  51203. lastMousePos = vertical ? e.y : e.x;
  51204. dragStartMousePos = lastMousePos;
  51205. dragStartRange = visibleRange.getStart();
  51206. if (dragStartMousePos < thumbStart)
  51207. {
  51208. moveScrollbarInPages (-1);
  51209. startTimer (400);
  51210. }
  51211. else if (dragStartMousePos >= thumbStart + thumbSize)
  51212. {
  51213. moveScrollbarInPages (1);
  51214. startTimer (400);
  51215. }
  51216. else
  51217. {
  51218. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51219. && (thumbAreaSize > thumbSize);
  51220. }
  51221. }
  51222. void ScrollBar::mouseDrag (const MouseEvent& e)
  51223. {
  51224. if (isDraggingThumb)
  51225. {
  51226. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  51227. setCurrentRangeStart (dragStartRange
  51228. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  51229. / (thumbAreaSize - thumbSize));
  51230. }
  51231. else
  51232. {
  51233. lastMousePos = (vertical) ? e.y : e.x;
  51234. }
  51235. }
  51236. void ScrollBar::mouseUp (const MouseEvent&)
  51237. {
  51238. isDraggingThumb = false;
  51239. stopTimer();
  51240. repaint();
  51241. }
  51242. void ScrollBar::mouseWheelMove (const MouseEvent&,
  51243. float wheelIncrementX,
  51244. float wheelIncrementY)
  51245. {
  51246. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  51247. if (increment < 0)
  51248. increment = jmin (increment * 10.0f, -1.0f);
  51249. else if (increment > 0)
  51250. increment = jmax (increment * 10.0f, 1.0f);
  51251. setCurrentRange (visibleRange - singleStepSize * increment);
  51252. }
  51253. void ScrollBar::timerCallback()
  51254. {
  51255. if (isMouseButtonDown())
  51256. {
  51257. startTimer (40);
  51258. if (lastMousePos < thumbStart)
  51259. setCurrentRange (visibleRange - visibleRange.getLength());
  51260. else if (lastMousePos > thumbStart + thumbSize)
  51261. setCurrentRangeStart (visibleRange.getEnd());
  51262. }
  51263. else
  51264. {
  51265. stopTimer();
  51266. }
  51267. }
  51268. bool ScrollBar::keyPressed (const KeyPress& key)
  51269. {
  51270. if (! isVisible())
  51271. return false;
  51272. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  51273. moveScrollbarInSteps (-1);
  51274. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  51275. moveScrollbarInSteps (1);
  51276. else if (key.isKeyCode (KeyPress::pageUpKey))
  51277. moveScrollbarInPages (-1);
  51278. else if (key.isKeyCode (KeyPress::pageDownKey))
  51279. moveScrollbarInPages (1);
  51280. else if (key.isKeyCode (KeyPress::homeKey))
  51281. scrollToTop();
  51282. else if (key.isKeyCode (KeyPress::endKey))
  51283. scrollToBottom();
  51284. else
  51285. return false;
  51286. return true;
  51287. }
  51288. END_JUCE_NAMESPACE
  51289. /*** End of inlined file: juce_ScrollBar.cpp ***/
  51290. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  51291. BEGIN_JUCE_NAMESPACE
  51292. StretchableLayoutManager::StretchableLayoutManager()
  51293. : totalSize (0)
  51294. {
  51295. }
  51296. StretchableLayoutManager::~StretchableLayoutManager()
  51297. {
  51298. }
  51299. void StretchableLayoutManager::clearAllItems()
  51300. {
  51301. items.clear();
  51302. totalSize = 0;
  51303. }
  51304. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51305. const double minimumSize,
  51306. const double maximumSize,
  51307. const double preferredSize)
  51308. {
  51309. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51310. if (layout == 0)
  51311. {
  51312. layout = new ItemLayoutProperties();
  51313. layout->itemIndex = itemIndex;
  51314. int i;
  51315. for (i = 0; i < items.size(); ++i)
  51316. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51317. break;
  51318. items.insert (i, layout);
  51319. }
  51320. layout->minSize = minimumSize;
  51321. layout->maxSize = maximumSize;
  51322. layout->preferredSize = preferredSize;
  51323. layout->currentSize = 0;
  51324. }
  51325. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51326. double& minimumSize,
  51327. double& maximumSize,
  51328. double& preferredSize) const
  51329. {
  51330. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51331. if (layout != 0)
  51332. {
  51333. minimumSize = layout->minSize;
  51334. maximumSize = layout->maxSize;
  51335. preferredSize = layout->preferredSize;
  51336. return true;
  51337. }
  51338. return false;
  51339. }
  51340. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51341. {
  51342. totalSize = newTotalSize;
  51343. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51344. }
  51345. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51346. {
  51347. int pos = 0;
  51348. for (int i = 0; i < itemIndex; ++i)
  51349. {
  51350. const ItemLayoutProperties* const layout = getInfoFor (i);
  51351. if (layout != 0)
  51352. pos += layout->currentSize;
  51353. }
  51354. return pos;
  51355. }
  51356. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51357. {
  51358. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51359. if (layout != 0)
  51360. return layout->currentSize;
  51361. return 0;
  51362. }
  51363. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51364. {
  51365. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51366. if (layout != 0)
  51367. return -layout->currentSize / (double) totalSize;
  51368. return 0;
  51369. }
  51370. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51371. int newPosition)
  51372. {
  51373. for (int i = items.size(); --i >= 0;)
  51374. {
  51375. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51376. if (layout->itemIndex == itemIndex)
  51377. {
  51378. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51379. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51380. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51381. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51382. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51383. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51384. endPos += layout->currentSize;
  51385. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51386. updatePrefSizesToMatchCurrentPositions();
  51387. break;
  51388. }
  51389. }
  51390. }
  51391. void StretchableLayoutManager::layOutComponents (Component** const components,
  51392. int numComponents,
  51393. int x, int y, int w, int h,
  51394. const bool vertically,
  51395. const bool resizeOtherDimension)
  51396. {
  51397. setTotalSize (vertically ? h : w);
  51398. int pos = vertically ? y : x;
  51399. for (int i = 0; i < numComponents; ++i)
  51400. {
  51401. const ItemLayoutProperties* const layout = getInfoFor (i);
  51402. if (layout != 0)
  51403. {
  51404. Component* const c = components[i];
  51405. if (c != 0)
  51406. {
  51407. if (i == numComponents - 1)
  51408. {
  51409. // if it's the last item, crop it to exactly fit the available space..
  51410. if (resizeOtherDimension)
  51411. {
  51412. if (vertically)
  51413. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51414. else
  51415. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51416. }
  51417. else
  51418. {
  51419. if (vertically)
  51420. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51421. else
  51422. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51423. }
  51424. }
  51425. else
  51426. {
  51427. if (resizeOtherDimension)
  51428. {
  51429. if (vertically)
  51430. c->setBounds (x, pos, w, layout->currentSize);
  51431. else
  51432. c->setBounds (pos, y, layout->currentSize, h);
  51433. }
  51434. else
  51435. {
  51436. if (vertically)
  51437. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51438. else
  51439. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51440. }
  51441. }
  51442. }
  51443. pos += layout->currentSize;
  51444. }
  51445. }
  51446. }
  51447. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51448. {
  51449. for (int i = items.size(); --i >= 0;)
  51450. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51451. return items.getUnchecked(i);
  51452. return 0;
  51453. }
  51454. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51455. const int endIndex,
  51456. const int availableSpace,
  51457. int startPos)
  51458. {
  51459. // calculate the total sizes
  51460. int i;
  51461. double totalIdealSize = 0.0;
  51462. int totalMinimums = 0;
  51463. for (i = startIndex; i < endIndex; ++i)
  51464. {
  51465. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51466. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51467. totalMinimums += layout->currentSize;
  51468. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51469. }
  51470. if (totalIdealSize <= 0)
  51471. totalIdealSize = 1.0;
  51472. // now calc the best sizes..
  51473. int extraSpace = availableSpace - totalMinimums;
  51474. while (extraSpace > 0)
  51475. {
  51476. int numWantingMoreSpace = 0;
  51477. int numHavingTakenExtraSpace = 0;
  51478. // first figure out how many comps want a slice of the extra space..
  51479. for (i = startIndex; i < endIndex; ++i)
  51480. {
  51481. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51482. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51483. const int bestSize = jlimit (layout->currentSize,
  51484. jmax (layout->currentSize,
  51485. sizeToRealSize (layout->maxSize, totalSize)),
  51486. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51487. if (bestSize > layout->currentSize)
  51488. ++numWantingMoreSpace;
  51489. }
  51490. // ..share out the extra space..
  51491. for (i = startIndex; i < endIndex; ++i)
  51492. {
  51493. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51494. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51495. int bestSize = jlimit (layout->currentSize,
  51496. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51497. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51498. const int extraWanted = bestSize - layout->currentSize;
  51499. if (extraWanted > 0)
  51500. {
  51501. const int extraAllowed = jmin (extraWanted,
  51502. extraSpace / jmax (1, numWantingMoreSpace));
  51503. if (extraAllowed > 0)
  51504. {
  51505. ++numHavingTakenExtraSpace;
  51506. --numWantingMoreSpace;
  51507. layout->currentSize += extraAllowed;
  51508. extraSpace -= extraAllowed;
  51509. }
  51510. }
  51511. }
  51512. if (numHavingTakenExtraSpace <= 0)
  51513. break;
  51514. }
  51515. // ..and calculate the end position
  51516. for (i = startIndex; i < endIndex; ++i)
  51517. {
  51518. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51519. startPos += layout->currentSize;
  51520. }
  51521. return startPos;
  51522. }
  51523. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51524. const int endIndex) const
  51525. {
  51526. int totalMinimums = 0;
  51527. for (int i = startIndex; i < endIndex; ++i)
  51528. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51529. return totalMinimums;
  51530. }
  51531. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51532. {
  51533. int totalMaximums = 0;
  51534. for (int i = startIndex; i < endIndex; ++i)
  51535. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51536. return totalMaximums;
  51537. }
  51538. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51539. {
  51540. for (int i = 0; i < items.size(); ++i)
  51541. {
  51542. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51543. layout->preferredSize
  51544. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51545. : getItemCurrentAbsoluteSize (i);
  51546. }
  51547. }
  51548. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51549. {
  51550. if (size < 0)
  51551. size *= -totalSpace;
  51552. return roundToInt (size);
  51553. }
  51554. END_JUCE_NAMESPACE
  51555. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51556. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51557. BEGIN_JUCE_NAMESPACE
  51558. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51559. const int itemIndex_,
  51560. const bool isVertical_)
  51561. : layout (layout_),
  51562. itemIndex (itemIndex_),
  51563. isVertical (isVertical_)
  51564. {
  51565. setRepaintsOnMouseActivity (true);
  51566. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51567. : MouseCursor::UpDownResizeCursor));
  51568. }
  51569. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51570. {
  51571. }
  51572. void StretchableLayoutResizerBar::paint (Graphics& g)
  51573. {
  51574. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51575. getWidth(), getHeight(),
  51576. isVertical,
  51577. isMouseOver(),
  51578. isMouseButtonDown());
  51579. }
  51580. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51581. {
  51582. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51583. }
  51584. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51585. {
  51586. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51587. : e.getDistanceFromDragStartY());
  51588. layout->setItemPosition (itemIndex, desiredPos);
  51589. hasBeenMoved();
  51590. }
  51591. void StretchableLayoutResizerBar::hasBeenMoved()
  51592. {
  51593. if (getParentComponent() != 0)
  51594. getParentComponent()->resized();
  51595. }
  51596. END_JUCE_NAMESPACE
  51597. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51598. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51599. BEGIN_JUCE_NAMESPACE
  51600. StretchableObjectResizer::StretchableObjectResizer()
  51601. {
  51602. }
  51603. StretchableObjectResizer::~StretchableObjectResizer()
  51604. {
  51605. }
  51606. void StretchableObjectResizer::addItem (const double size,
  51607. const double minSize, const double maxSize,
  51608. const int order)
  51609. {
  51610. // the order must be >= 0 but less than the maximum integer value.
  51611. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51612. Item* const item = new Item();
  51613. item->size = size;
  51614. item->minSize = minSize;
  51615. item->maxSize = maxSize;
  51616. item->order = order;
  51617. items.add (item);
  51618. }
  51619. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51620. {
  51621. const Item* const it = items [index];
  51622. return it != 0 ? it->size : 0;
  51623. }
  51624. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51625. {
  51626. int order = 0;
  51627. for (;;)
  51628. {
  51629. double currentSize = 0;
  51630. double minSize = 0;
  51631. double maxSize = 0;
  51632. int nextHighestOrder = std::numeric_limits<int>::max();
  51633. for (int i = 0; i < items.size(); ++i)
  51634. {
  51635. const Item* const it = items.getUnchecked(i);
  51636. currentSize += it->size;
  51637. if (it->order <= order)
  51638. {
  51639. minSize += it->minSize;
  51640. maxSize += it->maxSize;
  51641. }
  51642. else
  51643. {
  51644. minSize += it->size;
  51645. maxSize += it->size;
  51646. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51647. }
  51648. }
  51649. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51650. if (thisIterationTarget >= currentSize)
  51651. {
  51652. const double availableExtraSpace = maxSize - currentSize;
  51653. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51654. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51655. for (int i = 0; i < items.size(); ++i)
  51656. {
  51657. Item* const it = items.getUnchecked(i);
  51658. if (it->order <= order)
  51659. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51660. }
  51661. }
  51662. else
  51663. {
  51664. const double amountOfSlack = currentSize - minSize;
  51665. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51666. const double scale = targetAmountOfSlack / amountOfSlack;
  51667. for (int i = 0; i < items.size(); ++i)
  51668. {
  51669. Item* const it = items.getUnchecked(i);
  51670. if (it->order <= order)
  51671. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51672. }
  51673. }
  51674. if (nextHighestOrder < std::numeric_limits<int>::max())
  51675. order = nextHighestOrder;
  51676. else
  51677. break;
  51678. }
  51679. }
  51680. END_JUCE_NAMESPACE
  51681. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51682. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51683. BEGIN_JUCE_NAMESPACE
  51684. TabBarButton::TabBarButton (const String& name,
  51685. TabbedButtonBar* const owner_,
  51686. const int index)
  51687. : Button (name),
  51688. owner (owner_),
  51689. tabIndex (index),
  51690. overlapPixels (0)
  51691. {
  51692. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51693. setComponentEffect (&shadow);
  51694. setWantsKeyboardFocus (false);
  51695. }
  51696. TabBarButton::~TabBarButton()
  51697. {
  51698. }
  51699. void TabBarButton::paintButton (Graphics& g,
  51700. bool isMouseOverButton,
  51701. bool isButtonDown)
  51702. {
  51703. int x, y, w, h;
  51704. getActiveArea (x, y, w, h);
  51705. g.setOrigin (x, y);
  51706. getLookAndFeel()
  51707. .drawTabButton (g, w, h,
  51708. owner->getTabBackgroundColour (tabIndex),
  51709. tabIndex, getButtonText(), *this,
  51710. owner->getOrientation(),
  51711. isMouseOverButton, isButtonDown,
  51712. getToggleState());
  51713. }
  51714. void TabBarButton::clicked (const ModifierKeys& mods)
  51715. {
  51716. if (mods.isPopupMenu())
  51717. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51718. else
  51719. owner->setCurrentTabIndex (tabIndex);
  51720. }
  51721. bool TabBarButton::hitTest (int mx, int my)
  51722. {
  51723. int x, y, w, h;
  51724. getActiveArea (x, y, w, h);
  51725. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51726. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51727. {
  51728. if (((unsigned int) mx) < (unsigned int) getWidth()
  51729. && my >= y + overlapPixels
  51730. && my < y + h - overlapPixels)
  51731. return true;
  51732. }
  51733. else
  51734. {
  51735. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51736. && ((unsigned int) my) < (unsigned int) getHeight())
  51737. return true;
  51738. }
  51739. Path p;
  51740. getLookAndFeel()
  51741. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51742. owner->getOrientation(),
  51743. false, false, getToggleState());
  51744. return p.contains ((float) (mx - x),
  51745. (float) (my - y));
  51746. }
  51747. int TabBarButton::getBestTabLength (const int depth)
  51748. {
  51749. return jlimit (depth * 2,
  51750. depth * 7,
  51751. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51752. }
  51753. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51754. {
  51755. x = 0;
  51756. y = 0;
  51757. int r = getWidth();
  51758. int b = getHeight();
  51759. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51760. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51761. r -= spaceAroundImage;
  51762. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51763. x += spaceAroundImage;
  51764. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51765. y += spaceAroundImage;
  51766. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51767. b -= spaceAroundImage;
  51768. w = r - x;
  51769. h = b - y;
  51770. }
  51771. class TabAreaBehindFrontButtonComponent : public Component
  51772. {
  51773. public:
  51774. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51775. : owner (owner_)
  51776. {
  51777. setInterceptsMouseClicks (false, false);
  51778. }
  51779. ~TabAreaBehindFrontButtonComponent()
  51780. {
  51781. }
  51782. void paint (Graphics& g)
  51783. {
  51784. getLookAndFeel()
  51785. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51786. *owner, owner->getOrientation());
  51787. }
  51788. void enablementChanged()
  51789. {
  51790. repaint();
  51791. }
  51792. private:
  51793. TabbedButtonBar* const owner;
  51794. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51795. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51796. };
  51797. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51798. : orientation (orientation_),
  51799. currentTabIndex (-1)
  51800. {
  51801. setInterceptsMouseClicks (false, true);
  51802. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51803. setFocusContainer (true);
  51804. }
  51805. TabbedButtonBar::~TabbedButtonBar()
  51806. {
  51807. extraTabsButton = 0;
  51808. deleteAllChildren();
  51809. }
  51810. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51811. {
  51812. orientation = newOrientation;
  51813. for (int i = getNumChildComponents(); --i >= 0;)
  51814. getChildComponent (i)->resized();
  51815. resized();
  51816. }
  51817. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51818. {
  51819. return new TabBarButton (name, this, index);
  51820. }
  51821. void TabbedButtonBar::clearTabs()
  51822. {
  51823. tabs.clear();
  51824. tabColours.clear();
  51825. currentTabIndex = -1;
  51826. extraTabsButton = 0;
  51827. removeChildComponent (behindFrontTab);
  51828. deleteAllChildren();
  51829. addChildComponent (behindFrontTab);
  51830. setCurrentTabIndex (-1);
  51831. }
  51832. void TabbedButtonBar::addTab (const String& tabName,
  51833. const Colour& tabBackgroundColour,
  51834. int insertIndex)
  51835. {
  51836. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51837. if (tabName.isNotEmpty())
  51838. {
  51839. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51840. insertIndex = tabs.size();
  51841. for (int i = tabs.size(); --i >= insertIndex;)
  51842. {
  51843. TabBarButton* const tb = getTabButton (i);
  51844. if (tb != 0)
  51845. tb->tabIndex++;
  51846. }
  51847. tabs.insert (insertIndex, tabName);
  51848. tabColours.insert (insertIndex, tabBackgroundColour);
  51849. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51850. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51851. addAndMakeVisible (tb, insertIndex);
  51852. resized();
  51853. if (currentTabIndex < 0)
  51854. setCurrentTabIndex (0);
  51855. }
  51856. }
  51857. void TabbedButtonBar::setTabName (const int tabIndex,
  51858. const String& newName)
  51859. {
  51860. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51861. && tabs[tabIndex] != newName)
  51862. {
  51863. tabs.set (tabIndex, newName);
  51864. TabBarButton* const tb = getTabButton (tabIndex);
  51865. if (tb != 0)
  51866. tb->setButtonText (newName);
  51867. resized();
  51868. }
  51869. }
  51870. void TabbedButtonBar::removeTab (const int tabIndex)
  51871. {
  51872. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51873. {
  51874. const int oldTabIndex = currentTabIndex;
  51875. if (currentTabIndex == tabIndex)
  51876. currentTabIndex = -1;
  51877. tabs.remove (tabIndex);
  51878. tabColours.remove (tabIndex);
  51879. delete getTabButton (tabIndex);
  51880. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51881. {
  51882. TabBarButton* const tb = getTabButton (i);
  51883. if (tb != 0)
  51884. tb->tabIndex--;
  51885. }
  51886. resized();
  51887. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51888. }
  51889. }
  51890. void TabbedButtonBar::moveTab (const int currentIndex,
  51891. const int newIndex)
  51892. {
  51893. tabs.move (currentIndex, newIndex);
  51894. tabColours.move (currentIndex, newIndex);
  51895. resized();
  51896. }
  51897. int TabbedButtonBar::getNumTabs() const
  51898. {
  51899. return tabs.size();
  51900. }
  51901. const StringArray TabbedButtonBar::getTabNames() const
  51902. {
  51903. return tabs;
  51904. }
  51905. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51906. {
  51907. if (currentTabIndex != newIndex)
  51908. {
  51909. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51910. newIndex = -1;
  51911. currentTabIndex = newIndex;
  51912. for (int i = 0; i < getNumChildComponents(); ++i)
  51913. {
  51914. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51915. if (tb != 0)
  51916. tb->setToggleState (tb->tabIndex == newIndex, false);
  51917. }
  51918. resized();
  51919. if (sendChangeMessage_)
  51920. sendChangeMessage (this);
  51921. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51922. }
  51923. }
  51924. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51925. {
  51926. for (int i = getNumChildComponents(); --i >= 0;)
  51927. {
  51928. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51929. if (tb != 0 && tb->tabIndex == index)
  51930. return tb;
  51931. }
  51932. return 0;
  51933. }
  51934. void TabbedButtonBar::lookAndFeelChanged()
  51935. {
  51936. extraTabsButton = 0;
  51937. resized();
  51938. }
  51939. void TabbedButtonBar::resized()
  51940. {
  51941. const double minimumScale = 0.7;
  51942. int depth = getWidth();
  51943. int length = getHeight();
  51944. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51945. swapVariables (depth, length);
  51946. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51947. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51948. int i, totalLength = overlap;
  51949. int numVisibleButtons = tabs.size();
  51950. for (i = 0; i < getNumChildComponents(); ++i)
  51951. {
  51952. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51953. if (tb != 0)
  51954. {
  51955. totalLength += tb->getBestTabLength (depth) - overlap;
  51956. tb->overlapPixels = overlap / 2;
  51957. }
  51958. }
  51959. double scale = 1.0;
  51960. if (totalLength > length)
  51961. scale = jmax (minimumScale, length / (double) totalLength);
  51962. const bool isTooBig = totalLength * scale > length;
  51963. int tabsButtonPos = 0;
  51964. if (isTooBig)
  51965. {
  51966. if (extraTabsButton == 0)
  51967. {
  51968. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51969. extraTabsButton->addButtonListener (this);
  51970. extraTabsButton->setAlwaysOnTop (true);
  51971. extraTabsButton->setTriggeredOnMouseDown (true);
  51972. }
  51973. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51974. extraTabsButton->setSize (buttonSize, buttonSize);
  51975. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51976. {
  51977. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51978. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51979. }
  51980. else
  51981. {
  51982. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51983. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51984. }
  51985. totalLength = 0;
  51986. for (i = 0; i < tabs.size(); ++i)
  51987. {
  51988. TabBarButton* const tb = getTabButton (i);
  51989. if (tb != 0)
  51990. {
  51991. const int newLength = totalLength + tb->getBestTabLength (depth);
  51992. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51993. {
  51994. totalLength += overlap;
  51995. break;
  51996. }
  51997. numVisibleButtons = i + 1;
  51998. totalLength = newLength - overlap;
  51999. }
  52000. }
  52001. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  52002. }
  52003. else
  52004. {
  52005. extraTabsButton = 0;
  52006. }
  52007. int pos = 0;
  52008. TabBarButton* frontTab = 0;
  52009. for (i = 0; i < tabs.size(); ++i)
  52010. {
  52011. TabBarButton* const tb = getTabButton (i);
  52012. if (tb != 0)
  52013. {
  52014. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  52015. if (i < numVisibleButtons)
  52016. {
  52017. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  52018. tb->setBounds (pos, 0, bestLength, getHeight());
  52019. else
  52020. tb->setBounds (0, pos, getWidth(), bestLength);
  52021. tb->toBack();
  52022. if (tb->tabIndex == currentTabIndex)
  52023. frontTab = tb;
  52024. tb->setVisible (true);
  52025. }
  52026. else
  52027. {
  52028. tb->setVisible (false);
  52029. }
  52030. pos += bestLength - overlap;
  52031. }
  52032. }
  52033. behindFrontTab->setBounds (getLocalBounds());
  52034. if (frontTab != 0)
  52035. {
  52036. frontTab->toFront (false);
  52037. behindFrontTab->toBehind (frontTab);
  52038. }
  52039. }
  52040. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  52041. {
  52042. return tabColours [tabIndex];
  52043. }
  52044. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  52045. {
  52046. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  52047. && tabColours [tabIndex] != newColour)
  52048. {
  52049. tabColours.set (tabIndex, newColour);
  52050. repaint();
  52051. }
  52052. }
  52053. void TabbedButtonBar::buttonClicked (Button* button)
  52054. {
  52055. if (button == extraTabsButton)
  52056. {
  52057. PopupMenu m;
  52058. for (int i = 0; i < tabs.size(); ++i)
  52059. {
  52060. TabBarButton* const tb = getTabButton (i);
  52061. if (tb != 0 && ! tb->isVisible())
  52062. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  52063. }
  52064. const int res = m.showAt (extraTabsButton);
  52065. if (res != 0)
  52066. setCurrentTabIndex (res - 1);
  52067. }
  52068. }
  52069. void TabbedButtonBar::currentTabChanged (const int, const String&)
  52070. {
  52071. }
  52072. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  52073. {
  52074. }
  52075. END_JUCE_NAMESPACE
  52076. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  52077. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  52078. BEGIN_JUCE_NAMESPACE
  52079. class TabCompButtonBar : public TabbedButtonBar
  52080. {
  52081. public:
  52082. TabCompButtonBar (TabbedComponent* const owner_,
  52083. const TabbedButtonBar::Orientation orientation_)
  52084. : TabbedButtonBar (orientation_),
  52085. owner (owner_)
  52086. {
  52087. }
  52088. ~TabCompButtonBar()
  52089. {
  52090. }
  52091. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  52092. {
  52093. owner->changeCallback (newCurrentTabIndex, newTabName);
  52094. }
  52095. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  52096. {
  52097. owner->popupMenuClickOnTab (tabIndex, tabName);
  52098. }
  52099. const Colour getTabBackgroundColour (const int tabIndex)
  52100. {
  52101. return owner->tabs->getTabBackgroundColour (tabIndex);
  52102. }
  52103. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  52104. {
  52105. return owner->createTabButton (tabName, tabIndex);
  52106. }
  52107. juce_UseDebuggingNewOperator
  52108. private:
  52109. TabbedComponent* const owner;
  52110. TabCompButtonBar (const TabCompButtonBar&);
  52111. TabCompButtonBar& operator= (const TabCompButtonBar&);
  52112. };
  52113. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  52114. : panelComponent (0),
  52115. tabDepth (30),
  52116. outlineThickness (1),
  52117. edgeIndent (0)
  52118. {
  52119. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  52120. }
  52121. TabbedComponent::~TabbedComponent()
  52122. {
  52123. clearTabs();
  52124. delete tabs;
  52125. }
  52126. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  52127. {
  52128. tabs->setOrientation (orientation);
  52129. resized();
  52130. }
  52131. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  52132. {
  52133. return tabs->getOrientation();
  52134. }
  52135. void TabbedComponent::setTabBarDepth (const int newDepth)
  52136. {
  52137. if (tabDepth != newDepth)
  52138. {
  52139. tabDepth = newDepth;
  52140. resized();
  52141. }
  52142. }
  52143. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  52144. {
  52145. return new TabBarButton (tabName, tabs, tabIndex);
  52146. }
  52147. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  52148. void TabbedComponent::clearTabs()
  52149. {
  52150. if (panelComponent != 0)
  52151. {
  52152. panelComponent->setVisible (false);
  52153. removeChildComponent (panelComponent);
  52154. panelComponent = 0;
  52155. }
  52156. tabs->clearTabs();
  52157. for (int i = contentComponents.size(); --i >= 0;)
  52158. {
  52159. Component* const c = contentComponents.getUnchecked(i);
  52160. // be careful not to delete these components until they've been removed from the tab component
  52161. jassert (c == 0 || c->isValidComponent());
  52162. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  52163. delete c;
  52164. }
  52165. contentComponents.clear();
  52166. }
  52167. void TabbedComponent::addTab (const String& tabName,
  52168. const Colour& tabBackgroundColour,
  52169. Component* const contentComponent,
  52170. const bool deleteComponentWhenNotNeeded,
  52171. const int insertIndex)
  52172. {
  52173. contentComponents.insert (insertIndex, contentComponent);
  52174. if (contentComponent != 0)
  52175. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  52176. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  52177. }
  52178. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  52179. {
  52180. tabs->setTabName (tabIndex, newName);
  52181. }
  52182. void TabbedComponent::removeTab (const int tabIndex)
  52183. {
  52184. Component* const c = contentComponents [tabIndex];
  52185. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  52186. {
  52187. if (c == panelComponent)
  52188. panelComponent = 0;
  52189. delete c;
  52190. }
  52191. contentComponents.remove (tabIndex);
  52192. tabs->removeTab (tabIndex);
  52193. }
  52194. int TabbedComponent::getNumTabs() const
  52195. {
  52196. return tabs->getNumTabs();
  52197. }
  52198. const StringArray TabbedComponent::getTabNames() const
  52199. {
  52200. return tabs->getTabNames();
  52201. }
  52202. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  52203. {
  52204. return contentComponents [tabIndex];
  52205. }
  52206. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  52207. {
  52208. return tabs->getTabBackgroundColour (tabIndex);
  52209. }
  52210. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  52211. {
  52212. tabs->setTabBackgroundColour (tabIndex, newColour);
  52213. if (getCurrentTabIndex() == tabIndex)
  52214. repaint();
  52215. }
  52216. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  52217. {
  52218. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  52219. }
  52220. int TabbedComponent::getCurrentTabIndex() const
  52221. {
  52222. return tabs->getCurrentTabIndex();
  52223. }
  52224. const String& TabbedComponent::getCurrentTabName() const
  52225. {
  52226. return tabs->getCurrentTabName();
  52227. }
  52228. void TabbedComponent::setOutline (int thickness)
  52229. {
  52230. outlineThickness = thickness;
  52231. repaint();
  52232. }
  52233. void TabbedComponent::setIndent (const int indentThickness)
  52234. {
  52235. edgeIndent = indentThickness;
  52236. }
  52237. void TabbedComponent::paint (Graphics& g)
  52238. {
  52239. g.fillAll (findColour (backgroundColourId));
  52240. const TabbedButtonBar::Orientation o = getOrientation();
  52241. int x = 0;
  52242. int y = 0;
  52243. int r = getWidth();
  52244. int b = getHeight();
  52245. if (o == TabbedButtonBar::TabsAtTop)
  52246. y += tabDepth;
  52247. else if (o == TabbedButtonBar::TabsAtBottom)
  52248. b -= tabDepth;
  52249. else if (o == TabbedButtonBar::TabsAtLeft)
  52250. x += tabDepth;
  52251. else if (o == TabbedButtonBar::TabsAtRight)
  52252. r -= tabDepth;
  52253. g.reduceClipRegion (x, y, r - x, b - y);
  52254. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  52255. if (outlineThickness > 0)
  52256. {
  52257. if (o == TabbedButtonBar::TabsAtTop)
  52258. --y;
  52259. else if (o == TabbedButtonBar::TabsAtBottom)
  52260. ++b;
  52261. else if (o == TabbedButtonBar::TabsAtLeft)
  52262. --x;
  52263. else if (o == TabbedButtonBar::TabsAtRight)
  52264. ++r;
  52265. g.setColour (findColour (outlineColourId));
  52266. g.drawRect (x, y, r - x, b - y, outlineThickness);
  52267. }
  52268. }
  52269. void TabbedComponent::resized()
  52270. {
  52271. const TabbedButtonBar::Orientation o = getOrientation();
  52272. const int indent = edgeIndent + outlineThickness;
  52273. BorderSize indents (indent);
  52274. if (o == TabbedButtonBar::TabsAtTop)
  52275. {
  52276. tabs->setBounds (0, 0, getWidth(), tabDepth);
  52277. indents.setTop (tabDepth + edgeIndent);
  52278. }
  52279. else if (o == TabbedButtonBar::TabsAtBottom)
  52280. {
  52281. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  52282. indents.setBottom (tabDepth + edgeIndent);
  52283. }
  52284. else if (o == TabbedButtonBar::TabsAtLeft)
  52285. {
  52286. tabs->setBounds (0, 0, tabDepth, getHeight());
  52287. indents.setLeft (tabDepth + edgeIndent);
  52288. }
  52289. else if (o == TabbedButtonBar::TabsAtRight)
  52290. {
  52291. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  52292. indents.setRight (tabDepth + edgeIndent);
  52293. }
  52294. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  52295. for (int i = contentComponents.size(); --i >= 0;)
  52296. if (contentComponents.getUnchecked (i) != 0)
  52297. contentComponents.getUnchecked (i)->setBounds (bounds);
  52298. }
  52299. void TabbedComponent::lookAndFeelChanged()
  52300. {
  52301. for (int i = contentComponents.size(); --i >= 0;)
  52302. if (contentComponents.getUnchecked (i) != 0)
  52303. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  52304. }
  52305. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  52306. const String& newTabName)
  52307. {
  52308. if (panelComponent != 0)
  52309. {
  52310. panelComponent->setVisible (false);
  52311. removeChildComponent (panelComponent);
  52312. panelComponent = 0;
  52313. }
  52314. if (getCurrentTabIndex() >= 0)
  52315. {
  52316. panelComponent = contentComponents [getCurrentTabIndex()];
  52317. if (panelComponent != 0)
  52318. {
  52319. // do these ops as two stages instead of addAndMakeVisible() so that the
  52320. // component has always got a parent when it gets the visibilityChanged() callback
  52321. addChildComponent (panelComponent);
  52322. panelComponent->setVisible (true);
  52323. panelComponent->toFront (true);
  52324. }
  52325. repaint();
  52326. }
  52327. resized();
  52328. currentTabChanged (newCurrentTabIndex, newTabName);
  52329. }
  52330. void TabbedComponent::currentTabChanged (const int, const String&)
  52331. {
  52332. }
  52333. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52334. {
  52335. }
  52336. END_JUCE_NAMESPACE
  52337. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52338. /*** Start of inlined file: juce_Viewport.cpp ***/
  52339. BEGIN_JUCE_NAMESPACE
  52340. Viewport::Viewport (const String& componentName)
  52341. : Component (componentName),
  52342. scrollBarThickness (0),
  52343. singleStepX (16),
  52344. singleStepY (16),
  52345. showHScrollbar (true),
  52346. showVScrollbar (true),
  52347. verticalScrollBar (true),
  52348. horizontalScrollBar (false)
  52349. {
  52350. // content holder is used to clip the contents so they don't overlap the scrollbars
  52351. addAndMakeVisible (&contentHolder);
  52352. contentHolder.setInterceptsMouseClicks (false, true);
  52353. addChildComponent (&verticalScrollBar);
  52354. addChildComponent (&horizontalScrollBar);
  52355. verticalScrollBar.addListener (this);
  52356. horizontalScrollBar.addListener (this);
  52357. setInterceptsMouseClicks (false, true);
  52358. setWantsKeyboardFocus (true);
  52359. }
  52360. Viewport::~Viewport()
  52361. {
  52362. contentHolder.deleteAllChildren();
  52363. }
  52364. void Viewport::visibleAreaChanged (int, int, int, int)
  52365. {
  52366. }
  52367. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52368. {
  52369. if (contentComp.getComponent() != newViewedComponent)
  52370. {
  52371. {
  52372. ScopedPointer<Component> oldCompDeleter (contentComp);
  52373. contentComp = 0;
  52374. }
  52375. contentComp = newViewedComponent;
  52376. if (contentComp != 0)
  52377. {
  52378. contentComp->setTopLeftPosition (0, 0);
  52379. contentHolder.addAndMakeVisible (contentComp);
  52380. contentComp->addComponentListener (this);
  52381. }
  52382. updateVisibleArea();
  52383. }
  52384. }
  52385. int Viewport::getMaximumVisibleWidth() const
  52386. {
  52387. return contentHolder.getWidth();
  52388. }
  52389. int Viewport::getMaximumVisibleHeight() const
  52390. {
  52391. return contentHolder.getHeight();
  52392. }
  52393. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52394. {
  52395. if (contentComp != 0)
  52396. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52397. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52398. }
  52399. void Viewport::setViewPosition (const Point<int>& newPosition)
  52400. {
  52401. setViewPosition (newPosition.getX(), newPosition.getY());
  52402. }
  52403. void Viewport::setViewPositionProportionately (const double x, const double y)
  52404. {
  52405. if (contentComp != 0)
  52406. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52407. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52408. }
  52409. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52410. {
  52411. if (contentComp != 0)
  52412. {
  52413. int dx = 0, dy = 0;
  52414. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52415. {
  52416. if (mouseX < activeBorderThickness)
  52417. dx = activeBorderThickness - mouseX;
  52418. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52419. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52420. if (dx < 0)
  52421. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52422. else
  52423. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52424. }
  52425. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52426. {
  52427. if (mouseY < activeBorderThickness)
  52428. dy = activeBorderThickness - mouseY;
  52429. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52430. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52431. if (dy < 0)
  52432. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52433. else
  52434. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52435. }
  52436. if (dx != 0 || dy != 0)
  52437. {
  52438. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52439. contentComp->getY() + dy);
  52440. return true;
  52441. }
  52442. }
  52443. return false;
  52444. }
  52445. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52446. {
  52447. updateVisibleArea();
  52448. }
  52449. void Viewport::resized()
  52450. {
  52451. updateVisibleArea();
  52452. }
  52453. void Viewport::updateVisibleArea()
  52454. {
  52455. const int scrollbarWidth = getScrollBarThickness();
  52456. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52457. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52458. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52459. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52460. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52461. Rectangle<int> contentArea (getLocalBounds());
  52462. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52463. {
  52464. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52465. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52466. if (vBarVisible)
  52467. contentArea.setWidth (getWidth() - scrollbarWidth);
  52468. if (hBarVisible)
  52469. contentArea.setHeight (getHeight() - scrollbarWidth);
  52470. if (! contentArea.contains (contentComp->getBounds()))
  52471. {
  52472. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52473. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52474. }
  52475. }
  52476. if (vBarVisible)
  52477. contentArea.setWidth (getWidth() - scrollbarWidth);
  52478. if (hBarVisible)
  52479. contentArea.setHeight (getHeight() - scrollbarWidth);
  52480. contentHolder.setBounds (contentArea);
  52481. Rectangle<int> contentBounds;
  52482. if (contentComp != 0)
  52483. contentBounds = contentComp->getBounds();
  52484. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52485. if (hBarVisible)
  52486. {
  52487. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52488. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52489. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52490. horizontalScrollBar.setSingleStepSize (singleStepX);
  52491. horizontalScrollBar.cancelPendingUpdate();
  52492. }
  52493. if (vBarVisible)
  52494. {
  52495. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52496. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52497. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52498. verticalScrollBar.setSingleStepSize (singleStepY);
  52499. verticalScrollBar.cancelPendingUpdate();
  52500. }
  52501. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52502. horizontalScrollBar.setVisible (hBarVisible);
  52503. verticalScrollBar.setVisible (vBarVisible);
  52504. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52505. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52506. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52507. if (lastVisibleArea != visibleArea)
  52508. {
  52509. lastVisibleArea = visibleArea;
  52510. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52511. }
  52512. horizontalScrollBar.handleUpdateNowIfNeeded();
  52513. verticalScrollBar.handleUpdateNowIfNeeded();
  52514. }
  52515. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52516. {
  52517. if (singleStepX != stepX || singleStepY != stepY)
  52518. {
  52519. singleStepX = stepX;
  52520. singleStepY = stepY;
  52521. updateVisibleArea();
  52522. }
  52523. }
  52524. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52525. const bool showHorizontalScrollbarIfNeeded)
  52526. {
  52527. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52528. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52529. {
  52530. showVScrollbar = showVerticalScrollbarIfNeeded;
  52531. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52532. updateVisibleArea();
  52533. }
  52534. }
  52535. void Viewport::setScrollBarThickness (const int thickness)
  52536. {
  52537. if (scrollBarThickness != thickness)
  52538. {
  52539. scrollBarThickness = thickness;
  52540. updateVisibleArea();
  52541. }
  52542. }
  52543. int Viewport::getScrollBarThickness() const
  52544. {
  52545. return scrollBarThickness > 0 ? scrollBarThickness
  52546. : getLookAndFeel().getDefaultScrollbarWidth();
  52547. }
  52548. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52549. {
  52550. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52551. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52552. }
  52553. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52554. {
  52555. const int newRangeStartInt = roundToInt (newRangeStart);
  52556. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52557. {
  52558. setViewPosition (newRangeStartInt, getViewPositionY());
  52559. }
  52560. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52561. {
  52562. setViewPosition (getViewPositionX(), newRangeStartInt);
  52563. }
  52564. }
  52565. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52566. {
  52567. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52568. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52569. }
  52570. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52571. {
  52572. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52573. {
  52574. const bool hasVertBar = verticalScrollBar.isVisible();
  52575. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52576. if (hasHorzBar || hasVertBar)
  52577. {
  52578. if (wheelIncrementX != 0)
  52579. {
  52580. wheelIncrementX *= 14.0f * singleStepX;
  52581. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52582. : jmax (wheelIncrementX, 1.0f);
  52583. }
  52584. if (wheelIncrementY != 0)
  52585. {
  52586. wheelIncrementY *= 14.0f * singleStepY;
  52587. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52588. : jmax (wheelIncrementY, 1.0f);
  52589. }
  52590. Point<int> pos (getViewPosition());
  52591. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52592. {
  52593. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52594. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52595. }
  52596. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52597. {
  52598. if (wheelIncrementX == 0 && ! hasVertBar)
  52599. wheelIncrementX = wheelIncrementY;
  52600. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52601. }
  52602. else if (hasVertBar && wheelIncrementY != 0)
  52603. {
  52604. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52605. }
  52606. if (pos != getViewPosition())
  52607. {
  52608. setViewPosition (pos);
  52609. return true;
  52610. }
  52611. }
  52612. }
  52613. return false;
  52614. }
  52615. bool Viewport::keyPressed (const KeyPress& key)
  52616. {
  52617. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52618. || key.isKeyCode (KeyPress::downKey)
  52619. || key.isKeyCode (KeyPress::pageUpKey)
  52620. || key.isKeyCode (KeyPress::pageDownKey)
  52621. || key.isKeyCode (KeyPress::homeKey)
  52622. || key.isKeyCode (KeyPress::endKey);
  52623. if (verticalScrollBar.isVisible() && isUpDownKey)
  52624. return verticalScrollBar.keyPressed (key);
  52625. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52626. || key.isKeyCode (KeyPress::rightKey);
  52627. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52628. return horizontalScrollBar.keyPressed (key);
  52629. return false;
  52630. }
  52631. END_JUCE_NAMESPACE
  52632. /*** End of inlined file: juce_Viewport.cpp ***/
  52633. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52634. BEGIN_JUCE_NAMESPACE
  52635. static const Colour createBaseColour (const Colour& buttonColour,
  52636. const bool hasKeyboardFocus,
  52637. const bool isMouseOverButton,
  52638. const bool isButtonDown) throw()
  52639. {
  52640. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52641. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52642. if (isButtonDown)
  52643. return baseColour.contrasting (0.2f);
  52644. else if (isMouseOverButton)
  52645. return baseColour.contrasting (0.1f);
  52646. return baseColour;
  52647. }
  52648. LookAndFeel::LookAndFeel()
  52649. {
  52650. /* if this fails it means you're trying to create a LookAndFeel object before
  52651. the static Colours have been initialised. That ain't gonna work. It probably
  52652. means that you're using a static LookAndFeel object and that your compiler has
  52653. decided to intialise it before the Colours class.
  52654. */
  52655. jassert (Colours::white == Colour (0xffffffff));
  52656. // set up the standard set of colours..
  52657. const int textButtonColour = 0xffbbbbff;
  52658. const int textHighlightColour = 0x401111ee;
  52659. const int standardOutlineColour = 0xb2808080;
  52660. static const int standardColours[] =
  52661. {
  52662. TextButton::buttonColourId, textButtonColour,
  52663. TextButton::buttonOnColourId, 0xff4444ff,
  52664. TextButton::textColourOnId, 0xff000000,
  52665. TextButton::textColourOffId, 0xff000000,
  52666. ComboBox::buttonColourId, 0xffbbbbff,
  52667. ComboBox::outlineColourId, standardOutlineColour,
  52668. ToggleButton::textColourId, 0xff000000,
  52669. TextEditor::backgroundColourId, 0xffffffff,
  52670. TextEditor::textColourId, 0xff000000,
  52671. TextEditor::highlightColourId, textHighlightColour,
  52672. TextEditor::highlightedTextColourId, 0xff000000,
  52673. TextEditor::caretColourId, 0xff000000,
  52674. TextEditor::outlineColourId, 0x00000000,
  52675. TextEditor::focusedOutlineColourId, textButtonColour,
  52676. TextEditor::shadowColourId, 0x38000000,
  52677. Label::backgroundColourId, 0x00000000,
  52678. Label::textColourId, 0xff000000,
  52679. Label::outlineColourId, 0x00000000,
  52680. ScrollBar::backgroundColourId, 0x00000000,
  52681. ScrollBar::thumbColourId, 0xffffffff,
  52682. ScrollBar::trackColourId, 0xffffffff,
  52683. TreeView::linesColourId, 0x4c000000,
  52684. TreeView::backgroundColourId, 0x00000000,
  52685. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52686. PopupMenu::backgroundColourId, 0xffffffff,
  52687. PopupMenu::textColourId, 0xff000000,
  52688. PopupMenu::headerTextColourId, 0xff000000,
  52689. PopupMenu::highlightedTextColourId, 0xffffffff,
  52690. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52691. ComboBox::textColourId, 0xff000000,
  52692. ComboBox::backgroundColourId, 0xffffffff,
  52693. ComboBox::arrowColourId, 0x99000000,
  52694. ListBox::backgroundColourId, 0xffffffff,
  52695. ListBox::outlineColourId, standardOutlineColour,
  52696. ListBox::textColourId, 0xff000000,
  52697. Slider::backgroundColourId, 0x00000000,
  52698. Slider::thumbColourId, textButtonColour,
  52699. Slider::trackColourId, 0x7fffffff,
  52700. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52701. Slider::rotarySliderOutlineColourId, 0x66000000,
  52702. Slider::textBoxTextColourId, 0xff000000,
  52703. Slider::textBoxBackgroundColourId, 0xffffffff,
  52704. Slider::textBoxHighlightColourId, textHighlightColour,
  52705. Slider::textBoxOutlineColourId, standardOutlineColour,
  52706. ResizableWindow::backgroundColourId, 0xff777777,
  52707. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52708. AlertWindow::backgroundColourId, 0xffededed,
  52709. AlertWindow::textColourId, 0xff000000,
  52710. AlertWindow::outlineColourId, 0xff666666,
  52711. ProgressBar::backgroundColourId, 0xffeeeeee,
  52712. ProgressBar::foregroundColourId, 0xffaaaaee,
  52713. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52714. TooltipWindow::textColourId, 0xff000000,
  52715. TooltipWindow::outlineColourId, 0x4c000000,
  52716. TabbedComponent::backgroundColourId, 0x00000000,
  52717. TabbedComponent::outlineColourId, 0xff777777,
  52718. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52719. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52720. Toolbar::backgroundColourId, 0xfff6f8f9,
  52721. Toolbar::separatorColourId, 0x4c000000,
  52722. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52723. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52724. Toolbar::labelTextColourId, 0xff000000,
  52725. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52726. HyperlinkButton::textColourId, 0xcc1111ee,
  52727. GroupComponent::outlineColourId, 0x66000000,
  52728. GroupComponent::textColourId, 0xff000000,
  52729. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52730. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52731. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52732. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52733. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52734. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52735. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52736. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52737. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52738. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52739. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52740. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52741. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52742. CodeEditorComponent::caretColourId, 0xff000000,
  52743. CodeEditorComponent::highlightColourId, textHighlightColour,
  52744. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52745. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52746. ColourSelector::labelTextColourId, 0xff000000,
  52747. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52748. KeyMappingEditorComponent::textColourId, 0xff000000,
  52749. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52750. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52751. DrawableButton::textColourId, 0xff000000,
  52752. };
  52753. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52754. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52755. static String defaultSansName, defaultSerifName, defaultFixedName;
  52756. if (defaultSansName.isEmpty())
  52757. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52758. defaultSans = defaultSansName;
  52759. defaultSerif = defaultSerifName;
  52760. defaultFixed = defaultFixedName;
  52761. }
  52762. LookAndFeel::~LookAndFeel()
  52763. {
  52764. }
  52765. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52766. {
  52767. const int index = colourIds.indexOf (colourId);
  52768. if (index >= 0)
  52769. return colours [index];
  52770. jassertfalse;
  52771. return Colours::black;
  52772. }
  52773. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52774. {
  52775. const int index = colourIds.indexOf (colourId);
  52776. if (index >= 0)
  52777. {
  52778. colours.set (index, colour);
  52779. }
  52780. else
  52781. {
  52782. colourIds.add (colourId);
  52783. colours.add (colour);
  52784. }
  52785. }
  52786. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52787. {
  52788. return colourIds.contains (colourId);
  52789. }
  52790. static LookAndFeel* defaultLF = 0;
  52791. static LookAndFeel* currentDefaultLF = 0;
  52792. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52793. {
  52794. // if this happens, your app hasn't initialised itself properly.. if you're
  52795. // trying to hack your own main() function, have a look at
  52796. // JUCEApplication::initialiseForGUI()
  52797. jassert (currentDefaultLF != 0);
  52798. return *currentDefaultLF;
  52799. }
  52800. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52801. {
  52802. if (newDefaultLookAndFeel == 0)
  52803. {
  52804. if (defaultLF == 0)
  52805. defaultLF = new LookAndFeel();
  52806. newDefaultLookAndFeel = defaultLF;
  52807. }
  52808. currentDefaultLF = newDefaultLookAndFeel;
  52809. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52810. {
  52811. Component* const c = Desktop::getInstance().getComponent (i);
  52812. if (c != 0)
  52813. c->sendLookAndFeelChange();
  52814. }
  52815. }
  52816. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52817. {
  52818. if (currentDefaultLF == defaultLF)
  52819. currentDefaultLF = 0;
  52820. deleteAndZero (defaultLF);
  52821. }
  52822. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52823. {
  52824. String faceName (font.getTypefaceName());
  52825. if (faceName == Font::getDefaultSansSerifFontName())
  52826. faceName = defaultSans;
  52827. else if (faceName == Font::getDefaultSerifFontName())
  52828. faceName = defaultSerif;
  52829. else if (faceName == Font::getDefaultMonospacedFontName())
  52830. faceName = defaultFixed;
  52831. Font f (font);
  52832. f.setTypefaceName (faceName);
  52833. return Typeface::createSystemTypefaceFor (f);
  52834. }
  52835. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52836. {
  52837. defaultSans = newName;
  52838. }
  52839. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52840. {
  52841. return component.getMouseCursor();
  52842. }
  52843. void LookAndFeel::drawButtonBackground (Graphics& g,
  52844. Button& button,
  52845. const Colour& backgroundColour,
  52846. bool isMouseOverButton,
  52847. bool isButtonDown)
  52848. {
  52849. const int width = button.getWidth();
  52850. const int height = button.getHeight();
  52851. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52852. const float halfThickness = outlineThickness * 0.5f;
  52853. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52854. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52855. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52856. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52857. const Colour baseColour (createBaseColour (backgroundColour,
  52858. button.hasKeyboardFocus (true),
  52859. isMouseOverButton, isButtonDown)
  52860. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52861. drawGlassLozenge (g,
  52862. indentL,
  52863. indentT,
  52864. width - indentL - indentR,
  52865. height - indentT - indentB,
  52866. baseColour, outlineThickness, -1.0f,
  52867. button.isConnectedOnLeft(),
  52868. button.isConnectedOnRight(),
  52869. button.isConnectedOnTop(),
  52870. button.isConnectedOnBottom());
  52871. }
  52872. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52873. {
  52874. return button.getFont();
  52875. }
  52876. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52877. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52878. {
  52879. Font font (getFontForTextButton (button));
  52880. g.setFont (font);
  52881. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52882. : TextButton::textColourOffId)
  52883. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52884. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52885. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52886. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52887. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52888. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52889. g.drawFittedText (button.getButtonText(),
  52890. leftIndent,
  52891. yIndent,
  52892. button.getWidth() - leftIndent - rightIndent,
  52893. button.getHeight() - yIndent * 2,
  52894. Justification::centred, 2);
  52895. }
  52896. void LookAndFeel::drawTickBox (Graphics& g,
  52897. Component& component,
  52898. float x, float y, float w, float h,
  52899. const bool ticked,
  52900. const bool isEnabled,
  52901. const bool isMouseOverButton,
  52902. const bool isButtonDown)
  52903. {
  52904. const float boxSize = w * 0.7f;
  52905. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52906. createBaseColour (component.findColour (TextButton::buttonColourId)
  52907. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52908. true,
  52909. isMouseOverButton,
  52910. isButtonDown),
  52911. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52912. if (ticked)
  52913. {
  52914. Path tick;
  52915. tick.startNewSubPath (1.5f, 3.0f);
  52916. tick.lineTo (3.0f, 6.0f);
  52917. tick.lineTo (6.0f, 0.0f);
  52918. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52919. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52920. .translated (x, y));
  52921. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52922. }
  52923. }
  52924. void LookAndFeel::drawToggleButton (Graphics& g,
  52925. ToggleButton& button,
  52926. bool isMouseOverButton,
  52927. bool isButtonDown)
  52928. {
  52929. if (button.hasKeyboardFocus (true))
  52930. {
  52931. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52932. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52933. }
  52934. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52935. const float tickWidth = fontSize * 1.1f;
  52936. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52937. tickWidth, tickWidth,
  52938. button.getToggleState(),
  52939. button.isEnabled(),
  52940. isMouseOverButton,
  52941. isButtonDown);
  52942. g.setColour (button.findColour (ToggleButton::textColourId));
  52943. g.setFont (fontSize);
  52944. if (! button.isEnabled())
  52945. g.setOpacity (0.5f);
  52946. const int textX = (int) tickWidth + 5;
  52947. g.drawFittedText (button.getButtonText(),
  52948. textX, 0,
  52949. button.getWidth() - textX - 2, button.getHeight(),
  52950. Justification::centredLeft, 10);
  52951. }
  52952. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52953. {
  52954. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52955. const int tickWidth = jmin (24, button.getHeight());
  52956. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52957. button.getHeight());
  52958. }
  52959. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52960. const String& message,
  52961. const String& button1,
  52962. const String& button2,
  52963. const String& button3,
  52964. AlertWindow::AlertIconType iconType,
  52965. int numButtons,
  52966. Component* associatedComponent)
  52967. {
  52968. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52969. if (numButtons == 1)
  52970. {
  52971. aw->addButton (button1, 0,
  52972. KeyPress (KeyPress::escapeKey, 0, 0),
  52973. KeyPress (KeyPress::returnKey, 0, 0));
  52974. }
  52975. else
  52976. {
  52977. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52978. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52979. if (button1ShortCut == button2ShortCut)
  52980. button2ShortCut = KeyPress();
  52981. if (numButtons == 2)
  52982. {
  52983. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52984. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52985. }
  52986. else if (numButtons == 3)
  52987. {
  52988. aw->addButton (button1, 1, button1ShortCut);
  52989. aw->addButton (button2, 2, button2ShortCut);
  52990. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52991. }
  52992. }
  52993. return aw;
  52994. }
  52995. void LookAndFeel::drawAlertBox (Graphics& g,
  52996. AlertWindow& alert,
  52997. const Rectangle<int>& textArea,
  52998. TextLayout& textLayout)
  52999. {
  53000. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  53001. int iconSpaceUsed = 0;
  53002. Justification alignment (Justification::horizontallyCentred);
  53003. const int iconWidth = 80;
  53004. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  53005. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  53006. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  53007. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  53008. iconSize, iconSize);
  53009. if (alert.getAlertType() != AlertWindow::NoIcon)
  53010. {
  53011. Path icon;
  53012. uint32 colour;
  53013. char character;
  53014. if (alert.getAlertType() == AlertWindow::WarningIcon)
  53015. {
  53016. colour = 0x55ff5555;
  53017. character = '!';
  53018. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  53019. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  53020. (float) iconRect.getX(), (float) iconRect.getBottom());
  53021. icon = icon.createPathWithRoundedCorners (5.0f);
  53022. }
  53023. else
  53024. {
  53025. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  53026. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  53027. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  53028. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  53029. }
  53030. GlyphArrangement ga;
  53031. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  53032. String::charToString (character),
  53033. (float) iconRect.getX(), (float) iconRect.getY(),
  53034. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  53035. Justification::centred, false);
  53036. ga.createPath (icon);
  53037. icon.setUsingNonZeroWinding (false);
  53038. g.setColour (Colour (colour));
  53039. g.fillPath (icon);
  53040. iconSpaceUsed = iconWidth;
  53041. alignment = Justification::left;
  53042. }
  53043. g.setColour (alert.findColour (AlertWindow::textColourId));
  53044. textLayout.drawWithin (g,
  53045. textArea.getX() + iconSpaceUsed, textArea.getY(),
  53046. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  53047. alignment.getFlags() | Justification::top);
  53048. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  53049. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  53050. }
  53051. int LookAndFeel::getAlertBoxWindowFlags()
  53052. {
  53053. return ComponentPeer::windowAppearsOnTaskbar
  53054. | ComponentPeer::windowHasDropShadow;
  53055. }
  53056. int LookAndFeel::getAlertWindowButtonHeight()
  53057. {
  53058. return 28;
  53059. }
  53060. const Font LookAndFeel::getAlertWindowFont()
  53061. {
  53062. return Font (12.0f);
  53063. }
  53064. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  53065. int width, int height,
  53066. double progress, const String& textToShow)
  53067. {
  53068. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  53069. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  53070. g.fillAll (background);
  53071. if (progress >= 0.0f && progress < 1.0f)
  53072. {
  53073. drawGlassLozenge (g, 1.0f, 1.0f,
  53074. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  53075. (float) (height - 2),
  53076. foreground,
  53077. 0.5f, 0.0f,
  53078. true, true, true, true);
  53079. }
  53080. else
  53081. {
  53082. // spinning bar..
  53083. g.setColour (foreground);
  53084. const int stripeWidth = height * 2;
  53085. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  53086. Path p;
  53087. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  53088. p.addQuadrilateral (x, 0.0f,
  53089. x + stripeWidth * 0.5f, 0.0f,
  53090. x, (float) height,
  53091. x - stripeWidth * 0.5f, (float) height);
  53092. Image im (Image::ARGB, width, height, true);
  53093. {
  53094. Graphics g2 (im);
  53095. drawGlassLozenge (g2, 1.0f, 1.0f,
  53096. (float) (width - 2),
  53097. (float) (height - 2),
  53098. foreground,
  53099. 0.5f, 0.0f,
  53100. true, true, true, true);
  53101. }
  53102. g.setTiledImageFill (im, 0, 0, 0.85f);
  53103. g.fillPath (p);
  53104. }
  53105. if (textToShow.isNotEmpty())
  53106. {
  53107. g.setColour (Colour::contrasting (background, foreground));
  53108. g.setFont (height * 0.6f);
  53109. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  53110. }
  53111. }
  53112. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  53113. {
  53114. const float radius = jmin (w, h) * 0.4f;
  53115. const float thickness = radius * 0.15f;
  53116. Path p;
  53117. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  53118. radius * 0.6f, thickness,
  53119. thickness * 0.5f);
  53120. const float cx = x + w * 0.5f;
  53121. const float cy = y + h * 0.5f;
  53122. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  53123. for (int i = 0; i < 12; ++i)
  53124. {
  53125. const int n = (i + 12 - animationIndex) % 12;
  53126. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  53127. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  53128. .translated (cx, cy));
  53129. }
  53130. }
  53131. void LookAndFeel::drawScrollbarButton (Graphics& g,
  53132. ScrollBar& scrollbar,
  53133. int width, int height,
  53134. int buttonDirection,
  53135. bool /*isScrollbarVertical*/,
  53136. bool /*isMouseOverButton*/,
  53137. bool isButtonDown)
  53138. {
  53139. Path p;
  53140. if (buttonDirection == 0)
  53141. p.addTriangle (width * 0.5f, height * 0.2f,
  53142. width * 0.1f, height * 0.7f,
  53143. width * 0.9f, height * 0.7f);
  53144. else if (buttonDirection == 1)
  53145. p.addTriangle (width * 0.8f, height * 0.5f,
  53146. width * 0.3f, height * 0.1f,
  53147. width * 0.3f, height * 0.9f);
  53148. else if (buttonDirection == 2)
  53149. p.addTriangle (width * 0.5f, height * 0.8f,
  53150. width * 0.1f, height * 0.3f,
  53151. width * 0.9f, height * 0.3f);
  53152. else if (buttonDirection == 3)
  53153. p.addTriangle (width * 0.2f, height * 0.5f,
  53154. width * 0.7f, height * 0.1f,
  53155. width * 0.7f, height * 0.9f);
  53156. if (isButtonDown)
  53157. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  53158. else
  53159. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53160. g.fillPath (p);
  53161. g.setColour (Colour (0x80000000));
  53162. g.strokePath (p, PathStrokeType (0.5f));
  53163. }
  53164. void LookAndFeel::drawScrollbar (Graphics& g,
  53165. ScrollBar& scrollbar,
  53166. int x, int y,
  53167. int width, int height,
  53168. bool isScrollbarVertical,
  53169. int thumbStartPosition,
  53170. int thumbSize,
  53171. bool /*isMouseOver*/,
  53172. bool /*isMouseDown*/)
  53173. {
  53174. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  53175. Path slotPath, thumbPath;
  53176. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  53177. const float slotIndentx2 = slotIndent * 2.0f;
  53178. const float thumbIndent = slotIndent + 1.0f;
  53179. const float thumbIndentx2 = thumbIndent * 2.0f;
  53180. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  53181. if (isScrollbarVertical)
  53182. {
  53183. slotPath.addRoundedRectangle (x + slotIndent,
  53184. y + slotIndent,
  53185. width - slotIndentx2,
  53186. height - slotIndentx2,
  53187. (width - slotIndentx2) * 0.5f);
  53188. if (thumbSize > 0)
  53189. thumbPath.addRoundedRectangle (x + thumbIndent,
  53190. thumbStartPosition + thumbIndent,
  53191. width - thumbIndentx2,
  53192. thumbSize - thumbIndentx2,
  53193. (width - thumbIndentx2) * 0.5f);
  53194. gx1 = (float) x;
  53195. gx2 = x + width * 0.7f;
  53196. }
  53197. else
  53198. {
  53199. slotPath.addRoundedRectangle (x + slotIndent,
  53200. y + slotIndent,
  53201. width - slotIndentx2,
  53202. height - slotIndentx2,
  53203. (height - slotIndentx2) * 0.5f);
  53204. if (thumbSize > 0)
  53205. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  53206. y + thumbIndent,
  53207. thumbSize - thumbIndentx2,
  53208. height - thumbIndentx2,
  53209. (height - thumbIndentx2) * 0.5f);
  53210. gy1 = (float) y;
  53211. gy2 = y + height * 0.7f;
  53212. }
  53213. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53214. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  53215. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  53216. g.fillPath (slotPath);
  53217. if (isScrollbarVertical)
  53218. {
  53219. gx1 = x + width * 0.6f;
  53220. gx2 = (float) x + width;
  53221. }
  53222. else
  53223. {
  53224. gy1 = y + height * 0.6f;
  53225. gy2 = (float) y + height;
  53226. }
  53227. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  53228. Colour (0x19000000), gx2, gy2, false));
  53229. g.fillPath (slotPath);
  53230. g.setColour (thumbColour);
  53231. g.fillPath (thumbPath);
  53232. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  53233. Colours::transparentBlack, gx2, gy2, false));
  53234. g.saveState();
  53235. if (isScrollbarVertical)
  53236. g.reduceClipRegion (x + width / 2, y, width, height);
  53237. else
  53238. g.reduceClipRegion (x, y + height / 2, width, height);
  53239. g.fillPath (thumbPath);
  53240. g.restoreState();
  53241. g.setColour (Colour (0x4c000000));
  53242. g.strokePath (thumbPath, PathStrokeType (0.4f));
  53243. }
  53244. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  53245. {
  53246. return 0;
  53247. }
  53248. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  53249. {
  53250. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  53251. }
  53252. int LookAndFeel::getDefaultScrollbarWidth()
  53253. {
  53254. return 18;
  53255. }
  53256. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  53257. {
  53258. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  53259. : scrollbar.getHeight());
  53260. }
  53261. const Path LookAndFeel::getTickShape (const float height)
  53262. {
  53263. static const unsigned char tickShapeData[] =
  53264. {
  53265. 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,
  53266. 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,
  53267. 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,
  53268. 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,
  53269. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  53270. };
  53271. Path p;
  53272. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  53273. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53274. return p;
  53275. }
  53276. const Path LookAndFeel::getCrossShape (const float height)
  53277. {
  53278. static const unsigned char crossShapeData[] =
  53279. {
  53280. 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,
  53281. 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,
  53282. 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,
  53283. 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,
  53284. 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,
  53285. 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,
  53286. 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
  53287. };
  53288. Path p;
  53289. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  53290. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53291. return p;
  53292. }
  53293. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  53294. {
  53295. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53296. x += (w - boxSize) >> 1;
  53297. y += (h - boxSize) >> 1;
  53298. w = boxSize;
  53299. h = boxSize;
  53300. g.setColour (Colour (0xe5ffffff));
  53301. g.fillRect (x, y, w, h);
  53302. g.setColour (Colour (0x80000000));
  53303. g.drawRect (x, y, w, h);
  53304. const float size = boxSize / 2 + 1.0f;
  53305. const float centre = (float) (boxSize / 2);
  53306. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53307. if (isPlus)
  53308. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53309. }
  53310. void LookAndFeel::drawBubble (Graphics& g,
  53311. float tipX, float tipY,
  53312. float boxX, float boxY,
  53313. float boxW, float boxH)
  53314. {
  53315. int side = 0;
  53316. if (tipX < boxX)
  53317. side = 1;
  53318. else if (tipX > boxX + boxW)
  53319. side = 3;
  53320. else if (tipY > boxY + boxH)
  53321. side = 2;
  53322. const float indent = 2.0f;
  53323. Path p;
  53324. p.addBubble (boxX + indent,
  53325. boxY + indent,
  53326. boxW - indent * 2.0f,
  53327. boxH - indent * 2.0f,
  53328. 5.0f,
  53329. tipX, tipY,
  53330. side,
  53331. 0.5f,
  53332. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53333. //xxx need to take comp as param for colour
  53334. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53335. g.fillPath (p);
  53336. //xxx as above
  53337. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53338. g.strokePath (p, PathStrokeType (1.33f));
  53339. }
  53340. const Font LookAndFeel::getPopupMenuFont()
  53341. {
  53342. return Font (17.0f);
  53343. }
  53344. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53345. const bool isSeparator,
  53346. int standardMenuItemHeight,
  53347. int& idealWidth,
  53348. int& idealHeight)
  53349. {
  53350. if (isSeparator)
  53351. {
  53352. idealWidth = 50;
  53353. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53354. }
  53355. else
  53356. {
  53357. Font font (getPopupMenuFont());
  53358. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53359. font.setHeight (standardMenuItemHeight / 1.3f);
  53360. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53361. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53362. }
  53363. }
  53364. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53365. {
  53366. const Colour background (findColour (PopupMenu::backgroundColourId));
  53367. g.fillAll (background);
  53368. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53369. for (int i = 0; i < height; i += 3)
  53370. g.fillRect (0, i, width, 1);
  53371. #if ! JUCE_MAC
  53372. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53373. g.drawRect (0, 0, width, height);
  53374. #endif
  53375. }
  53376. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53377. int width, int height,
  53378. bool isScrollUpArrow)
  53379. {
  53380. const Colour background (findColour (PopupMenu::backgroundColourId));
  53381. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53382. background.withAlpha (0.0f),
  53383. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53384. false));
  53385. g.fillRect (1, 1, width - 2, height - 2);
  53386. const float hw = width * 0.5f;
  53387. const float arrowW = height * 0.3f;
  53388. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53389. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53390. Path p;
  53391. p.addTriangle (hw - arrowW, y1,
  53392. hw + arrowW, y1,
  53393. hw, y2);
  53394. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53395. g.fillPath (p);
  53396. }
  53397. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53398. int width, int height,
  53399. const bool isSeparator,
  53400. const bool isActive,
  53401. const bool isHighlighted,
  53402. const bool isTicked,
  53403. const bool hasSubMenu,
  53404. const String& text,
  53405. const String& shortcutKeyText,
  53406. Image* image,
  53407. const Colour* const textColourToUse)
  53408. {
  53409. const float halfH = height * 0.5f;
  53410. if (isSeparator)
  53411. {
  53412. const float separatorIndent = 5.5f;
  53413. g.setColour (Colour (0x33000000));
  53414. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53415. g.setColour (Colour (0x66ffffff));
  53416. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53417. }
  53418. else
  53419. {
  53420. Colour textColour (findColour (PopupMenu::textColourId));
  53421. if (textColourToUse != 0)
  53422. textColour = *textColourToUse;
  53423. if (isHighlighted)
  53424. {
  53425. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53426. g.fillRect (1, 1, width - 2, height - 2);
  53427. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53428. }
  53429. else
  53430. {
  53431. g.setColour (textColour);
  53432. }
  53433. if (! isActive)
  53434. g.setOpacity (0.3f);
  53435. Font font (getPopupMenuFont());
  53436. if (font.getHeight() > height / 1.3f)
  53437. font.setHeight (height / 1.3f);
  53438. g.setFont (font);
  53439. const int leftBorder = (height * 5) / 4;
  53440. const int rightBorder = 4;
  53441. if (image != 0)
  53442. {
  53443. g.drawImageWithin (*image,
  53444. 2, 1, leftBorder - 4, height - 2,
  53445. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53446. }
  53447. else if (isTicked)
  53448. {
  53449. const Path tick (getTickShape (1.0f));
  53450. const float th = font.getAscent();
  53451. const float ty = halfH - th * 0.5f;
  53452. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53453. th, true));
  53454. }
  53455. g.drawFittedText (text,
  53456. leftBorder, 0,
  53457. width - (leftBorder + rightBorder), height,
  53458. Justification::centredLeft, 1);
  53459. if (shortcutKeyText.isNotEmpty())
  53460. {
  53461. Font f2 (font);
  53462. f2.setHeight (f2.getHeight() * 0.75f);
  53463. f2.setHorizontalScale (0.95f);
  53464. g.setFont (f2);
  53465. g.drawText (shortcutKeyText,
  53466. leftBorder,
  53467. 0,
  53468. width - (leftBorder + rightBorder + 4),
  53469. height,
  53470. Justification::centredRight,
  53471. true);
  53472. }
  53473. if (hasSubMenu)
  53474. {
  53475. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53476. const float x = width - height * 0.6f;
  53477. Path p;
  53478. p.addTriangle (x, halfH - arrowH * 0.5f,
  53479. x, halfH + arrowH * 0.5f,
  53480. x + arrowH * 0.6f, halfH);
  53481. g.fillPath (p);
  53482. }
  53483. }
  53484. }
  53485. int LookAndFeel::getMenuWindowFlags()
  53486. {
  53487. return ComponentPeer::windowHasDropShadow;
  53488. }
  53489. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53490. bool, MenuBarComponent& menuBar)
  53491. {
  53492. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53493. if (menuBar.isEnabled())
  53494. {
  53495. drawShinyButtonShape (g,
  53496. -4.0f, 0.0f,
  53497. width + 8.0f, (float) height,
  53498. 0.0f,
  53499. baseColour,
  53500. 0.4f,
  53501. true, true, true, true);
  53502. }
  53503. else
  53504. {
  53505. g.fillAll (baseColour);
  53506. }
  53507. }
  53508. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53509. {
  53510. return Font (menuBar.getHeight() * 0.7f);
  53511. }
  53512. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53513. {
  53514. return getMenuBarFont (menuBar, itemIndex, itemText)
  53515. .getStringWidth (itemText) + menuBar.getHeight();
  53516. }
  53517. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53518. int width, int height,
  53519. int itemIndex,
  53520. const String& itemText,
  53521. bool isMouseOverItem,
  53522. bool isMenuOpen,
  53523. bool /*isMouseOverBar*/,
  53524. MenuBarComponent& menuBar)
  53525. {
  53526. if (! menuBar.isEnabled())
  53527. {
  53528. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53529. .withMultipliedAlpha (0.5f));
  53530. }
  53531. else if (isMenuOpen || isMouseOverItem)
  53532. {
  53533. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53534. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53535. }
  53536. else
  53537. {
  53538. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53539. }
  53540. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53541. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53542. }
  53543. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53544. TextEditor& textEditor)
  53545. {
  53546. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53547. }
  53548. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53549. {
  53550. if (textEditor.isEnabled())
  53551. {
  53552. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53553. {
  53554. const int border = 2;
  53555. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53556. g.drawRect (0, 0, width, height, border);
  53557. g.setOpacity (1.0f);
  53558. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53559. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53560. }
  53561. else
  53562. {
  53563. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53564. g.drawRect (0, 0, width, height);
  53565. g.setOpacity (1.0f);
  53566. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53567. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53568. }
  53569. }
  53570. }
  53571. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53572. const bool isButtonDown,
  53573. int buttonX, int buttonY,
  53574. int buttonW, int buttonH,
  53575. ComboBox& box)
  53576. {
  53577. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53578. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53579. {
  53580. g.setColour (box.findColour (TextButton::buttonColourId));
  53581. g.drawRect (0, 0, width, height, 2);
  53582. }
  53583. else
  53584. {
  53585. g.setColour (box.findColour (ComboBox::outlineColourId));
  53586. g.drawRect (0, 0, width, height);
  53587. }
  53588. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53589. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53590. box.hasKeyboardFocus (true),
  53591. false, isButtonDown)
  53592. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53593. drawGlassLozenge (g,
  53594. buttonX + outlineThickness, buttonY + outlineThickness,
  53595. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53596. baseColour, outlineThickness, -1.0f,
  53597. true, true, true, true);
  53598. if (box.isEnabled())
  53599. {
  53600. const float arrowX = 0.3f;
  53601. const float arrowH = 0.2f;
  53602. Path p;
  53603. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53604. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53605. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53606. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53607. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53608. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53609. g.setColour (box.findColour (ComboBox::arrowColourId));
  53610. g.fillPath (p);
  53611. }
  53612. }
  53613. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53614. {
  53615. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53616. }
  53617. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53618. {
  53619. return new Label (String::empty, String::empty);
  53620. }
  53621. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53622. {
  53623. label.setBounds (1, 1,
  53624. box.getWidth() + 3 - box.getHeight(),
  53625. box.getHeight() - 2);
  53626. label.setFont (getComboBoxFont (box));
  53627. }
  53628. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53629. {
  53630. g.fillAll (label.findColour (Label::backgroundColourId));
  53631. if (! label.isBeingEdited())
  53632. {
  53633. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53634. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53635. g.setFont (label.getFont());
  53636. g.drawFittedText (label.getText(),
  53637. label.getHorizontalBorderSize(),
  53638. label.getVerticalBorderSize(),
  53639. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53640. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53641. label.getJustificationType(),
  53642. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53643. label.getMinimumHorizontalScale());
  53644. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53645. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53646. }
  53647. else if (label.isEnabled())
  53648. {
  53649. g.setColour (label.findColour (Label::outlineColourId));
  53650. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53651. }
  53652. }
  53653. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53654. int x, int y,
  53655. int width, int height,
  53656. float /*sliderPos*/,
  53657. float /*minSliderPos*/,
  53658. float /*maxSliderPos*/,
  53659. const Slider::SliderStyle /*style*/,
  53660. Slider& slider)
  53661. {
  53662. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53663. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53664. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53665. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53666. Path indent;
  53667. if (slider.isHorizontal())
  53668. {
  53669. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53670. const float ih = sliderRadius;
  53671. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53672. gradCol2, 0.0f, iy + ih, false));
  53673. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53674. width + sliderRadius, ih,
  53675. 5.0f);
  53676. g.fillPath (indent);
  53677. }
  53678. else
  53679. {
  53680. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53681. const float iw = sliderRadius;
  53682. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53683. gradCol2, ix + iw, 0.0f, false));
  53684. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53685. iw, height + sliderRadius,
  53686. 5.0f);
  53687. g.fillPath (indent);
  53688. }
  53689. g.setColour (Colour (0x4c000000));
  53690. g.strokePath (indent, PathStrokeType (0.5f));
  53691. }
  53692. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53693. int x, int y,
  53694. int width, int height,
  53695. float sliderPos,
  53696. float minSliderPos,
  53697. float maxSliderPos,
  53698. const Slider::SliderStyle style,
  53699. Slider& slider)
  53700. {
  53701. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53702. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53703. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53704. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53705. slider.isMouseButtonDown() && slider.isEnabled()));
  53706. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53707. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53708. {
  53709. float kx, ky;
  53710. if (style == Slider::LinearVertical)
  53711. {
  53712. kx = x + width * 0.5f;
  53713. ky = sliderPos;
  53714. }
  53715. else
  53716. {
  53717. kx = sliderPos;
  53718. ky = y + height * 0.5f;
  53719. }
  53720. drawGlassSphere (g,
  53721. kx - sliderRadius,
  53722. ky - sliderRadius,
  53723. sliderRadius * 2.0f,
  53724. knobColour, outlineThickness);
  53725. }
  53726. else
  53727. {
  53728. if (style == Slider::ThreeValueVertical)
  53729. {
  53730. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53731. sliderPos - sliderRadius,
  53732. sliderRadius * 2.0f,
  53733. knobColour, outlineThickness);
  53734. }
  53735. else if (style == Slider::ThreeValueHorizontal)
  53736. {
  53737. drawGlassSphere (g,sliderPos - sliderRadius,
  53738. y + height * 0.5f - sliderRadius,
  53739. sliderRadius * 2.0f,
  53740. knobColour, outlineThickness);
  53741. }
  53742. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53743. {
  53744. const float sr = jmin (sliderRadius, width * 0.4f);
  53745. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53746. minSliderPos - sliderRadius,
  53747. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53748. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53749. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53750. }
  53751. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53752. {
  53753. const float sr = jmin (sliderRadius, height * 0.4f);
  53754. drawGlassPointer (g, minSliderPos - sr,
  53755. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53756. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53757. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53758. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53759. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53760. }
  53761. }
  53762. }
  53763. void LookAndFeel::drawLinearSlider (Graphics& g,
  53764. int x, int y,
  53765. int width, int height,
  53766. float sliderPos,
  53767. float minSliderPos,
  53768. float maxSliderPos,
  53769. const Slider::SliderStyle style,
  53770. Slider& slider)
  53771. {
  53772. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53773. if (style == Slider::LinearBar)
  53774. {
  53775. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53776. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53777. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53778. false,
  53779. isMouseOver,
  53780. isMouseOver || slider.isMouseButtonDown()));
  53781. drawShinyButtonShape (g,
  53782. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53783. baseColour,
  53784. slider.isEnabled() ? 0.9f : 0.3f,
  53785. true, true, true, true);
  53786. }
  53787. else
  53788. {
  53789. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53790. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53791. }
  53792. }
  53793. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53794. {
  53795. return jmin (7,
  53796. slider.getHeight() / 2,
  53797. slider.getWidth() / 2) + 2;
  53798. }
  53799. void LookAndFeel::drawRotarySlider (Graphics& g,
  53800. int x, int y,
  53801. int width, int height,
  53802. float sliderPos,
  53803. const float rotaryStartAngle,
  53804. const float rotaryEndAngle,
  53805. Slider& slider)
  53806. {
  53807. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53808. const float centreX = x + width * 0.5f;
  53809. const float centreY = y + height * 0.5f;
  53810. const float rx = centreX - radius;
  53811. const float ry = centreY - radius;
  53812. const float rw = radius * 2.0f;
  53813. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53814. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53815. if (radius > 12.0f)
  53816. {
  53817. if (slider.isEnabled())
  53818. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53819. else
  53820. g.setColour (Colour (0x80808080));
  53821. const float thickness = 0.7f;
  53822. {
  53823. Path filledArc;
  53824. filledArc.addPieSegment (rx, ry, rw, rw,
  53825. rotaryStartAngle,
  53826. angle,
  53827. thickness);
  53828. g.fillPath (filledArc);
  53829. }
  53830. if (thickness > 0)
  53831. {
  53832. const float innerRadius = radius * 0.2f;
  53833. Path p;
  53834. p.addTriangle (-innerRadius, 0.0f,
  53835. 0.0f, -radius * thickness * 1.1f,
  53836. innerRadius, 0.0f);
  53837. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53838. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53839. }
  53840. if (slider.isEnabled())
  53841. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53842. else
  53843. g.setColour (Colour (0x80808080));
  53844. Path outlineArc;
  53845. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53846. outlineArc.closeSubPath();
  53847. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53848. }
  53849. else
  53850. {
  53851. if (slider.isEnabled())
  53852. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53853. else
  53854. g.setColour (Colour (0x80808080));
  53855. Path p;
  53856. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53857. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53858. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53859. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53860. }
  53861. }
  53862. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53863. {
  53864. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53865. }
  53866. class SliderLabelComp : public Label
  53867. {
  53868. public:
  53869. SliderLabelComp() : Label (String::empty, String::empty) {}
  53870. ~SliderLabelComp() {}
  53871. void mouseWheelMove (const MouseEvent&, float, float) {}
  53872. };
  53873. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53874. {
  53875. Label* const l = new SliderLabelComp();
  53876. l->setJustificationType (Justification::centred);
  53877. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53878. l->setColour (Label::backgroundColourId,
  53879. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53880. : slider.findColour (Slider::textBoxBackgroundColourId));
  53881. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53882. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53883. l->setColour (TextEditor::backgroundColourId,
  53884. slider.findColour (Slider::textBoxBackgroundColourId)
  53885. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53886. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53887. return l;
  53888. }
  53889. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53890. {
  53891. return 0;
  53892. }
  53893. static const TextLayout layoutTooltipText (const String& text) throw()
  53894. {
  53895. const float tooltipFontSize = 12.0f;
  53896. const int maxToolTipWidth = 400;
  53897. const Font f (tooltipFontSize, Font::bold);
  53898. TextLayout tl (text, f);
  53899. tl.layout (maxToolTipWidth, Justification::left, true);
  53900. return tl;
  53901. }
  53902. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53903. {
  53904. const TextLayout tl (layoutTooltipText (tipText));
  53905. width = tl.getWidth() + 14;
  53906. height = tl.getHeight() + 6;
  53907. }
  53908. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53909. {
  53910. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53911. const Colour textCol (findColour (TooltipWindow::textColourId));
  53912. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53913. g.setColour (findColour (TooltipWindow::outlineColourId));
  53914. g.drawRect (0, 0, width, height, 1);
  53915. #endif
  53916. const TextLayout tl (layoutTooltipText (text));
  53917. g.setColour (findColour (TooltipWindow::textColourId));
  53918. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53919. }
  53920. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53921. {
  53922. return new TextButton (text, TRANS("click to browse for a different file"));
  53923. }
  53924. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53925. ComboBox* filenameBox,
  53926. Button* browseButton)
  53927. {
  53928. browseButton->setSize (80, filenameComp.getHeight());
  53929. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53930. if (tb != 0)
  53931. tb->changeWidthToFitText();
  53932. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53933. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53934. }
  53935. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53936. int imageX, int imageY, int imageW, int imageH,
  53937. const Colour& overlayColour,
  53938. float imageOpacity,
  53939. ImageButton& button)
  53940. {
  53941. if (! button.isEnabled())
  53942. imageOpacity *= 0.3f;
  53943. if (! overlayColour.isOpaque())
  53944. {
  53945. g.setOpacity (imageOpacity);
  53946. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53947. 0, 0, image->getWidth(), image->getHeight(), false);
  53948. }
  53949. if (! overlayColour.isTransparent())
  53950. {
  53951. g.setColour (overlayColour);
  53952. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53953. 0, 0, image->getWidth(), image->getHeight(), true);
  53954. }
  53955. }
  53956. void LookAndFeel::drawCornerResizer (Graphics& g,
  53957. int w, int h,
  53958. bool /*isMouseOver*/,
  53959. bool /*isMouseDragging*/)
  53960. {
  53961. const float lineThickness = jmin (w, h) * 0.075f;
  53962. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53963. {
  53964. g.setColour (Colours::lightgrey);
  53965. g.drawLine (w * i,
  53966. h + 1.0f,
  53967. w + 1.0f,
  53968. h * i,
  53969. lineThickness);
  53970. g.setColour (Colours::darkgrey);
  53971. g.drawLine (w * i + lineThickness,
  53972. h + 1.0f,
  53973. w + 1.0f,
  53974. h * i + lineThickness,
  53975. lineThickness);
  53976. }
  53977. }
  53978. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  53979. const BorderSize& /*borders*/)
  53980. {
  53981. }
  53982. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53983. const BorderSize& /*border*/, ResizableWindow& window)
  53984. {
  53985. g.fillAll (window.getBackgroundColour());
  53986. }
  53987. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  53988. const BorderSize& border, ResizableWindow&)
  53989. {
  53990. g.setColour (Colour (0x80000000));
  53991. g.drawRect (0, 0, w, h);
  53992. g.setColour (Colour (0x19000000));
  53993. g.drawRect (border.getLeft() - 1,
  53994. border.getTop() - 1,
  53995. w + 2 - border.getLeftAndRight(),
  53996. h + 2 - border.getTopAndBottom());
  53997. }
  53998. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53999. Graphics& g, int w, int h,
  54000. int titleSpaceX, int titleSpaceW,
  54001. const Image* icon,
  54002. bool drawTitleTextOnLeft)
  54003. {
  54004. const bool isActive = window.isActiveWindow();
  54005. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  54006. 0.0f, 0.0f,
  54007. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  54008. 0.0f, (float) h, false));
  54009. g.fillAll();
  54010. Font font (h * 0.65f, Font::bold);
  54011. g.setFont (font);
  54012. int textW = font.getStringWidth (window.getName());
  54013. int iconW = 0;
  54014. int iconH = 0;
  54015. if (icon != 0)
  54016. {
  54017. iconH = (int) font.getHeight();
  54018. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  54019. }
  54020. textW = jmin (titleSpaceW, textW + iconW);
  54021. int textX = drawTitleTextOnLeft ? titleSpaceX
  54022. : jmax (titleSpaceX, (w - textW) / 2);
  54023. if (textX + textW > titleSpaceX + titleSpaceW)
  54024. textX = titleSpaceX + titleSpaceW - textW;
  54025. if (icon != 0)
  54026. {
  54027. g.setOpacity (isActive ? 1.0f : 0.6f);
  54028. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  54029. RectanglePlacement::centred, false);
  54030. textX += iconW;
  54031. textW -= iconW;
  54032. }
  54033. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  54034. g.setColour (findColour (DocumentWindow::textColourId));
  54035. else
  54036. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  54037. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  54038. }
  54039. class GlassWindowButton : public Button
  54040. {
  54041. public:
  54042. GlassWindowButton (const String& name, const Colour& col,
  54043. const Path& normalShape_,
  54044. const Path& toggledShape_) throw()
  54045. : Button (name),
  54046. colour (col),
  54047. normalShape (normalShape_),
  54048. toggledShape (toggledShape_)
  54049. {
  54050. }
  54051. ~GlassWindowButton()
  54052. {
  54053. }
  54054. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  54055. {
  54056. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  54057. if (! isEnabled())
  54058. alpha *= 0.5f;
  54059. float x = 0, y = 0, diam;
  54060. if (getWidth() < getHeight())
  54061. {
  54062. diam = (float) getWidth();
  54063. y = (getHeight() - getWidth()) * 0.5f;
  54064. }
  54065. else
  54066. {
  54067. diam = (float) getHeight();
  54068. y = (getWidth() - getHeight()) * 0.5f;
  54069. }
  54070. x += diam * 0.05f;
  54071. y += diam * 0.05f;
  54072. diam *= 0.9f;
  54073. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  54074. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  54075. g.fillEllipse (x, y, diam, diam);
  54076. x += 2.0f;
  54077. y += 2.0f;
  54078. diam -= 4.0f;
  54079. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  54080. Path& p = getToggleState() ? toggledShape : normalShape;
  54081. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  54082. diam * 0.4f, diam * 0.4f, true));
  54083. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  54084. g.fillPath (p, t);
  54085. }
  54086. juce_UseDebuggingNewOperator
  54087. private:
  54088. Colour colour;
  54089. Path normalShape, toggledShape;
  54090. GlassWindowButton (const GlassWindowButton&);
  54091. GlassWindowButton& operator= (const GlassWindowButton&);
  54092. };
  54093. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  54094. {
  54095. Path shape;
  54096. const float crossThickness = 0.25f;
  54097. if (buttonType == DocumentWindow::closeButton)
  54098. {
  54099. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  54100. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  54101. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  54102. }
  54103. else if (buttonType == DocumentWindow::minimiseButton)
  54104. {
  54105. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  54106. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  54107. }
  54108. else if (buttonType == DocumentWindow::maximiseButton)
  54109. {
  54110. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  54111. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  54112. Path fullscreenShape;
  54113. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  54114. fullscreenShape.lineTo (0.0f, 100.0f);
  54115. fullscreenShape.lineTo (0.0f, 0.0f);
  54116. fullscreenShape.lineTo (100.0f, 0.0f);
  54117. fullscreenShape.lineTo (100.0f, 45.0f);
  54118. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  54119. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  54120. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  54121. }
  54122. jassertfalse;
  54123. return 0;
  54124. }
  54125. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54126. int titleBarX,
  54127. int titleBarY,
  54128. int titleBarW,
  54129. int titleBarH,
  54130. Button* minimiseButton,
  54131. Button* maximiseButton,
  54132. Button* closeButton,
  54133. bool positionTitleBarButtonsOnLeft)
  54134. {
  54135. const int buttonW = titleBarH - titleBarH / 8;
  54136. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54137. : titleBarX + titleBarW - buttonW - buttonW / 4;
  54138. if (closeButton != 0)
  54139. {
  54140. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54141. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  54142. }
  54143. if (positionTitleBarButtonsOnLeft)
  54144. swapVariables (minimiseButton, maximiseButton);
  54145. if (maximiseButton != 0)
  54146. {
  54147. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54148. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54149. }
  54150. if (minimiseButton != 0)
  54151. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54152. }
  54153. int LookAndFeel::getDefaultMenuBarHeight()
  54154. {
  54155. return 24;
  54156. }
  54157. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  54158. {
  54159. return new DropShadower (0.4f, 1, 5, 10);
  54160. }
  54161. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  54162. int w, int h,
  54163. bool /*isVerticalBar*/,
  54164. bool isMouseOver,
  54165. bool isMouseDragging)
  54166. {
  54167. float alpha = 0.5f;
  54168. if (isMouseOver || isMouseDragging)
  54169. {
  54170. g.fillAll (Colour (0x190000ff));
  54171. alpha = 1.0f;
  54172. }
  54173. const float cx = w * 0.5f;
  54174. const float cy = h * 0.5f;
  54175. const float cr = jmin (w, h) * 0.4f;
  54176. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  54177. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  54178. true));
  54179. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  54180. }
  54181. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  54182. const String& text,
  54183. const Justification& position,
  54184. GroupComponent& group)
  54185. {
  54186. const float textH = 15.0f;
  54187. const float indent = 3.0f;
  54188. const float textEdgeGap = 4.0f;
  54189. float cs = 5.0f;
  54190. Font f (textH);
  54191. Path p;
  54192. float x = indent;
  54193. float y = f.getAscent() - 3.0f;
  54194. float w = jmax (0.0f, width - x * 2.0f);
  54195. float h = jmax (0.0f, height - y - indent);
  54196. cs = jmin (cs, w * 0.5f, h * 0.5f);
  54197. const float cs2 = 2.0f * cs;
  54198. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  54199. float textX = cs + textEdgeGap;
  54200. if (position.testFlags (Justification::horizontallyCentred))
  54201. textX = cs + (w - cs2 - textW) * 0.5f;
  54202. else if (position.testFlags (Justification::right))
  54203. textX = w - cs - textW - textEdgeGap;
  54204. p.startNewSubPath (x + textX + textW, y);
  54205. p.lineTo (x + w - cs, y);
  54206. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  54207. p.lineTo (x + w, y + h - cs);
  54208. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54209. p.lineTo (x + cs, y + h);
  54210. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54211. p.lineTo (x, y + cs);
  54212. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54213. p.lineTo (x + textX, y);
  54214. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  54215. g.setColour (group.findColour (GroupComponent::outlineColourId)
  54216. .withMultipliedAlpha (alpha));
  54217. g.strokePath (p, PathStrokeType (2.0f));
  54218. g.setColour (group.findColour (GroupComponent::textColourId)
  54219. .withMultipliedAlpha (alpha));
  54220. g.setFont (f);
  54221. g.drawText (text,
  54222. roundToInt (x + textX), 0,
  54223. roundToInt (textW),
  54224. roundToInt (textH),
  54225. Justification::centred, true);
  54226. }
  54227. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  54228. {
  54229. return 1 + tabDepth / 3;
  54230. }
  54231. int LookAndFeel::getTabButtonSpaceAroundImage()
  54232. {
  54233. return 4;
  54234. }
  54235. void LookAndFeel::createTabButtonShape (Path& p,
  54236. int width, int height,
  54237. int /*tabIndex*/,
  54238. const String& /*text*/,
  54239. Button& /*button*/,
  54240. TabbedButtonBar::Orientation orientation,
  54241. const bool /*isMouseOver*/,
  54242. const bool /*isMouseDown*/,
  54243. const bool /*isFrontTab*/)
  54244. {
  54245. const float w = (float) width;
  54246. const float h = (float) height;
  54247. float length = w;
  54248. float depth = h;
  54249. if (orientation == TabbedButtonBar::TabsAtLeft
  54250. || orientation == TabbedButtonBar::TabsAtRight)
  54251. {
  54252. swapVariables (length, depth);
  54253. }
  54254. const float indent = (float) getTabButtonOverlap ((int) depth);
  54255. const float overhang = 4.0f;
  54256. if (orientation == TabbedButtonBar::TabsAtLeft)
  54257. {
  54258. p.startNewSubPath (w, 0.0f);
  54259. p.lineTo (0.0f, indent);
  54260. p.lineTo (0.0f, h - indent);
  54261. p.lineTo (w, h);
  54262. p.lineTo (w + overhang, h + overhang);
  54263. p.lineTo (w + overhang, -overhang);
  54264. }
  54265. else if (orientation == TabbedButtonBar::TabsAtRight)
  54266. {
  54267. p.startNewSubPath (0.0f, 0.0f);
  54268. p.lineTo (w, indent);
  54269. p.lineTo (w, h - indent);
  54270. p.lineTo (0.0f, h);
  54271. p.lineTo (-overhang, h + overhang);
  54272. p.lineTo (-overhang, -overhang);
  54273. }
  54274. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54275. {
  54276. p.startNewSubPath (0.0f, 0.0f);
  54277. p.lineTo (indent, h);
  54278. p.lineTo (w - indent, h);
  54279. p.lineTo (w, 0.0f);
  54280. p.lineTo (w + overhang, -overhang);
  54281. p.lineTo (-overhang, -overhang);
  54282. }
  54283. else
  54284. {
  54285. p.startNewSubPath (0.0f, h);
  54286. p.lineTo (indent, 0.0f);
  54287. p.lineTo (w - indent, 0.0f);
  54288. p.lineTo (w, h);
  54289. p.lineTo (w + overhang, h + overhang);
  54290. p.lineTo (-overhang, h + overhang);
  54291. }
  54292. p.closeSubPath();
  54293. p = p.createPathWithRoundedCorners (3.0f);
  54294. }
  54295. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54296. const Path& path,
  54297. const Colour& preferredColour,
  54298. int /*tabIndex*/,
  54299. const String& /*text*/,
  54300. Button& button,
  54301. TabbedButtonBar::Orientation /*orientation*/,
  54302. const bool /*isMouseOver*/,
  54303. const bool /*isMouseDown*/,
  54304. const bool isFrontTab)
  54305. {
  54306. g.setColour (isFrontTab ? preferredColour
  54307. : preferredColour.withMultipliedAlpha (0.9f));
  54308. g.fillPath (path);
  54309. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54310. : TabbedButtonBar::tabOutlineColourId, false)
  54311. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54312. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54313. }
  54314. void LookAndFeel::drawTabButtonText (Graphics& g,
  54315. int x, int y, int w, int h,
  54316. const Colour& preferredBackgroundColour,
  54317. int /*tabIndex*/,
  54318. const String& text,
  54319. Button& button,
  54320. TabbedButtonBar::Orientation orientation,
  54321. const bool isMouseOver,
  54322. const bool isMouseDown,
  54323. const bool isFrontTab)
  54324. {
  54325. int length = w;
  54326. int depth = h;
  54327. if (orientation == TabbedButtonBar::TabsAtLeft
  54328. || orientation == TabbedButtonBar::TabsAtRight)
  54329. {
  54330. swapVariables (length, depth);
  54331. }
  54332. Font font (depth * 0.6f);
  54333. font.setUnderline (button.hasKeyboardFocus (false));
  54334. GlyphArrangement textLayout;
  54335. textLayout.addFittedText (font, text.trim(),
  54336. 0.0f, 0.0f, (float) length, (float) depth,
  54337. Justification::centred,
  54338. jmax (1, depth / 12));
  54339. AffineTransform transform;
  54340. if (orientation == TabbedButtonBar::TabsAtLeft)
  54341. {
  54342. transform = transform.rotated (float_Pi * -0.5f)
  54343. .translated ((float) x, (float) (y + h));
  54344. }
  54345. else if (orientation == TabbedButtonBar::TabsAtRight)
  54346. {
  54347. transform = transform.rotated (float_Pi * 0.5f)
  54348. .translated ((float) (x + w), (float) y);
  54349. }
  54350. else
  54351. {
  54352. transform = transform.translated ((float) x, (float) y);
  54353. }
  54354. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54355. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54356. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54357. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54358. else
  54359. g.setColour (preferredBackgroundColour.contrasting());
  54360. if (! (isMouseOver || isMouseDown))
  54361. g.setOpacity (0.8f);
  54362. if (! button.isEnabled())
  54363. g.setOpacity (0.3f);
  54364. textLayout.draw (g, transform);
  54365. }
  54366. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54367. const String& text,
  54368. int tabDepth,
  54369. Button&)
  54370. {
  54371. Font f (tabDepth * 0.6f);
  54372. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54373. }
  54374. void LookAndFeel::drawTabButton (Graphics& g,
  54375. int w, int h,
  54376. const Colour& preferredColour,
  54377. int tabIndex,
  54378. const String& text,
  54379. Button& button,
  54380. TabbedButtonBar::Orientation orientation,
  54381. const bool isMouseOver,
  54382. const bool isMouseDown,
  54383. const bool isFrontTab)
  54384. {
  54385. int length = w;
  54386. int depth = h;
  54387. if (orientation == TabbedButtonBar::TabsAtLeft
  54388. || orientation == TabbedButtonBar::TabsAtRight)
  54389. {
  54390. swapVariables (length, depth);
  54391. }
  54392. Path tabShape;
  54393. createTabButtonShape (tabShape, w, h,
  54394. tabIndex, text, button, orientation,
  54395. isMouseOver, isMouseDown, isFrontTab);
  54396. fillTabButtonShape (g, tabShape, preferredColour,
  54397. tabIndex, text, button, orientation,
  54398. isMouseOver, isMouseDown, isFrontTab);
  54399. const int indent = getTabButtonOverlap (depth);
  54400. int x = 0, y = 0;
  54401. if (orientation == TabbedButtonBar::TabsAtLeft
  54402. || orientation == TabbedButtonBar::TabsAtRight)
  54403. {
  54404. y += indent;
  54405. h -= indent * 2;
  54406. }
  54407. else
  54408. {
  54409. x += indent;
  54410. w -= indent * 2;
  54411. }
  54412. drawTabButtonText (g, x, y, w, h, preferredColour,
  54413. tabIndex, text, button, orientation,
  54414. isMouseOver, isMouseDown, isFrontTab);
  54415. }
  54416. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54417. int w, int h,
  54418. TabbedButtonBar& tabBar,
  54419. TabbedButtonBar::Orientation orientation)
  54420. {
  54421. const float shadowSize = 0.2f;
  54422. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54423. Rectangle<int> shadowRect;
  54424. if (orientation == TabbedButtonBar::TabsAtLeft)
  54425. {
  54426. x1 = (float) w;
  54427. x2 = w * (1.0f - shadowSize);
  54428. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54429. }
  54430. else if (orientation == TabbedButtonBar::TabsAtRight)
  54431. {
  54432. x2 = w * shadowSize;
  54433. shadowRect.setBounds (0, 0, (int) x2, h);
  54434. }
  54435. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54436. {
  54437. y2 = h * shadowSize;
  54438. shadowRect.setBounds (0, 0, w, (int) y2);
  54439. }
  54440. else
  54441. {
  54442. y1 = (float) h;
  54443. y2 = h * (1.0f - shadowSize);
  54444. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54445. }
  54446. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54447. Colours::transparentBlack, x2, y2, false));
  54448. shadowRect.expand (2, 2);
  54449. g.fillRect (shadowRect);
  54450. g.setColour (Colour (0x80000000));
  54451. if (orientation == TabbedButtonBar::TabsAtLeft)
  54452. {
  54453. g.fillRect (w - 1, 0, 1, h);
  54454. }
  54455. else if (orientation == TabbedButtonBar::TabsAtRight)
  54456. {
  54457. g.fillRect (0, 0, 1, h);
  54458. }
  54459. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54460. {
  54461. g.fillRect (0, 0, w, 1);
  54462. }
  54463. else
  54464. {
  54465. g.fillRect (0, h - 1, w, 1);
  54466. }
  54467. }
  54468. Button* LookAndFeel::createTabBarExtrasButton()
  54469. {
  54470. const float thickness = 7.0f;
  54471. const float indent = 22.0f;
  54472. Path p;
  54473. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54474. DrawablePath ellipse;
  54475. ellipse.setPath (p);
  54476. ellipse.setFill (Colour (0x99ffffff));
  54477. p.clear();
  54478. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54479. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54480. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54481. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54482. p.setUsingNonZeroWinding (false);
  54483. DrawablePath dp;
  54484. dp.setPath (p);
  54485. dp.setFill (Colour (0x59000000));
  54486. DrawableComposite normalImage;
  54487. normalImage.insertDrawable (ellipse);
  54488. normalImage.insertDrawable (dp);
  54489. dp.setFill (Colour (0xcc000000));
  54490. DrawableComposite overImage;
  54491. overImage.insertDrawable (ellipse);
  54492. overImage.insertDrawable (dp);
  54493. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54494. db->setImages (&normalImage, &overImage, 0);
  54495. return db;
  54496. }
  54497. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54498. {
  54499. g.fillAll (Colours::white);
  54500. const int w = header.getWidth();
  54501. const int h = header.getHeight();
  54502. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54503. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54504. false));
  54505. g.fillRect (0, h / 2, w, h);
  54506. g.setColour (Colour (0x33000000));
  54507. g.fillRect (0, h - 1, w, 1);
  54508. for (int i = header.getNumColumns (true); --i >= 0;)
  54509. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54510. }
  54511. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54512. int width, int height,
  54513. bool isMouseOver, bool isMouseDown,
  54514. int columnFlags)
  54515. {
  54516. if (isMouseDown)
  54517. g.fillAll (Colour (0x8899aadd));
  54518. else if (isMouseOver)
  54519. g.fillAll (Colour (0x5599aadd));
  54520. int rightOfText = width - 4;
  54521. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54522. {
  54523. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54524. const float bottom = height - top;
  54525. const float w = height * 0.5f;
  54526. const float x = rightOfText - (w * 1.25f);
  54527. rightOfText = (int) x;
  54528. Path sortArrow;
  54529. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54530. g.setColour (Colour (0x99000000));
  54531. g.fillPath (sortArrow);
  54532. }
  54533. g.setColour (Colours::black);
  54534. g.setFont (height * 0.5f, Font::bold);
  54535. const int textX = 4;
  54536. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54537. }
  54538. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54539. {
  54540. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54541. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54542. background.darker (0.1f),
  54543. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54544. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54545. false));
  54546. g.fillAll();
  54547. }
  54548. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54549. {
  54550. return createTabBarExtrasButton();
  54551. }
  54552. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54553. bool isMouseOver, bool isMouseDown,
  54554. ToolbarItemComponent& component)
  54555. {
  54556. if (isMouseDown)
  54557. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54558. else if (isMouseOver)
  54559. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54560. }
  54561. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54562. const String& text, ToolbarItemComponent& component)
  54563. {
  54564. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54565. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54566. const float fontHeight = jmin (14.0f, height * 0.85f);
  54567. g.setFont (fontHeight);
  54568. g.drawFittedText (text,
  54569. x, y, width, height,
  54570. Justification::centred,
  54571. jmax (1, height / (int) fontHeight));
  54572. }
  54573. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54574. bool isOpen, int width, int height)
  54575. {
  54576. const int buttonSize = (height * 3) / 4;
  54577. const int buttonIndent = (height - buttonSize) / 2;
  54578. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54579. const int textX = buttonIndent * 2 + buttonSize + 2;
  54580. g.setColour (Colours::black);
  54581. g.setFont (height * 0.7f, Font::bold);
  54582. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54583. }
  54584. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54585. PropertyComponent&)
  54586. {
  54587. g.setColour (Colour (0x66ffffff));
  54588. g.fillRect (0, 0, width, height - 1);
  54589. }
  54590. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54591. PropertyComponent& component)
  54592. {
  54593. g.setColour (Colours::black);
  54594. if (! component.isEnabled())
  54595. g.setOpacity (0.6f);
  54596. g.setFont (jmin (height, 24) * 0.65f);
  54597. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54598. g.drawFittedText (component.getName(),
  54599. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54600. Justification::centredLeft, 2);
  54601. }
  54602. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54603. {
  54604. return Rectangle<int> (component.getWidth() / 3, 1,
  54605. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54606. }
  54607. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54608. {
  54609. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54610. {
  54611. Graphics g2 (content);
  54612. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54613. g2.fillPath (path);
  54614. g2.setColour (Colours::white.withAlpha (0.8f));
  54615. g2.strokePath (path, PathStrokeType (2.0f));
  54616. }
  54617. DropShadowEffect shadow;
  54618. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54619. shadow.applyEffect (content, g);
  54620. }
  54621. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54622. const String& instructions,
  54623. GlyphArrangement& text,
  54624. int width)
  54625. {
  54626. text.clear();
  54627. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54628. 8.0f, 22.0f, width - 16.0f,
  54629. Justification::centred);
  54630. text.addJustifiedText (Font (14.0f), instructions,
  54631. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54632. Justification::centred);
  54633. }
  54634. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54635. const String& filename, Image* icon,
  54636. const String& fileSizeDescription,
  54637. const String& fileTimeDescription,
  54638. const bool isDirectory,
  54639. const bool isItemSelected,
  54640. const int /*itemIndex*/)
  54641. {
  54642. if (isItemSelected)
  54643. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54644. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54645. g.setFont (height * 0.7f);
  54646. Image im;
  54647. if (icon != 0)
  54648. im = *icon;
  54649. if (im.isNull())
  54650. im = isDirectory ? getDefaultFolderImage()
  54651. : getDefaultDocumentFileImage();
  54652. const int x = 32;
  54653. if (im.isValid())
  54654. {
  54655. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54656. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54657. false);
  54658. }
  54659. if (width > 450 && ! isDirectory)
  54660. {
  54661. const int sizeX = roundToInt (width * 0.7f);
  54662. const int dateX = roundToInt (width * 0.8f);
  54663. g.drawFittedText (filename,
  54664. x, 0, sizeX - x, height,
  54665. Justification::centredLeft, 1);
  54666. g.setFont (height * 0.5f);
  54667. g.setColour (Colours::darkgrey);
  54668. if (! isDirectory)
  54669. {
  54670. g.drawFittedText (fileSizeDescription,
  54671. sizeX, 0, dateX - sizeX - 8, height,
  54672. Justification::centredRight, 1);
  54673. g.drawFittedText (fileTimeDescription,
  54674. dateX, 0, width - 8 - dateX, height,
  54675. Justification::centredRight, 1);
  54676. }
  54677. }
  54678. else
  54679. {
  54680. g.drawFittedText (filename,
  54681. x, 0, width - x, height,
  54682. Justification::centredLeft, 1);
  54683. }
  54684. }
  54685. Button* LookAndFeel::createFileBrowserGoUpButton()
  54686. {
  54687. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54688. Path arrowPath;
  54689. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54690. DrawablePath arrowImage;
  54691. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54692. arrowImage.setPath (arrowPath);
  54693. goUpButton->setImages (&arrowImage);
  54694. return goUpButton;
  54695. }
  54696. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54697. DirectoryContentsDisplayComponent* fileListComponent,
  54698. FilePreviewComponent* previewComp,
  54699. ComboBox* currentPathBox,
  54700. TextEditor* filenameBox,
  54701. Button* goUpButton)
  54702. {
  54703. const int x = 8;
  54704. int w = browserComp.getWidth() - x - x;
  54705. if (previewComp != 0)
  54706. {
  54707. const int previewWidth = w / 3;
  54708. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54709. w -= previewWidth + 4;
  54710. }
  54711. int y = 4;
  54712. const int controlsHeight = 22;
  54713. const int bottomSectionHeight = controlsHeight + 8;
  54714. const int upButtonWidth = 50;
  54715. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54716. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54717. y += controlsHeight + 4;
  54718. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54719. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54720. y = listAsComp->getBottom() + 4;
  54721. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54722. }
  54723. const Image LookAndFeel::getDefaultFolderImage()
  54724. {
  54725. 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,
  54726. 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,
  54727. 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,
  54728. 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,
  54729. 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,
  54730. 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,
  54731. 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,
  54732. 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,
  54733. 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,
  54734. 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,
  54735. 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,
  54736. 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,
  54737. 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,
  54738. 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,
  54739. 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,
  54740. 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,
  54741. 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,
  54742. 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,
  54743. 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,
  54744. 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,
  54745. 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,
  54746. 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,
  54747. 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,
  54748. 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,
  54749. 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,
  54750. 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,
  54751. 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,
  54752. 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,
  54753. 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,
  54754. 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,
  54755. 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,
  54756. 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,
  54757. 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,
  54758. 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,
  54759. 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,
  54760. 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,
  54761. 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,
  54762. 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,
  54763. 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,
  54764. 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,
  54765. 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,
  54766. 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,
  54767. 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,
  54768. 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};
  54769. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54770. }
  54771. const Image LookAndFeel::getDefaultDocumentFileImage()
  54772. {
  54773. 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,
  54774. 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,
  54775. 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,
  54776. 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,
  54777. 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,
  54778. 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,
  54779. 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,
  54780. 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,
  54781. 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,
  54782. 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,
  54783. 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,
  54784. 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,
  54785. 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,
  54786. 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,
  54787. 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,
  54788. 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,
  54789. 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,
  54790. 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,
  54791. 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,
  54792. 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,
  54793. 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,
  54794. 174,66,96,130,0,0};
  54795. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54796. }
  54797. void LookAndFeel::playAlertSound()
  54798. {
  54799. PlatformUtilities::beep();
  54800. }
  54801. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54802. {
  54803. g.setColour (Colours::white.withAlpha (0.7f));
  54804. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54805. g.setColour (Colours::black.withAlpha (0.2f));
  54806. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54807. const int totalBlocks = 7;
  54808. const int numBlocks = roundToInt (totalBlocks * level);
  54809. const float w = (width - 6.0f) / (float) totalBlocks;
  54810. for (int i = 0; i < totalBlocks; ++i)
  54811. {
  54812. if (i >= numBlocks)
  54813. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54814. else
  54815. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54816. : Colours::red);
  54817. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54818. }
  54819. }
  54820. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54821. {
  54822. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54823. if (keyDescription.isNotEmpty())
  54824. {
  54825. if (button.isEnabled())
  54826. {
  54827. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54828. g.fillAll (textColour.withAlpha (alpha));
  54829. g.setOpacity (0.3f);
  54830. g.drawBevel (0, 0, width, height, 2);
  54831. }
  54832. g.setColour (textColour);
  54833. g.setFont (height * 0.6f);
  54834. g.drawFittedText (keyDescription,
  54835. 3, 0, width - 6, height,
  54836. Justification::centred, 1);
  54837. }
  54838. else
  54839. {
  54840. const float thickness = 7.0f;
  54841. const float indent = 22.0f;
  54842. Path p;
  54843. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54844. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54845. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54846. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54847. p.setUsingNonZeroWinding (false);
  54848. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54849. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54850. }
  54851. if (button.hasKeyboardFocus (false))
  54852. {
  54853. g.setColour (textColour.withAlpha (0.4f));
  54854. g.drawRect (0, 0, width, height);
  54855. }
  54856. }
  54857. static void createRoundedPath (Path& p,
  54858. const float x, const float y,
  54859. const float w, const float h,
  54860. const float cs,
  54861. const bool curveTopLeft, const bool curveTopRight,
  54862. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54863. {
  54864. const float cs2 = 2.0f * cs;
  54865. if (curveTopLeft)
  54866. {
  54867. p.startNewSubPath (x, y + cs);
  54868. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54869. }
  54870. else
  54871. {
  54872. p.startNewSubPath (x, y);
  54873. }
  54874. if (curveTopRight)
  54875. {
  54876. p.lineTo (x + w - cs, y);
  54877. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54878. }
  54879. else
  54880. {
  54881. p.lineTo (x + w, y);
  54882. }
  54883. if (curveBottomRight)
  54884. {
  54885. p.lineTo (x + w, y + h - cs);
  54886. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54887. }
  54888. else
  54889. {
  54890. p.lineTo (x + w, y + h);
  54891. }
  54892. if (curveBottomLeft)
  54893. {
  54894. p.lineTo (x + cs, y + h);
  54895. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54896. }
  54897. else
  54898. {
  54899. p.lineTo (x, y + h);
  54900. }
  54901. p.closeSubPath();
  54902. }
  54903. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54904. float x, float y, float w, float h,
  54905. float maxCornerSize,
  54906. const Colour& baseColour,
  54907. const float strokeWidth,
  54908. const bool flatOnLeft,
  54909. const bool flatOnRight,
  54910. const bool flatOnTop,
  54911. const bool flatOnBottom) throw()
  54912. {
  54913. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54914. return;
  54915. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54916. Path outline;
  54917. createRoundedPath (outline, x, y, w, h, cs,
  54918. ! (flatOnLeft || flatOnTop),
  54919. ! (flatOnRight || flatOnTop),
  54920. ! (flatOnLeft || flatOnBottom),
  54921. ! (flatOnRight || flatOnBottom));
  54922. ColourGradient cg (baseColour, 0.0f, y,
  54923. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54924. false);
  54925. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54926. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54927. g.setGradientFill (cg);
  54928. g.fillPath (outline);
  54929. g.setColour (Colour (0x80000000));
  54930. g.strokePath (outline, PathStrokeType (strokeWidth));
  54931. }
  54932. void LookAndFeel::drawGlassSphere (Graphics& g,
  54933. const float x, const float y,
  54934. const float diameter,
  54935. const Colour& colour,
  54936. const float outlineThickness) throw()
  54937. {
  54938. if (diameter <= outlineThickness)
  54939. return;
  54940. Path p;
  54941. p.addEllipse (x, y, diameter, diameter);
  54942. {
  54943. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54944. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54945. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54946. g.setGradientFill (cg);
  54947. g.fillPath (p);
  54948. }
  54949. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54950. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54951. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54952. ColourGradient cg (Colours::transparentBlack,
  54953. x + diameter * 0.5f, y + diameter * 0.5f,
  54954. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54955. x, y + diameter * 0.5f, true);
  54956. cg.addColour (0.7, Colours::transparentBlack);
  54957. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54958. g.setGradientFill (cg);
  54959. g.fillPath (p);
  54960. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54961. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54962. }
  54963. void LookAndFeel::drawGlassPointer (Graphics& g,
  54964. const float x, const float y,
  54965. const float diameter,
  54966. const Colour& colour, const float outlineThickness,
  54967. const int direction) throw()
  54968. {
  54969. if (diameter <= outlineThickness)
  54970. return;
  54971. Path p;
  54972. p.startNewSubPath (x + diameter * 0.5f, y);
  54973. p.lineTo (x + diameter, y + diameter * 0.6f);
  54974. p.lineTo (x + diameter, y + diameter);
  54975. p.lineTo (x, y + diameter);
  54976. p.lineTo (x, y + diameter * 0.6f);
  54977. p.closeSubPath();
  54978. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54979. {
  54980. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54981. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54982. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54983. g.setGradientFill (cg);
  54984. g.fillPath (p);
  54985. }
  54986. ColourGradient cg (Colours::transparentBlack,
  54987. x + diameter * 0.5f, y + diameter * 0.5f,
  54988. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54989. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54990. cg.addColour (0.5, Colours::transparentBlack);
  54991. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54992. g.setGradientFill (cg);
  54993. g.fillPath (p);
  54994. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54995. g.strokePath (p, PathStrokeType (outlineThickness));
  54996. }
  54997. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54998. const float x, const float y,
  54999. const float width, const float height,
  55000. const Colour& colour,
  55001. const float outlineThickness,
  55002. const float cornerSize,
  55003. const bool flatOnLeft,
  55004. const bool flatOnRight,
  55005. const bool flatOnTop,
  55006. const bool flatOnBottom) throw()
  55007. {
  55008. if (width <= outlineThickness || height <= outlineThickness)
  55009. return;
  55010. const int intX = (int) x;
  55011. const int intY = (int) y;
  55012. const int intW = (int) width;
  55013. const int intH = (int) height;
  55014. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  55015. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  55016. const int intEdge = (int) edgeBlurRadius;
  55017. Path outline;
  55018. createRoundedPath (outline, x, y, width, height, cs,
  55019. ! (flatOnLeft || flatOnTop),
  55020. ! (flatOnRight || flatOnTop),
  55021. ! (flatOnLeft || flatOnBottom),
  55022. ! (flatOnRight || flatOnBottom));
  55023. {
  55024. ColourGradient cg (colour.darker (0.2f), 0, y,
  55025. colour.darker (0.2f), 0, y + height, false);
  55026. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  55027. cg.addColour (0.4, colour);
  55028. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  55029. g.setGradientFill (cg);
  55030. g.fillPath (outline);
  55031. }
  55032. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  55033. colour.darker (0.2f), x, y + height * 0.5f, true);
  55034. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  55035. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  55036. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  55037. {
  55038. g.saveState();
  55039. g.setGradientFill (cg);
  55040. g.reduceClipRegion (intX, intY, intEdge, intH);
  55041. g.fillPath (outline);
  55042. g.restoreState();
  55043. }
  55044. if (! (flatOnRight || flatOnTop || flatOnBottom))
  55045. {
  55046. cg.point1.setX (x + width - edgeBlurRadius);
  55047. cg.point2.setX (x + width);
  55048. g.saveState();
  55049. g.setGradientFill (cg);
  55050. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  55051. g.fillPath (outline);
  55052. g.restoreState();
  55053. }
  55054. {
  55055. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  55056. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  55057. Path highlight;
  55058. createRoundedPath (highlight,
  55059. x + leftIndent,
  55060. y + cs * 0.1f,
  55061. width - (leftIndent + rightIndent),
  55062. height * 0.4f, cs * 0.4f,
  55063. ! (flatOnLeft || flatOnTop),
  55064. ! (flatOnRight || flatOnTop),
  55065. ! (flatOnLeft || flatOnBottom),
  55066. ! (flatOnRight || flatOnBottom));
  55067. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  55068. Colours::transparentWhite, 0, y + height * 0.4f, false));
  55069. g.fillPath (highlight);
  55070. }
  55071. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  55072. g.strokePath (outline, PathStrokeType (outlineThickness));
  55073. }
  55074. END_JUCE_NAMESPACE
  55075. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  55076. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55077. BEGIN_JUCE_NAMESPACE
  55078. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  55079. {
  55080. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  55081. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  55082. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  55083. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  55084. setColour (Slider::thumbColourId, Colours::white);
  55085. setColour (Slider::trackColourId, Colour (0x7f000000));
  55086. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  55087. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  55088. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  55089. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  55090. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  55091. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  55092. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  55093. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  55094. }
  55095. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  55096. {
  55097. }
  55098. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  55099. Button& button,
  55100. const Colour& backgroundColour,
  55101. bool isMouseOverButton,
  55102. bool isButtonDown)
  55103. {
  55104. const int width = button.getWidth();
  55105. const int height = button.getHeight();
  55106. const float indent = 2.0f;
  55107. const int cornerSize = jmin (roundToInt (width * 0.4f),
  55108. roundToInt (height * 0.4f));
  55109. Path p;
  55110. p.addRoundedRectangle (indent, indent,
  55111. width - indent * 2.0f,
  55112. height - indent * 2.0f,
  55113. (float) cornerSize);
  55114. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  55115. if (isMouseOverButton)
  55116. {
  55117. if (isButtonDown)
  55118. bc = bc.brighter();
  55119. else if (bc.getBrightness() > 0.5f)
  55120. bc = bc.darker (0.1f);
  55121. else
  55122. bc = bc.brighter (0.1f);
  55123. }
  55124. g.setColour (bc);
  55125. g.fillPath (p);
  55126. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  55127. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  55128. }
  55129. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  55130. Component& /*component*/,
  55131. float x, float y, float w, float h,
  55132. const bool ticked,
  55133. const bool isEnabled,
  55134. const bool /*isMouseOverButton*/,
  55135. const bool isButtonDown)
  55136. {
  55137. Path box;
  55138. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  55139. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  55140. : Colours::lightgrey.withAlpha (0.1f));
  55141. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  55142. g.fillPath (box, trans);
  55143. g.setColour (Colours::black.withAlpha (0.6f));
  55144. g.strokePath (box, PathStrokeType (0.9f), trans);
  55145. if (ticked)
  55146. {
  55147. Path tick;
  55148. tick.startNewSubPath (1.5f, 3.0f);
  55149. tick.lineTo (3.0f, 6.0f);
  55150. tick.lineTo (6.0f, 0.0f);
  55151. g.setColour (isEnabled ? Colours::black : Colours::grey);
  55152. g.strokePath (tick, PathStrokeType (2.5f), trans);
  55153. }
  55154. }
  55155. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  55156. ToggleButton& button,
  55157. bool isMouseOverButton,
  55158. bool isButtonDown)
  55159. {
  55160. if (button.hasKeyboardFocus (true))
  55161. {
  55162. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  55163. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  55164. }
  55165. const int tickWidth = jmin (20, button.getHeight() - 4);
  55166. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  55167. (float) tickWidth, (float) tickWidth,
  55168. button.getToggleState(),
  55169. button.isEnabled(),
  55170. isMouseOverButton,
  55171. isButtonDown);
  55172. g.setColour (button.findColour (ToggleButton::textColourId));
  55173. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  55174. if (! button.isEnabled())
  55175. g.setOpacity (0.5f);
  55176. const int textX = tickWidth + 5;
  55177. g.drawFittedText (button.getButtonText(),
  55178. textX, 4,
  55179. button.getWidth() - textX - 2, button.getHeight() - 8,
  55180. Justification::centredLeft, 10);
  55181. }
  55182. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  55183. int width, int height,
  55184. double progress, const String& textToShow)
  55185. {
  55186. if (progress < 0 || progress >= 1.0)
  55187. {
  55188. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  55189. }
  55190. else
  55191. {
  55192. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  55193. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  55194. g.fillAll (background);
  55195. g.setColour (foreground);
  55196. g.fillRect (1, 1,
  55197. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  55198. height - 2);
  55199. if (textToShow.isNotEmpty())
  55200. {
  55201. g.setColour (Colour::contrasting (background, foreground));
  55202. g.setFont (height * 0.6f);
  55203. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  55204. }
  55205. }
  55206. }
  55207. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  55208. ScrollBar& bar,
  55209. int width, int height,
  55210. int buttonDirection,
  55211. bool isScrollbarVertical,
  55212. bool isMouseOverButton,
  55213. bool isButtonDown)
  55214. {
  55215. if (isScrollbarVertical)
  55216. width -= 2;
  55217. else
  55218. height -= 2;
  55219. Path p;
  55220. if (buttonDirection == 0)
  55221. p.addTriangle (width * 0.5f, height * 0.2f,
  55222. width * 0.1f, height * 0.7f,
  55223. width * 0.9f, height * 0.7f);
  55224. else if (buttonDirection == 1)
  55225. p.addTriangle (width * 0.8f, height * 0.5f,
  55226. width * 0.3f, height * 0.1f,
  55227. width * 0.3f, height * 0.9f);
  55228. else if (buttonDirection == 2)
  55229. p.addTriangle (width * 0.5f, height * 0.8f,
  55230. width * 0.1f, height * 0.3f,
  55231. width * 0.9f, height * 0.3f);
  55232. else if (buttonDirection == 3)
  55233. p.addTriangle (width * 0.2f, height * 0.5f,
  55234. width * 0.7f, height * 0.1f,
  55235. width * 0.7f, height * 0.9f);
  55236. if (isButtonDown)
  55237. g.setColour (Colours::white);
  55238. else if (isMouseOverButton)
  55239. g.setColour (Colours::white.withAlpha (0.7f));
  55240. else
  55241. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  55242. g.fillPath (p);
  55243. g.setColour (Colours::black.withAlpha (0.5f));
  55244. g.strokePath (p, PathStrokeType (0.5f));
  55245. }
  55246. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  55247. ScrollBar& bar,
  55248. int x, int y,
  55249. int width, int height,
  55250. bool isScrollbarVertical,
  55251. int thumbStartPosition,
  55252. int thumbSize,
  55253. bool isMouseOver,
  55254. bool isMouseDown)
  55255. {
  55256. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  55257. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55258. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  55259. if (thumbSize > 0.0f)
  55260. {
  55261. Rectangle<int> thumb;
  55262. if (isScrollbarVertical)
  55263. {
  55264. width -= 2;
  55265. g.fillRect (x + roundToInt (width * 0.35f), y,
  55266. roundToInt (width * 0.3f), height);
  55267. thumb.setBounds (x + 1, thumbStartPosition,
  55268. width - 2, thumbSize);
  55269. }
  55270. else
  55271. {
  55272. height -= 2;
  55273. g.fillRect (x, y + roundToInt (height * 0.35f),
  55274. width, roundToInt (height * 0.3f));
  55275. thumb.setBounds (thumbStartPosition, y + 1,
  55276. thumbSize, height - 2);
  55277. }
  55278. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55279. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  55280. g.fillRect (thumb);
  55281. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  55282. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  55283. if (thumbSize > 16)
  55284. {
  55285. for (int i = 3; --i >= 0;)
  55286. {
  55287. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  55288. g.setColour (Colours::black.withAlpha (0.15f));
  55289. if (isScrollbarVertical)
  55290. {
  55291. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  55292. g.setColour (Colours::white.withAlpha (0.15f));
  55293. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55294. }
  55295. else
  55296. {
  55297. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55298. g.setColour (Colours::white.withAlpha (0.15f));
  55299. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55300. }
  55301. }
  55302. }
  55303. }
  55304. }
  55305. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55306. {
  55307. return &scrollbarShadow;
  55308. }
  55309. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55310. {
  55311. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55312. g.setColour (Colours::black.withAlpha (0.6f));
  55313. g.drawRect (0, 0, width, height);
  55314. }
  55315. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55316. bool, MenuBarComponent& menuBar)
  55317. {
  55318. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55319. }
  55320. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55321. {
  55322. if (textEditor.isEnabled())
  55323. {
  55324. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55325. g.drawRect (0, 0, width, height);
  55326. }
  55327. }
  55328. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55329. const bool isButtonDown,
  55330. int buttonX, int buttonY,
  55331. int buttonW, int buttonH,
  55332. ComboBox& box)
  55333. {
  55334. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55335. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55336. : ComboBox::backgroundColourId));
  55337. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55338. g.setColour (box.findColour (ComboBox::outlineColourId));
  55339. g.drawRect (0, 0, width, height);
  55340. const float arrowX = 0.2f;
  55341. const float arrowH = 0.3f;
  55342. if (box.isEnabled())
  55343. {
  55344. Path p;
  55345. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55346. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55347. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55348. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55349. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55350. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55351. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55352. : ComboBox::buttonColourId));
  55353. g.fillPath (p);
  55354. }
  55355. }
  55356. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55357. {
  55358. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55359. f.setHorizontalScale (0.9f);
  55360. return f;
  55361. }
  55362. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55363. {
  55364. Path p;
  55365. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55366. g.setColour (fill);
  55367. g.fillPath (p);
  55368. g.setColour (outline);
  55369. g.strokePath (p, PathStrokeType (0.3f));
  55370. }
  55371. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55372. int x, int y,
  55373. int w, int h,
  55374. float sliderPos,
  55375. float minSliderPos,
  55376. float maxSliderPos,
  55377. const Slider::SliderStyle style,
  55378. Slider& slider)
  55379. {
  55380. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55381. if (style == Slider::LinearBar)
  55382. {
  55383. g.setColour (slider.findColour (Slider::thumbColourId));
  55384. g.fillRect (x, y, (int) sliderPos - x, h);
  55385. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55386. g.drawRect (x, y, (int) sliderPos - x, h);
  55387. }
  55388. else
  55389. {
  55390. g.setColour (slider.findColour (Slider::trackColourId)
  55391. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55392. if (slider.isHorizontal())
  55393. {
  55394. g.fillRect (x, y + roundToInt (h * 0.6f),
  55395. w, roundToInt (h * 0.2f));
  55396. }
  55397. else
  55398. {
  55399. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55400. jmin (4, roundToInt (w * 0.2f)), h);
  55401. }
  55402. float alpha = 0.35f;
  55403. if (slider.isEnabled())
  55404. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55405. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55406. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55407. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55408. {
  55409. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55410. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55411. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55412. fill, outline);
  55413. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55414. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55415. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55416. fill, outline);
  55417. }
  55418. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55419. {
  55420. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55421. minSliderPos - 7.0f, y + h * 0.9f ,
  55422. minSliderPos, y + h * 0.9f,
  55423. fill, outline);
  55424. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55425. maxSliderPos, y + h * 0.9f,
  55426. maxSliderPos + 7.0f, y + h * 0.9f,
  55427. fill, outline);
  55428. }
  55429. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55430. {
  55431. drawTriangle (g, sliderPos, y + h * 0.9f,
  55432. sliderPos - 7.0f, y + h * 0.2f,
  55433. sliderPos + 7.0f, y + h * 0.2f,
  55434. fill, outline);
  55435. }
  55436. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55437. {
  55438. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55439. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55440. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55441. fill, outline);
  55442. }
  55443. }
  55444. }
  55445. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55446. {
  55447. if (isIncrement)
  55448. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55449. else
  55450. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55451. }
  55452. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55453. {
  55454. return &scrollbarShadow;
  55455. }
  55456. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55457. {
  55458. return 8;
  55459. }
  55460. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55461. int w, int h,
  55462. bool isMouseOver,
  55463. bool isMouseDragging)
  55464. {
  55465. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55466. : Colours::darkgrey);
  55467. const float lineThickness = jmin (w, h) * 0.1f;
  55468. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55469. {
  55470. g.drawLine (w * i,
  55471. h + 1.0f,
  55472. w + 1.0f,
  55473. h * i,
  55474. lineThickness);
  55475. }
  55476. }
  55477. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55478. {
  55479. Path shape;
  55480. if (buttonType == DocumentWindow::closeButton)
  55481. {
  55482. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55483. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55484. ShapeButton* const b = new ShapeButton ("close",
  55485. Colour (0x7fff3333),
  55486. Colour (0xd7ff3333),
  55487. Colour (0xf7ff3333));
  55488. b->setShape (shape, true, true, true);
  55489. return b;
  55490. }
  55491. else if (buttonType == DocumentWindow::minimiseButton)
  55492. {
  55493. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55494. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55495. DrawablePath dp;
  55496. dp.setPath (shape);
  55497. dp.setFill (Colours::black.withAlpha (0.3f));
  55498. b->setImages (&dp);
  55499. return b;
  55500. }
  55501. else if (buttonType == DocumentWindow::maximiseButton)
  55502. {
  55503. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55504. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55505. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55506. DrawablePath dp;
  55507. dp.setPath (shape);
  55508. dp.setFill (Colours::black.withAlpha (0.3f));
  55509. b->setImages (&dp);
  55510. return b;
  55511. }
  55512. jassertfalse;
  55513. return 0;
  55514. }
  55515. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55516. int titleBarX,
  55517. int titleBarY,
  55518. int titleBarW,
  55519. int titleBarH,
  55520. Button* minimiseButton,
  55521. Button* maximiseButton,
  55522. Button* closeButton,
  55523. bool positionTitleBarButtonsOnLeft)
  55524. {
  55525. titleBarY += titleBarH / 8;
  55526. titleBarH -= titleBarH / 4;
  55527. const int buttonW = titleBarH;
  55528. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55529. : titleBarX + titleBarW - buttonW - 4;
  55530. if (closeButton != 0)
  55531. {
  55532. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55533. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55534. : -(buttonW + buttonW / 5);
  55535. }
  55536. if (positionTitleBarButtonsOnLeft)
  55537. swapVariables (minimiseButton, maximiseButton);
  55538. if (maximiseButton != 0)
  55539. {
  55540. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55541. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55542. }
  55543. if (minimiseButton != 0)
  55544. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55545. }
  55546. END_JUCE_NAMESPACE
  55547. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55548. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55549. BEGIN_JUCE_NAMESPACE
  55550. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55551. : model (0),
  55552. itemUnderMouse (-1),
  55553. currentPopupIndex (-1),
  55554. topLevelIndexClicked (0),
  55555. lastMouseX (0),
  55556. lastMouseY (0)
  55557. {
  55558. setRepaintsOnMouseActivity (true);
  55559. setWantsKeyboardFocus (false);
  55560. setMouseClickGrabsKeyboardFocus (false);
  55561. setModel (model_);
  55562. }
  55563. MenuBarComponent::~MenuBarComponent()
  55564. {
  55565. setModel (0);
  55566. Desktop::getInstance().removeGlobalMouseListener (this);
  55567. }
  55568. MenuBarModel* MenuBarComponent::getModel() const throw()
  55569. {
  55570. return model;
  55571. }
  55572. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55573. {
  55574. if (model != newModel)
  55575. {
  55576. if (model != 0)
  55577. model->removeListener (this);
  55578. model = newModel;
  55579. if (model != 0)
  55580. model->addListener (this);
  55581. repaint();
  55582. menuBarItemsChanged (0);
  55583. }
  55584. }
  55585. void MenuBarComponent::paint (Graphics& g)
  55586. {
  55587. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55588. getLookAndFeel().drawMenuBarBackground (g,
  55589. getWidth(),
  55590. getHeight(),
  55591. isMouseOverBar,
  55592. *this);
  55593. if (model != 0)
  55594. {
  55595. for (int i = 0; i < menuNames.size(); ++i)
  55596. {
  55597. g.saveState();
  55598. g.setOrigin (xPositions [i], 0);
  55599. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55600. getLookAndFeel().drawMenuBarItem (g,
  55601. xPositions[i + 1] - xPositions[i],
  55602. getHeight(),
  55603. i,
  55604. menuNames[i],
  55605. i == itemUnderMouse,
  55606. i == currentPopupIndex,
  55607. isMouseOverBar,
  55608. *this);
  55609. g.restoreState();
  55610. }
  55611. }
  55612. }
  55613. void MenuBarComponent::resized()
  55614. {
  55615. xPositions.clear();
  55616. int x = 2;
  55617. xPositions.add (x);
  55618. for (int i = 0; i < menuNames.size(); ++i)
  55619. {
  55620. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55621. xPositions.add (x);
  55622. }
  55623. }
  55624. int MenuBarComponent::getItemAt (const int x, const int y)
  55625. {
  55626. for (int i = 0; i < xPositions.size(); ++i)
  55627. if (x >= xPositions[i] && x < xPositions[i + 1])
  55628. return reallyContains (x, y, true) ? i : -1;
  55629. return -1;
  55630. }
  55631. void MenuBarComponent::repaintMenuItem (int index)
  55632. {
  55633. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55634. {
  55635. const int x1 = xPositions [index];
  55636. const int x2 = xPositions [index + 1];
  55637. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55638. }
  55639. }
  55640. void MenuBarComponent::setItemUnderMouse (const int index)
  55641. {
  55642. if (itemUnderMouse != index)
  55643. {
  55644. repaintMenuItem (itemUnderMouse);
  55645. itemUnderMouse = index;
  55646. repaintMenuItem (itemUnderMouse);
  55647. }
  55648. }
  55649. void MenuBarComponent::setOpenItem (int index)
  55650. {
  55651. if (currentPopupIndex != index)
  55652. {
  55653. repaintMenuItem (currentPopupIndex);
  55654. currentPopupIndex = index;
  55655. repaintMenuItem (currentPopupIndex);
  55656. if (index >= 0)
  55657. Desktop::getInstance().addGlobalMouseListener (this);
  55658. else
  55659. Desktop::getInstance().removeGlobalMouseListener (this);
  55660. }
  55661. }
  55662. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55663. {
  55664. setItemUnderMouse (getItemAt (x, y));
  55665. }
  55666. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55667. {
  55668. public:
  55669. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55670. : bar (bar_), topLevelIndex (topLevelIndex_)
  55671. {
  55672. }
  55673. ~AsyncCallback() {}
  55674. void modalStateFinished (int returnValue)
  55675. {
  55676. if (bar != 0)
  55677. bar->menuDismissed (topLevelIndex, returnValue);
  55678. }
  55679. private:
  55680. Component::SafePointer<MenuBarComponent> bar;
  55681. const int topLevelIndex;
  55682. AsyncCallback (const AsyncCallback&);
  55683. AsyncCallback& operator= (const AsyncCallback&);
  55684. };
  55685. void MenuBarComponent::showMenu (int index)
  55686. {
  55687. if (index != currentPopupIndex)
  55688. {
  55689. PopupMenu::dismissAllActiveMenus();
  55690. menuBarItemsChanged (0);
  55691. setOpenItem (index);
  55692. setItemUnderMouse (index);
  55693. if (index >= 0)
  55694. {
  55695. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55696. menuNames [itemUnderMouse]));
  55697. if (m.lookAndFeel == 0)
  55698. m.setLookAndFeel (&getLookAndFeel());
  55699. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55700. m.showMenu (itemPos + getScreenPosition(),
  55701. 0, itemPos.getWidth(), 0, 0, true, this,
  55702. new AsyncCallback (this, index));
  55703. }
  55704. }
  55705. }
  55706. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55707. {
  55708. topLevelIndexClicked = topLevelIndex;
  55709. postCommandMessage (itemId);
  55710. }
  55711. void MenuBarComponent::handleCommandMessage (int commandId)
  55712. {
  55713. const Point<int> mousePos (getMouseXYRelative());
  55714. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55715. if (! isCurrentlyBlockedByAnotherModalComponent())
  55716. setOpenItem (-1);
  55717. if (commandId != 0 && model != 0)
  55718. model->menuItemSelected (commandId, topLevelIndexClicked);
  55719. }
  55720. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55721. {
  55722. if (e.eventComponent == this)
  55723. updateItemUnderMouse (e.x, e.y);
  55724. }
  55725. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55726. {
  55727. if (e.eventComponent == this)
  55728. updateItemUnderMouse (e.x, e.y);
  55729. }
  55730. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55731. {
  55732. if (currentPopupIndex < 0)
  55733. {
  55734. const MouseEvent e2 (e.getEventRelativeTo (this));
  55735. updateItemUnderMouse (e2.x, e2.y);
  55736. currentPopupIndex = -2;
  55737. showMenu (itemUnderMouse);
  55738. }
  55739. }
  55740. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55741. {
  55742. const MouseEvent e2 (e.getEventRelativeTo (this));
  55743. const int item = getItemAt (e2.x, e2.y);
  55744. if (item >= 0)
  55745. showMenu (item);
  55746. }
  55747. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55748. {
  55749. const MouseEvent e2 (e.getEventRelativeTo (this));
  55750. updateItemUnderMouse (e2.x, e2.y);
  55751. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55752. {
  55753. setOpenItem (-1);
  55754. PopupMenu::dismissAllActiveMenus();
  55755. }
  55756. }
  55757. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55758. {
  55759. const MouseEvent e2 (e.getEventRelativeTo (this));
  55760. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55761. {
  55762. if (currentPopupIndex >= 0)
  55763. {
  55764. const int item = getItemAt (e2.x, e2.y);
  55765. if (item >= 0)
  55766. showMenu (item);
  55767. }
  55768. else
  55769. {
  55770. updateItemUnderMouse (e2.x, e2.y);
  55771. }
  55772. lastMouseX = e2.x;
  55773. lastMouseY = e2.y;
  55774. }
  55775. }
  55776. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55777. {
  55778. bool used = false;
  55779. const int numMenus = menuNames.size();
  55780. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55781. if (key.isKeyCode (KeyPress::leftKey))
  55782. {
  55783. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55784. used = true;
  55785. }
  55786. else if (key.isKeyCode (KeyPress::rightKey))
  55787. {
  55788. showMenu ((currentIndex + 1) % numMenus);
  55789. used = true;
  55790. }
  55791. return used;
  55792. }
  55793. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55794. {
  55795. StringArray newNames;
  55796. if (model != 0)
  55797. newNames = model->getMenuBarNames();
  55798. if (newNames != menuNames)
  55799. {
  55800. menuNames = newNames;
  55801. repaint();
  55802. resized();
  55803. }
  55804. }
  55805. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55806. const ApplicationCommandTarget::InvocationInfo& info)
  55807. {
  55808. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55809. return;
  55810. for (int i = 0; i < menuNames.size(); ++i)
  55811. {
  55812. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55813. if (menu.containsCommandItem (info.commandID))
  55814. {
  55815. setItemUnderMouse (i);
  55816. startTimer (200);
  55817. break;
  55818. }
  55819. }
  55820. }
  55821. void MenuBarComponent::timerCallback()
  55822. {
  55823. stopTimer();
  55824. const Point<int> mousePos (getMouseXYRelative());
  55825. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55826. }
  55827. END_JUCE_NAMESPACE
  55828. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55829. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55830. BEGIN_JUCE_NAMESPACE
  55831. MenuBarModel::MenuBarModel() throw()
  55832. : manager (0)
  55833. {
  55834. }
  55835. MenuBarModel::~MenuBarModel()
  55836. {
  55837. setApplicationCommandManagerToWatch (0);
  55838. }
  55839. void MenuBarModel::menuItemsChanged()
  55840. {
  55841. triggerAsyncUpdate();
  55842. }
  55843. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55844. {
  55845. if (manager != newManager)
  55846. {
  55847. if (manager != 0)
  55848. manager->removeListener (this);
  55849. manager = newManager;
  55850. if (manager != 0)
  55851. manager->addListener (this);
  55852. }
  55853. }
  55854. void MenuBarModel::addListener (Listener* const newListener) throw()
  55855. {
  55856. listeners.add (newListener);
  55857. }
  55858. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55859. {
  55860. // Trying to remove a listener that isn't on the list!
  55861. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55862. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55863. jassert (listeners.contains (listenerToRemove));
  55864. listeners.remove (listenerToRemove);
  55865. }
  55866. void MenuBarModel::handleAsyncUpdate()
  55867. {
  55868. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55869. }
  55870. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55871. {
  55872. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55873. }
  55874. void MenuBarModel::applicationCommandListChanged()
  55875. {
  55876. menuItemsChanged();
  55877. }
  55878. END_JUCE_NAMESPACE
  55879. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55880. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55881. BEGIN_JUCE_NAMESPACE
  55882. class PopupMenu::Item
  55883. {
  55884. public:
  55885. Item()
  55886. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55887. usesColour (false), customComp (0), commandManager (0)
  55888. {
  55889. }
  55890. Item (const int itemId_,
  55891. const String& text_,
  55892. const bool active_,
  55893. const bool isTicked_,
  55894. const Image& im,
  55895. const Colour& textColour_,
  55896. const bool usesColour_,
  55897. PopupMenuCustomComponent* const customComp_,
  55898. const PopupMenu* const subMenu_,
  55899. ApplicationCommandManager* const commandManager_)
  55900. : itemId (itemId_), text (text_), textColour (textColour_),
  55901. active (active_), isSeparator (false), isTicked (isTicked_),
  55902. usesColour (usesColour_), image (im), customComp (customComp_),
  55903. commandManager (commandManager_)
  55904. {
  55905. if (subMenu_ != 0)
  55906. subMenu = new PopupMenu (*subMenu_);
  55907. if (commandManager_ != 0 && itemId_ != 0)
  55908. {
  55909. String shortcutKey;
  55910. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55911. ->getKeyPressesAssignedToCommand (itemId_));
  55912. for (int i = 0; i < keyPresses.size(); ++i)
  55913. {
  55914. const String key (keyPresses.getReference(i).getTextDescription());
  55915. if (shortcutKey.isNotEmpty())
  55916. shortcutKey << ", ";
  55917. if (key.length() == 1)
  55918. shortcutKey << "shortcut: '" << key << '\'';
  55919. else
  55920. shortcutKey << key;
  55921. }
  55922. shortcutKey = shortcutKey.trim();
  55923. if (shortcutKey.isNotEmpty())
  55924. text << "<end>" << shortcutKey;
  55925. }
  55926. }
  55927. Item (const Item& other)
  55928. : itemId (other.itemId),
  55929. text (other.text),
  55930. textColour (other.textColour),
  55931. active (other.active),
  55932. isSeparator (other.isSeparator),
  55933. isTicked (other.isTicked),
  55934. usesColour (other.usesColour),
  55935. image (other.image),
  55936. customComp (other.customComp),
  55937. commandManager (other.commandManager)
  55938. {
  55939. if (other.subMenu != 0)
  55940. subMenu = new PopupMenu (*(other.subMenu));
  55941. }
  55942. ~Item()
  55943. {
  55944. customComp = 0;
  55945. }
  55946. bool canBeTriggered() const throw()
  55947. {
  55948. return active && ! (isSeparator || (subMenu != 0));
  55949. }
  55950. bool hasActiveSubMenu() const throw()
  55951. {
  55952. return active && (subMenu != 0);
  55953. }
  55954. const int itemId;
  55955. String text;
  55956. const Colour textColour;
  55957. const bool active, isSeparator, isTicked, usesColour;
  55958. Image image;
  55959. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55960. ScopedPointer <PopupMenu> subMenu;
  55961. ApplicationCommandManager* const commandManager;
  55962. juce_UseDebuggingNewOperator
  55963. private:
  55964. Item& operator= (const Item&);
  55965. };
  55966. class PopupMenu::ItemComponent : public Component
  55967. {
  55968. public:
  55969. ItemComponent (const PopupMenu::Item& itemInfo_)
  55970. : itemInfo (itemInfo_),
  55971. isHighlighted (false)
  55972. {
  55973. if (itemInfo.customComp != 0)
  55974. addAndMakeVisible (itemInfo.customComp);
  55975. }
  55976. ~ItemComponent()
  55977. {
  55978. if (itemInfo.customComp != 0)
  55979. removeChildComponent (itemInfo.customComp);
  55980. }
  55981. void getIdealSize (int& idealWidth,
  55982. int& idealHeight,
  55983. const int standardItemHeight)
  55984. {
  55985. if (itemInfo.customComp != 0)
  55986. {
  55987. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55988. }
  55989. else
  55990. {
  55991. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55992. itemInfo.isSeparator,
  55993. standardItemHeight,
  55994. idealWidth,
  55995. idealHeight);
  55996. }
  55997. }
  55998. void paint (Graphics& g)
  55999. {
  56000. if (itemInfo.customComp == 0)
  56001. {
  56002. String mainText (itemInfo.text);
  56003. String endText;
  56004. const int endIndex = mainText.indexOf ("<end>");
  56005. if (endIndex >= 0)
  56006. {
  56007. endText = mainText.substring (endIndex + 5).trim();
  56008. mainText = mainText.substring (0, endIndex);
  56009. }
  56010. getLookAndFeel()
  56011. .drawPopupMenuItem (g, getWidth(), getHeight(),
  56012. itemInfo.isSeparator,
  56013. itemInfo.active,
  56014. isHighlighted,
  56015. itemInfo.isTicked,
  56016. itemInfo.subMenu != 0,
  56017. mainText, endText,
  56018. itemInfo.image.isValid() ? &itemInfo.image : 0,
  56019. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  56020. }
  56021. }
  56022. void resized()
  56023. {
  56024. if (getNumChildComponents() > 0)
  56025. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  56026. }
  56027. void setHighlighted (bool shouldBeHighlighted)
  56028. {
  56029. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  56030. if (isHighlighted != shouldBeHighlighted)
  56031. {
  56032. isHighlighted = shouldBeHighlighted;
  56033. if (itemInfo.customComp != 0)
  56034. {
  56035. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  56036. itemInfo.customComp->repaint();
  56037. }
  56038. repaint();
  56039. }
  56040. }
  56041. PopupMenu::Item itemInfo;
  56042. juce_UseDebuggingNewOperator
  56043. private:
  56044. bool isHighlighted;
  56045. ItemComponent (const ItemComponent&);
  56046. ItemComponent& operator= (const ItemComponent&);
  56047. };
  56048. namespace PopupMenuSettings
  56049. {
  56050. static const int scrollZone = 24;
  56051. static const int borderSize = 2;
  56052. static const int timerInterval = 50;
  56053. static const int dismissCommandId = 0x6287345f;
  56054. }
  56055. class PopupMenu::Window : public Component,
  56056. private Timer
  56057. {
  56058. public:
  56059. Window()
  56060. : Component ("menu"),
  56061. owner (0),
  56062. currentChild (0),
  56063. activeSubMenu (0),
  56064. managerOfChosenCommand (0),
  56065. minimumWidth (0),
  56066. maximumNumColumns (7),
  56067. standardItemHeight (0),
  56068. isOver (false),
  56069. hasBeenOver (false),
  56070. isDown (false),
  56071. needsToScroll (false),
  56072. hideOnExit (false),
  56073. disableMouseMoves (false),
  56074. hasAnyJuceCompHadFocus (false),
  56075. numColumns (0),
  56076. contentHeight (0),
  56077. childYOffset (0),
  56078. timeEnteredCurrentChildComp (0),
  56079. scrollAcceleration (1.0)
  56080. {
  56081. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  56082. setWantsKeyboardFocus (true);
  56083. setMouseClickGrabsKeyboardFocus (false);
  56084. setOpaque (true);
  56085. setAlwaysOnTop (true);
  56086. Desktop::getInstance().addGlobalMouseListener (this);
  56087. getActiveWindows().add (this);
  56088. }
  56089. ~Window()
  56090. {
  56091. getActiveWindows().removeValue (this);
  56092. Desktop::getInstance().removeGlobalMouseListener (this);
  56093. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56094. activeSubMenu = 0;
  56095. deleteAllChildren();
  56096. }
  56097. static Window* create (const PopupMenu& menu,
  56098. const bool dismissOnMouseUp,
  56099. Window* const owner_,
  56100. const Rectangle<int>& target,
  56101. const int minimumWidth,
  56102. const int maximumNumColumns,
  56103. const int standardItemHeight,
  56104. const bool alignToRectangle,
  56105. const int itemIdThatMustBeVisible,
  56106. ApplicationCommandManager** managerOfChosenCommand,
  56107. Component* const componentAttachedTo)
  56108. {
  56109. if (menu.items.size() > 0)
  56110. {
  56111. int totalItems = 0;
  56112. ScopedPointer <Window> mw (new Window());
  56113. mw->setLookAndFeel (menu.lookAndFeel);
  56114. mw->setWantsKeyboardFocus (false);
  56115. mw->minimumWidth = minimumWidth;
  56116. mw->maximumNumColumns = maximumNumColumns;
  56117. mw->standardItemHeight = standardItemHeight;
  56118. mw->dismissOnMouseUp = dismissOnMouseUp;
  56119. for (int i = 0; i < menu.items.size(); ++i)
  56120. {
  56121. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  56122. mw->addItem (*item);
  56123. ++totalItems;
  56124. }
  56125. if (totalItems > 0)
  56126. {
  56127. mw->owner = owner_;
  56128. mw->managerOfChosenCommand = managerOfChosenCommand;
  56129. mw->componentAttachedTo = componentAttachedTo;
  56130. mw->componentAttachedToOriginal = componentAttachedTo;
  56131. mw->calculateWindowPos (target, alignToRectangle);
  56132. mw->setTopLeftPosition (mw->windowPos.getX(),
  56133. mw->windowPos.getY());
  56134. mw->updateYPositions();
  56135. if (itemIdThatMustBeVisible != 0)
  56136. {
  56137. const int y = target.getY() - mw->windowPos.getY();
  56138. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  56139. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  56140. }
  56141. mw->resizeToBestWindowPos();
  56142. mw->addToDesktop (ComponentPeer::windowIsTemporary
  56143. | mw->getLookAndFeel().getMenuWindowFlags());
  56144. return mw.release();
  56145. }
  56146. }
  56147. return 0;
  56148. }
  56149. void paint (Graphics& g)
  56150. {
  56151. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  56152. }
  56153. void paintOverChildren (Graphics& g)
  56154. {
  56155. if (isScrolling())
  56156. {
  56157. LookAndFeel& lf = getLookAndFeel();
  56158. if (isScrollZoneActive (false))
  56159. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  56160. if (isScrollZoneActive (true))
  56161. {
  56162. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  56163. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  56164. }
  56165. }
  56166. }
  56167. bool isScrollZoneActive (bool bottomOne) const
  56168. {
  56169. return isScrolling()
  56170. && (bottomOne
  56171. ? childYOffset < contentHeight - windowPos.getHeight()
  56172. : childYOffset > 0);
  56173. }
  56174. void addItem (const PopupMenu::Item& item)
  56175. {
  56176. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  56177. addAndMakeVisible (mic);
  56178. int itemW = 80;
  56179. int itemH = 16;
  56180. mic->getIdealSize (itemW, itemH, standardItemHeight);
  56181. mic->setSize (itemW, jlimit (2, 600, itemH));
  56182. mic->addMouseListener (this, false);
  56183. }
  56184. // hide this and all sub-comps
  56185. void hide (const PopupMenu::Item* const item)
  56186. {
  56187. if (isVisible())
  56188. {
  56189. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56190. activeSubMenu = 0;
  56191. currentChild = 0;
  56192. exitModalState (item != 0 ? item->itemId : 0);
  56193. setVisible (false);
  56194. if (item != 0
  56195. && item->commandManager != 0
  56196. && item->itemId != 0)
  56197. {
  56198. *managerOfChosenCommand = item->commandManager;
  56199. }
  56200. }
  56201. }
  56202. void dismissMenu (const PopupMenu::Item* const item)
  56203. {
  56204. if (owner != 0)
  56205. {
  56206. owner->dismissMenu (item);
  56207. }
  56208. else
  56209. {
  56210. if (item != 0)
  56211. {
  56212. // need a copy of this on the stack as the one passed in will get deleted during this call
  56213. const PopupMenu::Item mi (*item);
  56214. hide (&mi);
  56215. }
  56216. else
  56217. {
  56218. hide (0);
  56219. }
  56220. }
  56221. }
  56222. void mouseMove (const MouseEvent&)
  56223. {
  56224. timerCallback();
  56225. }
  56226. void mouseDown (const MouseEvent&)
  56227. {
  56228. timerCallback();
  56229. }
  56230. void mouseDrag (const MouseEvent&)
  56231. {
  56232. timerCallback();
  56233. }
  56234. void mouseUp (const MouseEvent&)
  56235. {
  56236. timerCallback();
  56237. }
  56238. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  56239. {
  56240. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  56241. lastMouse = Point<int> (-1, -1);
  56242. }
  56243. bool keyPressed (const KeyPress& key)
  56244. {
  56245. if (key.isKeyCode (KeyPress::downKey))
  56246. {
  56247. selectNextItem (1);
  56248. }
  56249. else if (key.isKeyCode (KeyPress::upKey))
  56250. {
  56251. selectNextItem (-1);
  56252. }
  56253. else if (key.isKeyCode (KeyPress::leftKey))
  56254. {
  56255. if (owner != 0)
  56256. {
  56257. Component::SafePointer<Window> parentWindow (owner);
  56258. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  56259. hide (0);
  56260. if (parentWindow != 0)
  56261. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  56262. disableTimerUntilMouseMoves();
  56263. }
  56264. else if (componentAttachedTo != 0)
  56265. {
  56266. componentAttachedTo->keyPressed (key);
  56267. }
  56268. }
  56269. else if (key.isKeyCode (KeyPress::rightKey))
  56270. {
  56271. disableTimerUntilMouseMoves();
  56272. if (showSubMenuFor (currentChild))
  56273. {
  56274. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56275. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  56276. activeSubMenu->selectNextItem (1);
  56277. }
  56278. else if (componentAttachedTo != 0)
  56279. {
  56280. componentAttachedTo->keyPressed (key);
  56281. }
  56282. }
  56283. else if (key.isKeyCode (KeyPress::returnKey))
  56284. {
  56285. triggerCurrentlyHighlightedItem();
  56286. }
  56287. else if (key.isKeyCode (KeyPress::escapeKey))
  56288. {
  56289. dismissMenu (0);
  56290. }
  56291. else
  56292. {
  56293. return false;
  56294. }
  56295. return true;
  56296. }
  56297. void inputAttemptWhenModal()
  56298. {
  56299. Component::SafePointer<Component> deletionChecker (this);
  56300. timerCallback();
  56301. if (deletionChecker != 0 && ! isOverAnyMenu())
  56302. {
  56303. if (componentAttachedTo != 0)
  56304. {
  56305. // we want to dismiss the menu, but if we do it synchronously, then
  56306. // the mouse-click will be allowed to pass through. That's good, except
  56307. // when the user clicks on the button that orginally popped the menu up,
  56308. // as they'll expect the menu to go away, and in fact it'll just
  56309. // come back. So only dismiss synchronously if they're not on the original
  56310. // comp that we're attached to.
  56311. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56312. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  56313. {
  56314. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56315. return;
  56316. }
  56317. }
  56318. dismissMenu (0);
  56319. }
  56320. }
  56321. void handleCommandMessage (int commandId)
  56322. {
  56323. Component::handleCommandMessage (commandId);
  56324. if (commandId == PopupMenuSettings::dismissCommandId)
  56325. dismissMenu (0);
  56326. }
  56327. void timerCallback()
  56328. {
  56329. if (! isVisible())
  56330. return;
  56331. if (componentAttachedTo != componentAttachedToOriginal)
  56332. {
  56333. dismissMenu (0);
  56334. return;
  56335. }
  56336. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56337. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56338. return;
  56339. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56340. // move rather than a real timer callback
  56341. const Point<int> globalMousePos (Desktop::getMousePosition());
  56342. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56343. const uint32 now = Time::getMillisecondCounter();
  56344. if (now > timeEnteredCurrentChildComp + 100
  56345. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56346. && currentChild->isValidComponent()
  56347. && (! disableMouseMoves)
  56348. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56349. {
  56350. showSubMenuFor (currentChild);
  56351. }
  56352. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56353. {
  56354. highlightItemUnderMouse (globalMousePos, localMousePos);
  56355. }
  56356. bool overScrollArea = false;
  56357. if (isScrolling()
  56358. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56359. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56360. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56361. {
  56362. if (now > lastScroll + 20)
  56363. {
  56364. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56365. int amount = 0;
  56366. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56367. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56368. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56369. lastScroll = now;
  56370. }
  56371. overScrollArea = true;
  56372. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56373. }
  56374. else
  56375. {
  56376. scrollAcceleration = 1.0;
  56377. }
  56378. const bool wasDown = isDown;
  56379. bool isOverAny = isOverAnyMenu();
  56380. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56381. {
  56382. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56383. isOverAny = isOverAnyMenu();
  56384. }
  56385. if (hideOnExit && hasBeenOver && ! isOverAny)
  56386. {
  56387. hide (0);
  56388. }
  56389. else
  56390. {
  56391. isDown = hasBeenOver
  56392. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56393. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56394. bool anyFocused = Process::isForegroundProcess();
  56395. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56396. {
  56397. // because no component at all may have focus, our test here will
  56398. // only be triggered when something has focus and then loses it.
  56399. anyFocused = ! hasAnyJuceCompHadFocus;
  56400. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56401. {
  56402. if (ComponentPeer::getPeer (i)->isFocused())
  56403. {
  56404. anyFocused = true;
  56405. hasAnyJuceCompHadFocus = true;
  56406. break;
  56407. }
  56408. }
  56409. }
  56410. if (! anyFocused)
  56411. {
  56412. if (now > lastFocused + 10)
  56413. {
  56414. wasHiddenBecauseOfAppChange() = true;
  56415. dismissMenu (0);
  56416. return; // may have been deleted by the previous call..
  56417. }
  56418. }
  56419. else if (wasDown && now > menuCreationTime + 250
  56420. && ! (isDown || overScrollArea))
  56421. {
  56422. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56423. if (isOver)
  56424. {
  56425. triggerCurrentlyHighlightedItem();
  56426. }
  56427. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56428. {
  56429. dismissMenu (0);
  56430. }
  56431. return; // may have been deleted by the previous calls..
  56432. }
  56433. else
  56434. {
  56435. lastFocused = now;
  56436. }
  56437. }
  56438. }
  56439. static Array<Window*>& getActiveWindows()
  56440. {
  56441. static Array<Window*> activeMenuWindows;
  56442. return activeMenuWindows;
  56443. }
  56444. static bool& wasHiddenBecauseOfAppChange() throw()
  56445. {
  56446. static bool b = false;
  56447. return b;
  56448. }
  56449. juce_UseDebuggingNewOperator
  56450. private:
  56451. Window* owner;
  56452. PopupMenu::ItemComponent* currentChild;
  56453. ScopedPointer <Window> activeSubMenu;
  56454. ApplicationCommandManager** managerOfChosenCommand;
  56455. Component::SafePointer<Component> componentAttachedTo;
  56456. Component* componentAttachedToOriginal;
  56457. Rectangle<int> windowPos;
  56458. Point<int> lastMouse;
  56459. int minimumWidth, maximumNumColumns, standardItemHeight;
  56460. bool isOver, hasBeenOver, isDown, needsToScroll;
  56461. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56462. int numColumns, contentHeight, childYOffset;
  56463. Array <int> columnWidths;
  56464. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56465. double scrollAcceleration;
  56466. bool overlaps (const Rectangle<int>& r) const
  56467. {
  56468. return r.intersects (getBounds())
  56469. || (owner != 0 && owner->overlaps (r));
  56470. }
  56471. bool isOverAnyMenu() const
  56472. {
  56473. return (owner != 0) ? owner->isOverAnyMenu()
  56474. : isOverChildren();
  56475. }
  56476. bool isOverChildren() const
  56477. {
  56478. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56479. return isVisible()
  56480. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56481. }
  56482. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56483. {
  56484. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56485. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56486. if (activeSubMenu != 0)
  56487. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56488. }
  56489. bool treeContains (const Window* const window) const throw()
  56490. {
  56491. const Window* mw = this;
  56492. while (mw->owner != 0)
  56493. mw = mw->owner;
  56494. while (mw != 0)
  56495. {
  56496. if (mw == window)
  56497. return true;
  56498. mw = mw->activeSubMenu;
  56499. }
  56500. return false;
  56501. }
  56502. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56503. {
  56504. const Rectangle<int> mon (Desktop::getInstance()
  56505. .getMonitorAreaContaining (target.getCentre(),
  56506. #if JUCE_MAC
  56507. true));
  56508. #else
  56509. false)); // on windows, don't stop the menu overlapping the taskbar
  56510. #endif
  56511. int x, y, widthToUse, heightToUse;
  56512. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56513. if (alignToRectangle)
  56514. {
  56515. x = target.getX();
  56516. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56517. const int spaceOver = target.getY() - mon.getY();
  56518. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56519. y = target.getBottom();
  56520. else
  56521. y = target.getY() - heightToUse;
  56522. }
  56523. else
  56524. {
  56525. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56526. if (owner != 0)
  56527. {
  56528. if (owner->owner != 0)
  56529. {
  56530. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56531. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56532. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56533. tendTowardsRight = true;
  56534. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56535. tendTowardsRight = false;
  56536. }
  56537. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56538. {
  56539. tendTowardsRight = true;
  56540. }
  56541. }
  56542. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56543. target.getX() - mon.getX()) - 32;
  56544. if (biggestSpace < widthToUse)
  56545. {
  56546. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56547. if (numColumns > 1)
  56548. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56549. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56550. }
  56551. if (tendTowardsRight)
  56552. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56553. else
  56554. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56555. y = target.getY();
  56556. if (target.getCentreY() > mon.getCentreY())
  56557. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56558. }
  56559. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56560. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56561. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56562. // sets this flag if it's big enough to obscure any of its parent menus
  56563. hideOnExit = (owner != 0)
  56564. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56565. }
  56566. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56567. {
  56568. numColumns = 0;
  56569. contentHeight = 0;
  56570. const int maxMenuH = getParentHeight() - 24;
  56571. int totalW;
  56572. do
  56573. {
  56574. ++numColumns;
  56575. totalW = workOutBestSize (maxMenuW);
  56576. if (totalW > maxMenuW)
  56577. {
  56578. numColumns = jmax (1, numColumns - 1);
  56579. totalW = workOutBestSize (maxMenuW); // to update col widths
  56580. break;
  56581. }
  56582. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56583. {
  56584. break;
  56585. }
  56586. } while (numColumns < maximumNumColumns);
  56587. const int actualH = jmin (contentHeight, maxMenuH);
  56588. needsToScroll = contentHeight > actualH;
  56589. width = updateYPositions();
  56590. height = actualH + PopupMenuSettings::borderSize * 2;
  56591. }
  56592. int workOutBestSize (const int maxMenuW)
  56593. {
  56594. int totalW = 0;
  56595. contentHeight = 0;
  56596. int childNum = 0;
  56597. for (int col = 0; col < numColumns; ++col)
  56598. {
  56599. int i, colW = 50, colH = 0;
  56600. const int numChildren = jmin (getNumChildComponents() - childNum,
  56601. (getNumChildComponents() + numColumns - 1) / numColumns);
  56602. for (i = numChildren; --i >= 0;)
  56603. {
  56604. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56605. colH += getChildComponent (childNum + i)->getHeight();
  56606. }
  56607. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56608. columnWidths.set (col, colW);
  56609. totalW += colW;
  56610. contentHeight = jmax (contentHeight, colH);
  56611. childNum += numChildren;
  56612. }
  56613. if (totalW < minimumWidth)
  56614. {
  56615. totalW = minimumWidth;
  56616. for (int col = 0; col < numColumns; ++col)
  56617. columnWidths.set (0, totalW / numColumns);
  56618. }
  56619. return totalW;
  56620. }
  56621. void ensureItemIsVisible (const int itemId, int wantedY)
  56622. {
  56623. jassert (itemId != 0)
  56624. for (int i = getNumChildComponents(); --i >= 0;)
  56625. {
  56626. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56627. if (m != 0
  56628. && m->itemInfo.itemId == itemId
  56629. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56630. {
  56631. const int currentY = m->getY();
  56632. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56633. {
  56634. if (wantedY < 0)
  56635. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56636. jmax (PopupMenuSettings::scrollZone,
  56637. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56638. currentY);
  56639. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56640. int deltaY = wantedY - currentY;
  56641. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56642. jmin (windowPos.getHeight(), mon.getHeight()));
  56643. const int newY = jlimit (mon.getY(),
  56644. mon.getBottom() - windowPos.getHeight(),
  56645. windowPos.getY() + deltaY);
  56646. deltaY -= newY - windowPos.getY();
  56647. childYOffset -= deltaY;
  56648. windowPos.setPosition (windowPos.getX(), newY);
  56649. updateYPositions();
  56650. }
  56651. break;
  56652. }
  56653. }
  56654. }
  56655. void resizeToBestWindowPos()
  56656. {
  56657. Rectangle<int> r (windowPos);
  56658. if (childYOffset < 0)
  56659. {
  56660. r.setBounds (r.getX(), r.getY() - childYOffset,
  56661. r.getWidth(), r.getHeight() + childYOffset);
  56662. }
  56663. else if (childYOffset > 0)
  56664. {
  56665. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56666. if (spaceAtBottom > 0)
  56667. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56668. }
  56669. setBounds (r);
  56670. updateYPositions();
  56671. }
  56672. void alterChildYPos (const int delta)
  56673. {
  56674. if (isScrolling())
  56675. {
  56676. childYOffset += delta;
  56677. if (delta < 0)
  56678. {
  56679. childYOffset = jmax (childYOffset, 0);
  56680. }
  56681. else if (delta > 0)
  56682. {
  56683. childYOffset = jmin (childYOffset,
  56684. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56685. }
  56686. updateYPositions();
  56687. }
  56688. else
  56689. {
  56690. childYOffset = 0;
  56691. }
  56692. resizeToBestWindowPos();
  56693. repaint();
  56694. }
  56695. int updateYPositions()
  56696. {
  56697. int x = 0;
  56698. int childNum = 0;
  56699. for (int col = 0; col < numColumns; ++col)
  56700. {
  56701. const int numChildren = jmin (getNumChildComponents() - childNum,
  56702. (getNumChildComponents() + numColumns - 1) / numColumns);
  56703. const int colW = columnWidths [col];
  56704. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56705. for (int i = 0; i < numChildren; ++i)
  56706. {
  56707. Component* const c = getChildComponent (childNum + i);
  56708. c->setBounds (x, y, colW, c->getHeight());
  56709. y += c->getHeight();
  56710. }
  56711. x += colW;
  56712. childNum += numChildren;
  56713. }
  56714. return x;
  56715. }
  56716. bool isScrolling() const throw()
  56717. {
  56718. return childYOffset != 0 || needsToScroll;
  56719. }
  56720. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56721. {
  56722. if (currentChild->isValidComponent())
  56723. currentChild->setHighlighted (false);
  56724. currentChild = child;
  56725. if (currentChild != 0)
  56726. {
  56727. currentChild->setHighlighted (true);
  56728. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56729. }
  56730. }
  56731. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56732. {
  56733. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56734. activeSubMenu = 0;
  56735. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56736. {
  56737. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56738. dismissOnMouseUp,
  56739. this,
  56740. childComp->getScreenBounds(),
  56741. 0, maximumNumColumns,
  56742. standardItemHeight,
  56743. false, 0, managerOfChosenCommand,
  56744. componentAttachedTo);
  56745. if (activeSubMenu != 0)
  56746. {
  56747. activeSubMenu->setVisible (true);
  56748. activeSubMenu->enterModalState (false);
  56749. activeSubMenu->toFront (false);
  56750. return true;
  56751. }
  56752. }
  56753. return false;
  56754. }
  56755. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56756. {
  56757. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56758. if (isOver)
  56759. hasBeenOver = true;
  56760. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56761. {
  56762. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56763. if (disableMouseMoves && isOver)
  56764. disableMouseMoves = false;
  56765. }
  56766. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56767. return;
  56768. bool isMovingTowardsMenu = false;
  56769. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56770. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56771. {
  56772. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56773. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56774. // extends from the last mouse pos to the submenu's rectangle..
  56775. float subX = (float) activeSubMenu->getScreenX();
  56776. if (activeSubMenu->getX() > getX())
  56777. {
  56778. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56779. }
  56780. else
  56781. {
  56782. lastMouse += Point<int> (2, 0);
  56783. subX += activeSubMenu->getWidth();
  56784. }
  56785. Path areaTowardsSubMenu;
  56786. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56787. (float) lastMouse.getY(),
  56788. subX,
  56789. (float) activeSubMenu->getScreenY(),
  56790. subX,
  56791. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56792. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56793. }
  56794. lastMouse = globalMousePos;
  56795. if (! isMovingTowardsMenu)
  56796. {
  56797. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56798. if (c == this)
  56799. c = 0;
  56800. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56801. if (mic == 0 && c != 0)
  56802. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56803. if (mic != currentChild
  56804. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56805. {
  56806. if (isOver && (c != 0) && (activeSubMenu != 0))
  56807. {
  56808. activeSubMenu->hide (0);
  56809. }
  56810. if (! isOver)
  56811. mic = 0;
  56812. setCurrentlyHighlightedChild (mic);
  56813. }
  56814. }
  56815. }
  56816. void triggerCurrentlyHighlightedItem()
  56817. {
  56818. if (currentChild->isValidComponent()
  56819. && currentChild->itemInfo.canBeTriggered()
  56820. && (currentChild->itemInfo.customComp == 0
  56821. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56822. {
  56823. dismissMenu (&currentChild->itemInfo);
  56824. }
  56825. }
  56826. void selectNextItem (const int delta)
  56827. {
  56828. disableTimerUntilMouseMoves();
  56829. PopupMenu::ItemComponent* mic = 0;
  56830. bool wasLastOne = (currentChild == 0);
  56831. const int numItems = getNumChildComponents();
  56832. for (int i = 0; i < numItems + 1; ++i)
  56833. {
  56834. int index = (delta > 0) ? i : (numItems - 1 - i);
  56835. index = (index + numItems) % numItems;
  56836. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56837. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56838. && wasLastOne)
  56839. break;
  56840. if (mic == currentChild)
  56841. wasLastOne = true;
  56842. }
  56843. setCurrentlyHighlightedChild (mic);
  56844. }
  56845. void disableTimerUntilMouseMoves()
  56846. {
  56847. disableMouseMoves = true;
  56848. if (owner != 0)
  56849. owner->disableTimerUntilMouseMoves();
  56850. }
  56851. Window (const Window&);
  56852. Window& operator= (const Window&);
  56853. };
  56854. PopupMenu::PopupMenu()
  56855. : lookAndFeel (0),
  56856. separatorPending (false)
  56857. {
  56858. }
  56859. PopupMenu::PopupMenu (const PopupMenu& other)
  56860. : lookAndFeel (other.lookAndFeel),
  56861. separatorPending (false)
  56862. {
  56863. items.addCopiesOf (other.items);
  56864. }
  56865. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56866. {
  56867. if (this != &other)
  56868. {
  56869. lookAndFeel = other.lookAndFeel;
  56870. clear();
  56871. items.addCopiesOf (other.items);
  56872. }
  56873. return *this;
  56874. }
  56875. PopupMenu::~PopupMenu()
  56876. {
  56877. clear();
  56878. }
  56879. void PopupMenu::clear()
  56880. {
  56881. items.clear();
  56882. separatorPending = false;
  56883. }
  56884. void PopupMenu::addSeparatorIfPending()
  56885. {
  56886. if (separatorPending)
  56887. {
  56888. separatorPending = false;
  56889. if (items.size() > 0)
  56890. items.add (new Item());
  56891. }
  56892. }
  56893. void PopupMenu::addItem (const int itemResultId,
  56894. const String& itemText,
  56895. const bool isActive,
  56896. const bool isTicked,
  56897. const Image& iconToUse)
  56898. {
  56899. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56900. // didn't pick anything, so you shouldn't use it as the id
  56901. // for an item..
  56902. addSeparatorIfPending();
  56903. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56904. Colours::black, false, 0, 0, 0));
  56905. }
  56906. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56907. const int commandID,
  56908. const String& displayName)
  56909. {
  56910. jassert (commandManager != 0 && commandID != 0);
  56911. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56912. if (registeredInfo != 0)
  56913. {
  56914. ApplicationCommandInfo info (*registeredInfo);
  56915. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56916. addSeparatorIfPending();
  56917. items.add (new Item (commandID,
  56918. displayName.isNotEmpty() ? displayName
  56919. : info.shortName,
  56920. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56921. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56922. Image::null,
  56923. Colours::black,
  56924. false,
  56925. 0, 0,
  56926. commandManager));
  56927. }
  56928. }
  56929. void PopupMenu::addColouredItem (const int itemResultId,
  56930. const String& itemText,
  56931. const Colour& itemTextColour,
  56932. const bool isActive,
  56933. const bool isTicked,
  56934. const Image& iconToUse)
  56935. {
  56936. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56937. // didn't pick anything, so you shouldn't use it as the id
  56938. // for an item..
  56939. addSeparatorIfPending();
  56940. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56941. itemTextColour, true, 0, 0, 0));
  56942. }
  56943. void PopupMenu::addCustomItem (const int itemResultId,
  56944. PopupMenuCustomComponent* const customComponent)
  56945. {
  56946. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56947. // didn't pick anything, so you shouldn't use it as the id
  56948. // for an item..
  56949. addSeparatorIfPending();
  56950. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56951. Colours::black, false, customComponent, 0, 0));
  56952. }
  56953. class NormalComponentWrapper : public PopupMenuCustomComponent
  56954. {
  56955. public:
  56956. NormalComponentWrapper (Component* const comp,
  56957. const int w, const int h,
  56958. const bool triggerMenuItemAutomaticallyWhenClicked)
  56959. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56960. width (w),
  56961. height (h)
  56962. {
  56963. addAndMakeVisible (comp);
  56964. }
  56965. ~NormalComponentWrapper() {}
  56966. void getIdealSize (int& idealWidth, int& idealHeight)
  56967. {
  56968. idealWidth = width;
  56969. idealHeight = height;
  56970. }
  56971. void resized()
  56972. {
  56973. if (getChildComponent(0) != 0)
  56974. getChildComponent(0)->setBounds (getLocalBounds());
  56975. }
  56976. juce_UseDebuggingNewOperator
  56977. private:
  56978. const int width, height;
  56979. NormalComponentWrapper (const NormalComponentWrapper&);
  56980. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56981. };
  56982. void PopupMenu::addCustomItem (const int itemResultId,
  56983. Component* customComponent,
  56984. int idealWidth, int idealHeight,
  56985. const bool triggerMenuItemAutomaticallyWhenClicked)
  56986. {
  56987. addCustomItem (itemResultId,
  56988. new NormalComponentWrapper (customComponent,
  56989. idealWidth, idealHeight,
  56990. triggerMenuItemAutomaticallyWhenClicked));
  56991. }
  56992. void PopupMenu::addSubMenu (const String& subMenuName,
  56993. const PopupMenu& subMenu,
  56994. const bool isActive,
  56995. const Image& iconToUse,
  56996. const bool isTicked)
  56997. {
  56998. addSeparatorIfPending();
  56999. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  57000. iconToUse, Colours::black, false, 0, &subMenu, 0));
  57001. }
  57002. void PopupMenu::addSeparator()
  57003. {
  57004. separatorPending = true;
  57005. }
  57006. class HeaderItemComponent : public PopupMenuCustomComponent
  57007. {
  57008. public:
  57009. HeaderItemComponent (const String& name)
  57010. : PopupMenuCustomComponent (false)
  57011. {
  57012. setName (name);
  57013. }
  57014. ~HeaderItemComponent()
  57015. {
  57016. }
  57017. void paint (Graphics& g)
  57018. {
  57019. Font f (getLookAndFeel().getPopupMenuFont());
  57020. f.setBold (true);
  57021. g.setFont (f);
  57022. g.setColour (findColour (PopupMenu::headerTextColourId));
  57023. g.drawFittedText (getName(),
  57024. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  57025. Justification::bottomLeft, 1);
  57026. }
  57027. void getIdealSize (int& idealWidth,
  57028. int& idealHeight)
  57029. {
  57030. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  57031. idealHeight += idealHeight / 2;
  57032. idealWidth += idealWidth / 4;
  57033. }
  57034. juce_UseDebuggingNewOperator
  57035. };
  57036. void PopupMenu::addSectionHeader (const String& title)
  57037. {
  57038. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  57039. }
  57040. // This invokes any command manager commands and deletes the menu window when it is dismissed
  57041. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  57042. {
  57043. public:
  57044. PopupMenuCompletionCallback()
  57045. : managerOfChosenCommand (0)
  57046. {
  57047. }
  57048. ~PopupMenuCompletionCallback() {}
  57049. void modalStateFinished (int result)
  57050. {
  57051. if (managerOfChosenCommand != 0 && result != 0)
  57052. {
  57053. ApplicationCommandTarget::InvocationInfo info (result);
  57054. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  57055. managerOfChosenCommand->invoke (info, true);
  57056. }
  57057. }
  57058. ApplicationCommandManager* managerOfChosenCommand;
  57059. ScopedPointer<Component> component;
  57060. private:
  57061. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  57062. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  57063. };
  57064. int PopupMenu::showMenu (const Rectangle<int>& target,
  57065. const int itemIdThatMustBeVisible,
  57066. const int minimumWidth,
  57067. const int maximumNumColumns,
  57068. const int standardItemHeight,
  57069. const bool alignToRectangle,
  57070. Component* const componentAttachedTo,
  57071. ModalComponentManager::Callback* userCallback)
  57072. {
  57073. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  57074. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  57075. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  57076. Window::wasHiddenBecauseOfAppChange() = false;
  57077. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  57078. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  57079. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  57080. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  57081. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  57082. &callback->managerOfChosenCommand, componentAttachedTo);
  57083. if (callback->component == 0)
  57084. return 0;
  57085. callbackDeleter.release();
  57086. callback->component->enterModalState (false, userCallbackDeleter.release());
  57087. callback->component->toFront (false); // need to do this after making it modal, or it could
  57088. // be stuck behind other comps that are already modal..
  57089. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  57090. if (userCallback != 0)
  57091. return 0;
  57092. const int result = callback->component->runModalLoop();
  57093. if (! Window::wasHiddenBecauseOfAppChange())
  57094. {
  57095. if (prevTopLevel != 0)
  57096. prevTopLevel->toFront (true);
  57097. if (prevFocused != 0)
  57098. prevFocused->grabKeyboardFocus();
  57099. }
  57100. return result;
  57101. }
  57102. int PopupMenu::show (const int itemIdThatMustBeVisible,
  57103. const int minimumWidth,
  57104. const int maximumNumColumns,
  57105. const int standardItemHeight,
  57106. ModalComponentManager::Callback* callback)
  57107. {
  57108. const Point<int> mousePos (Desktop::getMousePosition());
  57109. return showAt (mousePos.getX(), mousePos.getY(),
  57110. itemIdThatMustBeVisible,
  57111. minimumWidth,
  57112. maximumNumColumns,
  57113. standardItemHeight,
  57114. callback);
  57115. }
  57116. int PopupMenu::showAt (const int screenX,
  57117. const int screenY,
  57118. const int itemIdThatMustBeVisible,
  57119. const int minimumWidth,
  57120. const int maximumNumColumns,
  57121. const int standardItemHeight,
  57122. ModalComponentManager::Callback* callback)
  57123. {
  57124. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  57125. itemIdThatMustBeVisible,
  57126. minimumWidth, maximumNumColumns,
  57127. standardItemHeight,
  57128. false, 0, callback);
  57129. }
  57130. int PopupMenu::showAt (Component* componentToAttachTo,
  57131. const int itemIdThatMustBeVisible,
  57132. const int minimumWidth,
  57133. const int maximumNumColumns,
  57134. const int standardItemHeight,
  57135. ModalComponentManager::Callback* callback)
  57136. {
  57137. if (componentToAttachTo != 0)
  57138. {
  57139. return showMenu (componentToAttachTo->getScreenBounds(),
  57140. itemIdThatMustBeVisible,
  57141. minimumWidth,
  57142. maximumNumColumns,
  57143. standardItemHeight,
  57144. true, componentToAttachTo, callback);
  57145. }
  57146. else
  57147. {
  57148. return show (itemIdThatMustBeVisible,
  57149. minimumWidth,
  57150. maximumNumColumns,
  57151. standardItemHeight,
  57152. callback);
  57153. }
  57154. }
  57155. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  57156. {
  57157. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  57158. {
  57159. Window* const pmw = Window::getActiveWindows()[i];
  57160. if (pmw != 0)
  57161. pmw->dismissMenu (0);
  57162. }
  57163. }
  57164. int PopupMenu::getNumItems() const throw()
  57165. {
  57166. int num = 0;
  57167. for (int i = items.size(); --i >= 0;)
  57168. if (! (items.getUnchecked(i))->isSeparator)
  57169. ++num;
  57170. return num;
  57171. }
  57172. bool PopupMenu::containsCommandItem (const int commandID) const
  57173. {
  57174. for (int i = items.size(); --i >= 0;)
  57175. {
  57176. const Item* mi = items.getUnchecked (i);
  57177. if ((mi->itemId == commandID && mi->commandManager != 0)
  57178. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  57179. {
  57180. return true;
  57181. }
  57182. }
  57183. return false;
  57184. }
  57185. bool PopupMenu::containsAnyActiveItems() const throw()
  57186. {
  57187. for (int i = items.size(); --i >= 0;)
  57188. {
  57189. const Item* const mi = items.getUnchecked (i);
  57190. if (mi->subMenu != 0)
  57191. {
  57192. if (mi->subMenu->containsAnyActiveItems())
  57193. return true;
  57194. }
  57195. else if (mi->active)
  57196. {
  57197. return true;
  57198. }
  57199. }
  57200. return false;
  57201. }
  57202. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  57203. {
  57204. lookAndFeel = newLookAndFeel;
  57205. }
  57206. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  57207. : isHighlighted (false),
  57208. isTriggeredAutomatically (isTriggeredAutomatically_)
  57209. {
  57210. }
  57211. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  57212. {
  57213. }
  57214. void PopupMenuCustomComponent::triggerMenuItem()
  57215. {
  57216. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  57217. if (mic != 0)
  57218. {
  57219. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  57220. if (pmw != 0)
  57221. {
  57222. pmw->dismissMenu (&mic->itemInfo);
  57223. }
  57224. else
  57225. {
  57226. // something must have gone wrong with the component hierarchy if this happens..
  57227. jassertfalse;
  57228. }
  57229. }
  57230. else
  57231. {
  57232. // why isn't this component inside a menu? Not much point triggering the item if
  57233. // there's no menu.
  57234. jassertfalse;
  57235. }
  57236. }
  57237. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  57238. : subMenu (0),
  57239. itemId (0),
  57240. isSeparator (false),
  57241. isTicked (false),
  57242. isEnabled (false),
  57243. isCustomComponent (false),
  57244. isSectionHeader (false),
  57245. customColour (0),
  57246. customImage (0),
  57247. menu (menu_),
  57248. index (0)
  57249. {
  57250. }
  57251. PopupMenu::MenuItemIterator::~MenuItemIterator()
  57252. {
  57253. }
  57254. bool PopupMenu::MenuItemIterator::next()
  57255. {
  57256. if (index >= menu.items.size())
  57257. return false;
  57258. const Item* const item = menu.items.getUnchecked (index);
  57259. ++index;
  57260. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  57261. subMenu = item->subMenu;
  57262. itemId = item->itemId;
  57263. isSeparator = item->isSeparator;
  57264. isTicked = item->isTicked;
  57265. isEnabled = item->active;
  57266. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  57267. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  57268. customColour = item->usesColour ? &(item->textColour) : 0;
  57269. customImage = item->image;
  57270. commandManager = item->commandManager;
  57271. return true;
  57272. }
  57273. END_JUCE_NAMESPACE
  57274. /*** End of inlined file: juce_PopupMenu.cpp ***/
  57275. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  57276. BEGIN_JUCE_NAMESPACE
  57277. ComponentDragger::ComponentDragger()
  57278. : constrainer (0)
  57279. {
  57280. }
  57281. ComponentDragger::~ComponentDragger()
  57282. {
  57283. }
  57284. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  57285. ComponentBoundsConstrainer* const constrainer_)
  57286. {
  57287. jassert (componentToDrag->isValidComponent());
  57288. if (componentToDrag != 0)
  57289. {
  57290. constrainer = constrainer_;
  57291. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  57292. }
  57293. }
  57294. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  57295. {
  57296. jassert (componentToDrag->isValidComponent());
  57297. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  57298. if (componentToDrag != 0)
  57299. {
  57300. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  57301. const Component* const parentComp = componentToDrag->getParentComponent();
  57302. if (parentComp != 0)
  57303. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  57304. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  57305. if (constrainer != 0)
  57306. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57307. else
  57308. componentToDrag->setBounds (bounds);
  57309. }
  57310. }
  57311. END_JUCE_NAMESPACE
  57312. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57313. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57314. BEGIN_JUCE_NAMESPACE
  57315. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57316. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57317. class DragImageComponent : public Component,
  57318. public Timer
  57319. {
  57320. public:
  57321. DragImageComponent (const Image& im,
  57322. const String& desc,
  57323. Component* const sourceComponent,
  57324. Component* const mouseDragSource_,
  57325. DragAndDropContainer* const o,
  57326. const Point<int>& imageOffset_)
  57327. : image (im),
  57328. source (sourceComponent),
  57329. mouseDragSource (mouseDragSource_),
  57330. owner (o),
  57331. dragDesc (desc),
  57332. imageOffset (imageOffset_),
  57333. hasCheckedForExternalDrag (false),
  57334. drawImage (true)
  57335. {
  57336. setSize (im.getWidth(), im.getHeight());
  57337. if (mouseDragSource == 0)
  57338. mouseDragSource = source;
  57339. mouseDragSource->addMouseListener (this, false);
  57340. startTimer (200);
  57341. setInterceptsMouseClicks (false, false);
  57342. setAlwaysOnTop (true);
  57343. }
  57344. ~DragImageComponent()
  57345. {
  57346. if (owner->dragImageComponent == this)
  57347. owner->dragImageComponent.release();
  57348. if (mouseDragSource != 0)
  57349. {
  57350. mouseDragSource->removeMouseListener (this);
  57351. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57352. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57353. }
  57354. }
  57355. void paint (Graphics& g)
  57356. {
  57357. if (isOpaque())
  57358. g.fillAll (Colours::white);
  57359. if (drawImage)
  57360. {
  57361. g.setOpacity (1.0f);
  57362. g.drawImageAt (image, 0, 0);
  57363. }
  57364. }
  57365. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57366. {
  57367. Component* hit = getParentComponent();
  57368. if (hit == 0)
  57369. {
  57370. hit = Desktop::getInstance().findComponentAt (screenPos);
  57371. }
  57372. else
  57373. {
  57374. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57375. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57376. }
  57377. // (note: use a local copy of the dragDesc member in case the callback runs
  57378. // a modal loop and deletes this object before the method completes)
  57379. const String dragDescLocal (dragDesc);
  57380. while (hit != 0)
  57381. {
  57382. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57383. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57384. {
  57385. relativePos = hit->globalPositionToRelative (screenPos);
  57386. return ddt;
  57387. }
  57388. hit = hit->getParentComponent();
  57389. }
  57390. return 0;
  57391. }
  57392. void mouseUp (const MouseEvent& e)
  57393. {
  57394. if (e.originalComponent != this)
  57395. {
  57396. if (mouseDragSource != 0)
  57397. mouseDragSource->removeMouseListener (this);
  57398. bool dropAccepted = false;
  57399. DragAndDropTarget* ddt = 0;
  57400. Point<int> relPos;
  57401. if (isVisible())
  57402. {
  57403. setVisible (false);
  57404. ddt = findTarget (e.getScreenPosition(), relPos);
  57405. // fade this component and remove it - it'll be deleted later by the timer callback
  57406. dropAccepted = ddt != 0;
  57407. setVisible (true);
  57408. if (dropAccepted || source == 0)
  57409. {
  57410. fadeOutComponent (120);
  57411. }
  57412. else
  57413. {
  57414. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57415. source->getHeight() / 2)));
  57416. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57417. getHeight() / 2)));
  57418. fadeOutComponent (120,
  57419. target.getX() - ourCentre.getX(),
  57420. target.getY() - ourCentre.getY());
  57421. }
  57422. }
  57423. if (getParentComponent() != 0)
  57424. getParentComponent()->removeChildComponent (this);
  57425. if (dropAccepted && ddt != 0)
  57426. {
  57427. // (note: use a local copy of the dragDesc member in case the callback runs
  57428. // a modal loop and deletes this object before the method completes)
  57429. const String dragDescLocal (dragDesc);
  57430. currentlyOverComp = 0;
  57431. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57432. }
  57433. // careful - this object could now be deleted..
  57434. }
  57435. }
  57436. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57437. {
  57438. // (note: use a local copy of the dragDesc member in case the callback runs
  57439. // a modal loop and deletes this object before it returns)
  57440. const String dragDescLocal (dragDesc);
  57441. Point<int> newPos (screenPos + imageOffset);
  57442. if (getParentComponent() != 0)
  57443. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57444. //if (newX != getX() || newY != getY())
  57445. {
  57446. setTopLeftPosition (newPos.getX(), newPos.getY());
  57447. Point<int> relPos;
  57448. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57449. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57450. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57451. if (ddtComp != currentlyOverComp)
  57452. {
  57453. if (currentlyOverComp != 0 && source != 0
  57454. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57455. {
  57456. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57457. }
  57458. currentlyOverComp = ddtComp;
  57459. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57460. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57461. }
  57462. DragAndDropTarget* target = getCurrentlyOver();
  57463. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57464. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57465. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57466. {
  57467. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57468. {
  57469. hasCheckedForExternalDrag = true;
  57470. StringArray files;
  57471. bool canMoveFiles = false;
  57472. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57473. && files.size() > 0)
  57474. {
  57475. Component::SafePointer<Component> cdw (this);
  57476. setVisible (false);
  57477. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57478. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57479. if (cdw != 0)
  57480. delete this;
  57481. return;
  57482. }
  57483. }
  57484. }
  57485. }
  57486. }
  57487. void mouseDrag (const MouseEvent& e)
  57488. {
  57489. if (e.originalComponent != this)
  57490. updateLocation (true, e.getScreenPosition());
  57491. }
  57492. void timerCallback()
  57493. {
  57494. if (source == 0)
  57495. {
  57496. delete this;
  57497. }
  57498. else if (! isMouseButtonDownAnywhere())
  57499. {
  57500. if (mouseDragSource != 0)
  57501. mouseDragSource->removeMouseListener (this);
  57502. delete this;
  57503. }
  57504. }
  57505. private:
  57506. Image image;
  57507. Component::SafePointer<Component> source;
  57508. Component::SafePointer<Component> mouseDragSource;
  57509. DragAndDropContainer* const owner;
  57510. Component::SafePointer<Component> currentlyOverComp;
  57511. DragAndDropTarget* getCurrentlyOver()
  57512. {
  57513. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57514. }
  57515. String dragDesc;
  57516. const Point<int> imageOffset;
  57517. bool hasCheckedForExternalDrag, drawImage;
  57518. DragImageComponent (const DragImageComponent&);
  57519. DragImageComponent& operator= (const DragImageComponent&);
  57520. };
  57521. DragAndDropContainer::DragAndDropContainer()
  57522. {
  57523. }
  57524. DragAndDropContainer::~DragAndDropContainer()
  57525. {
  57526. dragImageComponent = 0;
  57527. }
  57528. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57529. Component* sourceComponent,
  57530. const Image& dragImage_,
  57531. const bool allowDraggingToExternalWindows,
  57532. const Point<int>* imageOffsetFromMouse)
  57533. {
  57534. Image dragImage (dragImage_);
  57535. if (dragImageComponent == 0)
  57536. {
  57537. Component* const thisComp = dynamic_cast <Component*> (this);
  57538. if (thisComp == 0)
  57539. {
  57540. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57541. return;
  57542. }
  57543. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57544. if (draggingSource == 0 || ! draggingSource->isDragging())
  57545. {
  57546. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57547. return;
  57548. }
  57549. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57550. Point<int> imageOffset;
  57551. if (dragImage.isNull())
  57552. {
  57553. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57554. .convertedToFormat (Image::ARGB);
  57555. dragImage.multiplyAllAlphas (0.6f);
  57556. const int lo = 150;
  57557. const int hi = 400;
  57558. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57559. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57560. for (int y = dragImage.getHeight(); --y >= 0;)
  57561. {
  57562. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57563. for (int x = dragImage.getWidth(); --x >= 0;)
  57564. {
  57565. const int dx = x - clipped.getX();
  57566. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57567. if (distance > lo)
  57568. {
  57569. const float alpha = (distance > hi) ? 0
  57570. : (hi - distance) / (float) (hi - lo)
  57571. + Random::getSystemRandom().nextFloat() * 0.008f;
  57572. dragImage.multiplyAlphaAt (x, y, alpha);
  57573. }
  57574. }
  57575. }
  57576. imageOffset = -clipped;
  57577. }
  57578. else
  57579. {
  57580. if (imageOffsetFromMouse == 0)
  57581. imageOffset = -dragImage.getBounds().getCentre();
  57582. else
  57583. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57584. }
  57585. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57586. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57587. currentDragDesc = sourceDescription;
  57588. if (allowDraggingToExternalWindows)
  57589. {
  57590. if (! Desktop::canUseSemiTransparentWindows())
  57591. dragImageComponent->setOpaque (true);
  57592. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57593. | ComponentPeer::windowIsTemporary
  57594. | ComponentPeer::windowIgnoresKeyPresses);
  57595. }
  57596. else
  57597. thisComp->addChildComponent (dragImageComponent);
  57598. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57599. dragImageComponent->setVisible (true);
  57600. }
  57601. }
  57602. bool DragAndDropContainer::isDragAndDropActive() const
  57603. {
  57604. return dragImageComponent != 0;
  57605. }
  57606. const String DragAndDropContainer::getCurrentDragDescription() const
  57607. {
  57608. return (dragImageComponent != 0) ? currentDragDesc
  57609. : String::empty;
  57610. }
  57611. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57612. {
  57613. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57614. }
  57615. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57616. {
  57617. return false;
  57618. }
  57619. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57620. {
  57621. }
  57622. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57623. {
  57624. }
  57625. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57626. {
  57627. }
  57628. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57629. {
  57630. return true;
  57631. }
  57632. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57633. {
  57634. }
  57635. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57636. {
  57637. }
  57638. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57639. {
  57640. }
  57641. END_JUCE_NAMESPACE
  57642. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57643. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57644. BEGIN_JUCE_NAMESPACE
  57645. class MouseCursor::SharedCursorHandle
  57646. {
  57647. public:
  57648. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57649. : handle (createStandardMouseCursor (type)),
  57650. refCount (1),
  57651. standardType (type),
  57652. isStandard (true)
  57653. {
  57654. }
  57655. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57656. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57657. refCount (1),
  57658. standardType (MouseCursor::NormalCursor),
  57659. isStandard (false)
  57660. {
  57661. }
  57662. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57663. {
  57664. const ScopedLock sl (getLock());
  57665. for (int i = 0; i < getCursors().size(); ++i)
  57666. {
  57667. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57668. if (sc->standardType == type)
  57669. return sc->retain();
  57670. }
  57671. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57672. getCursors().add (sc);
  57673. return sc;
  57674. }
  57675. SharedCursorHandle* retain() throw()
  57676. {
  57677. ++refCount;
  57678. return this;
  57679. }
  57680. void release()
  57681. {
  57682. if (--refCount == 0)
  57683. {
  57684. if (isStandard)
  57685. {
  57686. const ScopedLock sl (getLock());
  57687. getCursors().removeValue (this);
  57688. }
  57689. delete this;
  57690. }
  57691. }
  57692. void* getHandle() const throw() { return handle; }
  57693. juce_UseDebuggingNewOperator
  57694. private:
  57695. void* const handle;
  57696. Atomic <int> refCount;
  57697. const MouseCursor::StandardCursorType standardType;
  57698. const bool isStandard;
  57699. static CriticalSection& getLock()
  57700. {
  57701. static CriticalSection lock;
  57702. return lock;
  57703. }
  57704. static Array <SharedCursorHandle*>& getCursors()
  57705. {
  57706. static Array <SharedCursorHandle*> cursors;
  57707. return cursors;
  57708. }
  57709. ~SharedCursorHandle()
  57710. {
  57711. deleteMouseCursor (handle, isStandard);
  57712. }
  57713. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57714. };
  57715. MouseCursor::MouseCursor()
  57716. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57717. {
  57718. jassert (cursorHandle != 0);
  57719. }
  57720. MouseCursor::MouseCursor (const StandardCursorType type)
  57721. : cursorHandle (SharedCursorHandle::createStandard (type))
  57722. {
  57723. jassert (cursorHandle != 0);
  57724. }
  57725. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57726. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57727. {
  57728. }
  57729. MouseCursor::MouseCursor (const MouseCursor& other)
  57730. : cursorHandle (other.cursorHandle->retain())
  57731. {
  57732. }
  57733. MouseCursor::~MouseCursor()
  57734. {
  57735. cursorHandle->release();
  57736. }
  57737. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57738. {
  57739. other.cursorHandle->retain();
  57740. cursorHandle->release();
  57741. cursorHandle = other.cursorHandle;
  57742. return *this;
  57743. }
  57744. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57745. {
  57746. return getHandle() == other.getHandle();
  57747. }
  57748. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57749. {
  57750. return getHandle() != other.getHandle();
  57751. }
  57752. void* MouseCursor::getHandle() const throw()
  57753. {
  57754. return cursorHandle->getHandle();
  57755. }
  57756. void MouseCursor::showWaitCursor()
  57757. {
  57758. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57759. }
  57760. void MouseCursor::hideWaitCursor()
  57761. {
  57762. Desktop::getInstance().getMainMouseSource().revealCursor();
  57763. }
  57764. END_JUCE_NAMESPACE
  57765. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57766. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57767. BEGIN_JUCE_NAMESPACE
  57768. MouseEvent::MouseEvent (MouseInputSource& source_,
  57769. const Point<int>& position,
  57770. const ModifierKeys& mods_,
  57771. Component* const eventComponent_,
  57772. Component* const originator,
  57773. const Time& eventTime_,
  57774. const Point<int> mouseDownPos_,
  57775. const Time& mouseDownTime_,
  57776. const int numberOfClicks_,
  57777. const bool mouseWasDragged) throw()
  57778. : x (position.getX()),
  57779. y (position.getY()),
  57780. mods (mods_),
  57781. eventComponent (eventComponent_),
  57782. originalComponent (originator),
  57783. eventTime (eventTime_),
  57784. source (source_),
  57785. mouseDownPos (mouseDownPos_),
  57786. mouseDownTime (mouseDownTime_),
  57787. numberOfClicks (numberOfClicks_),
  57788. wasMovedSinceMouseDown (mouseWasDragged)
  57789. {
  57790. }
  57791. MouseEvent::~MouseEvent() throw()
  57792. {
  57793. }
  57794. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57795. {
  57796. if (otherComponent == 0)
  57797. {
  57798. jassertfalse;
  57799. return *this;
  57800. }
  57801. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57802. mods, otherComponent, originalComponent, eventTime,
  57803. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57804. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57805. }
  57806. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57807. {
  57808. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57809. eventTime, mouseDownPos, mouseDownTime,
  57810. numberOfClicks, wasMovedSinceMouseDown);
  57811. }
  57812. bool MouseEvent::mouseWasClicked() const throw()
  57813. {
  57814. return ! wasMovedSinceMouseDown;
  57815. }
  57816. int MouseEvent::getMouseDownX() const throw()
  57817. {
  57818. return mouseDownPos.getX();
  57819. }
  57820. int MouseEvent::getMouseDownY() const throw()
  57821. {
  57822. return mouseDownPos.getY();
  57823. }
  57824. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57825. {
  57826. return mouseDownPos;
  57827. }
  57828. int MouseEvent::getDistanceFromDragStartX() const throw()
  57829. {
  57830. return x - mouseDownPos.getX();
  57831. }
  57832. int MouseEvent::getDistanceFromDragStartY() const throw()
  57833. {
  57834. return y - mouseDownPos.getY();
  57835. }
  57836. int MouseEvent::getDistanceFromDragStart() const throw()
  57837. {
  57838. return mouseDownPos.getDistanceFrom (getPosition());
  57839. }
  57840. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57841. {
  57842. return getPosition() - mouseDownPos;
  57843. }
  57844. int MouseEvent::getLengthOfMousePress() const throw()
  57845. {
  57846. if (mouseDownTime.toMilliseconds() > 0)
  57847. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57848. return 0;
  57849. }
  57850. const Point<int> MouseEvent::getPosition() const throw()
  57851. {
  57852. return Point<int> (x, y);
  57853. }
  57854. int MouseEvent::getScreenX() const
  57855. {
  57856. return getScreenPosition().getX();
  57857. }
  57858. int MouseEvent::getScreenY() const
  57859. {
  57860. return getScreenPosition().getY();
  57861. }
  57862. const Point<int> MouseEvent::getScreenPosition() const
  57863. {
  57864. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57865. }
  57866. int MouseEvent::getMouseDownScreenX() const
  57867. {
  57868. return getMouseDownScreenPosition().getX();
  57869. }
  57870. int MouseEvent::getMouseDownScreenY() const
  57871. {
  57872. return getMouseDownScreenPosition().getY();
  57873. }
  57874. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57875. {
  57876. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57877. }
  57878. int MouseEvent::doubleClickTimeOutMs = 400;
  57879. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57880. {
  57881. doubleClickTimeOutMs = newTime;
  57882. }
  57883. int MouseEvent::getDoubleClickTimeout() throw()
  57884. {
  57885. return doubleClickTimeOutMs;
  57886. }
  57887. END_JUCE_NAMESPACE
  57888. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57889. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57890. BEGIN_JUCE_NAMESPACE
  57891. class MouseInputSourceInternal : public AsyncUpdater
  57892. {
  57893. public:
  57894. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57895. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  57896. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57897. mouseEventCounter (0)
  57898. {
  57899. zerostruct (mouseDowns);
  57900. }
  57901. ~MouseInputSourceInternal()
  57902. {
  57903. }
  57904. bool isDragging() const throw()
  57905. {
  57906. return buttonState.isAnyMouseButtonDown();
  57907. }
  57908. Component* getComponentUnderMouse() const
  57909. {
  57910. return static_cast <Component*> (componentUnderMouse);
  57911. }
  57912. const ModifierKeys getCurrentModifiers() const
  57913. {
  57914. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57915. }
  57916. ComponentPeer* getPeer()
  57917. {
  57918. if (! ComponentPeer::isValidPeer (lastPeer))
  57919. lastPeer = 0;
  57920. return lastPeer;
  57921. }
  57922. Component* findComponentAt (const Point<int>& screenPos)
  57923. {
  57924. ComponentPeer* const peer = getPeer();
  57925. if (peer != 0)
  57926. {
  57927. Component* const comp = peer->getComponent();
  57928. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57929. // (the contains() call is needed to test for overlapping desktop windows)
  57930. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57931. return comp->getComponentAt (relativePos);
  57932. }
  57933. return 0;
  57934. }
  57935. const Point<int> getScreenPosition() const throw()
  57936. {
  57937. return lastScreenPos + unboundedMouseOffset;
  57938. }
  57939. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57940. {
  57941. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57942. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57943. }
  57944. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57945. {
  57946. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57947. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57948. }
  57949. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57950. {
  57951. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57952. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57953. }
  57954. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57955. {
  57956. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57957. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57958. }
  57959. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57960. {
  57961. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57962. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57963. }
  57964. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57965. {
  57966. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57967. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57968. }
  57969. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57970. {
  57971. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57972. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57973. }
  57974. // (returns true if the button change caused a modal event loop)
  57975. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57976. {
  57977. if (buttonState == newButtonState)
  57978. return false;
  57979. setScreenPos (screenPos, time, false);
  57980. // (ignore secondary clicks when there's already a button down)
  57981. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57982. {
  57983. buttonState = newButtonState;
  57984. return false;
  57985. }
  57986. const int lastCounter = mouseEventCounter;
  57987. if (buttonState.isAnyMouseButtonDown())
  57988. {
  57989. Component* const current = getComponentUnderMouse();
  57990. if (current != 0)
  57991. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57992. enableUnboundedMouseMovement (false, false);
  57993. }
  57994. buttonState = newButtonState;
  57995. if (buttonState.isAnyMouseButtonDown())
  57996. {
  57997. Desktop::getInstance().incrementMouseClickCounter();
  57998. Component* const current = getComponentUnderMouse();
  57999. if (current != 0)
  58000. {
  58001. registerMouseDown (screenPos, time, current);
  58002. sendMouseDown (current, screenPos, time);
  58003. }
  58004. }
  58005. return lastCounter != mouseEventCounter;
  58006. }
  58007. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  58008. {
  58009. Component* current = getComponentUnderMouse();
  58010. if (newComponent != current)
  58011. {
  58012. Component::SafePointer<Component> safeNewComp (newComponent);
  58013. const ModifierKeys originalButtonState (buttonState);
  58014. if (current != 0)
  58015. {
  58016. setButtons (screenPos, time, ModifierKeys());
  58017. sendMouseExit (current, screenPos, time);
  58018. buttonState = originalButtonState;
  58019. }
  58020. componentUnderMouse = safeNewComp;
  58021. current = getComponentUnderMouse();
  58022. if (current != 0)
  58023. sendMouseEnter (current, screenPos, time);
  58024. revealCursor (false);
  58025. setButtons (screenPos, time, originalButtonState);
  58026. }
  58027. }
  58028. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  58029. {
  58030. ModifierKeys::updateCurrentModifiers();
  58031. if (newPeer != lastPeer)
  58032. {
  58033. setComponentUnderMouse (0, screenPos, time);
  58034. lastPeer = newPeer;
  58035. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  58036. }
  58037. }
  58038. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  58039. {
  58040. if (! isDragging())
  58041. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  58042. if (newScreenPos != lastScreenPos || forceUpdate)
  58043. {
  58044. cancelPendingUpdate();
  58045. lastScreenPos = newScreenPos;
  58046. Component* const current = getComponentUnderMouse();
  58047. if (current != 0)
  58048. {
  58049. if (isDragging())
  58050. {
  58051. registerMouseDrag (newScreenPos);
  58052. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  58053. if (isUnboundedMouseModeOn)
  58054. handleUnboundedDrag (current);
  58055. }
  58056. else
  58057. {
  58058. sendMouseMove (current, newScreenPos, time);
  58059. }
  58060. }
  58061. revealCursor (false);
  58062. }
  58063. }
  58064. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  58065. {
  58066. jassert (newPeer != 0);
  58067. lastTime = time;
  58068. ++mouseEventCounter;
  58069. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  58070. if (isDragging() && newMods.isAnyMouseButtonDown())
  58071. {
  58072. setScreenPos (screenPos, time, false);
  58073. }
  58074. else
  58075. {
  58076. setPeer (newPeer, screenPos, time);
  58077. ComponentPeer* peer = getPeer();
  58078. if (peer != 0)
  58079. {
  58080. if (setButtons (screenPos, time, newMods))
  58081. return; // some modal events have been dispatched, so the current event is now out-of-date
  58082. peer = getPeer();
  58083. if (peer != 0)
  58084. setScreenPos (screenPos, time, false);
  58085. }
  58086. }
  58087. }
  58088. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  58089. {
  58090. jassert (peer != 0);
  58091. lastTime = time;
  58092. ++mouseEventCounter;
  58093. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  58094. setPeer (peer, screenPos, time);
  58095. setScreenPos (screenPos, time, false);
  58096. triggerFakeMove();
  58097. if (! isDragging())
  58098. {
  58099. Component* current = getComponentUnderMouse();
  58100. if (current != 0)
  58101. sendMouseWheel (current, screenPos, time, x, y);
  58102. }
  58103. }
  58104. const Time getLastMouseDownTime() const throw()
  58105. {
  58106. return Time (mouseDowns[0].time);
  58107. }
  58108. const Point<int> getLastMouseDownPosition() const throw()
  58109. {
  58110. return mouseDowns[0].position;
  58111. }
  58112. int getNumberOfMultipleClicks() const throw()
  58113. {
  58114. int numClicks = 0;
  58115. if (mouseDowns[0].time != 0)
  58116. {
  58117. if (! mouseMovedSignificantlySincePressed)
  58118. ++numClicks;
  58119. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  58120. {
  58121. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  58122. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  58123. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  58124. {
  58125. ++numClicks;
  58126. }
  58127. else
  58128. {
  58129. break;
  58130. }
  58131. }
  58132. }
  58133. return numClicks;
  58134. }
  58135. bool hasMouseMovedSignificantlySincePressed() const throw()
  58136. {
  58137. return mouseMovedSignificantlySincePressed
  58138. || lastTime > mouseDowns[0].time + 300;
  58139. }
  58140. void triggerFakeMove()
  58141. {
  58142. triggerAsyncUpdate();
  58143. }
  58144. void handleAsyncUpdate()
  58145. {
  58146. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  58147. }
  58148. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  58149. {
  58150. enable = enable && isDragging();
  58151. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  58152. if (enable != isUnboundedMouseModeOn)
  58153. {
  58154. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  58155. {
  58156. // when released, return the mouse to within the component's bounds
  58157. Component* current = getComponentUnderMouse();
  58158. if (current != 0)
  58159. Desktop::setMousePosition (current->getScreenBounds()
  58160. .getConstrainedPoint (lastScreenPos));
  58161. }
  58162. isUnboundedMouseModeOn = enable;
  58163. unboundedMouseOffset = Point<int>();
  58164. revealCursor (true);
  58165. }
  58166. }
  58167. void handleUnboundedDrag (Component* current)
  58168. {
  58169. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  58170. if (! screenArea.contains (lastScreenPos))
  58171. {
  58172. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  58173. unboundedMouseOffset += (lastScreenPos - componentCentre);
  58174. Desktop::setMousePosition (componentCentre);
  58175. }
  58176. else if (isCursorVisibleUntilOffscreen
  58177. && (! unboundedMouseOffset.isOrigin())
  58178. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  58179. {
  58180. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  58181. unboundedMouseOffset = Point<int>();
  58182. }
  58183. }
  58184. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  58185. {
  58186. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  58187. {
  58188. cursor = MouseCursor::NoCursor;
  58189. forcedUpdate = true;
  58190. }
  58191. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  58192. {
  58193. currentCursorHandle = cursor.getHandle();
  58194. cursor.showInWindow (getPeer());
  58195. }
  58196. }
  58197. void hideCursor()
  58198. {
  58199. showMouseCursor (MouseCursor::NoCursor, true);
  58200. }
  58201. void revealCursor (bool forcedUpdate)
  58202. {
  58203. MouseCursor mc (MouseCursor::NormalCursor);
  58204. Component* current = getComponentUnderMouse();
  58205. if (current != 0)
  58206. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  58207. showMouseCursor (mc, forcedUpdate);
  58208. }
  58209. int index;
  58210. bool isMouseDevice;
  58211. Point<int> lastScreenPos;
  58212. ModifierKeys buttonState;
  58213. private:
  58214. MouseInputSource& source;
  58215. Component::SafePointer<Component> componentUnderMouse;
  58216. ComponentPeer* lastPeer;
  58217. Point<int> unboundedMouseOffset;
  58218. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  58219. void* currentCursorHandle;
  58220. int mouseEventCounter;
  58221. struct RecentMouseDown
  58222. {
  58223. Point<int> position;
  58224. int64 time;
  58225. Component* component;
  58226. };
  58227. RecentMouseDown mouseDowns[4];
  58228. bool mouseMovedSignificantlySincePressed;
  58229. int64 lastTime;
  58230. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  58231. {
  58232. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  58233. mouseDowns[i] = mouseDowns[i - 1];
  58234. mouseDowns[0].position = screenPos;
  58235. mouseDowns[0].time = time;
  58236. mouseDowns[0].component = component;
  58237. mouseMovedSignificantlySincePressed = false;
  58238. }
  58239. void registerMouseDrag (const Point<int>& screenPos) throw()
  58240. {
  58241. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  58242. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  58243. }
  58244. MouseInputSourceInternal (const MouseInputSourceInternal&);
  58245. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  58246. };
  58247. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  58248. {
  58249. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  58250. }
  58251. MouseInputSource::~MouseInputSource()
  58252. {
  58253. }
  58254. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  58255. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  58256. bool MouseInputSource::canHover() const { return isMouse(); }
  58257. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  58258. int MouseInputSource::getIndex() const { return pimpl->index; }
  58259. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  58260. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  58261. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  58262. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  58263. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  58264. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  58265. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  58266. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  58267. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  58268. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  58269. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  58270. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  58271. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  58272. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  58273. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  58274. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  58275. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  58276. {
  58277. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  58278. }
  58279. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  58280. {
  58281. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  58282. }
  58283. END_JUCE_NAMESPACE
  58284. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  58285. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  58286. BEGIN_JUCE_NAMESPACE
  58287. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  58288. : source (0),
  58289. hoverTimeMillisecs (hoverTimeMillisecs_),
  58290. hasJustHovered (false)
  58291. {
  58292. internalTimer.owner = this;
  58293. }
  58294. MouseHoverDetector::~MouseHoverDetector()
  58295. {
  58296. setHoverComponent (0);
  58297. }
  58298. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  58299. {
  58300. hoverTimeMillisecs = newTimeInMillisecs;
  58301. }
  58302. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  58303. {
  58304. if (source != newSourceComponent)
  58305. {
  58306. internalTimer.stopTimer();
  58307. hasJustHovered = false;
  58308. if (source != 0)
  58309. {
  58310. // ! you need to delete the hover detector before deleting its component
  58311. jassert (source->isValidComponent());
  58312. source->removeMouseListener (&internalTimer);
  58313. }
  58314. source = newSourceComponent;
  58315. if (newSourceComponent != 0)
  58316. newSourceComponent->addMouseListener (&internalTimer, false);
  58317. }
  58318. }
  58319. void MouseHoverDetector::hoverTimerCallback()
  58320. {
  58321. internalTimer.stopTimer();
  58322. if (source != 0)
  58323. {
  58324. const Point<int> pos (source->getMouseXYRelative());
  58325. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58326. {
  58327. hasJustHovered = true;
  58328. mouseHovered (pos.getX(), pos.getY());
  58329. }
  58330. }
  58331. }
  58332. void MouseHoverDetector::checkJustHoveredCallback()
  58333. {
  58334. if (hasJustHovered)
  58335. {
  58336. hasJustHovered = false;
  58337. mouseMovedAfterHover();
  58338. }
  58339. }
  58340. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58341. {
  58342. owner->hoverTimerCallback();
  58343. }
  58344. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58345. {
  58346. stopTimer();
  58347. owner->checkJustHoveredCallback();
  58348. }
  58349. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58350. {
  58351. stopTimer();
  58352. owner->checkJustHoveredCallback();
  58353. }
  58354. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58355. {
  58356. stopTimer();
  58357. owner->checkJustHoveredCallback();
  58358. }
  58359. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58360. {
  58361. stopTimer();
  58362. owner->checkJustHoveredCallback();
  58363. }
  58364. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58365. {
  58366. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58367. {
  58368. lastX = e.x;
  58369. lastY = e.y;
  58370. if (owner->source != 0)
  58371. startTimer (owner->hoverTimeMillisecs);
  58372. owner->checkJustHoveredCallback();
  58373. }
  58374. }
  58375. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58376. {
  58377. stopTimer();
  58378. owner->checkJustHoveredCallback();
  58379. }
  58380. END_JUCE_NAMESPACE
  58381. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58382. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58383. BEGIN_JUCE_NAMESPACE
  58384. void MouseListener::mouseEnter (const MouseEvent&)
  58385. {
  58386. }
  58387. void MouseListener::mouseExit (const MouseEvent&)
  58388. {
  58389. }
  58390. void MouseListener::mouseDown (const MouseEvent&)
  58391. {
  58392. }
  58393. void MouseListener::mouseUp (const MouseEvent&)
  58394. {
  58395. }
  58396. void MouseListener::mouseDrag (const MouseEvent&)
  58397. {
  58398. }
  58399. void MouseListener::mouseMove (const MouseEvent&)
  58400. {
  58401. }
  58402. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58403. {
  58404. }
  58405. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58406. {
  58407. }
  58408. END_JUCE_NAMESPACE
  58409. /*** End of inlined file: juce_MouseListener.cpp ***/
  58410. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58411. BEGIN_JUCE_NAMESPACE
  58412. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58413. const String& buttonTextWhenTrue,
  58414. const String& buttonTextWhenFalse)
  58415. : PropertyComponent (name),
  58416. onText (buttonTextWhenTrue),
  58417. offText (buttonTextWhenFalse)
  58418. {
  58419. addAndMakeVisible (&button);
  58420. button.setClickingTogglesState (false);
  58421. button.addButtonListener (this);
  58422. }
  58423. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58424. const String& name,
  58425. const String& buttonText)
  58426. : PropertyComponent (name),
  58427. onText (buttonText),
  58428. offText (buttonText)
  58429. {
  58430. addAndMakeVisible (&button);
  58431. button.setClickingTogglesState (false);
  58432. button.setButtonText (buttonText);
  58433. button.getToggleStateValue().referTo (valueToControl);
  58434. button.setClickingTogglesState (true);
  58435. }
  58436. BooleanPropertyComponent::~BooleanPropertyComponent()
  58437. {
  58438. }
  58439. void BooleanPropertyComponent::setState (const bool newState)
  58440. {
  58441. button.setToggleState (newState, true);
  58442. }
  58443. bool BooleanPropertyComponent::getState() const
  58444. {
  58445. return button.getToggleState();
  58446. }
  58447. void BooleanPropertyComponent::paint (Graphics& g)
  58448. {
  58449. PropertyComponent::paint (g);
  58450. g.setColour (Colours::white);
  58451. g.fillRect (button.getBounds());
  58452. g.setColour (findColour (ComboBox::outlineColourId));
  58453. g.drawRect (button.getBounds());
  58454. }
  58455. void BooleanPropertyComponent::refresh()
  58456. {
  58457. button.setToggleState (getState(), false);
  58458. button.setButtonText (button.getToggleState() ? onText : offText);
  58459. }
  58460. void BooleanPropertyComponent::buttonClicked (Button*)
  58461. {
  58462. setState (! getState());
  58463. }
  58464. END_JUCE_NAMESPACE
  58465. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58466. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58467. BEGIN_JUCE_NAMESPACE
  58468. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58469. const bool triggerOnMouseDown)
  58470. : PropertyComponent (name)
  58471. {
  58472. addAndMakeVisible (&button);
  58473. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58474. button.addButtonListener (this);
  58475. }
  58476. ButtonPropertyComponent::~ButtonPropertyComponent()
  58477. {
  58478. }
  58479. void ButtonPropertyComponent::refresh()
  58480. {
  58481. button.setButtonText (getButtonText());
  58482. }
  58483. void ButtonPropertyComponent::buttonClicked (Button*)
  58484. {
  58485. buttonClicked();
  58486. }
  58487. END_JUCE_NAMESPACE
  58488. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58489. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58490. BEGIN_JUCE_NAMESPACE
  58491. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58492. public Value::Listener
  58493. {
  58494. public:
  58495. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58496. : sourceValue (sourceValue_),
  58497. mappings (mappings_)
  58498. {
  58499. sourceValue.addListener (this);
  58500. }
  58501. ~RemapperValueSource() {}
  58502. const var getValue() const
  58503. {
  58504. return mappings.indexOf (sourceValue.getValue()) + 1;
  58505. }
  58506. void setValue (const var& newValue)
  58507. {
  58508. const var remappedVal (mappings [(int) newValue - 1]);
  58509. if (remappedVal != sourceValue)
  58510. sourceValue = remappedVal;
  58511. }
  58512. void valueChanged (Value&)
  58513. {
  58514. sendChangeMessage (true);
  58515. }
  58516. juce_UseDebuggingNewOperator
  58517. protected:
  58518. Value sourceValue;
  58519. Array<var> mappings;
  58520. RemapperValueSource (const RemapperValueSource&);
  58521. const RemapperValueSource& operator= (const RemapperValueSource&);
  58522. };
  58523. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58524. : PropertyComponent (name),
  58525. isCustomClass (true)
  58526. {
  58527. }
  58528. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58529. const String& name,
  58530. const StringArray& choices_,
  58531. const Array <var>& correspondingValues)
  58532. : PropertyComponent (name),
  58533. choices (choices_),
  58534. isCustomClass (false)
  58535. {
  58536. // The array of corresponding values must contain one value for each of the items in
  58537. // the choices array!
  58538. jassert (correspondingValues.size() == choices.size());
  58539. createComboBox();
  58540. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58541. }
  58542. ChoicePropertyComponent::~ChoicePropertyComponent()
  58543. {
  58544. }
  58545. void ChoicePropertyComponent::createComboBox()
  58546. {
  58547. addAndMakeVisible (&comboBox);
  58548. for (int i = 0; i < choices.size(); ++i)
  58549. {
  58550. if (choices[i].isNotEmpty())
  58551. comboBox.addItem (choices[i], i + 1);
  58552. else
  58553. comboBox.addSeparator();
  58554. }
  58555. comboBox.setEditableText (false);
  58556. }
  58557. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58558. {
  58559. jassertfalse; // you need to override this method in your subclass!
  58560. }
  58561. int ChoicePropertyComponent::getIndex() const
  58562. {
  58563. jassertfalse; // you need to override this method in your subclass!
  58564. return -1;
  58565. }
  58566. const StringArray& ChoicePropertyComponent::getChoices() const
  58567. {
  58568. return choices;
  58569. }
  58570. void ChoicePropertyComponent::refresh()
  58571. {
  58572. if (isCustomClass)
  58573. {
  58574. if (! comboBox.isVisible())
  58575. {
  58576. createComboBox();
  58577. comboBox.addListener (this);
  58578. }
  58579. comboBox.setSelectedId (getIndex() + 1, true);
  58580. }
  58581. }
  58582. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58583. {
  58584. if (isCustomClass)
  58585. {
  58586. const int newIndex = comboBox.getSelectedId() - 1;
  58587. if (newIndex != getIndex())
  58588. setIndex (newIndex);
  58589. }
  58590. }
  58591. END_JUCE_NAMESPACE
  58592. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58593. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58594. BEGIN_JUCE_NAMESPACE
  58595. PropertyComponent::PropertyComponent (const String& name,
  58596. const int preferredHeight_)
  58597. : Component (name),
  58598. preferredHeight (preferredHeight_)
  58599. {
  58600. jassert (name.isNotEmpty());
  58601. }
  58602. PropertyComponent::~PropertyComponent()
  58603. {
  58604. }
  58605. void PropertyComponent::paint (Graphics& g)
  58606. {
  58607. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58608. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58609. }
  58610. void PropertyComponent::resized()
  58611. {
  58612. if (getNumChildComponents() > 0)
  58613. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58614. }
  58615. void PropertyComponent::enablementChanged()
  58616. {
  58617. repaint();
  58618. }
  58619. END_JUCE_NAMESPACE
  58620. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58621. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58622. BEGIN_JUCE_NAMESPACE
  58623. class PropertyPanel::PropertyHolderComponent : public Component
  58624. {
  58625. public:
  58626. PropertyHolderComponent()
  58627. {
  58628. }
  58629. ~PropertyHolderComponent()
  58630. {
  58631. deleteAllChildren();
  58632. }
  58633. void paint (Graphics&)
  58634. {
  58635. }
  58636. void updateLayout (int width);
  58637. void refreshAll() const;
  58638. private:
  58639. PropertyHolderComponent (const PropertyHolderComponent&);
  58640. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58641. };
  58642. class PropertySectionComponent : public Component
  58643. {
  58644. public:
  58645. PropertySectionComponent (const String& sectionTitle,
  58646. const Array <PropertyComponent*>& newProperties,
  58647. const bool open)
  58648. : Component (sectionTitle),
  58649. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58650. isOpen_ (open)
  58651. {
  58652. for (int i = newProperties.size(); --i >= 0;)
  58653. {
  58654. addAndMakeVisible (newProperties.getUnchecked(i));
  58655. newProperties.getUnchecked(i)->refresh();
  58656. }
  58657. }
  58658. ~PropertySectionComponent()
  58659. {
  58660. deleteAllChildren();
  58661. }
  58662. void paint (Graphics& g)
  58663. {
  58664. if (titleHeight > 0)
  58665. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58666. }
  58667. void resized()
  58668. {
  58669. int y = titleHeight;
  58670. for (int i = getNumChildComponents(); --i >= 0;)
  58671. {
  58672. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58673. if (pec != 0)
  58674. {
  58675. const int prefH = pec->getPreferredHeight();
  58676. pec->setBounds (1, y, getWidth() - 2, prefH);
  58677. y += prefH;
  58678. }
  58679. }
  58680. }
  58681. int getPreferredHeight() const
  58682. {
  58683. int y = titleHeight;
  58684. if (isOpen())
  58685. {
  58686. for (int i = 0; i < getNumChildComponents(); ++i)
  58687. {
  58688. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58689. if (pec != 0)
  58690. y += pec->getPreferredHeight();
  58691. }
  58692. }
  58693. return y;
  58694. }
  58695. void setOpen (const bool open)
  58696. {
  58697. if (isOpen_ != open)
  58698. {
  58699. isOpen_ = open;
  58700. for (int i = 0; i < getNumChildComponents(); ++i)
  58701. {
  58702. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58703. if (pec != 0)
  58704. pec->setVisible (open);
  58705. }
  58706. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58707. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58708. if (pp != 0)
  58709. pp->resized();
  58710. }
  58711. }
  58712. bool isOpen() const
  58713. {
  58714. return isOpen_;
  58715. }
  58716. void refreshAll() const
  58717. {
  58718. for (int i = 0; i < getNumChildComponents(); ++i)
  58719. {
  58720. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58721. if (pec != 0)
  58722. pec->refresh();
  58723. }
  58724. }
  58725. void mouseDown (const MouseEvent&)
  58726. {
  58727. }
  58728. void mouseUp (const MouseEvent& e)
  58729. {
  58730. if (e.getMouseDownX() < titleHeight
  58731. && e.x < titleHeight
  58732. && e.y < titleHeight
  58733. && e.getNumberOfClicks() != 2)
  58734. {
  58735. setOpen (! isOpen());
  58736. }
  58737. }
  58738. void mouseDoubleClick (const MouseEvent& e)
  58739. {
  58740. if (e.y < titleHeight)
  58741. setOpen (! isOpen());
  58742. }
  58743. private:
  58744. int titleHeight;
  58745. bool isOpen_;
  58746. PropertySectionComponent (const PropertySectionComponent&);
  58747. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58748. };
  58749. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58750. {
  58751. int y = 0;
  58752. for (int i = getNumChildComponents(); --i >= 0;)
  58753. {
  58754. PropertySectionComponent* const section
  58755. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58756. if (section != 0)
  58757. {
  58758. const int prefH = section->getPreferredHeight();
  58759. section->setBounds (0, y, width, prefH);
  58760. y += prefH;
  58761. }
  58762. }
  58763. setSize (width, y);
  58764. repaint();
  58765. }
  58766. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58767. {
  58768. for (int i = getNumChildComponents(); --i >= 0;)
  58769. {
  58770. PropertySectionComponent* const section
  58771. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58772. if (section != 0)
  58773. section->refreshAll();
  58774. }
  58775. }
  58776. PropertyPanel::PropertyPanel()
  58777. {
  58778. messageWhenEmpty = TRANS("(nothing selected)");
  58779. addAndMakeVisible (&viewport);
  58780. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58781. viewport.setFocusContainer (true);
  58782. }
  58783. PropertyPanel::~PropertyPanel()
  58784. {
  58785. clear();
  58786. }
  58787. void PropertyPanel::paint (Graphics& g)
  58788. {
  58789. if (propertyHolderComponent->getNumChildComponents() == 0)
  58790. {
  58791. g.setColour (Colours::black.withAlpha (0.5f));
  58792. g.setFont (14.0f);
  58793. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58794. Justification::centred, true);
  58795. }
  58796. }
  58797. void PropertyPanel::resized()
  58798. {
  58799. viewport.setBounds (getLocalBounds());
  58800. updatePropHolderLayout();
  58801. }
  58802. void PropertyPanel::clear()
  58803. {
  58804. if (propertyHolderComponent->getNumChildComponents() > 0)
  58805. {
  58806. propertyHolderComponent->deleteAllChildren();
  58807. repaint();
  58808. }
  58809. }
  58810. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58811. {
  58812. if (propertyHolderComponent->getNumChildComponents() == 0)
  58813. repaint();
  58814. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58815. newProperties,
  58816. true), 0);
  58817. updatePropHolderLayout();
  58818. }
  58819. void PropertyPanel::addSection (const String& sectionTitle,
  58820. const Array <PropertyComponent*>& newProperties,
  58821. const bool shouldBeOpen)
  58822. {
  58823. jassert (sectionTitle.isNotEmpty());
  58824. if (propertyHolderComponent->getNumChildComponents() == 0)
  58825. repaint();
  58826. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58827. newProperties,
  58828. shouldBeOpen), 0);
  58829. updatePropHolderLayout();
  58830. }
  58831. void PropertyPanel::updatePropHolderLayout() const
  58832. {
  58833. const int maxWidth = viewport.getMaximumVisibleWidth();
  58834. propertyHolderComponent->updateLayout (maxWidth);
  58835. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58836. if (maxWidth != newMaxWidth)
  58837. {
  58838. // need to do this twice because of scrollbars changing the size, etc.
  58839. propertyHolderComponent->updateLayout (newMaxWidth);
  58840. }
  58841. }
  58842. void PropertyPanel::refreshAll() const
  58843. {
  58844. propertyHolderComponent->refreshAll();
  58845. }
  58846. const StringArray PropertyPanel::getSectionNames() const
  58847. {
  58848. StringArray s;
  58849. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58850. {
  58851. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58852. if (section != 0 && section->getName().isNotEmpty())
  58853. s.add (section->getName());
  58854. }
  58855. return s;
  58856. }
  58857. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58858. {
  58859. int index = 0;
  58860. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58861. {
  58862. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58863. if (section != 0 && section->getName().isNotEmpty())
  58864. {
  58865. if (index == sectionIndex)
  58866. return section->isOpen();
  58867. ++index;
  58868. }
  58869. }
  58870. return false;
  58871. }
  58872. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58873. {
  58874. int index = 0;
  58875. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58876. {
  58877. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58878. if (section != 0 && section->getName().isNotEmpty())
  58879. {
  58880. if (index == sectionIndex)
  58881. {
  58882. section->setOpen (shouldBeOpen);
  58883. break;
  58884. }
  58885. ++index;
  58886. }
  58887. }
  58888. }
  58889. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58890. {
  58891. int index = 0;
  58892. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58893. {
  58894. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58895. if (section != 0 && section->getName().isNotEmpty())
  58896. {
  58897. if (index == sectionIndex)
  58898. {
  58899. section->setEnabled (shouldBeEnabled);
  58900. break;
  58901. }
  58902. ++index;
  58903. }
  58904. }
  58905. }
  58906. XmlElement* PropertyPanel::getOpennessState() const
  58907. {
  58908. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58909. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58910. const StringArray sections (getSectionNames());
  58911. for (int i = 0; i < sections.size(); ++i)
  58912. {
  58913. if (sections[i].isNotEmpty())
  58914. {
  58915. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58916. e->setAttribute ("name", sections[i]);
  58917. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58918. }
  58919. }
  58920. return xml;
  58921. }
  58922. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58923. {
  58924. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58925. {
  58926. const StringArray sections (getSectionNames());
  58927. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58928. {
  58929. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58930. e->getBoolAttribute ("open"));
  58931. }
  58932. viewport.setViewPosition (viewport.getViewPositionX(),
  58933. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58934. }
  58935. }
  58936. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58937. {
  58938. if (messageWhenEmpty != newMessage)
  58939. {
  58940. messageWhenEmpty = newMessage;
  58941. repaint();
  58942. }
  58943. }
  58944. const String& PropertyPanel::getMessageWhenEmpty() const
  58945. {
  58946. return messageWhenEmpty;
  58947. }
  58948. END_JUCE_NAMESPACE
  58949. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58950. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58951. BEGIN_JUCE_NAMESPACE
  58952. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58953. const double rangeMin,
  58954. const double rangeMax,
  58955. const double interval,
  58956. const double skewFactor)
  58957. : PropertyComponent (name)
  58958. {
  58959. addAndMakeVisible (&slider);
  58960. slider.setRange (rangeMin, rangeMax, interval);
  58961. slider.setSkewFactor (skewFactor);
  58962. slider.setSliderStyle (Slider::LinearBar);
  58963. slider.addListener (this);
  58964. }
  58965. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58966. const String& name,
  58967. const double rangeMin,
  58968. const double rangeMax,
  58969. const double interval,
  58970. const double skewFactor)
  58971. : PropertyComponent (name)
  58972. {
  58973. addAndMakeVisible (&slider);
  58974. slider.setRange (rangeMin, rangeMax, interval);
  58975. slider.setSkewFactor (skewFactor);
  58976. slider.setSliderStyle (Slider::LinearBar);
  58977. slider.getValueObject().referTo (valueToControl);
  58978. }
  58979. SliderPropertyComponent::~SliderPropertyComponent()
  58980. {
  58981. }
  58982. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58983. {
  58984. }
  58985. double SliderPropertyComponent::getValue() const
  58986. {
  58987. return slider.getValue();
  58988. }
  58989. void SliderPropertyComponent::refresh()
  58990. {
  58991. slider.setValue (getValue(), false);
  58992. }
  58993. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58994. {
  58995. if (getValue() != slider.getValue())
  58996. setValue (slider.getValue());
  58997. }
  58998. END_JUCE_NAMESPACE
  58999. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  59000. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  59001. BEGIN_JUCE_NAMESPACE
  59002. class TextPropLabel : public Label
  59003. {
  59004. TextPropertyComponent& owner;
  59005. int maxChars;
  59006. bool isMultiline;
  59007. public:
  59008. TextPropLabel (TextPropertyComponent& owner_,
  59009. const int maxChars_, const bool isMultiline_)
  59010. : Label (String::empty, String::empty),
  59011. owner (owner_),
  59012. maxChars (maxChars_),
  59013. isMultiline (isMultiline_)
  59014. {
  59015. setEditable (true, true, false);
  59016. setColour (backgroundColourId, Colours::white);
  59017. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  59018. }
  59019. ~TextPropLabel()
  59020. {
  59021. }
  59022. TextEditor* createEditorComponent()
  59023. {
  59024. TextEditor* const textEditor = Label::createEditorComponent();
  59025. textEditor->setInputRestrictions (maxChars);
  59026. if (isMultiline)
  59027. {
  59028. textEditor->setMultiLine (true, true);
  59029. textEditor->setReturnKeyStartsNewLine (true);
  59030. }
  59031. return textEditor;
  59032. }
  59033. void textWasEdited()
  59034. {
  59035. owner.textWasEdited();
  59036. }
  59037. };
  59038. TextPropertyComponent::TextPropertyComponent (const String& name,
  59039. const int maxNumChars,
  59040. const bool isMultiLine)
  59041. : PropertyComponent (name)
  59042. {
  59043. createEditor (maxNumChars, isMultiLine);
  59044. }
  59045. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  59046. const String& name,
  59047. const int maxNumChars,
  59048. const bool isMultiLine)
  59049. : PropertyComponent (name)
  59050. {
  59051. createEditor (maxNumChars, isMultiLine);
  59052. textEditor->getTextValue().referTo (valueToControl);
  59053. }
  59054. TextPropertyComponent::~TextPropertyComponent()
  59055. {
  59056. deleteAllChildren();
  59057. }
  59058. void TextPropertyComponent::setText (const String& newText)
  59059. {
  59060. textEditor->setText (newText, true);
  59061. }
  59062. const String TextPropertyComponent::getText() const
  59063. {
  59064. return textEditor->getText();
  59065. }
  59066. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  59067. {
  59068. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  59069. if (isMultiLine)
  59070. {
  59071. textEditor->setJustificationType (Justification::topLeft);
  59072. preferredHeight = 120;
  59073. }
  59074. }
  59075. void TextPropertyComponent::refresh()
  59076. {
  59077. textEditor->setText (getText(), false);
  59078. }
  59079. void TextPropertyComponent::textWasEdited()
  59080. {
  59081. const String newText (textEditor->getText());
  59082. if (getText() != newText)
  59083. setText (newText);
  59084. }
  59085. END_JUCE_NAMESPACE
  59086. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  59087. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59088. BEGIN_JUCE_NAMESPACE
  59089. class SimpleDeviceManagerInputLevelMeter : public Component,
  59090. public Timer
  59091. {
  59092. public:
  59093. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  59094. : manager (manager_),
  59095. level (0)
  59096. {
  59097. startTimer (50);
  59098. manager->enableInputLevelMeasurement (true);
  59099. }
  59100. ~SimpleDeviceManagerInputLevelMeter()
  59101. {
  59102. manager->enableInputLevelMeasurement (false);
  59103. }
  59104. void timerCallback()
  59105. {
  59106. const float newLevel = (float) manager->getCurrentInputLevel();
  59107. if (std::abs (level - newLevel) > 0.005f)
  59108. {
  59109. level = newLevel;
  59110. repaint();
  59111. }
  59112. }
  59113. void paint (Graphics& g)
  59114. {
  59115. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  59116. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  59117. }
  59118. private:
  59119. AudioDeviceManager* const manager;
  59120. float level;
  59121. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  59122. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  59123. };
  59124. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  59125. public ListBoxModel
  59126. {
  59127. public:
  59128. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  59129. const String& noItemsMessage_,
  59130. const int minNumber_,
  59131. const int maxNumber_)
  59132. : ListBox (String::empty, 0),
  59133. deviceManager (deviceManager_),
  59134. noItemsMessage (noItemsMessage_),
  59135. minNumber (minNumber_),
  59136. maxNumber (maxNumber_)
  59137. {
  59138. items = MidiInput::getDevices();
  59139. setModel (this);
  59140. setOutlineThickness (1);
  59141. }
  59142. ~MidiInputSelectorComponentListBox()
  59143. {
  59144. }
  59145. int getNumRows()
  59146. {
  59147. return items.size();
  59148. }
  59149. void paintListBoxItem (int row,
  59150. Graphics& g,
  59151. int width, int height,
  59152. bool rowIsSelected)
  59153. {
  59154. if (((unsigned int) row) < (unsigned int) items.size())
  59155. {
  59156. if (rowIsSelected)
  59157. g.fillAll (findColour (TextEditor::highlightColourId)
  59158. .withMultipliedAlpha (0.3f));
  59159. const String item (items [row]);
  59160. bool enabled = deviceManager.isMidiInputEnabled (item);
  59161. const int x = getTickX();
  59162. const float tickW = height * 0.75f;
  59163. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59164. enabled, true, true, false);
  59165. g.setFont (height * 0.6f);
  59166. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59167. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59168. }
  59169. }
  59170. void listBoxItemClicked (int row, const MouseEvent& e)
  59171. {
  59172. selectRow (row);
  59173. if (e.x < getTickX())
  59174. flipEnablement (row);
  59175. }
  59176. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59177. {
  59178. flipEnablement (row);
  59179. }
  59180. void returnKeyPressed (int row)
  59181. {
  59182. flipEnablement (row);
  59183. }
  59184. void paint (Graphics& g)
  59185. {
  59186. ListBox::paint (g);
  59187. if (items.size() == 0)
  59188. {
  59189. g.setColour (Colours::grey);
  59190. g.setFont (13.0f);
  59191. g.drawText (noItemsMessage,
  59192. 0, 0, getWidth(), getHeight() / 2,
  59193. Justification::centred, true);
  59194. }
  59195. }
  59196. int getBestHeight (const int preferredHeight)
  59197. {
  59198. const int extra = getOutlineThickness() * 2;
  59199. return jmax (getRowHeight() * 2 + extra,
  59200. jmin (getRowHeight() * getNumRows() + extra,
  59201. preferredHeight));
  59202. }
  59203. juce_UseDebuggingNewOperator
  59204. private:
  59205. AudioDeviceManager& deviceManager;
  59206. const String noItemsMessage;
  59207. StringArray items;
  59208. int minNumber, maxNumber;
  59209. void flipEnablement (const int row)
  59210. {
  59211. if (((unsigned int) row) < (unsigned int) items.size())
  59212. {
  59213. const String item (items [row]);
  59214. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  59215. }
  59216. }
  59217. int getTickX() const
  59218. {
  59219. return getRowHeight() + 5;
  59220. }
  59221. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  59222. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  59223. };
  59224. class AudioDeviceSettingsPanel : public Component,
  59225. public ChangeListener,
  59226. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  59227. public ButtonListener
  59228. {
  59229. public:
  59230. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  59231. AudioIODeviceType::DeviceSetupDetails& setup_,
  59232. const bool hideAdvancedOptionsWithButton)
  59233. : type (type_),
  59234. setup (setup_)
  59235. {
  59236. if (hideAdvancedOptionsWithButton)
  59237. {
  59238. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  59239. showAdvancedSettingsButton->addButtonListener (this);
  59240. }
  59241. type->scanForDevices();
  59242. setup.manager->addChangeListener (this);
  59243. changeListenerCallback (0);
  59244. }
  59245. ~AudioDeviceSettingsPanel()
  59246. {
  59247. setup.manager->removeChangeListener (this);
  59248. }
  59249. void resized()
  59250. {
  59251. const int lx = proportionOfWidth (0.35f);
  59252. const int w = proportionOfWidth (0.4f);
  59253. const int h = 24;
  59254. const int space = 6;
  59255. const int dh = h + space;
  59256. int y = 0;
  59257. if (outputDeviceDropDown != 0)
  59258. {
  59259. outputDeviceDropDown->setBounds (lx, y, w, h);
  59260. if (testButton != 0)
  59261. testButton->setBounds (proportionOfWidth (0.77f),
  59262. outputDeviceDropDown->getY(),
  59263. proportionOfWidth (0.18f),
  59264. h);
  59265. y += dh;
  59266. }
  59267. if (inputDeviceDropDown != 0)
  59268. {
  59269. inputDeviceDropDown->setBounds (lx, y, w, h);
  59270. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  59271. inputDeviceDropDown->getY(),
  59272. proportionOfWidth (0.18f),
  59273. h);
  59274. y += dh;
  59275. }
  59276. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  59277. if (outputChanList != 0)
  59278. {
  59279. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  59280. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59281. y += bh + space;
  59282. }
  59283. if (inputChanList != 0)
  59284. {
  59285. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  59286. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59287. y += bh + space;
  59288. }
  59289. y += space * 2;
  59290. if (showAdvancedSettingsButton != 0)
  59291. {
  59292. showAdvancedSettingsButton->changeWidthToFitText (h);
  59293. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  59294. }
  59295. if (sampleRateDropDown != 0)
  59296. {
  59297. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  59298. || ! showAdvancedSettingsButton->isVisible());
  59299. sampleRateDropDown->setBounds (lx, y, w, h);
  59300. y += dh;
  59301. }
  59302. if (bufferSizeDropDown != 0)
  59303. {
  59304. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  59305. || ! showAdvancedSettingsButton->isVisible());
  59306. bufferSizeDropDown->setBounds (lx, y, w, h);
  59307. y += dh;
  59308. }
  59309. if (showUIButton != 0)
  59310. {
  59311. showUIButton->setVisible (showAdvancedSettingsButton == 0
  59312. || ! showAdvancedSettingsButton->isVisible());
  59313. showUIButton->changeWidthToFitText (h);
  59314. showUIButton->setTopLeftPosition (lx, y);
  59315. }
  59316. }
  59317. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59318. {
  59319. if (comboBoxThatHasChanged == 0)
  59320. return;
  59321. AudioDeviceManager::AudioDeviceSetup config;
  59322. setup.manager->getAudioDeviceSetup (config);
  59323. String error;
  59324. if (comboBoxThatHasChanged == outputDeviceDropDown
  59325. || comboBoxThatHasChanged == inputDeviceDropDown)
  59326. {
  59327. if (outputDeviceDropDown != 0)
  59328. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59329. : outputDeviceDropDown->getText();
  59330. if (inputDeviceDropDown != 0)
  59331. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59332. : inputDeviceDropDown->getText();
  59333. if (! type->hasSeparateInputsAndOutputs())
  59334. config.inputDeviceName = config.outputDeviceName;
  59335. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59336. config.useDefaultInputChannels = true;
  59337. else
  59338. config.useDefaultOutputChannels = true;
  59339. error = setup.manager->setAudioDeviceSetup (config, true);
  59340. showCorrectDeviceName (inputDeviceDropDown, true);
  59341. showCorrectDeviceName (outputDeviceDropDown, false);
  59342. updateControlPanelButton();
  59343. resized();
  59344. }
  59345. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59346. {
  59347. if (sampleRateDropDown->getSelectedId() > 0)
  59348. {
  59349. config.sampleRate = sampleRateDropDown->getSelectedId();
  59350. error = setup.manager->setAudioDeviceSetup (config, true);
  59351. }
  59352. }
  59353. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59354. {
  59355. if (bufferSizeDropDown->getSelectedId() > 0)
  59356. {
  59357. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59358. error = setup.manager->setAudioDeviceSetup (config, true);
  59359. }
  59360. }
  59361. if (error.isNotEmpty())
  59362. {
  59363. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59364. "Error when trying to open audio device!",
  59365. error);
  59366. }
  59367. }
  59368. void buttonClicked (Button* button)
  59369. {
  59370. if (button == showAdvancedSettingsButton)
  59371. {
  59372. showAdvancedSettingsButton->setVisible (false);
  59373. resized();
  59374. }
  59375. else if (button == showUIButton)
  59376. {
  59377. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59378. if (device != 0 && device->showControlPanel())
  59379. {
  59380. setup.manager->closeAudioDevice();
  59381. setup.manager->restartLastAudioDevice();
  59382. getTopLevelComponent()->toFront (true);
  59383. }
  59384. }
  59385. else if (button == testButton && testButton != 0)
  59386. {
  59387. setup.manager->playTestSound();
  59388. }
  59389. }
  59390. void updateControlPanelButton()
  59391. {
  59392. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59393. showUIButton = 0;
  59394. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59395. {
  59396. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59397. TRANS ("opens the device's own control panel")));
  59398. showUIButton->addButtonListener (this);
  59399. }
  59400. resized();
  59401. }
  59402. void changeListenerCallback (void*)
  59403. {
  59404. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59405. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59406. {
  59407. if (outputDeviceDropDown == 0)
  59408. {
  59409. outputDeviceDropDown = new ComboBox (String::empty);
  59410. outputDeviceDropDown->addListener (this);
  59411. addAndMakeVisible (outputDeviceDropDown);
  59412. outputDeviceLabel = new Label (String::empty,
  59413. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59414. : TRANS ("device:"));
  59415. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59416. if (setup.maxNumOutputChannels > 0)
  59417. {
  59418. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59419. testButton->addButtonListener (this);
  59420. }
  59421. }
  59422. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59423. }
  59424. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59425. {
  59426. if (inputDeviceDropDown == 0)
  59427. {
  59428. inputDeviceDropDown = new ComboBox (String::empty);
  59429. inputDeviceDropDown->addListener (this);
  59430. addAndMakeVisible (inputDeviceDropDown);
  59431. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59432. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59433. addAndMakeVisible (inputLevelMeter
  59434. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59435. }
  59436. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59437. }
  59438. updateControlPanelButton();
  59439. showCorrectDeviceName (inputDeviceDropDown, true);
  59440. showCorrectDeviceName (outputDeviceDropDown, false);
  59441. if (currentDevice != 0)
  59442. {
  59443. if (setup.maxNumOutputChannels > 0
  59444. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59445. {
  59446. if (outputChanList == 0)
  59447. {
  59448. addAndMakeVisible (outputChanList
  59449. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59450. TRANS ("(no audio output channels found)")));
  59451. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59452. outputChanLabel->attachToComponent (outputChanList, true);
  59453. }
  59454. outputChanList->refresh();
  59455. }
  59456. else
  59457. {
  59458. outputChanLabel = 0;
  59459. outputChanList = 0;
  59460. }
  59461. if (setup.maxNumInputChannels > 0
  59462. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59463. {
  59464. if (inputChanList == 0)
  59465. {
  59466. addAndMakeVisible (inputChanList
  59467. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59468. TRANS ("(no audio input channels found)")));
  59469. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59470. inputChanLabel->attachToComponent (inputChanList, true);
  59471. }
  59472. inputChanList->refresh();
  59473. }
  59474. else
  59475. {
  59476. inputChanLabel = 0;
  59477. inputChanList = 0;
  59478. }
  59479. // sample rate..
  59480. {
  59481. if (sampleRateDropDown == 0)
  59482. {
  59483. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59484. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59485. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59486. }
  59487. else
  59488. {
  59489. sampleRateDropDown->clear();
  59490. sampleRateDropDown->removeListener (this);
  59491. }
  59492. const int numRates = currentDevice->getNumSampleRates();
  59493. for (int i = 0; i < numRates; ++i)
  59494. {
  59495. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59496. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59497. }
  59498. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59499. sampleRateDropDown->addListener (this);
  59500. }
  59501. // buffer size
  59502. {
  59503. if (bufferSizeDropDown == 0)
  59504. {
  59505. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59506. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59507. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59508. }
  59509. else
  59510. {
  59511. bufferSizeDropDown->clear();
  59512. bufferSizeDropDown->removeListener (this);
  59513. }
  59514. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59515. double currentRate = currentDevice->getCurrentSampleRate();
  59516. if (currentRate == 0)
  59517. currentRate = 48000.0;
  59518. for (int i = 0; i < numBufferSizes; ++i)
  59519. {
  59520. const int bs = currentDevice->getBufferSizeSamples (i);
  59521. bufferSizeDropDown->addItem (String (bs)
  59522. + " samples ("
  59523. + String (bs * 1000.0 / currentRate, 1)
  59524. + " ms)",
  59525. bs);
  59526. }
  59527. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59528. bufferSizeDropDown->addListener (this);
  59529. }
  59530. }
  59531. else
  59532. {
  59533. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59534. sampleRateLabel = 0;
  59535. bufferSizeLabel = 0;
  59536. sampleRateDropDown = 0;
  59537. bufferSizeDropDown = 0;
  59538. if (outputDeviceDropDown != 0)
  59539. outputDeviceDropDown->setSelectedId (-1, true);
  59540. if (inputDeviceDropDown != 0)
  59541. inputDeviceDropDown->setSelectedId (-1, true);
  59542. }
  59543. resized();
  59544. setSize (getWidth(), getLowestY() + 4);
  59545. }
  59546. private:
  59547. AudioIODeviceType* const type;
  59548. const AudioIODeviceType::DeviceSetupDetails setup;
  59549. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59550. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59551. ScopedPointer<TextButton> testButton;
  59552. ScopedPointer<Component> inputLevelMeter;
  59553. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59554. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59555. {
  59556. if (box != 0)
  59557. {
  59558. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59559. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59560. box->setSelectedId (index + 1, true);
  59561. if (testButton != 0 && ! isInput)
  59562. testButton->setEnabled (index >= 0);
  59563. }
  59564. }
  59565. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59566. {
  59567. const StringArray devs (type->getDeviceNames (isInputs));
  59568. combo.clear (true);
  59569. for (int i = 0; i < devs.size(); ++i)
  59570. combo.addItem (devs[i], i + 1);
  59571. combo.addItem (TRANS("<< none >>"), -1);
  59572. combo.setSelectedId (-1, true);
  59573. }
  59574. int getLowestY() const
  59575. {
  59576. int y = 0;
  59577. for (int i = getNumChildComponents(); --i >= 0;)
  59578. y = jmax (y, getChildComponent (i)->getBottom());
  59579. return y;
  59580. }
  59581. public:
  59582. class ChannelSelectorListBox : public ListBox,
  59583. public ListBoxModel
  59584. {
  59585. public:
  59586. enum BoxType
  59587. {
  59588. audioInputType,
  59589. audioOutputType
  59590. };
  59591. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59592. const BoxType type_,
  59593. const String& noItemsMessage_)
  59594. : ListBox (String::empty, 0),
  59595. setup (setup_),
  59596. type (type_),
  59597. noItemsMessage (noItemsMessage_)
  59598. {
  59599. refresh();
  59600. setModel (this);
  59601. setOutlineThickness (1);
  59602. }
  59603. ~ChannelSelectorListBox()
  59604. {
  59605. }
  59606. void refresh()
  59607. {
  59608. items.clear();
  59609. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59610. if (currentDevice != 0)
  59611. {
  59612. if (type == audioInputType)
  59613. items = currentDevice->getInputChannelNames();
  59614. else if (type == audioOutputType)
  59615. items = currentDevice->getOutputChannelNames();
  59616. if (setup.useStereoPairs)
  59617. {
  59618. StringArray pairs;
  59619. for (int i = 0; i < items.size(); i += 2)
  59620. {
  59621. const String name (items[i]);
  59622. const String name2 (items[i + 1]);
  59623. String commonBit;
  59624. for (int j = 0; j < name.length(); ++j)
  59625. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59626. commonBit = name.substring (0, j);
  59627. // Make sure we only split the name at a space, because otherwise, things
  59628. // like "input 11" + "input 12" would become "input 11 + 2"
  59629. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59630. commonBit = commonBit.dropLastCharacters (1);
  59631. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59632. }
  59633. items = pairs;
  59634. }
  59635. }
  59636. updateContent();
  59637. repaint();
  59638. }
  59639. int getNumRows()
  59640. {
  59641. return items.size();
  59642. }
  59643. void paintListBoxItem (int row,
  59644. Graphics& g,
  59645. int width, int height,
  59646. bool rowIsSelected)
  59647. {
  59648. if (((unsigned int) row) < (unsigned int) items.size())
  59649. {
  59650. if (rowIsSelected)
  59651. g.fillAll (findColour (TextEditor::highlightColourId)
  59652. .withMultipliedAlpha (0.3f));
  59653. const String item (items [row]);
  59654. bool enabled = false;
  59655. AudioDeviceManager::AudioDeviceSetup config;
  59656. setup.manager->getAudioDeviceSetup (config);
  59657. if (setup.useStereoPairs)
  59658. {
  59659. if (type == audioInputType)
  59660. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59661. else if (type == audioOutputType)
  59662. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59663. }
  59664. else
  59665. {
  59666. if (type == audioInputType)
  59667. enabled = config.inputChannels [row];
  59668. else if (type == audioOutputType)
  59669. enabled = config.outputChannels [row];
  59670. }
  59671. const int x = getTickX();
  59672. const float tickW = height * 0.75f;
  59673. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59674. enabled, true, true, false);
  59675. g.setFont (height * 0.6f);
  59676. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59677. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59678. }
  59679. }
  59680. void listBoxItemClicked (int row, const MouseEvent& e)
  59681. {
  59682. selectRow (row);
  59683. if (e.x < getTickX())
  59684. flipEnablement (row);
  59685. }
  59686. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59687. {
  59688. flipEnablement (row);
  59689. }
  59690. void returnKeyPressed (int row)
  59691. {
  59692. flipEnablement (row);
  59693. }
  59694. void paint (Graphics& g)
  59695. {
  59696. ListBox::paint (g);
  59697. if (items.size() == 0)
  59698. {
  59699. g.setColour (Colours::grey);
  59700. g.setFont (13.0f);
  59701. g.drawText (noItemsMessage,
  59702. 0, 0, getWidth(), getHeight() / 2,
  59703. Justification::centred, true);
  59704. }
  59705. }
  59706. int getBestHeight (int maxHeight)
  59707. {
  59708. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59709. getNumRows())
  59710. + getOutlineThickness() * 2;
  59711. }
  59712. juce_UseDebuggingNewOperator
  59713. private:
  59714. const AudioIODeviceType::DeviceSetupDetails setup;
  59715. const BoxType type;
  59716. const String noItemsMessage;
  59717. StringArray items;
  59718. void flipEnablement (const int row)
  59719. {
  59720. jassert (type == audioInputType || type == audioOutputType);
  59721. if (((unsigned int) row) < (unsigned int) items.size())
  59722. {
  59723. AudioDeviceManager::AudioDeviceSetup config;
  59724. setup.manager->getAudioDeviceSetup (config);
  59725. if (setup.useStereoPairs)
  59726. {
  59727. BigInteger bits;
  59728. BigInteger& original = (type == audioInputType ? config.inputChannels
  59729. : config.outputChannels);
  59730. int i;
  59731. for (i = 0; i < 256; i += 2)
  59732. bits.setBit (i / 2, original [i] || original [i + 1]);
  59733. if (type == audioInputType)
  59734. {
  59735. config.useDefaultInputChannels = false;
  59736. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59737. }
  59738. else
  59739. {
  59740. config.useDefaultOutputChannels = false;
  59741. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59742. }
  59743. for (i = 0; i < 256; ++i)
  59744. original.setBit (i, bits [i / 2]);
  59745. }
  59746. else
  59747. {
  59748. if (type == audioInputType)
  59749. {
  59750. config.useDefaultInputChannels = false;
  59751. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59752. }
  59753. else
  59754. {
  59755. config.useDefaultOutputChannels = false;
  59756. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59757. }
  59758. }
  59759. String error (setup.manager->setAudioDeviceSetup (config, true));
  59760. if (! error.isEmpty())
  59761. {
  59762. //xxx
  59763. }
  59764. }
  59765. }
  59766. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59767. {
  59768. const int numActive = chans.countNumberOfSetBits();
  59769. if (chans [index])
  59770. {
  59771. if (numActive > minNumber)
  59772. chans.setBit (index, false);
  59773. }
  59774. else
  59775. {
  59776. if (numActive >= maxNumber)
  59777. {
  59778. const int firstActiveChan = chans.findNextSetBit();
  59779. chans.setBit (index > firstActiveChan
  59780. ? firstActiveChan : chans.getHighestBit(),
  59781. false);
  59782. }
  59783. chans.setBit (index, true);
  59784. }
  59785. }
  59786. int getTickX() const
  59787. {
  59788. return getRowHeight() + 5;
  59789. }
  59790. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59791. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59792. };
  59793. private:
  59794. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59795. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59796. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59797. };
  59798. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59799. const int minInputChannels_,
  59800. const int maxInputChannels_,
  59801. const int minOutputChannels_,
  59802. const int maxOutputChannels_,
  59803. const bool showMidiInputOptions,
  59804. const bool showMidiOutputSelector,
  59805. const bool showChannelsAsStereoPairs_,
  59806. const bool hideAdvancedOptionsWithButton_)
  59807. : deviceManager (deviceManager_),
  59808. deviceTypeDropDown (0),
  59809. deviceTypeDropDownLabel (0),
  59810. minOutputChannels (minOutputChannels_),
  59811. maxOutputChannels (maxOutputChannels_),
  59812. minInputChannels (minInputChannels_),
  59813. maxInputChannels (maxInputChannels_),
  59814. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59815. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59816. {
  59817. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59818. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59819. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59820. {
  59821. deviceTypeDropDown = new ComboBox (String::empty);
  59822. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59823. {
  59824. deviceTypeDropDown
  59825. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59826. i + 1);
  59827. }
  59828. addAndMakeVisible (deviceTypeDropDown);
  59829. deviceTypeDropDown->addListener (this);
  59830. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59831. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59832. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59833. }
  59834. if (showMidiInputOptions)
  59835. {
  59836. addAndMakeVisible (midiInputsList
  59837. = new MidiInputSelectorComponentListBox (deviceManager,
  59838. TRANS("(no midi inputs available)"),
  59839. 0, 0));
  59840. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59841. midiInputsLabel->setJustificationType (Justification::topRight);
  59842. midiInputsLabel->attachToComponent (midiInputsList, true);
  59843. }
  59844. else
  59845. {
  59846. midiInputsList = 0;
  59847. midiInputsLabel = 0;
  59848. }
  59849. if (showMidiOutputSelector)
  59850. {
  59851. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59852. midiOutputSelector->addListener (this);
  59853. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59854. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59855. }
  59856. else
  59857. {
  59858. midiOutputSelector = 0;
  59859. midiOutputLabel = 0;
  59860. }
  59861. deviceManager_.addChangeListener (this);
  59862. changeListenerCallback (0);
  59863. }
  59864. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59865. {
  59866. deviceManager.removeChangeListener (this);
  59867. }
  59868. void AudioDeviceSelectorComponent::resized()
  59869. {
  59870. const int lx = proportionOfWidth (0.35f);
  59871. const int w = proportionOfWidth (0.4f);
  59872. const int h = 24;
  59873. const int space = 6;
  59874. const int dh = h + space;
  59875. int y = 15;
  59876. if (deviceTypeDropDown != 0)
  59877. {
  59878. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59879. y += dh + space * 2;
  59880. }
  59881. if (audioDeviceSettingsComp != 0)
  59882. {
  59883. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59884. y += audioDeviceSettingsComp->getHeight() + space;
  59885. }
  59886. if (midiInputsList != 0)
  59887. {
  59888. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59889. midiInputsList->setBounds (lx, y, w, bh);
  59890. y += bh + space;
  59891. }
  59892. if (midiOutputSelector != 0)
  59893. midiOutputSelector->setBounds (lx, y, w, h);
  59894. }
  59895. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59896. {
  59897. if (child == audioDeviceSettingsComp)
  59898. resized();
  59899. }
  59900. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59901. {
  59902. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59903. if (device != 0 && device->hasControlPanel())
  59904. {
  59905. if (device->showControlPanel())
  59906. deviceManager.restartLastAudioDevice();
  59907. getTopLevelComponent()->toFront (true);
  59908. }
  59909. }
  59910. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59911. {
  59912. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59913. {
  59914. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59915. if (type != 0)
  59916. {
  59917. audioDeviceSettingsComp = 0;
  59918. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59919. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59920. }
  59921. }
  59922. else if (comboBoxThatHasChanged == midiOutputSelector)
  59923. {
  59924. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59925. }
  59926. }
  59927. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59928. {
  59929. if (deviceTypeDropDown != 0)
  59930. {
  59931. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59932. }
  59933. if (audioDeviceSettingsComp == 0
  59934. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59935. {
  59936. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59937. audioDeviceSettingsComp = 0;
  59938. AudioIODeviceType* const type
  59939. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59940. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59941. if (type != 0)
  59942. {
  59943. AudioIODeviceType::DeviceSetupDetails details;
  59944. details.manager = &deviceManager;
  59945. details.minNumInputChannels = minInputChannels;
  59946. details.maxNumInputChannels = maxInputChannels;
  59947. details.minNumOutputChannels = minOutputChannels;
  59948. details.maxNumOutputChannels = maxOutputChannels;
  59949. details.useStereoPairs = showChannelsAsStereoPairs;
  59950. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59951. if (audioDeviceSettingsComp != 0)
  59952. {
  59953. addAndMakeVisible (audioDeviceSettingsComp);
  59954. audioDeviceSettingsComp->resized();
  59955. }
  59956. }
  59957. }
  59958. if (midiInputsList != 0)
  59959. {
  59960. midiInputsList->updateContent();
  59961. midiInputsList->repaint();
  59962. }
  59963. if (midiOutputSelector != 0)
  59964. {
  59965. midiOutputSelector->clear();
  59966. const StringArray midiOuts (MidiOutput::getDevices());
  59967. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59968. midiOutputSelector->addSeparator();
  59969. for (int i = 0; i < midiOuts.size(); ++i)
  59970. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59971. int current = -1;
  59972. if (deviceManager.getDefaultMidiOutput() != 0)
  59973. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59974. midiOutputSelector->setSelectedId (current, true);
  59975. }
  59976. resized();
  59977. }
  59978. END_JUCE_NAMESPACE
  59979. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59980. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59981. BEGIN_JUCE_NAMESPACE
  59982. BubbleComponent::BubbleComponent()
  59983. : side (0),
  59984. allowablePlacements (above | below | left | right),
  59985. arrowTipX (0.0f),
  59986. arrowTipY (0.0f)
  59987. {
  59988. setInterceptsMouseClicks (false, false);
  59989. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59990. setComponentEffect (&shadow);
  59991. }
  59992. BubbleComponent::~BubbleComponent()
  59993. {
  59994. }
  59995. void BubbleComponent::paint (Graphics& g)
  59996. {
  59997. int x = content.getX();
  59998. int y = content.getY();
  59999. int w = content.getWidth();
  60000. int h = content.getHeight();
  60001. int cw, ch;
  60002. getContentSize (cw, ch);
  60003. if (side == 3)
  60004. x += w - cw;
  60005. else if (side != 1)
  60006. x += (w - cw) / 2;
  60007. w = cw;
  60008. if (side == 2)
  60009. y += h - ch;
  60010. else if (side != 0)
  60011. y += (h - ch) / 2;
  60012. h = ch;
  60013. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  60014. (float) x, (float) y,
  60015. (float) w, (float) h);
  60016. const int cx = x + (w - cw) / 2;
  60017. const int cy = y + (h - ch) / 2;
  60018. const int indent = 3;
  60019. g.setOrigin (cx + indent, cy + indent);
  60020. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  60021. paintContent (g, cw - indent * 2, ch - indent * 2);
  60022. }
  60023. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  60024. {
  60025. allowablePlacements = newPlacement;
  60026. }
  60027. void BubbleComponent::setPosition (Component* componentToPointTo)
  60028. {
  60029. jassert (componentToPointTo->isValidComponent());
  60030. Point<int> pos;
  60031. if (getParentComponent() != 0)
  60032. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  60033. else
  60034. pos = componentToPointTo->relativePositionToGlobal (pos);
  60035. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  60036. }
  60037. void BubbleComponent::setPosition (const int arrowTipX_,
  60038. const int arrowTipY_)
  60039. {
  60040. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  60041. }
  60042. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  60043. {
  60044. Rectangle<int> availableSpace;
  60045. if (getParentComponent() != 0)
  60046. {
  60047. availableSpace.setSize (getParentComponent()->getWidth(),
  60048. getParentComponent()->getHeight());
  60049. }
  60050. else
  60051. {
  60052. availableSpace = getParentMonitorArea();
  60053. }
  60054. int x = 0;
  60055. int y = 0;
  60056. int w = 150;
  60057. int h = 30;
  60058. getContentSize (w, h);
  60059. w += 30;
  60060. h += 30;
  60061. const float edgeIndent = 2.0f;
  60062. const int arrowLength = jmin (10, h / 3, w / 3);
  60063. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  60064. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  60065. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  60066. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  60067. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  60068. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  60069. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  60070. {
  60071. spaceLeft = spaceRight = 0;
  60072. }
  60073. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  60074. && (spaceLeft > w + 20 || spaceRight > w + 20))
  60075. {
  60076. spaceAbove = spaceBelow = 0;
  60077. }
  60078. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  60079. {
  60080. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  60081. arrowTipX = w * 0.5f;
  60082. content.setSize (w, h - arrowLength);
  60083. if (spaceAbove >= spaceBelow)
  60084. {
  60085. // above
  60086. y = rectangleToPointTo.getY() - h;
  60087. content.setPosition (0, 0);
  60088. arrowTipY = h - edgeIndent;
  60089. side = 2;
  60090. }
  60091. else
  60092. {
  60093. // below
  60094. y = rectangleToPointTo.getBottom();
  60095. content.setPosition (0, arrowLength);
  60096. arrowTipY = edgeIndent;
  60097. side = 0;
  60098. }
  60099. }
  60100. else
  60101. {
  60102. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  60103. arrowTipY = h * 0.5f;
  60104. content.setSize (w - arrowLength, h);
  60105. if (spaceLeft > spaceRight)
  60106. {
  60107. // on the left
  60108. x = rectangleToPointTo.getX() - w;
  60109. content.setPosition (0, 0);
  60110. arrowTipX = w - edgeIndent;
  60111. side = 3;
  60112. }
  60113. else
  60114. {
  60115. // on the right
  60116. x = rectangleToPointTo.getRight();
  60117. content.setPosition (arrowLength, 0);
  60118. arrowTipX = edgeIndent;
  60119. side = 1;
  60120. }
  60121. }
  60122. setBounds (x, y, w, h);
  60123. }
  60124. END_JUCE_NAMESPACE
  60125. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  60126. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  60127. BEGIN_JUCE_NAMESPACE
  60128. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  60129. : fadeOutLength (fadeOutLengthMs),
  60130. deleteAfterUse (false)
  60131. {
  60132. }
  60133. BubbleMessageComponent::~BubbleMessageComponent()
  60134. {
  60135. fadeOutComponent (fadeOutLength);
  60136. }
  60137. void BubbleMessageComponent::showAt (int x, int y,
  60138. const String& text,
  60139. const int numMillisecondsBeforeRemoving,
  60140. const bool removeWhenMouseClicked,
  60141. const bool deleteSelfAfterUse)
  60142. {
  60143. textLayout.clear();
  60144. textLayout.setText (text, Font (14.0f));
  60145. textLayout.layout (256, Justification::centredLeft, true);
  60146. setPosition (x, y);
  60147. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  60148. }
  60149. void BubbleMessageComponent::showAt (Component* const component,
  60150. const String& text,
  60151. const int numMillisecondsBeforeRemoving,
  60152. const bool removeWhenMouseClicked,
  60153. const bool deleteSelfAfterUse)
  60154. {
  60155. textLayout.clear();
  60156. textLayout.setText (text, Font (14.0f));
  60157. textLayout.layout (256, Justification::centredLeft, true);
  60158. setPosition (component);
  60159. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  60160. }
  60161. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  60162. const bool removeWhenMouseClicked,
  60163. const bool deleteSelfAfterUse)
  60164. {
  60165. setVisible (true);
  60166. deleteAfterUse = deleteSelfAfterUse;
  60167. if (numMillisecondsBeforeRemoving > 0)
  60168. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  60169. else
  60170. expiryTime = 0;
  60171. startTimer (77);
  60172. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  60173. if (! (removeWhenMouseClicked && isShowing()))
  60174. mouseClickCounter += 0xfffff;
  60175. repaint();
  60176. }
  60177. void BubbleMessageComponent::getContentSize (int& w, int& h)
  60178. {
  60179. w = textLayout.getWidth() + 16;
  60180. h = textLayout.getHeight() + 16;
  60181. }
  60182. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  60183. {
  60184. g.setColour (findColour (TooltipWindow::textColourId));
  60185. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  60186. }
  60187. void BubbleMessageComponent::timerCallback()
  60188. {
  60189. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  60190. {
  60191. stopTimer();
  60192. setVisible (false);
  60193. if (deleteAfterUse)
  60194. delete this;
  60195. }
  60196. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  60197. {
  60198. stopTimer();
  60199. fadeOutComponent (fadeOutLength);
  60200. if (deleteAfterUse)
  60201. delete this;
  60202. }
  60203. }
  60204. END_JUCE_NAMESPACE
  60205. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  60206. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  60207. BEGIN_JUCE_NAMESPACE
  60208. class ColourComponentSlider : public Slider
  60209. {
  60210. public:
  60211. ColourComponentSlider (const String& name)
  60212. : Slider (name)
  60213. {
  60214. setRange (0.0, 255.0, 1.0);
  60215. }
  60216. ~ColourComponentSlider()
  60217. {
  60218. }
  60219. const String getTextFromValue (double value)
  60220. {
  60221. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  60222. }
  60223. double getValueFromText (const String& text)
  60224. {
  60225. return (double) text.getHexValue32();
  60226. }
  60227. private:
  60228. ColourComponentSlider (const ColourComponentSlider&);
  60229. ColourComponentSlider& operator= (const ColourComponentSlider&);
  60230. };
  60231. class ColourSpaceMarker : public Component
  60232. {
  60233. public:
  60234. ColourSpaceMarker()
  60235. {
  60236. setInterceptsMouseClicks (false, false);
  60237. }
  60238. ~ColourSpaceMarker()
  60239. {
  60240. }
  60241. void paint (Graphics& g)
  60242. {
  60243. g.setColour (Colour::greyLevel (0.1f));
  60244. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  60245. g.setColour (Colour::greyLevel (0.9f));
  60246. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  60247. }
  60248. private:
  60249. ColourSpaceMarker (const ColourSpaceMarker&);
  60250. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  60251. };
  60252. class ColourSelector::ColourSpaceView : public Component
  60253. {
  60254. public:
  60255. ColourSpaceView (ColourSelector* owner_,
  60256. float& h_, float& s_, float& v_,
  60257. const int edgeSize)
  60258. : owner (owner_),
  60259. h (h_), s (s_), v (v_),
  60260. lastHue (0.0f),
  60261. edge (edgeSize)
  60262. {
  60263. addAndMakeVisible (&marker);
  60264. setMouseCursor (MouseCursor::CrosshairCursor);
  60265. }
  60266. ~ColourSpaceView()
  60267. {
  60268. }
  60269. void paint (Graphics& g)
  60270. {
  60271. if (colours.isNull())
  60272. {
  60273. const int width = getWidth() / 2;
  60274. const int height = getHeight() / 2;
  60275. colours = Image (Image::RGB, width, height, false);
  60276. Image::BitmapData pixels (colours, true);
  60277. for (int y = 0; y < height; ++y)
  60278. {
  60279. const float val = 1.0f - y / (float) height;
  60280. for (int x = 0; x < width; ++x)
  60281. {
  60282. const float sat = x / (float) width;
  60283. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  60284. }
  60285. }
  60286. }
  60287. g.setOpacity (1.0f);
  60288. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  60289. 0, 0, colours.getWidth(), colours.getHeight());
  60290. }
  60291. void mouseDown (const MouseEvent& e)
  60292. {
  60293. mouseDrag (e);
  60294. }
  60295. void mouseDrag (const MouseEvent& e)
  60296. {
  60297. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  60298. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  60299. owner->setSV (sat, val);
  60300. }
  60301. void updateIfNeeded()
  60302. {
  60303. if (lastHue != h)
  60304. {
  60305. lastHue = h;
  60306. colours = Image::null;
  60307. repaint();
  60308. }
  60309. updateMarker();
  60310. }
  60311. void resized()
  60312. {
  60313. colours = Image::null;
  60314. updateMarker();
  60315. }
  60316. private:
  60317. ColourSelector* const owner;
  60318. float& h;
  60319. float& s;
  60320. float& v;
  60321. float lastHue;
  60322. ColourSpaceMarker marker;
  60323. const int edge;
  60324. Image colours;
  60325. void updateMarker()
  60326. {
  60327. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  60328. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  60329. edge * 2, edge * 2);
  60330. }
  60331. ColourSpaceView (const ColourSpaceView&);
  60332. ColourSpaceView& operator= (const ColourSpaceView&);
  60333. };
  60334. class HueSelectorMarker : public Component
  60335. {
  60336. public:
  60337. HueSelectorMarker()
  60338. {
  60339. setInterceptsMouseClicks (false, false);
  60340. }
  60341. ~HueSelectorMarker()
  60342. {
  60343. }
  60344. void paint (Graphics& g)
  60345. {
  60346. Path p;
  60347. p.addTriangle (1.0f, 1.0f,
  60348. getWidth() * 0.3f, getHeight() * 0.5f,
  60349. 1.0f, getHeight() - 1.0f);
  60350. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60351. getWidth() * 0.7f, getHeight() * 0.5f,
  60352. getWidth() - 1.0f, getHeight() - 1.0f);
  60353. g.setColour (Colours::white.withAlpha (0.75f));
  60354. g.fillPath (p);
  60355. g.setColour (Colours::black.withAlpha (0.75f));
  60356. g.strokePath (p, PathStrokeType (1.2f));
  60357. }
  60358. private:
  60359. HueSelectorMarker (const HueSelectorMarker&);
  60360. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60361. };
  60362. class ColourSelector::HueSelectorComp : public Component
  60363. {
  60364. public:
  60365. HueSelectorComp (ColourSelector* owner_,
  60366. float& h_, float& s_, float& v_,
  60367. const int edgeSize)
  60368. : owner (owner_),
  60369. h (h_), s (s_), v (v_),
  60370. lastHue (0.0f),
  60371. edge (edgeSize)
  60372. {
  60373. addAndMakeVisible (&marker);
  60374. }
  60375. ~HueSelectorComp()
  60376. {
  60377. }
  60378. void paint (Graphics& g)
  60379. {
  60380. const float yScale = 1.0f / (getHeight() - edge * 2);
  60381. const Rectangle<int> clip (g.getClipBounds());
  60382. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60383. {
  60384. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60385. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60386. }
  60387. }
  60388. void resized()
  60389. {
  60390. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60391. getWidth(), edge * 2);
  60392. }
  60393. void mouseDown (const MouseEvent& e)
  60394. {
  60395. mouseDrag (e);
  60396. }
  60397. void mouseDrag (const MouseEvent& e)
  60398. {
  60399. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60400. owner->setHue (hue);
  60401. }
  60402. void updateIfNeeded()
  60403. {
  60404. resized();
  60405. }
  60406. private:
  60407. ColourSelector* const owner;
  60408. float& h;
  60409. float& s;
  60410. float& v;
  60411. float lastHue;
  60412. HueSelectorMarker marker;
  60413. const int edge;
  60414. HueSelectorComp (const HueSelectorComp&);
  60415. HueSelectorComp& operator= (const HueSelectorComp&);
  60416. };
  60417. class ColourSelector::SwatchComponent : public Component
  60418. {
  60419. public:
  60420. SwatchComponent (ColourSelector* owner_, int index_)
  60421. : owner (owner_),
  60422. index (index_)
  60423. {
  60424. }
  60425. ~SwatchComponent()
  60426. {
  60427. }
  60428. void paint (Graphics& g)
  60429. {
  60430. const Colour colour (owner->getSwatchColour (index));
  60431. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60432. Colour (0xffdddddd).overlaidWith (colour),
  60433. Colour (0xffffffff).overlaidWith (colour));
  60434. }
  60435. void mouseDown (const MouseEvent&)
  60436. {
  60437. PopupMenu m;
  60438. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60439. m.addSeparator();
  60440. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60441. const int r = m.showAt (this);
  60442. if (r == 1)
  60443. {
  60444. owner->setCurrentColour (owner->getSwatchColour (index));
  60445. }
  60446. else if (r == 2)
  60447. {
  60448. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60449. {
  60450. owner->setSwatchColour (index, owner->getCurrentColour());
  60451. repaint();
  60452. }
  60453. }
  60454. }
  60455. private:
  60456. ColourSelector* const owner;
  60457. const int index;
  60458. SwatchComponent (const SwatchComponent&);
  60459. SwatchComponent& operator= (const SwatchComponent&);
  60460. };
  60461. ColourSelector::ColourSelector (const int flags_,
  60462. const int edgeGap_,
  60463. const int gapAroundColourSpaceComponent)
  60464. : colour (Colours::white),
  60465. colourSpace (0),
  60466. hueSelector (0),
  60467. flags (flags_),
  60468. edgeGap (edgeGap_)
  60469. {
  60470. // not much point having a selector with no components in it!
  60471. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60472. updateHSV();
  60473. if ((flags & showSliders) != 0)
  60474. {
  60475. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60476. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60477. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60478. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60479. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60480. for (int i = 4; --i >= 0;)
  60481. sliders[i]->addListener (this);
  60482. }
  60483. else
  60484. {
  60485. zeromem (sliders, sizeof (sliders));
  60486. }
  60487. if ((flags & showColourspace) != 0)
  60488. {
  60489. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60490. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60491. }
  60492. update();
  60493. }
  60494. ColourSelector::~ColourSelector()
  60495. {
  60496. dispatchPendingMessages();
  60497. swatchComponents.clear();
  60498. deleteAllChildren();
  60499. }
  60500. const Colour ColourSelector::getCurrentColour() const
  60501. {
  60502. return ((flags & showAlphaChannel) != 0) ? colour
  60503. : colour.withAlpha ((uint8) 0xff);
  60504. }
  60505. void ColourSelector::setCurrentColour (const Colour& c)
  60506. {
  60507. if (c != colour)
  60508. {
  60509. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60510. updateHSV();
  60511. update();
  60512. }
  60513. }
  60514. void ColourSelector::setHue (float newH)
  60515. {
  60516. newH = jlimit (0.0f, 1.0f, newH);
  60517. if (h != newH)
  60518. {
  60519. h = newH;
  60520. colour = Colour (h, s, v, colour.getFloatAlpha());
  60521. update();
  60522. }
  60523. }
  60524. void ColourSelector::setSV (float newS, float newV)
  60525. {
  60526. newS = jlimit (0.0f, 1.0f, newS);
  60527. newV = jlimit (0.0f, 1.0f, newV);
  60528. if (s != newS || v != newV)
  60529. {
  60530. s = newS;
  60531. v = newV;
  60532. colour = Colour (h, s, v, colour.getFloatAlpha());
  60533. update();
  60534. }
  60535. }
  60536. void ColourSelector::updateHSV()
  60537. {
  60538. colour.getHSB (h, s, v);
  60539. }
  60540. void ColourSelector::update()
  60541. {
  60542. if (sliders[0] != 0)
  60543. {
  60544. sliders[0]->setValue ((int) colour.getRed());
  60545. sliders[1]->setValue ((int) colour.getGreen());
  60546. sliders[2]->setValue ((int) colour.getBlue());
  60547. sliders[3]->setValue ((int) colour.getAlpha());
  60548. }
  60549. if (colourSpace != 0)
  60550. {
  60551. colourSpace->updateIfNeeded();
  60552. hueSelector->updateIfNeeded();
  60553. }
  60554. if ((flags & showColourAtTop) != 0)
  60555. repaint (previewArea);
  60556. sendChangeMessage (this);
  60557. }
  60558. void ColourSelector::paint (Graphics& g)
  60559. {
  60560. g.fillAll (findColour (backgroundColourId));
  60561. if ((flags & showColourAtTop) != 0)
  60562. {
  60563. const Colour currentColour (getCurrentColour());
  60564. g.fillCheckerBoard (previewArea, 10, 10,
  60565. Colour (0xffdddddd).overlaidWith (currentColour),
  60566. Colour (0xffffffff).overlaidWith (currentColour));
  60567. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60568. g.setFont (14.0f, true);
  60569. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60570. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60571. Justification::centred, false);
  60572. }
  60573. if ((flags & showSliders) != 0)
  60574. {
  60575. g.setColour (findColour (labelTextColourId));
  60576. g.setFont (11.0f);
  60577. for (int i = 4; --i >= 0;)
  60578. {
  60579. if (sliders[i]->isVisible())
  60580. g.drawText (sliders[i]->getName() + ":",
  60581. 0, sliders[i]->getY(),
  60582. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60583. Justification::centredRight, false);
  60584. }
  60585. }
  60586. }
  60587. void ColourSelector::resized()
  60588. {
  60589. const int swatchesPerRow = 8;
  60590. const int swatchHeight = 22;
  60591. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60592. const int numSwatches = getNumSwatches();
  60593. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60594. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60595. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60596. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60597. int y = topSpace;
  60598. if ((flags & showColourspace) != 0)
  60599. {
  60600. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60601. colourSpace->setBounds (edgeGap, y,
  60602. getWidth() - hueWidth - edgeGap - 4,
  60603. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60604. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60605. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60606. colourSpace->getHeight());
  60607. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60608. }
  60609. if ((flags & showSliders) != 0)
  60610. {
  60611. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60612. for (int i = 0; i < numSliders; ++i)
  60613. {
  60614. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60615. proportionOfWidth (0.72f), sliderHeight - 2);
  60616. y += sliderHeight;
  60617. }
  60618. }
  60619. if (numSwatches > 0)
  60620. {
  60621. const int startX = 8;
  60622. const int xGap = 4;
  60623. const int yGap = 4;
  60624. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60625. y += edgeGap;
  60626. if (swatchComponents.size() != numSwatches)
  60627. {
  60628. swatchComponents.clear();
  60629. for (int i = 0; i < numSwatches; ++i)
  60630. {
  60631. SwatchComponent* const sc = new SwatchComponent (this, i);
  60632. swatchComponents.add (sc);
  60633. addAndMakeVisible (sc);
  60634. }
  60635. }
  60636. int x = startX;
  60637. for (int i = 0; i < swatchComponents.size(); ++i)
  60638. {
  60639. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60640. sc->setBounds (x + xGap / 2,
  60641. y + yGap / 2,
  60642. swatchWidth - xGap,
  60643. swatchHeight - yGap);
  60644. if (((i + 1) % swatchesPerRow) == 0)
  60645. {
  60646. x = startX;
  60647. y += swatchHeight;
  60648. }
  60649. else
  60650. {
  60651. x += swatchWidth;
  60652. }
  60653. }
  60654. }
  60655. }
  60656. void ColourSelector::sliderValueChanged (Slider*)
  60657. {
  60658. if (sliders[0] != 0)
  60659. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60660. (uint8) sliders[1]->getValue(),
  60661. (uint8) sliders[2]->getValue(),
  60662. (uint8) sliders[3]->getValue()));
  60663. }
  60664. int ColourSelector::getNumSwatches() const
  60665. {
  60666. return 0;
  60667. }
  60668. const Colour ColourSelector::getSwatchColour (const int) const
  60669. {
  60670. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60671. return Colours::black;
  60672. }
  60673. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60674. {
  60675. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60676. }
  60677. END_JUCE_NAMESPACE
  60678. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60679. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60680. BEGIN_JUCE_NAMESPACE
  60681. class ShadowWindow : public Component
  60682. {
  60683. Component* owner;
  60684. Image shadowImageSections [12];
  60685. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60686. public:
  60687. ShadowWindow (Component* const owner_,
  60688. const int type_,
  60689. const Image shadowImageSections_ [12])
  60690. : owner (owner_),
  60691. type (type_)
  60692. {
  60693. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60694. shadowImageSections [i] = shadowImageSections_ [i];
  60695. setInterceptsMouseClicks (false, false);
  60696. if (owner_->isOnDesktop())
  60697. {
  60698. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60699. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60700. | ComponentPeer::windowIsTemporary
  60701. | ComponentPeer::windowIgnoresKeyPresses);
  60702. }
  60703. else if (owner_->getParentComponent() != 0)
  60704. {
  60705. owner_->getParentComponent()->addChildComponent (this);
  60706. }
  60707. }
  60708. ~ShadowWindow()
  60709. {
  60710. }
  60711. void paint (Graphics& g)
  60712. {
  60713. const Image& topLeft = shadowImageSections [type * 3];
  60714. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60715. const Image& filler = shadowImageSections [type * 3 + 2];
  60716. g.setOpacity (1.0f);
  60717. if (type < 2)
  60718. {
  60719. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60720. g.drawImage (topLeft,
  60721. 0, 0, topLeft.getWidth(), imH,
  60722. 0, 0, topLeft.getWidth(), imH);
  60723. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60724. g.drawImage (bottomRight,
  60725. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60726. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60727. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60728. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60729. }
  60730. else
  60731. {
  60732. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60733. g.drawImage (topLeft,
  60734. 0, 0, imW, topLeft.getHeight(),
  60735. 0, 0, imW, topLeft.getHeight());
  60736. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60737. g.drawImage (bottomRight,
  60738. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60739. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60740. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60741. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60742. }
  60743. }
  60744. void resized()
  60745. {
  60746. repaint(); // (needed for correct repainting)
  60747. }
  60748. private:
  60749. ShadowWindow (const ShadowWindow&);
  60750. ShadowWindow& operator= (const ShadowWindow&);
  60751. };
  60752. DropShadower::DropShadower (const float alpha_,
  60753. const int xOffset_,
  60754. const int yOffset_,
  60755. const float blurRadius_)
  60756. : owner (0),
  60757. numShadows (0),
  60758. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60759. xOffset (xOffset_),
  60760. yOffset (yOffset_),
  60761. alpha (alpha_),
  60762. blurRadius (blurRadius_),
  60763. inDestructor (false),
  60764. reentrant (false)
  60765. {
  60766. }
  60767. DropShadower::~DropShadower()
  60768. {
  60769. if (owner != 0)
  60770. owner->removeComponentListener (this);
  60771. inDestructor = true;
  60772. deleteShadowWindows();
  60773. }
  60774. void DropShadower::deleteShadowWindows()
  60775. {
  60776. if (numShadows > 0)
  60777. {
  60778. int i;
  60779. for (i = numShadows; --i >= 0;)
  60780. delete shadowWindows[i];
  60781. numShadows = 0;
  60782. }
  60783. }
  60784. void DropShadower::setOwner (Component* componentToFollow)
  60785. {
  60786. if (componentToFollow != owner)
  60787. {
  60788. if (owner != 0)
  60789. owner->removeComponentListener (this);
  60790. // (the component can't be null)
  60791. jassert (componentToFollow != 0);
  60792. owner = componentToFollow;
  60793. jassert (owner != 0);
  60794. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60795. owner->addComponentListener (this);
  60796. updateShadows();
  60797. }
  60798. }
  60799. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60800. {
  60801. updateShadows();
  60802. }
  60803. void DropShadower::componentBroughtToFront (Component&)
  60804. {
  60805. bringShadowWindowsToFront();
  60806. }
  60807. void DropShadower::componentChildrenChanged (Component&)
  60808. {
  60809. }
  60810. void DropShadower::componentParentHierarchyChanged (Component&)
  60811. {
  60812. deleteShadowWindows();
  60813. updateShadows();
  60814. }
  60815. void DropShadower::componentVisibilityChanged (Component&)
  60816. {
  60817. updateShadows();
  60818. }
  60819. void DropShadower::updateShadows()
  60820. {
  60821. if (reentrant || inDestructor || (owner == 0))
  60822. return;
  60823. reentrant = true;
  60824. ComponentPeer* const nw = owner->getPeer();
  60825. const bool isOwnerVisible = owner->isVisible()
  60826. && (nw == 0 || ! nw->isMinimised());
  60827. const bool createShadowWindows = numShadows == 0
  60828. && owner->getWidth() > 0
  60829. && owner->getHeight() > 0
  60830. && isOwnerVisible
  60831. && (Desktop::canUseSemiTransparentWindows()
  60832. || owner->getParentComponent() != 0);
  60833. if (createShadowWindows)
  60834. {
  60835. // keep a cached version of the image to save doing the gaussian too often
  60836. String imageId;
  60837. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60838. const int hash = imageId.hashCode();
  60839. Image bigIm (ImageCache::getFromHashCode (hash));
  60840. if (bigIm.isNull())
  60841. {
  60842. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60843. Graphics bigG (bigIm);
  60844. bigG.setColour (Colours::black.withAlpha (alpha));
  60845. bigG.fillRect (shadowEdge + xOffset,
  60846. shadowEdge + yOffset,
  60847. bigIm.getWidth() - (shadowEdge * 2),
  60848. bigIm.getHeight() - (shadowEdge * 2));
  60849. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60850. blurKernel.createGaussianBlur (blurRadius);
  60851. blurKernel.applyToImage (bigIm, bigIm,
  60852. Rectangle<int> (xOffset, yOffset,
  60853. bigIm.getWidth(), bigIm.getHeight()));
  60854. ImageCache::addImageToCache (bigIm, hash);
  60855. }
  60856. const int iw = bigIm.getWidth();
  60857. const int ih = bigIm.getHeight();
  60858. const int shadowEdge2 = shadowEdge * 2;
  60859. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60860. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60861. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60862. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60863. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60864. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60865. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60866. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60867. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60868. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60869. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60870. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60871. for (int i = 0; i < 4; ++i)
  60872. {
  60873. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60874. ++numShadows;
  60875. }
  60876. }
  60877. if (numShadows > 0)
  60878. {
  60879. for (int i = numShadows; --i >= 0;)
  60880. {
  60881. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60882. shadowWindows[i]->setVisible (isOwnerVisible);
  60883. }
  60884. const int x = owner->getX();
  60885. const int y = owner->getY() - shadowEdge;
  60886. const int w = owner->getWidth();
  60887. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60888. shadowWindows[0]->setBounds (x - shadowEdge,
  60889. y,
  60890. shadowEdge,
  60891. h);
  60892. shadowWindows[1]->setBounds (x + w,
  60893. y,
  60894. shadowEdge,
  60895. h);
  60896. shadowWindows[2]->setBounds (x,
  60897. y,
  60898. w,
  60899. shadowEdge);
  60900. shadowWindows[3]->setBounds (x,
  60901. owner->getBottom(),
  60902. w,
  60903. shadowEdge);
  60904. }
  60905. reentrant = false;
  60906. if (createShadowWindows)
  60907. bringShadowWindowsToFront();
  60908. }
  60909. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60910. const int sx, const int sy)
  60911. {
  60912. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60913. Graphics g (shadowImageSections[num]);
  60914. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60915. }
  60916. void DropShadower::bringShadowWindowsToFront()
  60917. {
  60918. if (! (inDestructor || reentrant))
  60919. {
  60920. updateShadows();
  60921. reentrant = true;
  60922. for (int i = numShadows; --i >= 0;)
  60923. shadowWindows[i]->toBehind (owner);
  60924. reentrant = false;
  60925. }
  60926. }
  60927. END_JUCE_NAMESPACE
  60928. /*** End of inlined file: juce_DropShadower.cpp ***/
  60929. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60930. BEGIN_JUCE_NAMESPACE
  60931. class MagnifyingPeer : public ComponentPeer
  60932. {
  60933. public:
  60934. MagnifyingPeer (Component* const component_,
  60935. MagnifierComponent* const magnifierComp_)
  60936. : ComponentPeer (component_, 0),
  60937. magnifierComp (magnifierComp_)
  60938. {
  60939. }
  60940. ~MagnifyingPeer()
  60941. {
  60942. }
  60943. void* getNativeHandle() const { return 0; }
  60944. void setVisible (bool) {}
  60945. void setTitle (const String&) {}
  60946. void setPosition (int, int) {}
  60947. void setSize (int, int) {}
  60948. void setBounds (int, int, int, int, bool) {}
  60949. void setMinimised (bool) {}
  60950. bool isMinimised() const { return false; }
  60951. void setFullScreen (bool) {}
  60952. bool isFullScreen() const { return false; }
  60953. const BorderSize getFrameSize() const { return BorderSize (0); }
  60954. bool setAlwaysOnTop (bool) { return true; }
  60955. void toFront (bool) {}
  60956. void toBehind (ComponentPeer*) {}
  60957. void setIcon (const Image&) {}
  60958. bool isFocused() const
  60959. {
  60960. return magnifierComp->hasKeyboardFocus (true);
  60961. }
  60962. void grabFocus()
  60963. {
  60964. ComponentPeer* peer = magnifierComp->getPeer();
  60965. if (peer != 0)
  60966. peer->grabFocus();
  60967. }
  60968. void textInputRequired (const Point<int>& position)
  60969. {
  60970. ComponentPeer* peer = magnifierComp->getPeer();
  60971. if (peer != 0)
  60972. peer->textInputRequired (position);
  60973. }
  60974. const Rectangle<int> getBounds() const
  60975. {
  60976. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60977. component->getWidth(), component->getHeight());
  60978. }
  60979. const Point<int> getScreenPosition() const
  60980. {
  60981. return magnifierComp->getScreenPosition();
  60982. }
  60983. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60984. {
  60985. const double zoom = magnifierComp->getScaleFactor();
  60986. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60987. roundToInt (relativePosition.getY() * zoom)));
  60988. }
  60989. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60990. {
  60991. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60992. const double zoom = magnifierComp->getScaleFactor();
  60993. return Point<int> (roundToInt (p.getX() / zoom),
  60994. roundToInt (p.getY() / zoom));
  60995. }
  60996. bool contains (const Point<int>& position, bool) const
  60997. {
  60998. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60999. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  61000. }
  61001. void repaint (const Rectangle<int>& area)
  61002. {
  61003. const double zoom = magnifierComp->getScaleFactor();
  61004. magnifierComp->repaint ((int) (area.getX() * zoom),
  61005. (int) (area.getY() * zoom),
  61006. roundToInt (area.getWidth() * zoom) + 1,
  61007. roundToInt (area.getHeight() * zoom) + 1);
  61008. }
  61009. void performAnyPendingRepaintsNow()
  61010. {
  61011. }
  61012. juce_UseDebuggingNewOperator
  61013. private:
  61014. MagnifierComponent* const magnifierComp;
  61015. MagnifyingPeer (const MagnifyingPeer&);
  61016. MagnifyingPeer& operator= (const MagnifyingPeer&);
  61017. };
  61018. class PeerHolderComp : public Component
  61019. {
  61020. public:
  61021. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  61022. : magnifierComp (magnifierComp_)
  61023. {
  61024. setVisible (true);
  61025. }
  61026. ~PeerHolderComp()
  61027. {
  61028. }
  61029. ComponentPeer* createNewPeer (int, void*)
  61030. {
  61031. return new MagnifyingPeer (this, magnifierComp);
  61032. }
  61033. void childBoundsChanged (Component* c)
  61034. {
  61035. if (c != 0)
  61036. {
  61037. setSize (c->getWidth(), c->getHeight());
  61038. magnifierComp->childBoundsChanged (this);
  61039. }
  61040. }
  61041. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  61042. {
  61043. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  61044. Component* const p = magnifierComp->getParentComponent();
  61045. if (p != 0)
  61046. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  61047. }
  61048. private:
  61049. MagnifierComponent* const magnifierComp;
  61050. PeerHolderComp (const PeerHolderComp&);
  61051. PeerHolderComp& operator= (const PeerHolderComp&);
  61052. };
  61053. MagnifierComponent::MagnifierComponent (Component* const content_,
  61054. const bool deleteContentCompWhenNoLongerNeeded)
  61055. : content (content_),
  61056. scaleFactor (0.0),
  61057. peer (0),
  61058. deleteContent (deleteContentCompWhenNoLongerNeeded),
  61059. quality (Graphics::lowResamplingQuality),
  61060. mouseSource (0, true)
  61061. {
  61062. holderComp = new PeerHolderComp (this);
  61063. setScaleFactor (1.0);
  61064. }
  61065. MagnifierComponent::~MagnifierComponent()
  61066. {
  61067. delete holderComp;
  61068. if (deleteContent)
  61069. delete content;
  61070. }
  61071. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  61072. {
  61073. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  61074. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  61075. if (scaleFactor != newScaleFactor)
  61076. {
  61077. scaleFactor = newScaleFactor;
  61078. if (scaleFactor == 1.0)
  61079. {
  61080. holderComp->removeFromDesktop();
  61081. peer = 0;
  61082. addChildComponent (content);
  61083. childBoundsChanged (content);
  61084. }
  61085. else
  61086. {
  61087. holderComp->addAndMakeVisible (content);
  61088. holderComp->childBoundsChanged (content);
  61089. childBoundsChanged (holderComp);
  61090. holderComp->addToDesktop (0);
  61091. peer = holderComp->getPeer();
  61092. }
  61093. repaint();
  61094. }
  61095. }
  61096. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  61097. {
  61098. quality = newQuality;
  61099. }
  61100. void MagnifierComponent::paint (Graphics& g)
  61101. {
  61102. const int w = holderComp->getWidth();
  61103. const int h = holderComp->getHeight();
  61104. if (w == 0 || h == 0)
  61105. return;
  61106. const Rectangle<int> r (g.getClipBounds());
  61107. const int srcX = (int) (r.getX() / scaleFactor);
  61108. const int srcY = (int) (r.getY() / scaleFactor);
  61109. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  61110. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  61111. if (scaleFactor >= 1.0)
  61112. {
  61113. ++srcW;
  61114. ++srcH;
  61115. }
  61116. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  61117. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  61118. {
  61119. Graphics g2 (temp);
  61120. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  61121. holderComp->paintEntireComponent (g2);
  61122. }
  61123. g.setImageResamplingQuality (quality);
  61124. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  61125. }
  61126. void MagnifierComponent::childBoundsChanged (Component* c)
  61127. {
  61128. if (c != 0)
  61129. setSize (roundToInt (c->getWidth() * scaleFactor),
  61130. roundToInt (c->getHeight() * scaleFactor));
  61131. }
  61132. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  61133. {
  61134. if (peer != 0)
  61135. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  61136. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  61137. }
  61138. void MagnifierComponent::mouseDown (const MouseEvent& e)
  61139. {
  61140. passOnMouseEventToPeer (e);
  61141. }
  61142. void MagnifierComponent::mouseUp (const MouseEvent& e)
  61143. {
  61144. passOnMouseEventToPeer (e);
  61145. }
  61146. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  61147. {
  61148. passOnMouseEventToPeer (e);
  61149. }
  61150. void MagnifierComponent::mouseMove (const MouseEvent& e)
  61151. {
  61152. passOnMouseEventToPeer (e);
  61153. }
  61154. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  61155. {
  61156. passOnMouseEventToPeer (e);
  61157. }
  61158. void MagnifierComponent::mouseExit (const MouseEvent& e)
  61159. {
  61160. passOnMouseEventToPeer (e);
  61161. }
  61162. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  61163. {
  61164. if (peer != 0)
  61165. peer->handleMouseWheel (e.source.getIndex(),
  61166. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  61167. ix * 256.0f, iy * 256.0f);
  61168. else
  61169. Component::mouseWheelMove (e, ix, iy);
  61170. }
  61171. int MagnifierComponent::scaleInt (const int n) const
  61172. {
  61173. return roundToInt (n / scaleFactor);
  61174. }
  61175. END_JUCE_NAMESPACE
  61176. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  61177. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61178. BEGIN_JUCE_NAMESPACE
  61179. class MidiKeyboardUpDownButton : public Button
  61180. {
  61181. public:
  61182. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  61183. const int delta_)
  61184. : Button (String::empty),
  61185. owner (owner_),
  61186. delta (delta_)
  61187. {
  61188. setOpaque (true);
  61189. }
  61190. ~MidiKeyboardUpDownButton()
  61191. {
  61192. }
  61193. void clicked()
  61194. {
  61195. int note = owner->getLowestVisibleKey();
  61196. if (delta < 0)
  61197. note = (note - 1) / 12;
  61198. else
  61199. note = note / 12 + 1;
  61200. owner->setLowestVisibleKey (note * 12);
  61201. }
  61202. void paintButton (Graphics& g,
  61203. bool isMouseOverButton,
  61204. bool isButtonDown)
  61205. {
  61206. owner->drawUpDownButton (g, getWidth(), getHeight(),
  61207. isMouseOverButton, isButtonDown,
  61208. delta > 0);
  61209. }
  61210. private:
  61211. MidiKeyboardComponent* const owner;
  61212. const int delta;
  61213. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  61214. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  61215. };
  61216. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  61217. const Orientation orientation_)
  61218. : state (state_),
  61219. xOffset (0),
  61220. blackNoteLength (1),
  61221. keyWidth (16.0f),
  61222. orientation (orientation_),
  61223. midiChannel (1),
  61224. midiInChannelMask (0xffff),
  61225. velocity (1.0f),
  61226. noteUnderMouse (-1),
  61227. mouseDownNote (-1),
  61228. rangeStart (0),
  61229. rangeEnd (127),
  61230. firstKey (12 * 4),
  61231. canScroll (true),
  61232. mouseDragging (false),
  61233. useMousePositionForVelocity (true),
  61234. keyMappingOctave (6),
  61235. octaveNumForMiddleC (3)
  61236. {
  61237. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  61238. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  61239. // initialise with a default set of querty key-mappings..
  61240. const char* const keymap = "awsedftgyhujkolp;";
  61241. for (int i = String (keymap).length(); --i >= 0;)
  61242. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  61243. setOpaque (true);
  61244. setWantsKeyboardFocus (true);
  61245. state.addListener (this);
  61246. }
  61247. MidiKeyboardComponent::~MidiKeyboardComponent()
  61248. {
  61249. state.removeListener (this);
  61250. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  61251. deleteAllChildren();
  61252. }
  61253. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  61254. {
  61255. keyWidth = widthInPixels;
  61256. resized();
  61257. }
  61258. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  61259. {
  61260. if (orientation != newOrientation)
  61261. {
  61262. orientation = newOrientation;
  61263. resized();
  61264. }
  61265. }
  61266. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  61267. const int highestNote)
  61268. {
  61269. jassert (lowestNote >= 0 && lowestNote <= 127);
  61270. jassert (highestNote >= 0 && highestNote <= 127);
  61271. jassert (lowestNote <= highestNote);
  61272. if (rangeStart != lowestNote || rangeEnd != highestNote)
  61273. {
  61274. rangeStart = jlimit (0, 127, lowestNote);
  61275. rangeEnd = jlimit (0, 127, highestNote);
  61276. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  61277. resized();
  61278. }
  61279. }
  61280. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  61281. {
  61282. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  61283. if (noteNumber != firstKey)
  61284. {
  61285. firstKey = noteNumber;
  61286. sendChangeMessage (this);
  61287. resized();
  61288. }
  61289. }
  61290. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  61291. {
  61292. if (canScroll != canScroll_)
  61293. {
  61294. canScroll = canScroll_;
  61295. resized();
  61296. }
  61297. }
  61298. void MidiKeyboardComponent::colourChanged()
  61299. {
  61300. repaint();
  61301. }
  61302. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  61303. {
  61304. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  61305. if (midiChannel != midiChannelNumber)
  61306. {
  61307. resetAnyKeysInUse();
  61308. midiChannel = jlimit (1, 16, midiChannelNumber);
  61309. }
  61310. }
  61311. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  61312. {
  61313. midiInChannelMask = midiChannelMask;
  61314. triggerAsyncUpdate();
  61315. }
  61316. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  61317. {
  61318. velocity = jlimit (0.0f, 1.0f, velocity_);
  61319. useMousePositionForVelocity = useMousePositionForVelocity_;
  61320. }
  61321. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  61322. {
  61323. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  61324. static const float blackNoteWidth = 0.7f;
  61325. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  61326. 1.0f, 2 - blackNoteWidth * 0.4f,
  61327. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  61328. 4.0f, 5 - blackNoteWidth * 0.5f,
  61329. 5.0f, 6 - blackNoteWidth * 0.3f,
  61330. 6.0f };
  61331. static const float widths[] = { 1.0f, blackNoteWidth,
  61332. 1.0f, blackNoteWidth,
  61333. 1.0f, 1.0f, blackNoteWidth,
  61334. 1.0f, blackNoteWidth,
  61335. 1.0f, blackNoteWidth,
  61336. 1.0f };
  61337. const int octave = midiNoteNumber / 12;
  61338. const int note = midiNoteNumber % 12;
  61339. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  61340. w = roundToInt (widths [note] * keyWidth_);
  61341. }
  61342. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  61343. {
  61344. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  61345. int rx, rw;
  61346. getKeyPosition (rangeStart, keyWidth, rx, rw);
  61347. x -= xOffset + rx;
  61348. }
  61349. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61350. {
  61351. int x, y;
  61352. getKeyPos (midiNoteNumber, x, y);
  61353. return x;
  61354. }
  61355. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61356. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61357. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61358. {
  61359. if (! reallyContains (pos.getX(), pos.getY(), false))
  61360. return -1;
  61361. Point<int> p (pos);
  61362. if (orientation != horizontalKeyboard)
  61363. {
  61364. p = Point<int> (p.getY(), p.getX());
  61365. if (orientation == verticalKeyboardFacingLeft)
  61366. p = Point<int> (p.getX(), getWidth() - p.getY());
  61367. else
  61368. p = Point<int> (getHeight() - p.getX(), p.getY());
  61369. }
  61370. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61371. }
  61372. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61373. {
  61374. if (pos.getY() < blackNoteLength)
  61375. {
  61376. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61377. {
  61378. for (int i = 0; i < 5; ++i)
  61379. {
  61380. const int note = octaveStart + blackNotes [i];
  61381. if (note >= rangeStart && note <= rangeEnd)
  61382. {
  61383. int kx, kw;
  61384. getKeyPos (note, kx, kw);
  61385. kx += xOffset;
  61386. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61387. {
  61388. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61389. return note;
  61390. }
  61391. }
  61392. }
  61393. }
  61394. }
  61395. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61396. {
  61397. for (int i = 0; i < 7; ++i)
  61398. {
  61399. const int note = octaveStart + whiteNotes [i];
  61400. if (note >= rangeStart && note <= rangeEnd)
  61401. {
  61402. int kx, kw;
  61403. getKeyPos (note, kx, kw);
  61404. kx += xOffset;
  61405. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61406. {
  61407. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61408. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61409. return note;
  61410. }
  61411. }
  61412. }
  61413. }
  61414. mousePositionVelocity = 0;
  61415. return -1;
  61416. }
  61417. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61418. {
  61419. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61420. {
  61421. int x, w;
  61422. getKeyPos (noteNum, x, w);
  61423. if (orientation == horizontalKeyboard)
  61424. repaint (x, 0, w, getHeight());
  61425. else if (orientation == verticalKeyboardFacingLeft)
  61426. repaint (0, x, getWidth(), w);
  61427. else if (orientation == verticalKeyboardFacingRight)
  61428. repaint (0, getHeight() - x - w, getWidth(), w);
  61429. }
  61430. }
  61431. void MidiKeyboardComponent::paint (Graphics& g)
  61432. {
  61433. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61434. const Colour lineColour (findColour (keySeparatorLineColourId));
  61435. const Colour textColour (findColour (textLabelColourId));
  61436. int x, w, octave;
  61437. for (octave = 0; octave < 128; octave += 12)
  61438. {
  61439. for (int white = 0; white < 7; ++white)
  61440. {
  61441. const int noteNum = octave + whiteNotes [white];
  61442. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61443. {
  61444. getKeyPos (noteNum, x, w);
  61445. if (orientation == horizontalKeyboard)
  61446. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61447. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61448. noteUnderMouse == noteNum,
  61449. lineColour, textColour);
  61450. else if (orientation == verticalKeyboardFacingLeft)
  61451. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61452. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61453. noteUnderMouse == noteNum,
  61454. lineColour, textColour);
  61455. else if (orientation == verticalKeyboardFacingRight)
  61456. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61457. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61458. noteUnderMouse == noteNum,
  61459. lineColour, textColour);
  61460. }
  61461. }
  61462. }
  61463. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61464. if (orientation == verticalKeyboardFacingLeft)
  61465. {
  61466. x1 = getWidth() - 1.0f;
  61467. x2 = getWidth() - 5.0f;
  61468. }
  61469. else if (orientation == verticalKeyboardFacingRight)
  61470. x2 = 5.0f;
  61471. else
  61472. y2 = 5.0f;
  61473. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61474. Colours::transparentBlack, x2, y2, false));
  61475. getKeyPos (rangeEnd, x, w);
  61476. x += w;
  61477. if (orientation == verticalKeyboardFacingLeft)
  61478. g.fillRect (getWidth() - 5, 0, 5, x);
  61479. else if (orientation == verticalKeyboardFacingRight)
  61480. g.fillRect (0, 0, 5, x);
  61481. else
  61482. g.fillRect (0, 0, x, 5);
  61483. g.setColour (lineColour);
  61484. if (orientation == verticalKeyboardFacingLeft)
  61485. g.fillRect (0, 0, 1, x);
  61486. else if (orientation == verticalKeyboardFacingRight)
  61487. g.fillRect (getWidth() - 1, 0, 1, x);
  61488. else
  61489. g.fillRect (0, getHeight() - 1, x, 1);
  61490. const Colour blackNoteColour (findColour (blackNoteColourId));
  61491. for (octave = 0; octave < 128; octave += 12)
  61492. {
  61493. for (int black = 0; black < 5; ++black)
  61494. {
  61495. const int noteNum = octave + blackNotes [black];
  61496. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61497. {
  61498. getKeyPos (noteNum, x, w);
  61499. if (orientation == horizontalKeyboard)
  61500. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61501. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61502. noteUnderMouse == noteNum,
  61503. blackNoteColour);
  61504. else if (orientation == verticalKeyboardFacingLeft)
  61505. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61506. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61507. noteUnderMouse == noteNum,
  61508. blackNoteColour);
  61509. else if (orientation == verticalKeyboardFacingRight)
  61510. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61511. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61512. noteUnderMouse == noteNum,
  61513. blackNoteColour);
  61514. }
  61515. }
  61516. }
  61517. }
  61518. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61519. Graphics& g, int x, int y, int w, int h,
  61520. bool isDown, bool isOver,
  61521. const Colour& lineColour,
  61522. const Colour& textColour)
  61523. {
  61524. Colour c (Colours::transparentWhite);
  61525. if (isDown)
  61526. c = findColour (keyDownOverlayColourId);
  61527. if (isOver)
  61528. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61529. g.setColour (c);
  61530. g.fillRect (x, y, w, h);
  61531. const String text (getWhiteNoteText (midiNoteNumber));
  61532. if (! text.isEmpty())
  61533. {
  61534. g.setColour (textColour);
  61535. Font f (jmin (12.0f, keyWidth * 0.9f));
  61536. f.setHorizontalScale (0.8f);
  61537. g.setFont (f);
  61538. Justification justification (Justification::centredBottom);
  61539. if (orientation == verticalKeyboardFacingLeft)
  61540. justification = Justification::centredLeft;
  61541. else if (orientation == verticalKeyboardFacingRight)
  61542. justification = Justification::centredRight;
  61543. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61544. }
  61545. g.setColour (lineColour);
  61546. if (orientation == horizontalKeyboard)
  61547. g.fillRect (x, y, 1, h);
  61548. else if (orientation == verticalKeyboardFacingLeft)
  61549. g.fillRect (x, y, w, 1);
  61550. else if (orientation == verticalKeyboardFacingRight)
  61551. g.fillRect (x, y + h - 1, w, 1);
  61552. if (midiNoteNumber == rangeEnd)
  61553. {
  61554. if (orientation == horizontalKeyboard)
  61555. g.fillRect (x + w, y, 1, h);
  61556. else if (orientation == verticalKeyboardFacingLeft)
  61557. g.fillRect (x, y + h, w, 1);
  61558. else if (orientation == verticalKeyboardFacingRight)
  61559. g.fillRect (x, y - 1, w, 1);
  61560. }
  61561. }
  61562. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61563. Graphics& g, int x, int y, int w, int h,
  61564. bool isDown, bool isOver,
  61565. const Colour& noteFillColour)
  61566. {
  61567. Colour c (noteFillColour);
  61568. if (isDown)
  61569. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61570. if (isOver)
  61571. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61572. g.setColour (c);
  61573. g.fillRect (x, y, w, h);
  61574. if (isDown)
  61575. {
  61576. g.setColour (noteFillColour);
  61577. g.drawRect (x, y, w, h);
  61578. }
  61579. else
  61580. {
  61581. const int xIndent = jmax (1, jmin (w, h) / 8);
  61582. g.setColour (c.brighter());
  61583. if (orientation == horizontalKeyboard)
  61584. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61585. else if (orientation == verticalKeyboardFacingLeft)
  61586. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61587. else if (orientation == verticalKeyboardFacingRight)
  61588. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61589. }
  61590. }
  61591. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61592. {
  61593. octaveNumForMiddleC = octaveNumForMiddleC_;
  61594. repaint();
  61595. }
  61596. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61597. {
  61598. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61599. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61600. return String::empty;
  61601. }
  61602. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61603. const bool isMouseOver_,
  61604. const bool isButtonDown,
  61605. const bool movesOctavesUp)
  61606. {
  61607. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61608. float angle;
  61609. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61610. angle = movesOctavesUp ? 0.0f : 0.5f;
  61611. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61612. angle = movesOctavesUp ? 0.25f : 0.75f;
  61613. else
  61614. angle = movesOctavesUp ? 0.75f : 0.25f;
  61615. Path path;
  61616. path.lineTo (0.0f, 1.0f);
  61617. path.lineTo (1.0f, 0.5f);
  61618. path.closeSubPath();
  61619. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61620. g.setColour (findColour (upDownButtonArrowColourId)
  61621. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61622. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61623. w - 2.0f,
  61624. h - 2.0f,
  61625. true));
  61626. }
  61627. void MidiKeyboardComponent::resized()
  61628. {
  61629. int w = getWidth();
  61630. int h = getHeight();
  61631. if (w > 0 && h > 0)
  61632. {
  61633. if (orientation != horizontalKeyboard)
  61634. swapVariables (w, h);
  61635. blackNoteLength = roundToInt (h * 0.7f);
  61636. int kx2, kw2;
  61637. getKeyPos (rangeEnd, kx2, kw2);
  61638. kx2 += kw2;
  61639. if (firstKey != rangeStart)
  61640. {
  61641. int kx1, kw1;
  61642. getKeyPos (rangeStart, kx1, kw1);
  61643. if (kx2 - kx1 <= w)
  61644. {
  61645. firstKey = rangeStart;
  61646. sendChangeMessage (this);
  61647. repaint();
  61648. }
  61649. }
  61650. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61651. scrollDown->setVisible (showScrollButtons);
  61652. scrollUp->setVisible (showScrollButtons);
  61653. xOffset = 0;
  61654. if (showScrollButtons)
  61655. {
  61656. const int scrollButtonW = jmin (12, w / 2);
  61657. if (orientation == horizontalKeyboard)
  61658. {
  61659. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61660. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61661. }
  61662. else if (orientation == verticalKeyboardFacingLeft)
  61663. {
  61664. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61665. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61666. }
  61667. else if (orientation == verticalKeyboardFacingRight)
  61668. {
  61669. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61670. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61671. }
  61672. int endOfLastKey, kw;
  61673. getKeyPos (rangeEnd, endOfLastKey, kw);
  61674. endOfLastKey += kw;
  61675. float mousePositionVelocity;
  61676. const int spaceAvailable = w - scrollButtonW * 2;
  61677. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61678. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61679. {
  61680. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61681. sendChangeMessage (this);
  61682. }
  61683. int newOffset = 0;
  61684. getKeyPos (firstKey, newOffset, kw);
  61685. xOffset = newOffset - scrollButtonW;
  61686. }
  61687. else
  61688. {
  61689. firstKey = rangeStart;
  61690. }
  61691. timerCallback();
  61692. repaint();
  61693. }
  61694. }
  61695. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61696. {
  61697. triggerAsyncUpdate();
  61698. }
  61699. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61700. {
  61701. triggerAsyncUpdate();
  61702. }
  61703. void MidiKeyboardComponent::handleAsyncUpdate()
  61704. {
  61705. for (int i = rangeStart; i <= rangeEnd; ++i)
  61706. {
  61707. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61708. {
  61709. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61710. repaintNote (i);
  61711. }
  61712. }
  61713. }
  61714. void MidiKeyboardComponent::resetAnyKeysInUse()
  61715. {
  61716. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61717. {
  61718. state.allNotesOff (midiChannel);
  61719. keysPressed.clear();
  61720. mouseDownNote = -1;
  61721. }
  61722. }
  61723. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61724. {
  61725. float mousePositionVelocity = 0.0f;
  61726. const int newNote = (mouseDragging || isMouseOver())
  61727. ? xyToNote (pos, mousePositionVelocity) : -1;
  61728. if (noteUnderMouse != newNote)
  61729. {
  61730. if (mouseDownNote >= 0)
  61731. {
  61732. state.noteOff (midiChannel, mouseDownNote);
  61733. mouseDownNote = -1;
  61734. }
  61735. if (mouseDragging && newNote >= 0)
  61736. {
  61737. if (! useMousePositionForVelocity)
  61738. mousePositionVelocity = 1.0f;
  61739. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61740. mouseDownNote = newNote;
  61741. }
  61742. repaintNote (noteUnderMouse);
  61743. noteUnderMouse = newNote;
  61744. repaintNote (noteUnderMouse);
  61745. }
  61746. else if (mouseDownNote >= 0 && ! mouseDragging)
  61747. {
  61748. state.noteOff (midiChannel, mouseDownNote);
  61749. mouseDownNote = -1;
  61750. }
  61751. }
  61752. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61753. {
  61754. updateNoteUnderMouse (e.getPosition());
  61755. stopTimer();
  61756. }
  61757. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61758. {
  61759. float mousePositionVelocity;
  61760. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61761. if (newNote >= 0)
  61762. mouseDraggedToKey (newNote, e);
  61763. updateNoteUnderMouse (e.getPosition());
  61764. }
  61765. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61766. {
  61767. return true;
  61768. }
  61769. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61770. {
  61771. }
  61772. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61773. {
  61774. float mousePositionVelocity;
  61775. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61776. mouseDragging = false;
  61777. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61778. {
  61779. repaintNote (noteUnderMouse);
  61780. noteUnderMouse = -1;
  61781. mouseDragging = true;
  61782. updateNoteUnderMouse (e.getPosition());
  61783. startTimer (500);
  61784. }
  61785. }
  61786. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61787. {
  61788. mouseDragging = false;
  61789. updateNoteUnderMouse (e.getPosition());
  61790. stopTimer();
  61791. }
  61792. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61793. {
  61794. updateNoteUnderMouse (e.getPosition());
  61795. }
  61796. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61797. {
  61798. updateNoteUnderMouse (e.getPosition());
  61799. }
  61800. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61801. {
  61802. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61803. }
  61804. void MidiKeyboardComponent::timerCallback()
  61805. {
  61806. updateNoteUnderMouse (getMouseXYRelative());
  61807. }
  61808. void MidiKeyboardComponent::clearKeyMappings()
  61809. {
  61810. resetAnyKeysInUse();
  61811. keyPressNotes.clear();
  61812. keyPresses.clear();
  61813. }
  61814. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61815. const int midiNoteOffsetFromC)
  61816. {
  61817. removeKeyPressForNote (midiNoteOffsetFromC);
  61818. keyPressNotes.add (midiNoteOffsetFromC);
  61819. keyPresses.add (key);
  61820. }
  61821. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61822. {
  61823. for (int i = keyPressNotes.size(); --i >= 0;)
  61824. {
  61825. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61826. {
  61827. keyPressNotes.remove (i);
  61828. keyPresses.remove (i);
  61829. }
  61830. }
  61831. }
  61832. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61833. {
  61834. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61835. keyMappingOctave = newOctaveNumber;
  61836. }
  61837. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61838. {
  61839. bool keyPressUsed = false;
  61840. for (int i = keyPresses.size(); --i >= 0;)
  61841. {
  61842. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61843. if (keyPresses.getReference(i).isCurrentlyDown())
  61844. {
  61845. if (! keysPressed [note])
  61846. {
  61847. keysPressed.setBit (note);
  61848. state.noteOn (midiChannel, note, velocity);
  61849. keyPressUsed = true;
  61850. }
  61851. }
  61852. else
  61853. {
  61854. if (keysPressed [note])
  61855. {
  61856. keysPressed.clearBit (note);
  61857. state.noteOff (midiChannel, note);
  61858. keyPressUsed = true;
  61859. }
  61860. }
  61861. }
  61862. return keyPressUsed;
  61863. }
  61864. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61865. {
  61866. resetAnyKeysInUse();
  61867. }
  61868. END_JUCE_NAMESPACE
  61869. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61870. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61871. #if JUCE_OPENGL
  61872. BEGIN_JUCE_NAMESPACE
  61873. extern void juce_glViewport (const int w, const int h);
  61874. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61875. const int alphaBits_,
  61876. const int depthBufferBits_,
  61877. const int stencilBufferBits_)
  61878. : redBits (bitsPerRGBComponent),
  61879. greenBits (bitsPerRGBComponent),
  61880. blueBits (bitsPerRGBComponent),
  61881. alphaBits (alphaBits_),
  61882. depthBufferBits (depthBufferBits_),
  61883. stencilBufferBits (stencilBufferBits_),
  61884. accumulationBufferRedBits (0),
  61885. accumulationBufferGreenBits (0),
  61886. accumulationBufferBlueBits (0),
  61887. accumulationBufferAlphaBits (0),
  61888. fullSceneAntiAliasingNumSamples (0)
  61889. {
  61890. }
  61891. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61892. : redBits (other.redBits),
  61893. greenBits (other.greenBits),
  61894. blueBits (other.blueBits),
  61895. alphaBits (other.alphaBits),
  61896. depthBufferBits (other.depthBufferBits),
  61897. stencilBufferBits (other.stencilBufferBits),
  61898. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61899. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61900. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61901. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61902. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61903. {
  61904. }
  61905. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61906. {
  61907. redBits = other.redBits;
  61908. greenBits = other.greenBits;
  61909. blueBits = other.blueBits;
  61910. alphaBits = other.alphaBits;
  61911. depthBufferBits = other.depthBufferBits;
  61912. stencilBufferBits = other.stencilBufferBits;
  61913. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61914. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61915. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61916. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61917. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61918. return *this;
  61919. }
  61920. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61921. {
  61922. return redBits == other.redBits
  61923. && greenBits == other.greenBits
  61924. && blueBits == other.blueBits
  61925. && alphaBits == other.alphaBits
  61926. && depthBufferBits == other.depthBufferBits
  61927. && stencilBufferBits == other.stencilBufferBits
  61928. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61929. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61930. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61931. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61932. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61933. }
  61934. static Array<OpenGLContext*> knownContexts;
  61935. OpenGLContext::OpenGLContext() throw()
  61936. {
  61937. knownContexts.add (this);
  61938. }
  61939. OpenGLContext::~OpenGLContext()
  61940. {
  61941. knownContexts.removeValue (this);
  61942. }
  61943. OpenGLContext* OpenGLContext::getCurrentContext()
  61944. {
  61945. for (int i = knownContexts.size(); --i >= 0;)
  61946. {
  61947. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61948. if (oglc->isActive())
  61949. return oglc;
  61950. }
  61951. return 0;
  61952. }
  61953. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61954. {
  61955. public:
  61956. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61957. : ComponentMovementWatcher (owner_),
  61958. owner (owner_),
  61959. wasShowing (false)
  61960. {
  61961. }
  61962. ~OpenGLComponentWatcher() {}
  61963. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61964. {
  61965. owner->updateContextPosition();
  61966. }
  61967. void componentPeerChanged()
  61968. {
  61969. const ScopedLock sl (owner->getContextLock());
  61970. owner->deleteContext();
  61971. }
  61972. void componentVisibilityChanged (Component&)
  61973. {
  61974. const bool isShowingNow = owner->isShowing();
  61975. if (wasShowing != isShowingNow)
  61976. {
  61977. wasShowing = isShowingNow;
  61978. if (! isShowingNow)
  61979. {
  61980. const ScopedLock sl (owner->getContextLock());
  61981. owner->deleteContext();
  61982. }
  61983. }
  61984. }
  61985. juce_UseDebuggingNewOperator
  61986. private:
  61987. OpenGLComponent* const owner;
  61988. bool wasShowing;
  61989. };
  61990. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61991. : type (type_),
  61992. contextToShareListsWith (0),
  61993. needToUpdateViewport (true)
  61994. {
  61995. setOpaque (true);
  61996. componentWatcher = new OpenGLComponentWatcher (this);
  61997. }
  61998. OpenGLComponent::~OpenGLComponent()
  61999. {
  62000. deleteContext();
  62001. componentWatcher = 0;
  62002. }
  62003. void OpenGLComponent::deleteContext()
  62004. {
  62005. const ScopedLock sl (contextLock);
  62006. context = 0;
  62007. }
  62008. void OpenGLComponent::updateContextPosition()
  62009. {
  62010. needToUpdateViewport = true;
  62011. if (getWidth() > 0 && getHeight() > 0)
  62012. {
  62013. Component* const topComp = getTopLevelComponent();
  62014. if (topComp->getPeer() != 0)
  62015. {
  62016. const ScopedLock sl (contextLock);
  62017. if (context != 0)
  62018. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  62019. getScreenY() - topComp->getScreenY(),
  62020. getWidth(),
  62021. getHeight(),
  62022. topComp->getHeight());
  62023. }
  62024. }
  62025. }
  62026. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  62027. {
  62028. OpenGLPixelFormat pf;
  62029. const ScopedLock sl (contextLock);
  62030. if (context != 0)
  62031. pf = context->getPixelFormat();
  62032. return pf;
  62033. }
  62034. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  62035. {
  62036. if (! (preferredPixelFormat == formatToUse))
  62037. {
  62038. const ScopedLock sl (contextLock);
  62039. deleteContext();
  62040. preferredPixelFormat = formatToUse;
  62041. }
  62042. }
  62043. void OpenGLComponent::shareWith (OpenGLContext* c)
  62044. {
  62045. if (contextToShareListsWith != c)
  62046. {
  62047. const ScopedLock sl (contextLock);
  62048. deleteContext();
  62049. contextToShareListsWith = c;
  62050. }
  62051. }
  62052. bool OpenGLComponent::makeCurrentContextActive()
  62053. {
  62054. if (context == 0)
  62055. {
  62056. const ScopedLock sl (contextLock);
  62057. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  62058. {
  62059. context = createContext();
  62060. if (context != 0)
  62061. {
  62062. updateContextPosition();
  62063. if (context->makeActive())
  62064. newOpenGLContextCreated();
  62065. }
  62066. }
  62067. }
  62068. return context != 0 && context->makeActive();
  62069. }
  62070. void OpenGLComponent::makeCurrentContextInactive()
  62071. {
  62072. if (context != 0)
  62073. context->makeInactive();
  62074. }
  62075. bool OpenGLComponent::isActiveContext() const throw()
  62076. {
  62077. return context != 0 && context->isActive();
  62078. }
  62079. void OpenGLComponent::swapBuffers()
  62080. {
  62081. if (context != 0)
  62082. context->swapBuffers();
  62083. }
  62084. void OpenGLComponent::paint (Graphics&)
  62085. {
  62086. if (renderAndSwapBuffers())
  62087. {
  62088. ComponentPeer* const peer = getPeer();
  62089. if (peer != 0)
  62090. {
  62091. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  62092. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  62093. }
  62094. }
  62095. }
  62096. bool OpenGLComponent::renderAndSwapBuffers()
  62097. {
  62098. const ScopedLock sl (contextLock);
  62099. if (! makeCurrentContextActive())
  62100. return false;
  62101. if (needToUpdateViewport)
  62102. {
  62103. needToUpdateViewport = false;
  62104. juce_glViewport (getWidth(), getHeight());
  62105. }
  62106. renderOpenGL();
  62107. swapBuffers();
  62108. return true;
  62109. }
  62110. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  62111. {
  62112. Component::internalRepaint (x, y, w, h);
  62113. if (context != 0)
  62114. context->repaint();
  62115. }
  62116. END_JUCE_NAMESPACE
  62117. #endif
  62118. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  62119. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  62120. BEGIN_JUCE_NAMESPACE
  62121. PreferencesPanel::PreferencesPanel()
  62122. : buttonSize (70)
  62123. {
  62124. }
  62125. PreferencesPanel::~PreferencesPanel()
  62126. {
  62127. currentPage = 0;
  62128. deleteAllChildren();
  62129. }
  62130. void PreferencesPanel::addSettingsPage (const String& title,
  62131. const Drawable* icon,
  62132. const Drawable* overIcon,
  62133. const Drawable* downIcon)
  62134. {
  62135. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  62136. button->setImages (icon, overIcon, downIcon);
  62137. button->setRadioGroupId (1);
  62138. button->addButtonListener (this);
  62139. button->setClickingTogglesState (true);
  62140. button->setWantsKeyboardFocus (false);
  62141. addAndMakeVisible (button);
  62142. resized();
  62143. if (currentPage == 0)
  62144. setCurrentPage (title);
  62145. }
  62146. void PreferencesPanel::addSettingsPage (const String& title,
  62147. const void* imageData,
  62148. const int imageDataSize)
  62149. {
  62150. DrawableImage icon, iconOver, iconDown;
  62151. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  62152. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  62153. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  62154. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  62155. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  62156. addSettingsPage (title, &icon, &iconOver, &iconDown);
  62157. }
  62158. class PrefsDialogWindow : public DialogWindow
  62159. {
  62160. public:
  62161. PrefsDialogWindow (const String& dialogtitle,
  62162. const Colour& backgroundColour)
  62163. : DialogWindow (dialogtitle, backgroundColour, true)
  62164. {
  62165. }
  62166. ~PrefsDialogWindow()
  62167. {
  62168. }
  62169. void closeButtonPressed()
  62170. {
  62171. exitModalState (0);
  62172. }
  62173. private:
  62174. PrefsDialogWindow (const PrefsDialogWindow&);
  62175. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  62176. };
  62177. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  62178. int dialogWidth,
  62179. int dialogHeight,
  62180. const Colour& backgroundColour)
  62181. {
  62182. setSize (dialogWidth, dialogHeight);
  62183. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  62184. dw.setContentComponent (this, true, true);
  62185. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  62186. dw.runModalLoop();
  62187. dw.setContentComponent (0, false, false);
  62188. }
  62189. void PreferencesPanel::resized()
  62190. {
  62191. int x = 0;
  62192. for (int i = 0; i < getNumChildComponents(); ++i)
  62193. {
  62194. Component* c = getChildComponent (i);
  62195. if (dynamic_cast <DrawableButton*> (c) == 0)
  62196. {
  62197. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  62198. }
  62199. else
  62200. {
  62201. c->setBounds (x, 0, buttonSize, buttonSize);
  62202. x += buttonSize;
  62203. }
  62204. }
  62205. }
  62206. void PreferencesPanel::paint (Graphics& g)
  62207. {
  62208. g.setColour (Colours::grey);
  62209. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  62210. }
  62211. void PreferencesPanel::setCurrentPage (const String& pageName)
  62212. {
  62213. if (currentPageName != pageName)
  62214. {
  62215. currentPageName = pageName;
  62216. currentPage = 0;
  62217. currentPage = createComponentForPage (pageName);
  62218. if (currentPage != 0)
  62219. {
  62220. addAndMakeVisible (currentPage);
  62221. currentPage->toBack();
  62222. resized();
  62223. }
  62224. for (int i = 0; i < getNumChildComponents(); ++i)
  62225. {
  62226. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  62227. if (db != 0 && db->getName() == pageName)
  62228. {
  62229. db->setToggleState (true, false);
  62230. break;
  62231. }
  62232. }
  62233. }
  62234. }
  62235. void PreferencesPanel::buttonClicked (Button*)
  62236. {
  62237. for (int i = 0; i < getNumChildComponents(); ++i)
  62238. {
  62239. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  62240. if (db != 0 && db->getToggleState())
  62241. {
  62242. setCurrentPage (db->getName());
  62243. break;
  62244. }
  62245. }
  62246. }
  62247. END_JUCE_NAMESPACE
  62248. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  62249. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62250. #if JUCE_WINDOWS || JUCE_LINUX
  62251. BEGIN_JUCE_NAMESPACE
  62252. SystemTrayIconComponent::SystemTrayIconComponent()
  62253. {
  62254. addToDesktop (0);
  62255. }
  62256. SystemTrayIconComponent::~SystemTrayIconComponent()
  62257. {
  62258. }
  62259. END_JUCE_NAMESPACE
  62260. #endif
  62261. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62262. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  62263. BEGIN_JUCE_NAMESPACE
  62264. class AlertWindowTextEditor : public TextEditor
  62265. {
  62266. public:
  62267. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  62268. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  62269. {
  62270. setSelectAllWhenFocused (true);
  62271. }
  62272. ~AlertWindowTextEditor()
  62273. {
  62274. }
  62275. void returnPressed()
  62276. {
  62277. // pass these up the component hierarchy to be trigger the buttons
  62278. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  62279. }
  62280. void escapePressed()
  62281. {
  62282. // pass these up the component hierarchy to be trigger the buttons
  62283. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  62284. }
  62285. private:
  62286. AlertWindowTextEditor (const AlertWindowTextEditor&);
  62287. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  62288. static juce_wchar getDefaultPasswordChar() throw()
  62289. {
  62290. #if JUCE_LINUX
  62291. return 0x2022;
  62292. #else
  62293. return 0x25cf;
  62294. #endif
  62295. }
  62296. };
  62297. AlertWindow::AlertWindow (const String& title,
  62298. const String& message,
  62299. AlertIconType iconType,
  62300. Component* associatedComponent_)
  62301. : TopLevelWindow (title, true),
  62302. alertIconType (iconType),
  62303. associatedComponent (associatedComponent_)
  62304. {
  62305. if (message.isEmpty())
  62306. text = " "; // to force an update if the message is empty
  62307. setMessage (message);
  62308. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  62309. {
  62310. Component* const c = Desktop::getInstance().getComponent (i);
  62311. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  62312. {
  62313. setAlwaysOnTop (true);
  62314. break;
  62315. }
  62316. }
  62317. if (! JUCEApplication::isStandaloneApp())
  62318. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62319. lookAndFeelChanged();
  62320. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  62321. }
  62322. AlertWindow::~AlertWindow()
  62323. {
  62324. for (int i = customComps.size(); --i >= 0;)
  62325. removeChildComponent ((Component*) customComps[i]);
  62326. deleteAllChildren();
  62327. }
  62328. void AlertWindow::userTriedToCloseWindow()
  62329. {
  62330. exitModalState (0);
  62331. }
  62332. void AlertWindow::setMessage (const String& message)
  62333. {
  62334. const String newMessage (message.substring (0, 2048));
  62335. if (text != newMessage)
  62336. {
  62337. text = newMessage;
  62338. font.setHeight (15.0f);
  62339. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  62340. textLayout.setText (getName() + "\n\n", titleFont);
  62341. textLayout.appendText (text, font);
  62342. updateLayout (true);
  62343. repaint();
  62344. }
  62345. }
  62346. void AlertWindow::buttonClicked (Button* button)
  62347. {
  62348. for (int i = 0; i < buttons.size(); i++)
  62349. {
  62350. TextButton* const c = (TextButton*) buttons[i];
  62351. if (button->getName() == c->getName())
  62352. {
  62353. if (c->getParentComponent() != 0)
  62354. c->getParentComponent()->exitModalState (c->getCommandID());
  62355. break;
  62356. }
  62357. }
  62358. }
  62359. void AlertWindow::addButton (const String& name,
  62360. const int returnValue,
  62361. const KeyPress& shortcutKey1,
  62362. const KeyPress& shortcutKey2)
  62363. {
  62364. TextButton* const b = new TextButton (name, String::empty);
  62365. b->setWantsKeyboardFocus (true);
  62366. b->setMouseClickGrabsKeyboardFocus (false);
  62367. b->setCommandToTrigger (0, returnValue, false);
  62368. b->addShortcut (shortcutKey1);
  62369. b->addShortcut (shortcutKey2);
  62370. b->addButtonListener (this);
  62371. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  62372. addAndMakeVisible (b, 0);
  62373. buttons.add (b);
  62374. updateLayout (false);
  62375. }
  62376. int AlertWindow::getNumButtons() const
  62377. {
  62378. return buttons.size();
  62379. }
  62380. void AlertWindow::triggerButtonClick (const String& buttonName)
  62381. {
  62382. for (int i = buttons.size(); --i >= 0;)
  62383. {
  62384. TextButton* const b = (TextButton*) buttons[i];
  62385. if (buttonName == b->getName())
  62386. {
  62387. b->triggerClick();
  62388. break;
  62389. }
  62390. }
  62391. }
  62392. void AlertWindow::addTextEditor (const String& name,
  62393. const String& initialContents,
  62394. const String& onScreenLabel,
  62395. const bool isPasswordBox)
  62396. {
  62397. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62398. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62399. tc->setFont (font);
  62400. tc->setText (initialContents);
  62401. tc->setCaretPosition (initialContents.length());
  62402. addAndMakeVisible (tc);
  62403. textBoxes.add (tc);
  62404. allComps.add (tc);
  62405. textboxNames.add (onScreenLabel);
  62406. updateLayout (false);
  62407. }
  62408. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62409. {
  62410. for (int i = textBoxes.size(); --i >= 0;)
  62411. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  62412. return ((TextEditor*)textBoxes[i])->getText();
  62413. return String::empty;
  62414. }
  62415. void AlertWindow::addComboBox (const String& name,
  62416. const StringArray& items,
  62417. const String& onScreenLabel)
  62418. {
  62419. ComboBox* const cb = new ComboBox (name);
  62420. for (int i = 0; i < items.size(); ++i)
  62421. cb->addItem (items[i], i + 1);
  62422. addAndMakeVisible (cb);
  62423. cb->setSelectedItemIndex (0);
  62424. comboBoxes.add (cb);
  62425. allComps.add (cb);
  62426. comboBoxNames.add (onScreenLabel);
  62427. updateLayout (false);
  62428. }
  62429. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62430. {
  62431. for (int i = comboBoxes.size(); --i >= 0;)
  62432. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62433. return (ComboBox*) comboBoxes[i];
  62434. return 0;
  62435. }
  62436. class AlertTextComp : public TextEditor
  62437. {
  62438. public:
  62439. AlertTextComp (const String& message,
  62440. const Font& font)
  62441. {
  62442. setReadOnly (true);
  62443. setMultiLine (true, true);
  62444. setCaretVisible (false);
  62445. setScrollbarsShown (true);
  62446. lookAndFeelChanged();
  62447. setWantsKeyboardFocus (false);
  62448. setFont (font);
  62449. setText (message, false);
  62450. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62451. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62452. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62453. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62454. }
  62455. ~AlertTextComp()
  62456. {
  62457. }
  62458. int getPreferredWidth() const throw() { return bestWidth; }
  62459. void updateLayout (const int width)
  62460. {
  62461. TextLayout text;
  62462. text.appendText (getText(), getFont());
  62463. text.layout (width - 8, Justification::topLeft, true);
  62464. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62465. }
  62466. private:
  62467. int bestWidth;
  62468. AlertTextComp (const AlertTextComp&);
  62469. AlertTextComp& operator= (const AlertTextComp&);
  62470. };
  62471. void AlertWindow::addTextBlock (const String& textBlock)
  62472. {
  62473. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62474. textBlocks.add (c);
  62475. allComps.add (c);
  62476. addAndMakeVisible (c);
  62477. updateLayout (false);
  62478. }
  62479. void AlertWindow::addProgressBarComponent (double& progressValue)
  62480. {
  62481. ProgressBar* const pb = new ProgressBar (progressValue);
  62482. progressBars.add (pb);
  62483. allComps.add (pb);
  62484. addAndMakeVisible (pb);
  62485. updateLayout (false);
  62486. }
  62487. void AlertWindow::addCustomComponent (Component* const component)
  62488. {
  62489. customComps.add (component);
  62490. allComps.add (component);
  62491. addAndMakeVisible (component);
  62492. updateLayout (false);
  62493. }
  62494. int AlertWindow::getNumCustomComponents() const
  62495. {
  62496. return customComps.size();
  62497. }
  62498. Component* AlertWindow::getCustomComponent (const int index) const
  62499. {
  62500. return (Component*) customComps [index];
  62501. }
  62502. Component* AlertWindow::removeCustomComponent (const int index)
  62503. {
  62504. Component* const c = getCustomComponent (index);
  62505. if (c != 0)
  62506. {
  62507. customComps.removeValue (c);
  62508. allComps.removeValue (c);
  62509. removeChildComponent (c);
  62510. updateLayout (false);
  62511. }
  62512. return c;
  62513. }
  62514. void AlertWindow::paint (Graphics& g)
  62515. {
  62516. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62517. g.setColour (findColour (textColourId));
  62518. g.setFont (getLookAndFeel().getAlertWindowFont());
  62519. int i;
  62520. for (i = textBoxes.size(); --i >= 0;)
  62521. {
  62522. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62523. g.drawFittedText (textboxNames[i],
  62524. te->getX(), te->getY() - 14,
  62525. te->getWidth(), 14,
  62526. Justification::centredLeft, 1);
  62527. }
  62528. for (i = comboBoxNames.size(); --i >= 0;)
  62529. {
  62530. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62531. g.drawFittedText (comboBoxNames[i],
  62532. cb->getX(), cb->getY() - 14,
  62533. cb->getWidth(), 14,
  62534. Justification::centredLeft, 1);
  62535. }
  62536. for (i = customComps.size(); --i >= 0;)
  62537. {
  62538. const Component* const c = (Component*) customComps[i];
  62539. g.drawFittedText (c->getName(),
  62540. c->getX(), c->getY() - 14,
  62541. c->getWidth(), 14,
  62542. Justification::centredLeft, 1);
  62543. }
  62544. }
  62545. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62546. {
  62547. const int titleH = 24;
  62548. const int iconWidth = 80;
  62549. const int wid = jmax (font.getStringWidth (text),
  62550. font.getStringWidth (getName()));
  62551. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62552. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62553. const int edgeGap = 10;
  62554. const int labelHeight = 18;
  62555. int iconSpace;
  62556. if (alertIconType == NoIcon)
  62557. {
  62558. textLayout.layout (w, Justification::horizontallyCentred, true);
  62559. iconSpace = 0;
  62560. }
  62561. else
  62562. {
  62563. textLayout.layout (w, Justification::left, true);
  62564. iconSpace = iconWidth;
  62565. }
  62566. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62567. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62568. const int textLayoutH = textLayout.getHeight();
  62569. const int textBottom = 16 + titleH + textLayoutH;
  62570. int h = textBottom;
  62571. int buttonW = 40;
  62572. int i;
  62573. for (i = 0; i < buttons.size(); ++i)
  62574. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62575. w = jmax (buttonW, w);
  62576. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62577. if (buttons.size() > 0)
  62578. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62579. for (i = customComps.size(); --i >= 0;)
  62580. {
  62581. Component* c = (Component*) customComps[i];
  62582. w = jmax (w, (c->getWidth() * 100) / 80);
  62583. h += 10 + c->getHeight();
  62584. if (c->getName().isNotEmpty())
  62585. h += labelHeight;
  62586. }
  62587. for (i = textBlocks.size(); --i >= 0;)
  62588. {
  62589. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62590. w = jmax (w, ac->getPreferredWidth());
  62591. }
  62592. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62593. for (i = textBlocks.size(); --i >= 0;)
  62594. {
  62595. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62596. ac->updateLayout ((int) (w * 0.8f));
  62597. h += ac->getHeight() + 10;
  62598. }
  62599. h = jmin (getParentHeight() - 50, h);
  62600. if (onlyIncreaseSize)
  62601. {
  62602. w = jmax (w, getWidth());
  62603. h = jmax (h, getHeight());
  62604. }
  62605. if (! isVisible())
  62606. {
  62607. centreAroundComponent (associatedComponent, w, h);
  62608. }
  62609. else
  62610. {
  62611. const int cx = getX() + getWidth() / 2;
  62612. const int cy = getY() + getHeight() / 2;
  62613. setBounds (cx - w / 2,
  62614. cy - h / 2,
  62615. w, h);
  62616. }
  62617. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62618. const int spacer = 16;
  62619. int totalWidth = -spacer;
  62620. for (i = buttons.size(); --i >= 0;)
  62621. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62622. int x = (w - totalWidth) / 2;
  62623. int y = (int) (getHeight() * 0.95f);
  62624. for (i = 0; i < buttons.size(); ++i)
  62625. {
  62626. TextButton* const c = (TextButton*) buttons[i];
  62627. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62628. c->setTopLeftPosition (x, ny);
  62629. if (ny < y)
  62630. y = ny;
  62631. x += c->getWidth() + spacer;
  62632. c->toFront (false);
  62633. }
  62634. y = textBottom;
  62635. for (i = 0; i < allComps.size(); ++i)
  62636. {
  62637. Component* const c = (Component*) allComps[i];
  62638. h = 22;
  62639. const int comboIndex = comboBoxes.indexOf (c);
  62640. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62641. y += labelHeight;
  62642. const int tbIndex = textBoxes.indexOf (c);
  62643. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62644. y += labelHeight;
  62645. if (customComps.contains (c))
  62646. {
  62647. if (c->getName().isNotEmpty())
  62648. y += labelHeight;
  62649. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62650. h = c->getHeight();
  62651. }
  62652. else if (textBlocks.contains (c))
  62653. {
  62654. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62655. h = c->getHeight();
  62656. }
  62657. else
  62658. {
  62659. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62660. }
  62661. y += h + 10;
  62662. }
  62663. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62664. }
  62665. bool AlertWindow::containsAnyExtraComponents() const
  62666. {
  62667. return textBoxes.size()
  62668. + comboBoxes.size()
  62669. + progressBars.size()
  62670. + customComps.size() > 0;
  62671. }
  62672. void AlertWindow::mouseDown (const MouseEvent&)
  62673. {
  62674. dragger.startDraggingComponent (this, &constrainer);
  62675. }
  62676. void AlertWindow::mouseDrag (const MouseEvent& e)
  62677. {
  62678. dragger.dragComponent (this, e);
  62679. }
  62680. bool AlertWindow::keyPressed (const KeyPress& key)
  62681. {
  62682. for (int i = buttons.size(); --i >= 0;)
  62683. {
  62684. TextButton* const b = (TextButton*) buttons[i];
  62685. if (b->isRegisteredForShortcut (key))
  62686. {
  62687. b->triggerClick();
  62688. return true;
  62689. }
  62690. }
  62691. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62692. {
  62693. exitModalState (0);
  62694. return true;
  62695. }
  62696. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62697. {
  62698. ((TextButton*) buttons.getFirst())->triggerClick();
  62699. return true;
  62700. }
  62701. return false;
  62702. }
  62703. void AlertWindow::lookAndFeelChanged()
  62704. {
  62705. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62706. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62707. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62708. }
  62709. int AlertWindow::getDesktopWindowStyleFlags() const
  62710. {
  62711. return getLookAndFeel().getAlertBoxWindowFlags();
  62712. }
  62713. struct AlertWindowInfo
  62714. {
  62715. String title, message, button1, button2, button3;
  62716. AlertWindow::AlertIconType iconType;
  62717. int numButtons;
  62718. Component::SafePointer<Component> associatedComponent;
  62719. int run() const
  62720. {
  62721. return (int) (pointer_sized_int)
  62722. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62723. }
  62724. private:
  62725. int show() const
  62726. {
  62727. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62728. : LookAndFeel::getDefaultLookAndFeel();
  62729. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62730. iconType, numButtons, associatedComponent));
  62731. jassert (alertBox != 0); // you have to return one of these!
  62732. return alertBox->runModalLoop();
  62733. }
  62734. static void* showCallback (void* userData)
  62735. {
  62736. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62737. }
  62738. };
  62739. void AlertWindow::showMessageBox (AlertIconType iconType,
  62740. const String& title,
  62741. const String& message,
  62742. const String& buttonText,
  62743. Component* associatedComponent)
  62744. {
  62745. AlertWindowInfo info;
  62746. info.title = title;
  62747. info.message = message;
  62748. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62749. info.iconType = iconType;
  62750. info.numButtons = 1;
  62751. info.associatedComponent = associatedComponent;
  62752. info.run();
  62753. }
  62754. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62755. const String& title,
  62756. const String& message,
  62757. const String& button1Text,
  62758. const String& button2Text,
  62759. Component* associatedComponent)
  62760. {
  62761. AlertWindowInfo info;
  62762. info.title = title;
  62763. info.message = message;
  62764. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62765. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62766. info.iconType = iconType;
  62767. info.numButtons = 2;
  62768. info.associatedComponent = associatedComponent;
  62769. return info.run() != 0;
  62770. }
  62771. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62772. const String& title,
  62773. const String& message,
  62774. const String& button1Text,
  62775. const String& button2Text,
  62776. const String& button3Text,
  62777. Component* associatedComponent)
  62778. {
  62779. AlertWindowInfo info;
  62780. info.title = title;
  62781. info.message = message;
  62782. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62783. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62784. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62785. info.iconType = iconType;
  62786. info.numButtons = 3;
  62787. info.associatedComponent = associatedComponent;
  62788. return info.run();
  62789. }
  62790. END_JUCE_NAMESPACE
  62791. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62792. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62793. BEGIN_JUCE_NAMESPACE
  62794. CallOutBox::CallOutBox (Component& contentComponent,
  62795. Component& componentToPointTo,
  62796. Component* const parentComponent)
  62797. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62798. {
  62799. addAndMakeVisible (&content);
  62800. if (parentComponent != 0)
  62801. {
  62802. updatePosition (parentComponent->getLocalBounds(),
  62803. componentToPointTo.getLocalBounds()
  62804. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  62805. parentComponent->addAndMakeVisible (this);
  62806. }
  62807. else
  62808. {
  62809. if (! JUCEApplication::isStandaloneApp())
  62810. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62811. updatePosition (componentToPointTo.getScreenBounds(),
  62812. componentToPointTo.getParentMonitorArea());
  62813. addToDesktop (ComponentPeer::windowIsTemporary);
  62814. }
  62815. }
  62816. CallOutBox::~CallOutBox()
  62817. {
  62818. }
  62819. void CallOutBox::setArrowSize (const float newSize)
  62820. {
  62821. arrowSize = newSize;
  62822. borderSpace = jmax (20, (int) arrowSize);
  62823. refreshPath();
  62824. }
  62825. void CallOutBox::paint (Graphics& g)
  62826. {
  62827. if (background.isNull())
  62828. {
  62829. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62830. Graphics g (background);
  62831. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62832. }
  62833. g.setColour (Colours::black);
  62834. g.drawImageAt (background, 0, 0);
  62835. }
  62836. void CallOutBox::resized()
  62837. {
  62838. content.setTopLeftPosition (borderSpace, borderSpace);
  62839. refreshPath();
  62840. }
  62841. void CallOutBox::moved()
  62842. {
  62843. refreshPath();
  62844. }
  62845. void CallOutBox::childBoundsChanged (Component*)
  62846. {
  62847. updatePosition (targetArea, availableArea);
  62848. }
  62849. bool CallOutBox::hitTest (int x, int y)
  62850. {
  62851. return outline.contains ((float) x, (float) y);
  62852. }
  62853. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62854. void CallOutBox::inputAttemptWhenModal()
  62855. {
  62856. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62857. if (targetArea.contains (mousePos))
  62858. {
  62859. // if you click on the area that originally popped-up the callout, you expect it
  62860. // to get rid of the box, but deleting the box here allows the click to pass through and
  62861. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62862. postCommandMessage (callOutBoxDismissCommandId);
  62863. }
  62864. else
  62865. {
  62866. exitModalState (0);
  62867. setVisible (false);
  62868. }
  62869. }
  62870. void CallOutBox::handleCommandMessage (int commandId)
  62871. {
  62872. Component::handleCommandMessage (commandId);
  62873. if (commandId == callOutBoxDismissCommandId)
  62874. {
  62875. exitModalState (0);
  62876. setVisible (false);
  62877. }
  62878. }
  62879. bool CallOutBox::keyPressed (const KeyPress& key)
  62880. {
  62881. if (key.isKeyCode (KeyPress::escapeKey))
  62882. {
  62883. inputAttemptWhenModal();
  62884. return true;
  62885. }
  62886. return false;
  62887. }
  62888. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62889. {
  62890. targetArea = newAreaToPointTo;
  62891. availableArea = newAreaToFitIn;
  62892. Rectangle<int> bounds (0, 0,
  62893. content.getWidth() + borderSpace * 2,
  62894. content.getHeight() + borderSpace * 2);
  62895. const int hw = bounds.getWidth() / 2;
  62896. const int hh = bounds.getHeight() / 2;
  62897. const float hwReduced = (float) (hw - borderSpace * 3);
  62898. const float hhReduced = (float) (hh - borderSpace * 3);
  62899. const float arrowIndent = borderSpace - arrowSize;
  62900. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62901. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62902. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62903. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62904. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62905. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62906. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62907. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62908. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62909. float nearest = 1.0e9f;
  62910. for (int i = 0; i < 4; ++i)
  62911. {
  62912. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62913. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62914. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62915. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62916. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62917. distanceFromCentre *= 2.0f;
  62918. if (distanceFromCentre < nearest)
  62919. {
  62920. nearest = distanceFromCentre;
  62921. targetPoint = targets[i];
  62922. bounds.setPosition ((int) (centre.getX() - hw),
  62923. (int) (centre.getY() - hh));
  62924. }
  62925. }
  62926. setBounds (bounds);
  62927. }
  62928. void CallOutBox::refreshPath()
  62929. {
  62930. repaint();
  62931. background = Image::null;
  62932. outline.clear();
  62933. const float gap = 4.5f;
  62934. const float cornerSize = 9.0f;
  62935. const float cornerSize2 = 2.0f * cornerSize;
  62936. const float arrowBaseWidth = arrowSize * 0.7f;
  62937. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62938. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62939. outline.startNewSubPath (left + cornerSize, top);
  62940. if (targetY <= top)
  62941. {
  62942. outline.lineTo (targetX - arrowBaseWidth, top);
  62943. outline.lineTo (targetX, targetY);
  62944. outline.lineTo (targetX + arrowBaseWidth, top);
  62945. }
  62946. outline.lineTo (right - cornerSize, top);
  62947. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62948. if (targetX >= right)
  62949. {
  62950. outline.lineTo (right, targetY - arrowBaseWidth);
  62951. outline.lineTo (targetX, targetY);
  62952. outline.lineTo (right, targetY + arrowBaseWidth);
  62953. }
  62954. outline.lineTo (right, bottom - cornerSize);
  62955. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62956. if (targetY >= bottom)
  62957. {
  62958. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62959. outline.lineTo (targetX, targetY);
  62960. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62961. }
  62962. outline.lineTo (left + cornerSize, bottom);
  62963. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62964. if (targetX <= left)
  62965. {
  62966. outline.lineTo (left, targetY + arrowBaseWidth);
  62967. outline.lineTo (targetX, targetY);
  62968. outline.lineTo (left, targetY - arrowBaseWidth);
  62969. }
  62970. outline.lineTo (left, top + cornerSize);
  62971. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62972. outline.closeSubPath();
  62973. }
  62974. END_JUCE_NAMESPACE
  62975. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62976. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62977. BEGIN_JUCE_NAMESPACE
  62978. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62979. static Array <ComponentPeer*> heavyweightPeers;
  62980. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62981. : component (component_),
  62982. styleFlags (styleFlags_),
  62983. lastPaintTime (0),
  62984. constrainer (0),
  62985. lastDragAndDropCompUnderMouse (0),
  62986. fakeMouseMessageSent (false),
  62987. isWindowMinimised (false)
  62988. {
  62989. heavyweightPeers.add (this);
  62990. }
  62991. ComponentPeer::~ComponentPeer()
  62992. {
  62993. heavyweightPeers.removeValue (this);
  62994. Desktop::getInstance().triggerFocusCallback();
  62995. }
  62996. int ComponentPeer::getNumPeers() throw()
  62997. {
  62998. return heavyweightPeers.size();
  62999. }
  63000. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  63001. {
  63002. return heavyweightPeers [index];
  63003. }
  63004. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  63005. {
  63006. for (int i = heavyweightPeers.size(); --i >= 0;)
  63007. {
  63008. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  63009. if (peer->getComponent() == component)
  63010. return peer;
  63011. }
  63012. return 0;
  63013. }
  63014. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  63015. {
  63016. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  63017. }
  63018. void ComponentPeer::updateCurrentModifiers() throw()
  63019. {
  63020. ModifierKeys::updateCurrentModifiers();
  63021. }
  63022. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  63023. {
  63024. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  63025. jassert (mouse != 0); // not enough sources!
  63026. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  63027. }
  63028. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  63029. {
  63030. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  63031. jassert (mouse != 0); // not enough sources!
  63032. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  63033. }
  63034. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  63035. {
  63036. Graphics g (&contextToPaintTo);
  63037. #if JUCE_ENABLE_REPAINT_DEBUGGING
  63038. g.saveState();
  63039. #endif
  63040. JUCE_TRY
  63041. {
  63042. component->paintEntireComponent (g);
  63043. }
  63044. JUCE_CATCH_EXCEPTION
  63045. #if JUCE_ENABLE_REPAINT_DEBUGGING
  63046. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  63047. // clearly when things are being repainted.
  63048. {
  63049. g.restoreState();
  63050. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  63051. (uint8) Random::getSystemRandom().nextInt (255),
  63052. (uint8) Random::getSystemRandom().nextInt (255),
  63053. (uint8) 0x50));
  63054. }
  63055. #endif
  63056. /** If this fails, it's probably be because your CPU floating-point precision mode has
  63057. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  63058. mess up a lot of the calculations that the library needs to do.
  63059. */
  63060. jassert (roundToInt (10.1f) == 10);
  63061. }
  63062. bool ComponentPeer::handleKeyPress (const int keyCode,
  63063. const juce_wchar textCharacter)
  63064. {
  63065. updateCurrentModifiers();
  63066. Component* target = Component::getCurrentlyFocusedComponent() != 0
  63067. ? Component::getCurrentlyFocusedComponent()
  63068. : component;
  63069. if (target->isCurrentlyBlockedByAnotherModalComponent())
  63070. {
  63071. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  63072. if (currentModalComp != 0)
  63073. target = currentModalComp;
  63074. }
  63075. const KeyPress keyInfo (keyCode,
  63076. ModifierKeys::getCurrentModifiers().getRawFlags()
  63077. & ModifierKeys::allKeyboardModifiers,
  63078. textCharacter);
  63079. bool keyWasUsed = false;
  63080. while (target != 0)
  63081. {
  63082. const Component::SafePointer<Component> deletionChecker (target);
  63083. if (target->keyListeners_ != 0)
  63084. {
  63085. for (int i = target->keyListeners_->size(); --i >= 0;)
  63086. {
  63087. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  63088. if (keyWasUsed || deletionChecker == 0)
  63089. return keyWasUsed;
  63090. i = jmin (i, target->keyListeners_->size());
  63091. }
  63092. }
  63093. keyWasUsed = target->keyPressed (keyInfo);
  63094. if (keyWasUsed || deletionChecker == 0)
  63095. break;
  63096. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  63097. {
  63098. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  63099. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  63100. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  63101. break;
  63102. }
  63103. target = target->parentComponent_;
  63104. }
  63105. return keyWasUsed;
  63106. }
  63107. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  63108. {
  63109. updateCurrentModifiers();
  63110. Component* target = Component::getCurrentlyFocusedComponent() != 0
  63111. ? Component::getCurrentlyFocusedComponent()
  63112. : component;
  63113. if (target->isCurrentlyBlockedByAnotherModalComponent())
  63114. {
  63115. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  63116. if (currentModalComp != 0)
  63117. target = currentModalComp;
  63118. }
  63119. bool keyWasUsed = false;
  63120. while (target != 0)
  63121. {
  63122. const Component::SafePointer<Component> deletionChecker (target);
  63123. keyWasUsed = target->keyStateChanged (isKeyDown);
  63124. if (keyWasUsed || deletionChecker == 0)
  63125. break;
  63126. if (target->keyListeners_ != 0)
  63127. {
  63128. for (int i = target->keyListeners_->size(); --i >= 0;)
  63129. {
  63130. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  63131. if (keyWasUsed || deletionChecker == 0)
  63132. return keyWasUsed;
  63133. i = jmin (i, target->keyListeners_->size());
  63134. }
  63135. }
  63136. target = target->parentComponent_;
  63137. }
  63138. return keyWasUsed;
  63139. }
  63140. void ComponentPeer::handleModifierKeysChange()
  63141. {
  63142. updateCurrentModifiers();
  63143. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63144. if (target == 0)
  63145. target = Component::getCurrentlyFocusedComponent();
  63146. if (target == 0)
  63147. target = component;
  63148. if (target != 0)
  63149. target->internalModifierKeysChanged();
  63150. }
  63151. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  63152. {
  63153. Component* const c = Component::getCurrentlyFocusedComponent();
  63154. if (component->isParentOf (c))
  63155. {
  63156. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  63157. if (ti != 0 && ti->isTextInputActive())
  63158. return ti;
  63159. }
  63160. return 0;
  63161. }
  63162. void ComponentPeer::handleBroughtToFront()
  63163. {
  63164. updateCurrentModifiers();
  63165. if (component != 0)
  63166. component->internalBroughtToFront();
  63167. }
  63168. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  63169. {
  63170. constrainer = newConstrainer;
  63171. }
  63172. void ComponentPeer::handleMovedOrResized()
  63173. {
  63174. jassert (component->isValidComponent());
  63175. updateCurrentModifiers();
  63176. const bool nowMinimised = isMinimised();
  63177. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  63178. {
  63179. const Component::SafePointer<Component> deletionChecker (component);
  63180. const Rectangle<int> newBounds (getBounds());
  63181. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  63182. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  63183. if (wasMoved || wasResized)
  63184. {
  63185. component->bounds_ = newBounds;
  63186. if (wasResized)
  63187. component->repaint();
  63188. component->sendMovedResizedMessages (wasMoved, wasResized);
  63189. if (deletionChecker == 0)
  63190. return;
  63191. }
  63192. }
  63193. if (isWindowMinimised != nowMinimised)
  63194. {
  63195. isWindowMinimised = nowMinimised;
  63196. component->minimisationStateChanged (nowMinimised);
  63197. component->sendVisibilityChangeMessage();
  63198. }
  63199. if (! isFullScreen())
  63200. lastNonFullscreenBounds = component->getBounds();
  63201. }
  63202. void ComponentPeer::handleFocusGain()
  63203. {
  63204. updateCurrentModifiers();
  63205. if (component->isParentOf (lastFocusedComponent))
  63206. {
  63207. Component::currentlyFocusedComponent = lastFocusedComponent;
  63208. Desktop::getInstance().triggerFocusCallback();
  63209. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  63210. }
  63211. else
  63212. {
  63213. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  63214. component->grabKeyboardFocus();
  63215. else
  63216. Component::bringModalComponentToFront();
  63217. }
  63218. }
  63219. void ComponentPeer::handleFocusLoss()
  63220. {
  63221. updateCurrentModifiers();
  63222. if (component->hasKeyboardFocus (true))
  63223. {
  63224. lastFocusedComponent = Component::currentlyFocusedComponent;
  63225. if (lastFocusedComponent != 0)
  63226. {
  63227. Component::currentlyFocusedComponent = 0;
  63228. Desktop::getInstance().triggerFocusCallback();
  63229. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  63230. }
  63231. }
  63232. }
  63233. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  63234. {
  63235. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  63236. ? static_cast <Component*> (lastFocusedComponent)
  63237. : component;
  63238. }
  63239. void ComponentPeer::handleScreenSizeChange()
  63240. {
  63241. updateCurrentModifiers();
  63242. component->parentSizeChanged();
  63243. handleMovedOrResized();
  63244. }
  63245. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  63246. {
  63247. lastNonFullscreenBounds = newBounds;
  63248. }
  63249. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  63250. {
  63251. return lastNonFullscreenBounds;
  63252. }
  63253. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  63254. const StringArray& files,
  63255. FileDragAndDropTarget* const lastOne)
  63256. {
  63257. while (c != 0)
  63258. {
  63259. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  63260. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  63261. return t;
  63262. c = c->getParentComponent();
  63263. }
  63264. return 0;
  63265. }
  63266. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  63267. {
  63268. updateCurrentModifiers();
  63269. FileDragAndDropTarget* lastTarget
  63270. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63271. FileDragAndDropTarget* newTarget = 0;
  63272. Component* const compUnderMouse = component->getComponentAt (position);
  63273. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  63274. {
  63275. lastDragAndDropCompUnderMouse = compUnderMouse;
  63276. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  63277. if (newTarget != lastTarget)
  63278. {
  63279. if (lastTarget != 0)
  63280. lastTarget->fileDragExit (files);
  63281. dragAndDropTargetComponent = 0;
  63282. if (newTarget != 0)
  63283. {
  63284. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  63285. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  63286. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  63287. }
  63288. }
  63289. }
  63290. else
  63291. {
  63292. newTarget = lastTarget;
  63293. }
  63294. if (newTarget != 0)
  63295. {
  63296. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  63297. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63298. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  63299. }
  63300. }
  63301. void ComponentPeer::handleFileDragExit (const StringArray& files)
  63302. {
  63303. handleFileDragMove (files, Point<int> (-1, -1));
  63304. jassert (dragAndDropTargetComponent == 0);
  63305. lastDragAndDropCompUnderMouse = 0;
  63306. }
  63307. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  63308. {
  63309. handleFileDragMove (files, position);
  63310. if (dragAndDropTargetComponent != 0)
  63311. {
  63312. FileDragAndDropTarget* const target
  63313. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63314. dragAndDropTargetComponent = 0;
  63315. lastDragAndDropCompUnderMouse = 0;
  63316. if (target != 0)
  63317. {
  63318. Component* const targetComp = dynamic_cast <Component*> (target);
  63319. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63320. {
  63321. targetComp->internalModalInputAttempt();
  63322. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63323. return;
  63324. }
  63325. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63326. target->filesDropped (files, pos.getX(), pos.getY());
  63327. }
  63328. }
  63329. }
  63330. void ComponentPeer::handleUserClosingWindow()
  63331. {
  63332. updateCurrentModifiers();
  63333. component->userTriedToCloseWindow();
  63334. }
  63335. void ComponentPeer::bringModalComponentToFront()
  63336. {
  63337. Component::bringModalComponentToFront();
  63338. }
  63339. void ComponentPeer::clearMaskedRegion()
  63340. {
  63341. maskedRegion.clear();
  63342. }
  63343. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  63344. {
  63345. maskedRegion.add (x, y, w, h);
  63346. }
  63347. const StringArray ComponentPeer::getAvailableRenderingEngines()
  63348. {
  63349. StringArray s;
  63350. s.add ("Software Renderer");
  63351. return s;
  63352. }
  63353. int ComponentPeer::getCurrentRenderingEngine() throw()
  63354. {
  63355. return 0;
  63356. }
  63357. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  63358. {
  63359. }
  63360. END_JUCE_NAMESPACE
  63361. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  63362. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  63363. BEGIN_JUCE_NAMESPACE
  63364. DialogWindow::DialogWindow (const String& name,
  63365. const Colour& backgroundColour_,
  63366. const bool escapeKeyTriggersCloseButton_,
  63367. const bool addToDesktop_)
  63368. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  63369. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  63370. {
  63371. }
  63372. DialogWindow::~DialogWindow()
  63373. {
  63374. }
  63375. void DialogWindow::resized()
  63376. {
  63377. DocumentWindow::resized();
  63378. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  63379. if (escapeKeyTriggersCloseButton
  63380. && getCloseButton() != 0
  63381. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63382. {
  63383. getCloseButton()->addShortcut (esc);
  63384. }
  63385. }
  63386. class TempDialogWindow : public DialogWindow
  63387. {
  63388. public:
  63389. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63390. : DialogWindow (title, colour, escapeCloses, true)
  63391. {
  63392. if (! JUCEApplication::isStandaloneApp())
  63393. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63394. }
  63395. ~TempDialogWindow()
  63396. {
  63397. }
  63398. void closeButtonPressed()
  63399. {
  63400. setVisible (false);
  63401. }
  63402. private:
  63403. TempDialogWindow (const TempDialogWindow&);
  63404. TempDialogWindow& operator= (const TempDialogWindow&);
  63405. };
  63406. int DialogWindow::showModalDialog (const String& dialogTitle,
  63407. Component* contentComponent,
  63408. Component* componentToCentreAround,
  63409. const Colour& colour,
  63410. const bool escapeKeyTriggersCloseButton,
  63411. const bool shouldBeResizable,
  63412. const bool useBottomRightCornerResizer)
  63413. {
  63414. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63415. dw.setContentComponent (contentComponent, true, true);
  63416. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63417. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63418. const int result = dw.runModalLoop();
  63419. dw.setContentComponent (0, false);
  63420. return result;
  63421. }
  63422. END_JUCE_NAMESPACE
  63423. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63424. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63425. BEGIN_JUCE_NAMESPACE
  63426. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63427. {
  63428. public:
  63429. ButtonListenerProxy (DocumentWindow& owner_)
  63430. : owner (owner_)
  63431. {
  63432. }
  63433. void buttonClicked (Button* button)
  63434. {
  63435. if (button == owner.getMinimiseButton())
  63436. owner.minimiseButtonPressed();
  63437. else if (button == owner.getMaximiseButton())
  63438. owner.maximiseButtonPressed();
  63439. else if (button == owner.getCloseButton())
  63440. owner.closeButtonPressed();
  63441. }
  63442. juce_UseDebuggingNewOperator
  63443. private:
  63444. DocumentWindow& owner;
  63445. ButtonListenerProxy (const ButtonListenerProxy&);
  63446. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63447. };
  63448. DocumentWindow::DocumentWindow (const String& title,
  63449. const Colour& backgroundColour,
  63450. const int requiredButtons_,
  63451. const bool addToDesktop_)
  63452. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63453. titleBarHeight (26),
  63454. menuBarHeight (24),
  63455. requiredButtons (requiredButtons_),
  63456. #if JUCE_MAC
  63457. positionTitleBarButtonsOnLeft (true),
  63458. #else
  63459. positionTitleBarButtonsOnLeft (false),
  63460. #endif
  63461. drawTitleTextCentred (true),
  63462. menuBarModel (0)
  63463. {
  63464. setResizeLimits (128, 128, 32768, 32768);
  63465. lookAndFeelChanged();
  63466. }
  63467. DocumentWindow::~DocumentWindow()
  63468. {
  63469. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63470. titleBarButtons[i] = 0;
  63471. menuBar = 0;
  63472. }
  63473. void DocumentWindow::repaintTitleBar()
  63474. {
  63475. repaint (getTitleBarArea());
  63476. }
  63477. void DocumentWindow::setName (const String& newName)
  63478. {
  63479. if (newName != getName())
  63480. {
  63481. Component::setName (newName);
  63482. repaintTitleBar();
  63483. }
  63484. }
  63485. void DocumentWindow::setIcon (const Image& imageToUse)
  63486. {
  63487. titleBarIcon = imageToUse;
  63488. repaintTitleBar();
  63489. }
  63490. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63491. {
  63492. titleBarHeight = newHeight;
  63493. resized();
  63494. repaintTitleBar();
  63495. }
  63496. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63497. const bool positionTitleBarButtonsOnLeft_)
  63498. {
  63499. requiredButtons = requiredButtons_;
  63500. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63501. lookAndFeelChanged();
  63502. }
  63503. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63504. {
  63505. drawTitleTextCentred = textShouldBeCentred;
  63506. repaintTitleBar();
  63507. }
  63508. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63509. const int menuBarHeight_)
  63510. {
  63511. if (menuBarModel != menuBarModel_)
  63512. {
  63513. menuBar = 0;
  63514. menuBarModel = menuBarModel_;
  63515. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63516. : getLookAndFeel().getDefaultMenuBarHeight();
  63517. if (menuBarModel != 0)
  63518. {
  63519. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63520. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63521. menuBar->setEnabled (isActiveWindow());
  63522. }
  63523. resized();
  63524. }
  63525. }
  63526. void DocumentWindow::closeButtonPressed()
  63527. {
  63528. /* If you've got a close button, you have to override this method to get
  63529. rid of your window!
  63530. If the window is just a pop-up, you should override this method and make
  63531. it delete the window in whatever way is appropriate for your app. E.g. you
  63532. might just want to call "delete this".
  63533. If your app is centred around this window such that the whole app should quit when
  63534. the window is closed, then you will probably want to use this method as an opportunity
  63535. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63536. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63537. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63538. or closing it via the taskbar icon on Windows).
  63539. */
  63540. jassertfalse;
  63541. }
  63542. void DocumentWindow::minimiseButtonPressed()
  63543. {
  63544. setMinimised (true);
  63545. }
  63546. void DocumentWindow::maximiseButtonPressed()
  63547. {
  63548. setFullScreen (! isFullScreen());
  63549. }
  63550. void DocumentWindow::paint (Graphics& g)
  63551. {
  63552. ResizableWindow::paint (g);
  63553. if (resizableBorder == 0)
  63554. {
  63555. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63556. const BorderSize border (getBorderThickness());
  63557. g.fillRect (0, 0, getWidth(), border.getTop());
  63558. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63559. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63560. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63561. }
  63562. const Rectangle<int> titleBarArea (getTitleBarArea());
  63563. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63564. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63565. int titleSpaceX1 = 6;
  63566. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63567. for (int i = 0; i < 3; ++i)
  63568. {
  63569. if (titleBarButtons[i] != 0)
  63570. {
  63571. if (positionTitleBarButtonsOnLeft)
  63572. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63573. else
  63574. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63575. }
  63576. }
  63577. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63578. titleBarArea.getWidth(),
  63579. titleBarArea.getHeight(),
  63580. titleSpaceX1,
  63581. jmax (1, titleSpaceX2 - titleSpaceX1),
  63582. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63583. ! drawTitleTextCentred);
  63584. }
  63585. void DocumentWindow::resized()
  63586. {
  63587. ResizableWindow::resized();
  63588. if (titleBarButtons[1] != 0)
  63589. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63590. const Rectangle<int> titleBarArea (getTitleBarArea());
  63591. getLookAndFeel()
  63592. .positionDocumentWindowButtons (*this,
  63593. titleBarArea.getX(), titleBarArea.getY(),
  63594. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63595. titleBarButtons[0],
  63596. titleBarButtons[1],
  63597. titleBarButtons[2],
  63598. positionTitleBarButtonsOnLeft);
  63599. if (menuBar != 0)
  63600. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63601. titleBarArea.getWidth(), menuBarHeight);
  63602. }
  63603. const BorderSize DocumentWindow::getBorderThickness()
  63604. {
  63605. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63606. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63607. }
  63608. const BorderSize DocumentWindow::getContentComponentBorder()
  63609. {
  63610. BorderSize border (getBorderThickness());
  63611. border.setTop (border.getTop()
  63612. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63613. + (menuBar != 0 ? menuBarHeight : 0));
  63614. return border;
  63615. }
  63616. int DocumentWindow::getTitleBarHeight() const
  63617. {
  63618. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63619. }
  63620. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63621. {
  63622. const BorderSize border (getBorderThickness());
  63623. return Rectangle<int> (border.getLeft(), border.getTop(),
  63624. getWidth() - border.getLeftAndRight(),
  63625. getTitleBarHeight());
  63626. }
  63627. Button* DocumentWindow::getCloseButton() const throw()
  63628. {
  63629. return titleBarButtons[2];
  63630. }
  63631. Button* DocumentWindow::getMinimiseButton() const throw()
  63632. {
  63633. return titleBarButtons[0];
  63634. }
  63635. Button* DocumentWindow::getMaximiseButton() const throw()
  63636. {
  63637. return titleBarButtons[1];
  63638. }
  63639. int DocumentWindow::getDesktopWindowStyleFlags() const
  63640. {
  63641. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63642. if ((requiredButtons & minimiseButton) != 0)
  63643. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63644. if ((requiredButtons & maximiseButton) != 0)
  63645. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63646. if ((requiredButtons & closeButton) != 0)
  63647. styleFlags |= ComponentPeer::windowHasCloseButton;
  63648. return styleFlags;
  63649. }
  63650. void DocumentWindow::lookAndFeelChanged()
  63651. {
  63652. int i;
  63653. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63654. titleBarButtons[i] = 0;
  63655. if (! isUsingNativeTitleBar())
  63656. {
  63657. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63658. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63659. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63660. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63661. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63662. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63663. for (i = 0; i < 3; ++i)
  63664. {
  63665. if (titleBarButtons[i] != 0)
  63666. {
  63667. if (buttonListener == 0)
  63668. buttonListener = new ButtonListenerProxy (*this);
  63669. titleBarButtons[i]->addButtonListener (buttonListener);
  63670. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63671. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63672. Component::addAndMakeVisible (titleBarButtons[i]);
  63673. }
  63674. }
  63675. if (getCloseButton() != 0)
  63676. {
  63677. #if JUCE_MAC
  63678. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63679. #else
  63680. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63681. #endif
  63682. }
  63683. }
  63684. activeWindowStatusChanged();
  63685. ResizableWindow::lookAndFeelChanged();
  63686. }
  63687. void DocumentWindow::parentHierarchyChanged()
  63688. {
  63689. lookAndFeelChanged();
  63690. }
  63691. void DocumentWindow::activeWindowStatusChanged()
  63692. {
  63693. ResizableWindow::activeWindowStatusChanged();
  63694. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63695. if (titleBarButtons[i] != 0)
  63696. titleBarButtons[i]->setEnabled (isActiveWindow());
  63697. if (menuBar != 0)
  63698. menuBar->setEnabled (isActiveWindow());
  63699. }
  63700. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63701. {
  63702. if (getTitleBarArea().contains (e.x, e.y)
  63703. && getMaximiseButton() != 0)
  63704. {
  63705. getMaximiseButton()->triggerClick();
  63706. }
  63707. }
  63708. void DocumentWindow::userTriedToCloseWindow()
  63709. {
  63710. closeButtonPressed();
  63711. }
  63712. END_JUCE_NAMESPACE
  63713. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63714. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63715. BEGIN_JUCE_NAMESPACE
  63716. ResizableWindow::ResizableWindow (const String& name,
  63717. const bool addToDesktop_)
  63718. : TopLevelWindow (name, addToDesktop_),
  63719. resizeToFitContent (false),
  63720. fullscreen (false),
  63721. lastNonFullScreenPos (50, 50, 256, 256),
  63722. constrainer (0)
  63723. #if JUCE_DEBUG
  63724. , hasBeenResized (false)
  63725. #endif
  63726. {
  63727. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63728. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63729. if (addToDesktop_)
  63730. Component::addToDesktop (getDesktopWindowStyleFlags());
  63731. }
  63732. ResizableWindow::ResizableWindow (const String& name,
  63733. const Colour& backgroundColour_,
  63734. const bool addToDesktop_)
  63735. : TopLevelWindow (name, addToDesktop_),
  63736. resizeToFitContent (false),
  63737. fullscreen (false),
  63738. lastNonFullScreenPos (50, 50, 256, 256),
  63739. constrainer (0)
  63740. #if JUCE_DEBUG
  63741. , hasBeenResized (false)
  63742. #endif
  63743. {
  63744. setBackgroundColour (backgroundColour_);
  63745. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63746. if (addToDesktop_)
  63747. Component::addToDesktop (getDesktopWindowStyleFlags());
  63748. }
  63749. ResizableWindow::~ResizableWindow()
  63750. {
  63751. resizableCorner = 0;
  63752. resizableBorder = 0;
  63753. contentComponent.deleteAndZero();
  63754. // have you been adding your own components directly to this window..? tut tut tut.
  63755. // Read the instructions for using a ResizableWindow!
  63756. jassert (getNumChildComponents() == 0);
  63757. }
  63758. int ResizableWindow::getDesktopWindowStyleFlags() const
  63759. {
  63760. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63761. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63762. styleFlags |= ComponentPeer::windowIsResizable;
  63763. return styleFlags;
  63764. }
  63765. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63766. const bool deleteOldOne,
  63767. const bool resizeToFit)
  63768. {
  63769. resizeToFitContent = resizeToFit;
  63770. if (newContentComponent != static_cast <Component*> (contentComponent))
  63771. {
  63772. if (deleteOldOne)
  63773. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63774. // external deletion of the content comp)
  63775. else
  63776. removeChildComponent (contentComponent);
  63777. contentComponent = newContentComponent;
  63778. Component::addAndMakeVisible (contentComponent);
  63779. }
  63780. if (resizeToFit)
  63781. childBoundsChanged (contentComponent);
  63782. resized(); // must always be called to position the new content comp
  63783. }
  63784. void ResizableWindow::setContentComponentSize (int width, int height)
  63785. {
  63786. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63787. const BorderSize border (getContentComponentBorder());
  63788. setSize (width + border.getLeftAndRight(),
  63789. height + border.getTopAndBottom());
  63790. }
  63791. const BorderSize ResizableWindow::getBorderThickness()
  63792. {
  63793. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63794. }
  63795. const BorderSize ResizableWindow::getContentComponentBorder()
  63796. {
  63797. return getBorderThickness();
  63798. }
  63799. void ResizableWindow::moved()
  63800. {
  63801. updateLastPos();
  63802. }
  63803. void ResizableWindow::visibilityChanged()
  63804. {
  63805. TopLevelWindow::visibilityChanged();
  63806. updateLastPos();
  63807. }
  63808. void ResizableWindow::resized()
  63809. {
  63810. if (resizableBorder != 0)
  63811. {
  63812. resizableBorder->setVisible (! isFullScreen());
  63813. resizableBorder->setBorderThickness (getBorderThickness());
  63814. resizableBorder->setSize (getWidth(), getHeight());
  63815. resizableBorder->toBack();
  63816. }
  63817. if (resizableCorner != 0)
  63818. {
  63819. resizableCorner->setVisible (! isFullScreen());
  63820. const int resizerSize = 18;
  63821. resizableCorner->setBounds (getWidth() - resizerSize,
  63822. getHeight() - resizerSize,
  63823. resizerSize, resizerSize);
  63824. }
  63825. if (contentComponent != 0)
  63826. contentComponent->setBoundsInset (getContentComponentBorder());
  63827. updateLastPos();
  63828. #if JUCE_DEBUG
  63829. hasBeenResized = true;
  63830. #endif
  63831. }
  63832. void ResizableWindow::childBoundsChanged (Component* child)
  63833. {
  63834. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63835. {
  63836. // not going to look very good if this component has a zero size..
  63837. jassert (child->getWidth() > 0);
  63838. jassert (child->getHeight() > 0);
  63839. const BorderSize borders (getContentComponentBorder());
  63840. setSize (child->getWidth() + borders.getLeftAndRight(),
  63841. child->getHeight() + borders.getTopAndBottom());
  63842. }
  63843. }
  63844. void ResizableWindow::activeWindowStatusChanged()
  63845. {
  63846. const BorderSize border (getContentComponentBorder());
  63847. Rectangle<int> area (getLocalBounds());
  63848. repaint (area.removeFromTop (border.getTop()));
  63849. repaint (area.removeFromLeft (border.getLeft()));
  63850. repaint (area.removeFromRight (border.getRight()));
  63851. repaint (area.removeFromBottom (border.getBottom()));
  63852. }
  63853. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63854. const bool useBottomRightCornerResizer)
  63855. {
  63856. if (shouldBeResizable)
  63857. {
  63858. if (useBottomRightCornerResizer)
  63859. {
  63860. resizableBorder = 0;
  63861. if (resizableCorner == 0)
  63862. {
  63863. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63864. resizableCorner->setAlwaysOnTop (true);
  63865. }
  63866. }
  63867. else
  63868. {
  63869. resizableCorner = 0;
  63870. if (resizableBorder == 0)
  63871. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63872. }
  63873. }
  63874. else
  63875. {
  63876. resizableCorner = 0;
  63877. resizableBorder = 0;
  63878. }
  63879. if (isUsingNativeTitleBar())
  63880. recreateDesktopWindow();
  63881. childBoundsChanged (contentComponent);
  63882. resized();
  63883. }
  63884. bool ResizableWindow::isResizable() const throw()
  63885. {
  63886. return resizableCorner != 0
  63887. || resizableBorder != 0;
  63888. }
  63889. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63890. const int newMinimumHeight,
  63891. const int newMaximumWidth,
  63892. const int newMaximumHeight) throw()
  63893. {
  63894. // if you've set up a custom constrainer then these settings won't have any effect..
  63895. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63896. if (constrainer == 0)
  63897. setConstrainer (&defaultConstrainer);
  63898. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63899. newMaximumWidth, newMaximumHeight);
  63900. setBoundsConstrained (getBounds());
  63901. }
  63902. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63903. {
  63904. if (constrainer != newConstrainer)
  63905. {
  63906. constrainer = newConstrainer;
  63907. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63908. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63909. resizableCorner = 0;
  63910. resizableBorder = 0;
  63911. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63912. ComponentPeer* const peer = getPeer();
  63913. if (peer != 0)
  63914. peer->setConstrainer (newConstrainer);
  63915. }
  63916. }
  63917. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63918. {
  63919. if (constrainer != 0)
  63920. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63921. else
  63922. setBounds (bounds);
  63923. }
  63924. void ResizableWindow::paint (Graphics& g)
  63925. {
  63926. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63927. getBorderThickness(), *this);
  63928. if (! isFullScreen())
  63929. {
  63930. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63931. getBorderThickness(), *this);
  63932. }
  63933. #if JUCE_DEBUG
  63934. /* If this fails, then you've probably written a subclass with a resized()
  63935. callback but forgotten to make it call its parent class's resized() method.
  63936. It's important when you override methods like resized(), moved(),
  63937. etc., that you make sure the base class methods also get called.
  63938. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63939. because your content should all be inside the content component - and it's the
  63940. content component's resized() method that you should be using to do your
  63941. layout.
  63942. */
  63943. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63944. #endif
  63945. }
  63946. void ResizableWindow::lookAndFeelChanged()
  63947. {
  63948. resized();
  63949. if (isOnDesktop())
  63950. {
  63951. Component::addToDesktop (getDesktopWindowStyleFlags());
  63952. ComponentPeer* const peer = getPeer();
  63953. if (peer != 0)
  63954. peer->setConstrainer (constrainer);
  63955. }
  63956. }
  63957. const Colour ResizableWindow::getBackgroundColour() const throw()
  63958. {
  63959. return findColour (backgroundColourId, false);
  63960. }
  63961. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63962. {
  63963. Colour backgroundColour (newColour);
  63964. if (! Desktop::canUseSemiTransparentWindows())
  63965. backgroundColour = newColour.withAlpha (1.0f);
  63966. setColour (backgroundColourId, backgroundColour);
  63967. setOpaque (backgroundColour.isOpaque());
  63968. repaint();
  63969. }
  63970. bool ResizableWindow::isFullScreen() const
  63971. {
  63972. if (isOnDesktop())
  63973. {
  63974. ComponentPeer* const peer = getPeer();
  63975. return peer != 0 && peer->isFullScreen();
  63976. }
  63977. return fullscreen;
  63978. }
  63979. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63980. {
  63981. if (shouldBeFullScreen != isFullScreen())
  63982. {
  63983. updateLastPos();
  63984. fullscreen = shouldBeFullScreen;
  63985. if (isOnDesktop())
  63986. {
  63987. ComponentPeer* const peer = getPeer();
  63988. if (peer != 0)
  63989. {
  63990. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63991. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63992. peer->setFullScreen (shouldBeFullScreen);
  63993. if (! shouldBeFullScreen)
  63994. setBounds (lastPos);
  63995. }
  63996. else
  63997. {
  63998. jassertfalse;
  63999. }
  64000. }
  64001. else
  64002. {
  64003. if (shouldBeFullScreen)
  64004. setBounds (0, 0, getParentWidth(), getParentHeight());
  64005. else
  64006. setBounds (lastNonFullScreenPos);
  64007. }
  64008. resized();
  64009. }
  64010. }
  64011. bool ResizableWindow::isMinimised() const
  64012. {
  64013. ComponentPeer* const peer = getPeer();
  64014. return (peer != 0) && peer->isMinimised();
  64015. }
  64016. void ResizableWindow::setMinimised (const bool shouldMinimise)
  64017. {
  64018. if (shouldMinimise != isMinimised())
  64019. {
  64020. ComponentPeer* const peer = getPeer();
  64021. if (peer != 0)
  64022. {
  64023. updateLastPos();
  64024. peer->setMinimised (shouldMinimise);
  64025. }
  64026. else
  64027. {
  64028. jassertfalse;
  64029. }
  64030. }
  64031. }
  64032. void ResizableWindow::updateLastPos()
  64033. {
  64034. if (isShowing() && ! (isFullScreen() || isMinimised()))
  64035. {
  64036. lastNonFullScreenPos = getBounds();
  64037. }
  64038. }
  64039. void ResizableWindow::parentSizeChanged()
  64040. {
  64041. if (isFullScreen() && getParentComponent() != 0)
  64042. {
  64043. setBounds (0, 0, getParentWidth(), getParentHeight());
  64044. }
  64045. }
  64046. const String ResizableWindow::getWindowStateAsString()
  64047. {
  64048. updateLastPos();
  64049. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  64050. }
  64051. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  64052. {
  64053. StringArray tokens;
  64054. tokens.addTokens (s, false);
  64055. tokens.removeEmptyStrings();
  64056. tokens.trim();
  64057. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  64058. const int firstCoord = fs ? 1 : 0;
  64059. if (tokens.size() != firstCoord + 4)
  64060. return false;
  64061. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  64062. tokens[firstCoord + 1].getIntValue(),
  64063. tokens[firstCoord + 2].getIntValue(),
  64064. tokens[firstCoord + 3].getIntValue());
  64065. if (newPos.isEmpty())
  64066. return false;
  64067. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  64068. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  64069. if (peer != 0)
  64070. peer->getFrameSize().addTo (newPos);
  64071. if (! screen.contains (newPos))
  64072. {
  64073. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  64074. jmin (newPos.getHeight(), screen.getHeight()));
  64075. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  64076. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  64077. }
  64078. if (peer != 0)
  64079. {
  64080. peer->getFrameSize().subtractFrom (newPos);
  64081. peer->setNonFullScreenBounds (newPos);
  64082. }
  64083. lastNonFullScreenPos = newPos;
  64084. setFullScreen (fs);
  64085. if (! fs)
  64086. setBoundsConstrained (newPos);
  64087. return true;
  64088. }
  64089. void ResizableWindow::mouseDown (const MouseEvent&)
  64090. {
  64091. if (! isFullScreen())
  64092. dragger.startDraggingComponent (this, constrainer);
  64093. }
  64094. void ResizableWindow::mouseDrag (const MouseEvent& e)
  64095. {
  64096. if (! isFullScreen())
  64097. dragger.dragComponent (this, e);
  64098. }
  64099. #if JUCE_DEBUG
  64100. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  64101. {
  64102. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  64103. manages its child components automatically, and if you add your own it'll cause
  64104. trouble. Instead, use setContentComponent() to give it a component which
  64105. will be automatically resized and kept in the right place - then you can add
  64106. subcomponents to the content comp. See the notes for the ResizableWindow class
  64107. for more info.
  64108. If you really know what you're doing and want to avoid this assertion, just call
  64109. Component::addChildComponent directly.
  64110. */
  64111. jassertfalse;
  64112. Component::addChildComponent (child, zOrder);
  64113. }
  64114. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  64115. {
  64116. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  64117. manages its child components automatically, and if you add your own it'll cause
  64118. trouble. Instead, use setContentComponent() to give it a component which
  64119. will be automatically resized and kept in the right place - then you can add
  64120. subcomponents to the content comp. See the notes for the ResizableWindow class
  64121. for more info.
  64122. If you really know what you're doing and want to avoid this assertion, just call
  64123. Component::addAndMakeVisible directly.
  64124. */
  64125. jassertfalse;
  64126. Component::addAndMakeVisible (child, zOrder);
  64127. }
  64128. #endif
  64129. END_JUCE_NAMESPACE
  64130. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  64131. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  64132. BEGIN_JUCE_NAMESPACE
  64133. SplashScreen::SplashScreen()
  64134. {
  64135. setOpaque (true);
  64136. }
  64137. SplashScreen::~SplashScreen()
  64138. {
  64139. }
  64140. void SplashScreen::show (const String& title,
  64141. const Image& backgroundImage_,
  64142. const int minimumTimeToDisplayFor,
  64143. const bool useDropShadow,
  64144. const bool removeOnMouseClick)
  64145. {
  64146. backgroundImage = backgroundImage_;
  64147. jassert (backgroundImage_.isValid());
  64148. if (backgroundImage_.isValid())
  64149. {
  64150. setOpaque (! backgroundImage_.hasAlphaChannel());
  64151. show (title,
  64152. backgroundImage_.getWidth(),
  64153. backgroundImage_.getHeight(),
  64154. minimumTimeToDisplayFor,
  64155. useDropShadow,
  64156. removeOnMouseClick);
  64157. }
  64158. }
  64159. void SplashScreen::show (const String& title,
  64160. const int width,
  64161. const int height,
  64162. const int minimumTimeToDisplayFor,
  64163. const bool useDropShadow,
  64164. const bool removeOnMouseClick)
  64165. {
  64166. setName (title);
  64167. setAlwaysOnTop (true);
  64168. setVisible (true);
  64169. centreWithSize (width, height);
  64170. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  64171. toFront (false);
  64172. MessageManager::getInstance()->runDispatchLoopUntil (300);
  64173. repaint();
  64174. originalClickCounter = removeOnMouseClick
  64175. ? Desktop::getMouseButtonClickCounter()
  64176. : std::numeric_limits<int>::max();
  64177. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  64178. startTimer (50);
  64179. }
  64180. void SplashScreen::paint (Graphics& g)
  64181. {
  64182. g.setOpacity (1.0f);
  64183. g.drawImage (backgroundImage,
  64184. 0, 0, getWidth(), getHeight(),
  64185. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  64186. }
  64187. void SplashScreen::timerCallback()
  64188. {
  64189. if (Time::getCurrentTime() > earliestTimeToDelete
  64190. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  64191. {
  64192. delete this;
  64193. }
  64194. }
  64195. END_JUCE_NAMESPACE
  64196. /*** End of inlined file: juce_SplashScreen.cpp ***/
  64197. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  64198. BEGIN_JUCE_NAMESPACE
  64199. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  64200. const bool hasProgressBar,
  64201. const bool hasCancelButton,
  64202. const int timeOutMsWhenCancelling_,
  64203. const String& cancelButtonText)
  64204. : Thread ("Juce Progress Window"),
  64205. progress (0.0),
  64206. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  64207. {
  64208. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  64209. .createAlertWindow (title, String::empty, cancelButtonText,
  64210. String::empty, String::empty,
  64211. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  64212. if (hasProgressBar)
  64213. alertWindow->addProgressBarComponent (progress);
  64214. }
  64215. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  64216. {
  64217. stopThread (timeOutMsWhenCancelling);
  64218. }
  64219. bool ThreadWithProgressWindow::runThread (const int priority)
  64220. {
  64221. startThread (priority);
  64222. startTimer (100);
  64223. {
  64224. const ScopedLock sl (messageLock);
  64225. alertWindow->setMessage (message);
  64226. }
  64227. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  64228. stopThread (timeOutMsWhenCancelling);
  64229. alertWindow->setVisible (false);
  64230. return finishedNaturally;
  64231. }
  64232. void ThreadWithProgressWindow::setProgress (const double newProgress)
  64233. {
  64234. progress = newProgress;
  64235. }
  64236. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  64237. {
  64238. const ScopedLock sl (messageLock);
  64239. message = newStatusMessage;
  64240. }
  64241. void ThreadWithProgressWindow::timerCallback()
  64242. {
  64243. if (! isThreadRunning())
  64244. {
  64245. // thread has finished normally..
  64246. alertWindow->exitModalState (1);
  64247. alertWindow->setVisible (false);
  64248. }
  64249. else
  64250. {
  64251. const ScopedLock sl (messageLock);
  64252. alertWindow->setMessage (message);
  64253. }
  64254. }
  64255. END_JUCE_NAMESPACE
  64256. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  64257. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  64258. BEGIN_JUCE_NAMESPACE
  64259. TooltipWindow::TooltipWindow (Component* const parentComponent,
  64260. const int millisecondsBeforeTipAppears_)
  64261. : Component ("tooltip"),
  64262. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  64263. mouseClicks (0),
  64264. lastHideTime (0),
  64265. lastComponentUnderMouse (0),
  64266. changedCompsSinceShown (true)
  64267. {
  64268. if (Desktop::getInstance().getMainMouseSource().canHover())
  64269. startTimer (123);
  64270. setAlwaysOnTop (true);
  64271. setOpaque (true);
  64272. if (parentComponent != 0)
  64273. parentComponent->addChildComponent (this);
  64274. }
  64275. TooltipWindow::~TooltipWindow()
  64276. {
  64277. hide();
  64278. }
  64279. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  64280. {
  64281. millisecondsBeforeTipAppears = newTimeMs;
  64282. }
  64283. void TooltipWindow::paint (Graphics& g)
  64284. {
  64285. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  64286. }
  64287. void TooltipWindow::mouseEnter (const MouseEvent&)
  64288. {
  64289. hide();
  64290. }
  64291. void TooltipWindow::showFor (const String& tip)
  64292. {
  64293. jassert (tip.isNotEmpty());
  64294. if (tipShowing != tip)
  64295. repaint();
  64296. tipShowing = tip;
  64297. Point<int> mousePos (Desktop::getMousePosition());
  64298. if (getParentComponent() != 0)
  64299. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  64300. int x, y, w, h;
  64301. getLookAndFeel().getTooltipSize (tip, w, h);
  64302. if (mousePos.getX() > getParentWidth() / 2)
  64303. x = mousePos.getX() - (w + 12);
  64304. else
  64305. x = mousePos.getX() + 24;
  64306. if (mousePos.getY() > getParentHeight() / 2)
  64307. y = mousePos.getY() - (h + 6);
  64308. else
  64309. y = mousePos.getY() + 6;
  64310. setBounds (x, y, w, h);
  64311. setVisible (true);
  64312. if (getParentComponent() == 0)
  64313. {
  64314. addToDesktop (ComponentPeer::windowHasDropShadow
  64315. | ComponentPeer::windowIsTemporary
  64316. | ComponentPeer::windowIgnoresKeyPresses);
  64317. }
  64318. toFront (false);
  64319. }
  64320. const String TooltipWindow::getTipFor (Component* const c)
  64321. {
  64322. if (c != 0
  64323. && Process::isForegroundProcess()
  64324. && ! Component::isMouseButtonDownAnywhere())
  64325. {
  64326. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  64327. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  64328. return ttc->getTooltip();
  64329. }
  64330. return String::empty;
  64331. }
  64332. void TooltipWindow::hide()
  64333. {
  64334. tipShowing = String::empty;
  64335. removeFromDesktop();
  64336. setVisible (false);
  64337. }
  64338. void TooltipWindow::timerCallback()
  64339. {
  64340. const unsigned int now = Time::getApproximateMillisecondCounter();
  64341. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  64342. const String newTip (getTipFor (newComp));
  64343. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  64344. lastComponentUnderMouse = newComp;
  64345. lastTipUnderMouse = newTip;
  64346. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  64347. const bool mouseWasClicked = clickCount > mouseClicks;
  64348. mouseClicks = clickCount;
  64349. const Point<int> mousePos (Desktop::getMousePosition());
  64350. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  64351. lastMousePos = mousePos;
  64352. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  64353. lastCompChangeTime = now;
  64354. if (isVisible() || now < lastHideTime + 500)
  64355. {
  64356. // if a tip is currently visible (or has just disappeared), update to a new one
  64357. // immediately if needed..
  64358. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  64359. {
  64360. if (isVisible())
  64361. {
  64362. lastHideTime = now;
  64363. hide();
  64364. }
  64365. }
  64366. else if (tipChanged)
  64367. {
  64368. showFor (newTip);
  64369. }
  64370. }
  64371. else
  64372. {
  64373. // if there isn't currently a tip, but one is needed, only let it
  64374. // appear after a timeout..
  64375. if (newTip.isNotEmpty()
  64376. && newTip != tipShowing
  64377. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64378. {
  64379. showFor (newTip);
  64380. }
  64381. }
  64382. }
  64383. END_JUCE_NAMESPACE
  64384. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64385. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64386. BEGIN_JUCE_NAMESPACE
  64387. /** Keeps track of the active top level window.
  64388. */
  64389. class TopLevelWindowManager : public Timer,
  64390. public DeletedAtShutdown
  64391. {
  64392. public:
  64393. TopLevelWindowManager()
  64394. : currentActive (0)
  64395. {
  64396. }
  64397. ~TopLevelWindowManager()
  64398. {
  64399. clearSingletonInstance();
  64400. }
  64401. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64402. void timerCallback()
  64403. {
  64404. startTimer (jmin (1731, getTimerInterval() * 2));
  64405. TopLevelWindow* active = 0;
  64406. if (Process::isForegroundProcess())
  64407. {
  64408. active = currentActive;
  64409. Component* const c = Component::getCurrentlyFocusedComponent();
  64410. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64411. if (tlw == 0 && c != 0)
  64412. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64413. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64414. if (tlw != 0)
  64415. active = tlw;
  64416. }
  64417. if (active != currentActive)
  64418. {
  64419. currentActive = active;
  64420. for (int i = windows.size(); --i >= 0;)
  64421. {
  64422. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64423. tlw->setWindowActive (isWindowActive (tlw));
  64424. i = jmin (i, windows.size() - 1);
  64425. }
  64426. Desktop::getInstance().triggerFocusCallback();
  64427. }
  64428. }
  64429. bool addWindow (TopLevelWindow* const w)
  64430. {
  64431. windows.add (w);
  64432. startTimer (10);
  64433. return isWindowActive (w);
  64434. }
  64435. void removeWindow (TopLevelWindow* const w)
  64436. {
  64437. startTimer (10);
  64438. if (currentActive == w)
  64439. currentActive = 0;
  64440. windows.removeValue (w);
  64441. if (windows.size() == 0)
  64442. deleteInstance();
  64443. }
  64444. Array <TopLevelWindow*> windows;
  64445. private:
  64446. TopLevelWindow* currentActive;
  64447. bool isWindowActive (TopLevelWindow* const tlw) const
  64448. {
  64449. return (tlw == currentActive
  64450. || tlw->isParentOf (currentActive)
  64451. || tlw->hasKeyboardFocus (true))
  64452. && tlw->isShowing();
  64453. }
  64454. TopLevelWindowManager (const TopLevelWindowManager&);
  64455. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64456. };
  64457. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64458. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64459. {
  64460. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64461. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64462. }
  64463. TopLevelWindow::TopLevelWindow (const String& name,
  64464. const bool addToDesktop_)
  64465. : Component (name),
  64466. useDropShadow (true),
  64467. useNativeTitleBar (false),
  64468. windowIsActive_ (false)
  64469. {
  64470. setOpaque (true);
  64471. if (addToDesktop_)
  64472. Component::addToDesktop (getDesktopWindowStyleFlags());
  64473. else
  64474. setDropShadowEnabled (true);
  64475. setWantsKeyboardFocus (true);
  64476. setBroughtToFrontOnMouseClick (true);
  64477. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64478. }
  64479. TopLevelWindow::~TopLevelWindow()
  64480. {
  64481. shadower = 0;
  64482. TopLevelWindowManager::getInstance()->removeWindow (this);
  64483. }
  64484. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64485. {
  64486. if (hasKeyboardFocus (true))
  64487. TopLevelWindowManager::getInstance()->timerCallback();
  64488. else
  64489. TopLevelWindowManager::getInstance()->startTimer (10);
  64490. }
  64491. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64492. {
  64493. if (windowIsActive_ != isNowActive)
  64494. {
  64495. windowIsActive_ = isNowActive;
  64496. activeWindowStatusChanged();
  64497. }
  64498. }
  64499. void TopLevelWindow::activeWindowStatusChanged()
  64500. {
  64501. }
  64502. void TopLevelWindow::parentHierarchyChanged()
  64503. {
  64504. setDropShadowEnabled (useDropShadow);
  64505. }
  64506. void TopLevelWindow::visibilityChanged()
  64507. {
  64508. if (isShowing())
  64509. toFront (true);
  64510. }
  64511. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64512. {
  64513. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64514. if (useDropShadow)
  64515. styleFlags |= ComponentPeer::windowHasDropShadow;
  64516. if (useNativeTitleBar)
  64517. styleFlags |= ComponentPeer::windowHasTitleBar;
  64518. return styleFlags;
  64519. }
  64520. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64521. {
  64522. useDropShadow = useShadow;
  64523. if (isOnDesktop())
  64524. {
  64525. shadower = 0;
  64526. Component::addToDesktop (getDesktopWindowStyleFlags());
  64527. }
  64528. else
  64529. {
  64530. if (useShadow && isOpaque())
  64531. {
  64532. if (shadower == 0)
  64533. {
  64534. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64535. if (shadower != 0)
  64536. shadower->setOwner (this);
  64537. }
  64538. }
  64539. else
  64540. {
  64541. shadower = 0;
  64542. }
  64543. }
  64544. }
  64545. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64546. {
  64547. if (useNativeTitleBar != useNativeTitleBar_)
  64548. {
  64549. useNativeTitleBar = useNativeTitleBar_;
  64550. recreateDesktopWindow();
  64551. sendLookAndFeelChange();
  64552. }
  64553. }
  64554. void TopLevelWindow::recreateDesktopWindow()
  64555. {
  64556. if (isOnDesktop())
  64557. {
  64558. Component::addToDesktop (getDesktopWindowStyleFlags());
  64559. toFront (true);
  64560. }
  64561. }
  64562. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64563. {
  64564. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64565. because this class needs to make sure its layout corresponds with settings like whether
  64566. it's got a native title bar or not.
  64567. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64568. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64569. method, then add or remove whatever flags are necessary from this value before returning it.
  64570. */
  64571. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64572. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64573. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64574. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64575. sendLookAndFeelChange();
  64576. }
  64577. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64578. {
  64579. if (c == 0)
  64580. c = TopLevelWindow::getActiveTopLevelWindow();
  64581. if (c == 0)
  64582. {
  64583. centreWithSize (width, height);
  64584. }
  64585. else
  64586. {
  64587. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64588. (c->getHeight() - height) / 2)));
  64589. Rectangle<int> parentArea (c->getParentMonitorArea());
  64590. if (getParentComponent() != 0)
  64591. {
  64592. p = getParentComponent()->globalPositionToRelative (p);
  64593. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64594. }
  64595. parentArea.reduce (12, 12);
  64596. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64597. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64598. width, height);
  64599. }
  64600. }
  64601. int TopLevelWindow::getNumTopLevelWindows() throw()
  64602. {
  64603. return TopLevelWindowManager::getInstance()->windows.size();
  64604. }
  64605. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64606. {
  64607. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64608. }
  64609. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64610. {
  64611. TopLevelWindow* best = 0;
  64612. int bestNumTWLParents = -1;
  64613. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64614. {
  64615. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64616. if (tlw->isActiveWindow())
  64617. {
  64618. int numTWLParents = 0;
  64619. const Component* c = tlw->getParentComponent();
  64620. while (c != 0)
  64621. {
  64622. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64623. ++numTWLParents;
  64624. c = c->getParentComponent();
  64625. }
  64626. if (bestNumTWLParents < numTWLParents)
  64627. {
  64628. best = tlw;
  64629. bestNumTWLParents = numTWLParents;
  64630. }
  64631. }
  64632. }
  64633. return best;
  64634. }
  64635. END_JUCE_NAMESPACE
  64636. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64637. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64638. BEGIN_JUCE_NAMESPACE
  64639. namespace RelativeCoordinateHelpers
  64640. {
  64641. static void skipComma (const juce_wchar* const s, int& i)
  64642. {
  64643. while (CharacterFunctions::isWhitespace (s[i]))
  64644. ++i;
  64645. if (s[i] == ',')
  64646. ++i;
  64647. }
  64648. }
  64649. const String RelativeCoordinate::Strings::parent ("parent");
  64650. const String RelativeCoordinate::Strings::left ("left");
  64651. const String RelativeCoordinate::Strings::right ("right");
  64652. const String RelativeCoordinate::Strings::top ("top");
  64653. const String RelativeCoordinate::Strings::bottom ("bottom");
  64654. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64655. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64656. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64657. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64658. RelativeCoordinate::RelativeCoordinate()
  64659. {
  64660. }
  64661. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64662. : term (term_)
  64663. {
  64664. }
  64665. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64666. : term (other.term)
  64667. {
  64668. }
  64669. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64670. {
  64671. term = other.term;
  64672. return *this;
  64673. }
  64674. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64675. : term (absoluteDistanceFromOrigin)
  64676. {
  64677. }
  64678. RelativeCoordinate::RelativeCoordinate (const String& s)
  64679. {
  64680. try
  64681. {
  64682. term = Expression (s);
  64683. }
  64684. catch (...)
  64685. {}
  64686. }
  64687. RelativeCoordinate::~RelativeCoordinate()
  64688. {
  64689. }
  64690. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64691. {
  64692. return term.toString() == other.term.toString();
  64693. }
  64694. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64695. {
  64696. return ! operator== (other);
  64697. }
  64698. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64699. {
  64700. try
  64701. {
  64702. if (context != 0)
  64703. return term.evaluate (*context);
  64704. else
  64705. return term.evaluate();
  64706. }
  64707. catch (...)
  64708. {}
  64709. return 0.0;
  64710. }
  64711. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64712. {
  64713. try
  64714. {
  64715. if (context != 0)
  64716. term.evaluate (*context);
  64717. else
  64718. term.evaluate();
  64719. }
  64720. catch (...)
  64721. {
  64722. return true;
  64723. }
  64724. return false;
  64725. }
  64726. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64727. {
  64728. try
  64729. {
  64730. if (context != 0)
  64731. {
  64732. term = term.adjustedToGiveNewResult (newPos, *context);
  64733. }
  64734. else
  64735. {
  64736. Expression::EvaluationContext defaultContext;
  64737. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64738. }
  64739. }
  64740. catch (...)
  64741. {}
  64742. }
  64743. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64744. {
  64745. try
  64746. {
  64747. return term.referencesSymbol (coordName, context);
  64748. }
  64749. catch (...)
  64750. {}
  64751. return false;
  64752. }
  64753. bool RelativeCoordinate::isDynamic() const
  64754. {
  64755. return term.usesAnySymbols();
  64756. }
  64757. const String RelativeCoordinate::toString() const
  64758. {
  64759. return term.toString();
  64760. }
  64761. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64762. {
  64763. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64764. if (term.referencesSymbol (oldName, 0))
  64765. term = term.withRenamedSymbol (oldName, newName);
  64766. }
  64767. RelativePoint::RelativePoint()
  64768. {
  64769. }
  64770. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64771. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64772. {
  64773. }
  64774. RelativePoint::RelativePoint (const float x_, const float y_)
  64775. : x (x_), y (y_)
  64776. {
  64777. }
  64778. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64779. : x (x_), y (y_)
  64780. {
  64781. }
  64782. RelativePoint::RelativePoint (const String& s)
  64783. {
  64784. int i = 0;
  64785. x = RelativeCoordinate (Expression::parse (s, i));
  64786. RelativeCoordinateHelpers::skipComma (s, i);
  64787. y = RelativeCoordinate (Expression::parse (s, i));
  64788. }
  64789. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64790. {
  64791. return x == other.x && y == other.y;
  64792. }
  64793. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64794. {
  64795. return ! operator== (other);
  64796. }
  64797. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64798. {
  64799. return Point<float> ((float) x.resolve (context),
  64800. (float) y.resolve (context));
  64801. }
  64802. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64803. {
  64804. x.moveToAbsolute (newPos.getX(), context);
  64805. y.moveToAbsolute (newPos.getY(), context);
  64806. }
  64807. const String RelativePoint::toString() const
  64808. {
  64809. return x.toString() + ", " + y.toString();
  64810. }
  64811. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64812. {
  64813. x.renameSymbolIfUsed (oldName, newName);
  64814. y.renameSymbolIfUsed (oldName, newName);
  64815. }
  64816. bool RelativePoint::isDynamic() const
  64817. {
  64818. return x.isDynamic() || y.isDynamic();
  64819. }
  64820. RelativeRectangle::RelativeRectangle()
  64821. {
  64822. }
  64823. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64824. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64825. : left (left_), right (right_), top (top_), bottom (bottom_)
  64826. {
  64827. }
  64828. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64829. : left (rect.getX()),
  64830. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64831. top (rect.getY()),
  64832. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64833. {
  64834. }
  64835. RelativeRectangle::RelativeRectangle (const String& s)
  64836. {
  64837. int i = 0;
  64838. left = RelativeCoordinate (Expression::parse (s, i));
  64839. RelativeCoordinateHelpers::skipComma (s, i);
  64840. top = RelativeCoordinate (Expression::parse (s, i));
  64841. RelativeCoordinateHelpers::skipComma (s, i);
  64842. right = RelativeCoordinate (Expression::parse (s, i));
  64843. RelativeCoordinateHelpers::skipComma (s, i);
  64844. bottom = RelativeCoordinate (Expression::parse (s, i));
  64845. }
  64846. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64847. {
  64848. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64849. }
  64850. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64851. {
  64852. return ! operator== (other);
  64853. }
  64854. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64855. {
  64856. const double l = left.resolve (context);
  64857. const double r = right.resolve (context);
  64858. const double t = top.resolve (context);
  64859. const double b = bottom.resolve (context);
  64860. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64861. }
  64862. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64863. {
  64864. left.moveToAbsolute (newPos.getX(), context);
  64865. right.moveToAbsolute (newPos.getRight(), context);
  64866. top.moveToAbsolute (newPos.getY(), context);
  64867. bottom.moveToAbsolute (newPos.getBottom(), context);
  64868. }
  64869. const String RelativeRectangle::toString() const
  64870. {
  64871. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64872. }
  64873. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64874. {
  64875. left.renameSymbolIfUsed (oldName, newName);
  64876. right.renameSymbolIfUsed (oldName, newName);
  64877. top.renameSymbolIfUsed (oldName, newName);
  64878. bottom.renameSymbolIfUsed (oldName, newName);
  64879. }
  64880. RelativePointPath::RelativePointPath()
  64881. : usesNonZeroWinding (true),
  64882. containsDynamicPoints (false)
  64883. {
  64884. }
  64885. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64886. : usesNonZeroWinding (true),
  64887. containsDynamicPoints (false)
  64888. {
  64889. ValueTree state (DrawablePath::valueTreeType);
  64890. other.writeTo (state, 0);
  64891. parse (state);
  64892. }
  64893. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64894. : usesNonZeroWinding (true),
  64895. containsDynamicPoints (false)
  64896. {
  64897. parse (drawable);
  64898. }
  64899. RelativePointPath::RelativePointPath (const Path& path)
  64900. {
  64901. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64902. Path::Iterator i (path);
  64903. while (i.next())
  64904. {
  64905. switch (i.elementType)
  64906. {
  64907. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64908. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64909. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64910. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64911. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64912. default: jassertfalse; break;
  64913. }
  64914. }
  64915. }
  64916. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64917. {
  64918. DrawablePath::ValueTreeWrapper wrapper (state);
  64919. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64920. ValueTree pathTree (wrapper.getPathState());
  64921. pathTree.removeAllChildren (undoManager);
  64922. for (int i = 0; i < elements.size(); ++i)
  64923. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64924. }
  64925. void RelativePointPath::parse (const ValueTree& state)
  64926. {
  64927. DrawablePath::ValueTreeWrapper wrapper (state);
  64928. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64929. RelativePoint points[3];
  64930. const ValueTree pathTree (wrapper.getPathState());
  64931. const int num = pathTree.getNumChildren();
  64932. for (int i = 0; i < num; ++i)
  64933. {
  64934. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64935. const int numCps = e.getNumControlPoints();
  64936. for (int j = 0; j < numCps; ++j)
  64937. {
  64938. points[j] = e.getControlPoint (j);
  64939. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64940. }
  64941. const Identifier type (e.getType());
  64942. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64943. elements.add (new StartSubPath (points[0]));
  64944. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64945. elements.add (new CloseSubPath());
  64946. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64947. elements.add (new LineTo (points[0]));
  64948. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64949. elements.add (new QuadraticTo (points[0], points[1]));
  64950. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64951. elements.add (new CubicTo (points[0], points[1], points[2]));
  64952. else
  64953. jassertfalse;
  64954. }
  64955. }
  64956. RelativePointPath::~RelativePointPath()
  64957. {
  64958. }
  64959. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64960. {
  64961. elements.swapWithArray (other.elements);
  64962. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64963. }
  64964. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64965. {
  64966. for (int i = 0; i < elements.size(); ++i)
  64967. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64968. }
  64969. bool RelativePointPath::containsAnyDynamicPoints() const
  64970. {
  64971. return containsDynamicPoints;
  64972. }
  64973. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64974. {
  64975. }
  64976. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64977. : ElementBase (startSubPathElement), startPos (pos)
  64978. {
  64979. }
  64980. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64981. {
  64982. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64983. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64984. return v;
  64985. }
  64986. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64987. {
  64988. path.startNewSubPath (startPos.resolve (coordFinder));
  64989. }
  64990. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64991. {
  64992. numPoints = 1;
  64993. return &startPos;
  64994. }
  64995. RelativePointPath::CloseSubPath::CloseSubPath()
  64996. : ElementBase (closeSubPathElement)
  64997. {
  64998. }
  64999. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  65000. {
  65001. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  65002. }
  65003. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  65004. {
  65005. path.closeSubPath();
  65006. }
  65007. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  65008. {
  65009. numPoints = 0;
  65010. return 0;
  65011. }
  65012. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  65013. : ElementBase (lineToElement), endPoint (endPoint_)
  65014. {
  65015. }
  65016. const ValueTree RelativePointPath::LineTo::createTree() const
  65017. {
  65018. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  65019. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  65020. return v;
  65021. }
  65022. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  65023. {
  65024. path.lineTo (endPoint.resolve (coordFinder));
  65025. }
  65026. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  65027. {
  65028. numPoints = 1;
  65029. return &endPoint;
  65030. }
  65031. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  65032. : ElementBase (quadraticToElement)
  65033. {
  65034. controlPoints[0] = controlPoint;
  65035. controlPoints[1] = endPoint;
  65036. }
  65037. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  65038. {
  65039. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  65040. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  65041. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  65042. return v;
  65043. }
  65044. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  65045. {
  65046. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  65047. controlPoints[1].resolve (coordFinder));
  65048. }
  65049. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  65050. {
  65051. numPoints = 2;
  65052. return controlPoints;
  65053. }
  65054. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  65055. : ElementBase (cubicToElement)
  65056. {
  65057. controlPoints[0] = controlPoint1;
  65058. controlPoints[1] = controlPoint2;
  65059. controlPoints[2] = endPoint;
  65060. }
  65061. const ValueTree RelativePointPath::CubicTo::createTree() const
  65062. {
  65063. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  65064. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  65065. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  65066. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  65067. return v;
  65068. }
  65069. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  65070. {
  65071. path.cubicTo (controlPoints[0].resolve (coordFinder),
  65072. controlPoints[1].resolve (coordFinder),
  65073. controlPoints[2].resolve (coordFinder));
  65074. }
  65075. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  65076. {
  65077. numPoints = 3;
  65078. return controlPoints;
  65079. }
  65080. RelativeParallelogram::RelativeParallelogram()
  65081. {
  65082. }
  65083. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  65084. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  65085. {
  65086. }
  65087. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  65088. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  65089. {
  65090. }
  65091. RelativeParallelogram::~RelativeParallelogram()
  65092. {
  65093. }
  65094. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  65095. {
  65096. points[0] = topLeft.resolve (coordFinder);
  65097. points[1] = topRight.resolve (coordFinder);
  65098. points[2] = bottomLeft.resolve (coordFinder);
  65099. }
  65100. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  65101. {
  65102. resolveThreePoints (points, coordFinder);
  65103. points[3] = points[1] + (points[2] - points[0]);
  65104. }
  65105. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  65106. {
  65107. Point<float> points[4];
  65108. resolveFourCorners (points, coordFinder);
  65109. return Rectangle<float>::findAreaContainingPoints (points, 4);
  65110. }
  65111. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  65112. {
  65113. Point<float> points[4];
  65114. resolveFourCorners (points, coordFinder);
  65115. path.startNewSubPath (points[0]);
  65116. path.lineTo (points[1]);
  65117. path.lineTo (points[3]);
  65118. path.lineTo (points[2]);
  65119. path.closeSubPath();
  65120. }
  65121. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  65122. {
  65123. Point<float> corners[3];
  65124. resolveThreePoints (corners, coordFinder);
  65125. const Line<float> top (corners[0], corners[1]);
  65126. const Line<float> left (corners[0], corners[2]);
  65127. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  65128. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  65129. topRight.moveToAbsolute (newTopRight, coordFinder);
  65130. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  65131. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  65132. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  65133. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  65134. }
  65135. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  65136. {
  65137. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  65138. }
  65139. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  65140. {
  65141. return ! operator== (other);
  65142. }
  65143. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  65144. {
  65145. const Point<float> tr (corners[1] - corners[0]);
  65146. const Point<float> bl (corners[2] - corners[0]);
  65147. target -= corners[0];
  65148. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  65149. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  65150. }
  65151. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  65152. {
  65153. return corners[0]
  65154. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  65155. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  65156. }
  65157. END_JUCE_NAMESPACE
  65158. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  65159. #endif
  65160. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  65161. /*** Start of inlined file: juce_Colour.cpp ***/
  65162. BEGIN_JUCE_NAMESPACE
  65163. namespace ColourHelpers
  65164. {
  65165. static uint8 floatAlphaToInt (const float alpha) throw()
  65166. {
  65167. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  65168. }
  65169. static void convertHSBtoRGB (float h, float s, float v,
  65170. uint8& r, uint8& g, uint8& b) throw()
  65171. {
  65172. v = jlimit (0.0f, 1.0f, v);
  65173. v *= 255.0f;
  65174. const uint8 intV = (uint8) roundToInt (v);
  65175. if (s <= 0)
  65176. {
  65177. r = intV;
  65178. g = intV;
  65179. b = intV;
  65180. }
  65181. else
  65182. {
  65183. s = jmin (1.0f, s);
  65184. h = jlimit (0.0f, 1.0f, h);
  65185. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  65186. const float f = h - std::floor (h);
  65187. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  65188. const float y = v * (1.0f - s * f);
  65189. const float z = v * (1.0f - (s * (1.0f - f)));
  65190. if (h < 1.0f)
  65191. {
  65192. r = intV;
  65193. g = (uint8) roundToInt (z);
  65194. b = x;
  65195. }
  65196. else if (h < 2.0f)
  65197. {
  65198. r = (uint8) roundToInt (y);
  65199. g = intV;
  65200. b = x;
  65201. }
  65202. else if (h < 3.0f)
  65203. {
  65204. r = x;
  65205. g = intV;
  65206. b = (uint8) roundToInt (z);
  65207. }
  65208. else if (h < 4.0f)
  65209. {
  65210. r = x;
  65211. g = (uint8) roundToInt (y);
  65212. b = intV;
  65213. }
  65214. else if (h < 5.0f)
  65215. {
  65216. r = (uint8) roundToInt (z);
  65217. g = x;
  65218. b = intV;
  65219. }
  65220. else if (h < 6.0f)
  65221. {
  65222. r = intV;
  65223. g = x;
  65224. b = (uint8) roundToInt (y);
  65225. }
  65226. else
  65227. {
  65228. r = 0;
  65229. g = 0;
  65230. b = 0;
  65231. }
  65232. }
  65233. }
  65234. }
  65235. Colour::Colour() throw()
  65236. : argb (0)
  65237. {
  65238. }
  65239. Colour::Colour (const Colour& other) throw()
  65240. : argb (other.argb)
  65241. {
  65242. }
  65243. Colour& Colour::operator= (const Colour& other) throw()
  65244. {
  65245. argb = other.argb;
  65246. return *this;
  65247. }
  65248. bool Colour::operator== (const Colour& other) const throw()
  65249. {
  65250. return argb.getARGB() == other.argb.getARGB();
  65251. }
  65252. bool Colour::operator!= (const Colour& other) const throw()
  65253. {
  65254. return argb.getARGB() != other.argb.getARGB();
  65255. }
  65256. Colour::Colour (const uint32 argb_) throw()
  65257. : argb (argb_)
  65258. {
  65259. }
  65260. Colour::Colour (const uint8 red,
  65261. const uint8 green,
  65262. const uint8 blue) throw()
  65263. {
  65264. argb.setARGB (0xff, red, green, blue);
  65265. }
  65266. const Colour Colour::fromRGB (const uint8 red,
  65267. const uint8 green,
  65268. const uint8 blue) throw()
  65269. {
  65270. return Colour (red, green, blue);
  65271. }
  65272. Colour::Colour (const uint8 red,
  65273. const uint8 green,
  65274. const uint8 blue,
  65275. const uint8 alpha) throw()
  65276. {
  65277. argb.setARGB (alpha, red, green, blue);
  65278. }
  65279. const Colour Colour::fromRGBA (const uint8 red,
  65280. const uint8 green,
  65281. const uint8 blue,
  65282. const uint8 alpha) throw()
  65283. {
  65284. return Colour (red, green, blue, alpha);
  65285. }
  65286. Colour::Colour (const uint8 red,
  65287. const uint8 green,
  65288. const uint8 blue,
  65289. const float alpha) throw()
  65290. {
  65291. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65292. }
  65293. const Colour Colour::fromRGBAFloat (const uint8 red,
  65294. const uint8 green,
  65295. const uint8 blue,
  65296. const float alpha) throw()
  65297. {
  65298. return Colour (red, green, blue, alpha);
  65299. }
  65300. Colour::Colour (const float hue,
  65301. const float saturation,
  65302. const float brightness,
  65303. const float alpha) throw()
  65304. {
  65305. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65306. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65307. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65308. }
  65309. const Colour Colour::fromHSV (const float hue,
  65310. const float saturation,
  65311. const float brightness,
  65312. const float alpha) throw()
  65313. {
  65314. return Colour (hue, saturation, brightness, alpha);
  65315. }
  65316. Colour::Colour (const float hue,
  65317. const float saturation,
  65318. const float brightness,
  65319. const uint8 alpha) throw()
  65320. {
  65321. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65322. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65323. argb.setARGB (alpha, r, g, b);
  65324. }
  65325. Colour::~Colour() throw()
  65326. {
  65327. }
  65328. const PixelARGB Colour::getPixelARGB() const throw()
  65329. {
  65330. PixelARGB p (argb);
  65331. p.premultiply();
  65332. return p;
  65333. }
  65334. uint32 Colour::getARGB() const throw()
  65335. {
  65336. return argb.getARGB();
  65337. }
  65338. bool Colour::isTransparent() const throw()
  65339. {
  65340. return getAlpha() == 0;
  65341. }
  65342. bool Colour::isOpaque() const throw()
  65343. {
  65344. return getAlpha() == 0xff;
  65345. }
  65346. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65347. {
  65348. PixelARGB newCol (argb);
  65349. newCol.setAlpha (newAlpha);
  65350. return Colour (newCol.getARGB());
  65351. }
  65352. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65353. {
  65354. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65355. PixelARGB newCol (argb);
  65356. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65357. return Colour (newCol.getARGB());
  65358. }
  65359. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65360. {
  65361. jassert (alphaMultiplier >= 0);
  65362. PixelARGB newCol (argb);
  65363. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65364. return Colour (newCol.getARGB());
  65365. }
  65366. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65367. {
  65368. const int destAlpha = getAlpha();
  65369. if (destAlpha > 0)
  65370. {
  65371. const int invA = 0xff - (int) src.getAlpha();
  65372. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65373. if (resA > 0)
  65374. {
  65375. const int da = (invA * destAlpha) / resA;
  65376. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65377. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65378. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65379. (uint8) resA);
  65380. }
  65381. return *this;
  65382. }
  65383. else
  65384. {
  65385. return src;
  65386. }
  65387. }
  65388. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65389. {
  65390. if (proportionOfOther <= 0)
  65391. return *this;
  65392. if (proportionOfOther >= 1.0f)
  65393. return other;
  65394. PixelARGB c1 (getPixelARGB());
  65395. const PixelARGB c2 (other.getPixelARGB());
  65396. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65397. c1.unpremultiply();
  65398. return Colour (c1.getARGB());
  65399. }
  65400. float Colour::getFloatRed() const throw()
  65401. {
  65402. return getRed() / 255.0f;
  65403. }
  65404. float Colour::getFloatGreen() const throw()
  65405. {
  65406. return getGreen() / 255.0f;
  65407. }
  65408. float Colour::getFloatBlue() const throw()
  65409. {
  65410. return getBlue() / 255.0f;
  65411. }
  65412. float Colour::getFloatAlpha() const throw()
  65413. {
  65414. return getAlpha() / 255.0f;
  65415. }
  65416. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65417. {
  65418. const int r = getRed();
  65419. const int g = getGreen();
  65420. const int b = getBlue();
  65421. const int hi = jmax (r, g, b);
  65422. const int lo = jmin (r, g, b);
  65423. if (hi != 0)
  65424. {
  65425. s = (hi - lo) / (float) hi;
  65426. if (s != 0)
  65427. {
  65428. const float invDiff = 1.0f / (hi - lo);
  65429. const float red = (hi - r) * invDiff;
  65430. const float green = (hi - g) * invDiff;
  65431. const float blue = (hi - b) * invDiff;
  65432. if (r == hi)
  65433. h = blue - green;
  65434. else if (g == hi)
  65435. h = 2.0f + red - blue;
  65436. else
  65437. h = 4.0f + green - red;
  65438. h *= 1.0f / 6.0f;
  65439. if (h < 0)
  65440. ++h;
  65441. }
  65442. else
  65443. {
  65444. h = 0;
  65445. }
  65446. }
  65447. else
  65448. {
  65449. s = 0;
  65450. h = 0;
  65451. }
  65452. v = hi / 255.0f;
  65453. }
  65454. float Colour::getHue() const throw()
  65455. {
  65456. float h, s, b;
  65457. getHSB (h, s, b);
  65458. return h;
  65459. }
  65460. const Colour Colour::withHue (const float hue) const throw()
  65461. {
  65462. float h, s, b;
  65463. getHSB (h, s, b);
  65464. return Colour (hue, s, b, getAlpha());
  65465. }
  65466. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65467. {
  65468. float h, s, b;
  65469. getHSB (h, s, b);
  65470. h += amountToRotate;
  65471. h -= std::floor (h);
  65472. return Colour (h, s, b, getAlpha());
  65473. }
  65474. float Colour::getSaturation() const throw()
  65475. {
  65476. float h, s, b;
  65477. getHSB (h, s, b);
  65478. return s;
  65479. }
  65480. const Colour Colour::withSaturation (const float saturation) const throw()
  65481. {
  65482. float h, s, b;
  65483. getHSB (h, s, b);
  65484. return Colour (h, saturation, b, getAlpha());
  65485. }
  65486. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65487. {
  65488. float h, s, b;
  65489. getHSB (h, s, b);
  65490. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65491. }
  65492. float Colour::getBrightness() const throw()
  65493. {
  65494. float h, s, b;
  65495. getHSB (h, s, b);
  65496. return b;
  65497. }
  65498. const Colour Colour::withBrightness (const float brightness) const throw()
  65499. {
  65500. float h, s, b;
  65501. getHSB (h, s, b);
  65502. return Colour (h, s, brightness, getAlpha());
  65503. }
  65504. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65505. {
  65506. float h, s, b;
  65507. getHSB (h, s, b);
  65508. b *= amount;
  65509. if (b > 1.0f)
  65510. b = 1.0f;
  65511. return Colour (h, s, b, getAlpha());
  65512. }
  65513. const Colour Colour::brighter (float amount) const throw()
  65514. {
  65515. amount = 1.0f / (1.0f + amount);
  65516. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65517. (uint8) (255 - (amount * (255 - getGreen()))),
  65518. (uint8) (255 - (amount * (255 - getBlue()))),
  65519. getAlpha());
  65520. }
  65521. const Colour Colour::darker (float amount) const throw()
  65522. {
  65523. amount = 1.0f / (1.0f + amount);
  65524. return Colour ((uint8) (amount * getRed()),
  65525. (uint8) (amount * getGreen()),
  65526. (uint8) (amount * getBlue()),
  65527. getAlpha());
  65528. }
  65529. const Colour Colour::greyLevel (const float brightness) throw()
  65530. {
  65531. const uint8 level
  65532. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65533. return Colour (level, level, level);
  65534. }
  65535. const Colour Colour::contrasting (const float amount) const throw()
  65536. {
  65537. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65538. ? Colours::black
  65539. : Colours::white).withAlpha (amount));
  65540. }
  65541. const Colour Colour::contrasting (const Colour& colour1,
  65542. const Colour& colour2) throw()
  65543. {
  65544. const float b1 = colour1.getBrightness();
  65545. const float b2 = colour2.getBrightness();
  65546. float best = 0.0f;
  65547. float bestDist = 0.0f;
  65548. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65549. {
  65550. const float d1 = std::abs (i - b1);
  65551. const float d2 = std::abs (i - b2);
  65552. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65553. if (dist > bestDist)
  65554. {
  65555. best = i;
  65556. bestDist = dist;
  65557. }
  65558. }
  65559. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65560. .withBrightness (best);
  65561. }
  65562. const String Colour::toString() const
  65563. {
  65564. return String::toHexString ((int) argb.getARGB());
  65565. }
  65566. const Colour Colour::fromString (const String& encodedColourString)
  65567. {
  65568. return Colour ((uint32) encodedColourString.getHexValue32());
  65569. }
  65570. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65571. {
  65572. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65573. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65574. .toUpperCase();
  65575. }
  65576. END_JUCE_NAMESPACE
  65577. /*** End of inlined file: juce_Colour.cpp ***/
  65578. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65579. BEGIN_JUCE_NAMESPACE
  65580. ColourGradient::ColourGradient() throw()
  65581. {
  65582. #if JUCE_DEBUG
  65583. point1.setX (987654.0f);
  65584. #endif
  65585. }
  65586. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65587. const Colour& colour2, const float x2_, const float y2_,
  65588. const bool isRadial_)
  65589. : point1 (x1_, y1_),
  65590. point2 (x2_, y2_),
  65591. isRadial (isRadial_)
  65592. {
  65593. colours.add (ColourPoint (0.0, colour1));
  65594. colours.add (ColourPoint (1.0, colour2));
  65595. }
  65596. ColourGradient::~ColourGradient()
  65597. {
  65598. }
  65599. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65600. {
  65601. return point1 == other.point1 && point2 == other.point2
  65602. && isRadial == other.isRadial
  65603. && colours == other.colours;
  65604. }
  65605. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65606. {
  65607. return ! operator== (other);
  65608. }
  65609. void ColourGradient::clearColours()
  65610. {
  65611. colours.clear();
  65612. }
  65613. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65614. {
  65615. // must be within the two end-points
  65616. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65617. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65618. int i;
  65619. for (i = 0; i < colours.size(); ++i)
  65620. if (colours.getReference(i).position > pos)
  65621. break;
  65622. colours.insert (i, ColourPoint (pos, colour));
  65623. return i;
  65624. }
  65625. void ColourGradient::removeColour (int index)
  65626. {
  65627. jassert (index > 0 && index < colours.size() - 1);
  65628. colours.remove (index);
  65629. }
  65630. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65631. {
  65632. for (int i = 0; i < colours.size(); ++i)
  65633. {
  65634. Colour& c = colours.getReference(i).colour;
  65635. c = c.withMultipliedAlpha (multiplier);
  65636. }
  65637. }
  65638. int ColourGradient::getNumColours() const throw()
  65639. {
  65640. return colours.size();
  65641. }
  65642. double ColourGradient::getColourPosition (const int index) const throw()
  65643. {
  65644. if (((unsigned int) index) < (unsigned int) colours.size())
  65645. return colours.getReference (index).position;
  65646. return 0;
  65647. }
  65648. const Colour ColourGradient::getColour (const int index) const throw()
  65649. {
  65650. if (((unsigned int) index) < (unsigned int) colours.size())
  65651. return colours.getReference (index).colour;
  65652. return Colour();
  65653. }
  65654. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65655. {
  65656. if (((unsigned int) index) < (unsigned int) colours.size())
  65657. colours.getReference (index).colour = newColour;
  65658. }
  65659. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65660. {
  65661. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65662. if (position <= 0 || colours.size() <= 1)
  65663. return colours.getReference(0).colour;
  65664. int i = colours.size() - 1;
  65665. while (position < colours.getReference(i).position)
  65666. --i;
  65667. const ColourPoint& p1 = colours.getReference (i);
  65668. if (i >= colours.size() - 1)
  65669. return p1.colour;
  65670. const ColourPoint& p2 = colours.getReference (i + 1);
  65671. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65672. }
  65673. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65674. {
  65675. #if JUCE_DEBUG
  65676. // trying to use the object without setting its co-ordinates? Have a careful read of
  65677. // the comments for the constructors.
  65678. jassert (point1.getX() != 987654.0f);
  65679. #endif
  65680. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65681. 3 * (int) point1.transformedBy (transform)
  65682. .getDistanceFrom (point2.transformedBy (transform)));
  65683. lookupTable.malloc (numEntries);
  65684. if (colours.size() >= 2)
  65685. {
  65686. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65687. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65688. int index = 0;
  65689. for (int j = 1; j < colours.size(); ++j)
  65690. {
  65691. const ColourPoint& p = colours.getReference (j);
  65692. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65693. const PixelARGB pix2 (p.colour.getPixelARGB());
  65694. for (int i = 0; i < numToDo; ++i)
  65695. {
  65696. jassert (index >= 0 && index < numEntries);
  65697. lookupTable[index] = pix1;
  65698. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65699. ++index;
  65700. }
  65701. pix1 = pix2;
  65702. }
  65703. while (index < numEntries)
  65704. lookupTable [index++] = pix1;
  65705. }
  65706. else
  65707. {
  65708. jassertfalse; // no colours specified!
  65709. }
  65710. return numEntries;
  65711. }
  65712. bool ColourGradient::isOpaque() const throw()
  65713. {
  65714. for (int i = 0; i < colours.size(); ++i)
  65715. if (! colours.getReference(i).colour.isOpaque())
  65716. return false;
  65717. return true;
  65718. }
  65719. bool ColourGradient::isInvisible() const throw()
  65720. {
  65721. for (int i = 0; i < colours.size(); ++i)
  65722. if (! colours.getReference(i).colour.isTransparent())
  65723. return false;
  65724. return true;
  65725. }
  65726. END_JUCE_NAMESPACE
  65727. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65728. /*** Start of inlined file: juce_Colours.cpp ***/
  65729. BEGIN_JUCE_NAMESPACE
  65730. const Colour Colours::transparentBlack (0);
  65731. const Colour Colours::transparentWhite (0x00ffffff);
  65732. const Colour Colours::aliceblue (0xfff0f8ff);
  65733. const Colour Colours::antiquewhite (0xfffaebd7);
  65734. const Colour Colours::aqua (0xff00ffff);
  65735. const Colour Colours::aquamarine (0xff7fffd4);
  65736. const Colour Colours::azure (0xfff0ffff);
  65737. const Colour Colours::beige (0xfff5f5dc);
  65738. const Colour Colours::bisque (0xffffe4c4);
  65739. const Colour Colours::black (0xff000000);
  65740. const Colour Colours::blanchedalmond (0xffffebcd);
  65741. const Colour Colours::blue (0xff0000ff);
  65742. const Colour Colours::blueviolet (0xff8a2be2);
  65743. const Colour Colours::brown (0xffa52a2a);
  65744. const Colour Colours::burlywood (0xffdeb887);
  65745. const Colour Colours::cadetblue (0xff5f9ea0);
  65746. const Colour Colours::chartreuse (0xff7fff00);
  65747. const Colour Colours::chocolate (0xffd2691e);
  65748. const Colour Colours::coral (0xffff7f50);
  65749. const Colour Colours::cornflowerblue (0xff6495ed);
  65750. const Colour Colours::cornsilk (0xfffff8dc);
  65751. const Colour Colours::crimson (0xffdc143c);
  65752. const Colour Colours::cyan (0xff00ffff);
  65753. const Colour Colours::darkblue (0xff00008b);
  65754. const Colour Colours::darkcyan (0xff008b8b);
  65755. const Colour Colours::darkgoldenrod (0xffb8860b);
  65756. const Colour Colours::darkgrey (0xff555555);
  65757. const Colour Colours::darkgreen (0xff006400);
  65758. const Colour Colours::darkkhaki (0xffbdb76b);
  65759. const Colour Colours::darkmagenta (0xff8b008b);
  65760. const Colour Colours::darkolivegreen (0xff556b2f);
  65761. const Colour Colours::darkorange (0xffff8c00);
  65762. const Colour Colours::darkorchid (0xff9932cc);
  65763. const Colour Colours::darkred (0xff8b0000);
  65764. const Colour Colours::darksalmon (0xffe9967a);
  65765. const Colour Colours::darkseagreen (0xff8fbc8f);
  65766. const Colour Colours::darkslateblue (0xff483d8b);
  65767. const Colour Colours::darkslategrey (0xff2f4f4f);
  65768. const Colour Colours::darkturquoise (0xff00ced1);
  65769. const Colour Colours::darkviolet (0xff9400d3);
  65770. const Colour Colours::deeppink (0xffff1493);
  65771. const Colour Colours::deepskyblue (0xff00bfff);
  65772. const Colour Colours::dimgrey (0xff696969);
  65773. const Colour Colours::dodgerblue (0xff1e90ff);
  65774. const Colour Colours::firebrick (0xffb22222);
  65775. const Colour Colours::floralwhite (0xfffffaf0);
  65776. const Colour Colours::forestgreen (0xff228b22);
  65777. const Colour Colours::fuchsia (0xffff00ff);
  65778. const Colour Colours::gainsboro (0xffdcdcdc);
  65779. const Colour Colours::gold (0xffffd700);
  65780. const Colour Colours::goldenrod (0xffdaa520);
  65781. const Colour Colours::grey (0xff808080);
  65782. const Colour Colours::green (0xff008000);
  65783. const Colour Colours::greenyellow (0xffadff2f);
  65784. const Colour Colours::honeydew (0xfff0fff0);
  65785. const Colour Colours::hotpink (0xffff69b4);
  65786. const Colour Colours::indianred (0xffcd5c5c);
  65787. const Colour Colours::indigo (0xff4b0082);
  65788. const Colour Colours::ivory (0xfffffff0);
  65789. const Colour Colours::khaki (0xfff0e68c);
  65790. const Colour Colours::lavender (0xffe6e6fa);
  65791. const Colour Colours::lavenderblush (0xfffff0f5);
  65792. const Colour Colours::lemonchiffon (0xfffffacd);
  65793. const Colour Colours::lightblue (0xffadd8e6);
  65794. const Colour Colours::lightcoral (0xfff08080);
  65795. const Colour Colours::lightcyan (0xffe0ffff);
  65796. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65797. const Colour Colours::lightgreen (0xff90ee90);
  65798. const Colour Colours::lightgrey (0xffd3d3d3);
  65799. const Colour Colours::lightpink (0xffffb6c1);
  65800. const Colour Colours::lightsalmon (0xffffa07a);
  65801. const Colour Colours::lightseagreen (0xff20b2aa);
  65802. const Colour Colours::lightskyblue (0xff87cefa);
  65803. const Colour Colours::lightslategrey (0xff778899);
  65804. const Colour Colours::lightsteelblue (0xffb0c4de);
  65805. const Colour Colours::lightyellow (0xffffffe0);
  65806. const Colour Colours::lime (0xff00ff00);
  65807. const Colour Colours::limegreen (0xff32cd32);
  65808. const Colour Colours::linen (0xfffaf0e6);
  65809. const Colour Colours::magenta (0xffff00ff);
  65810. const Colour Colours::maroon (0xff800000);
  65811. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65812. const Colour Colours::mediumblue (0xff0000cd);
  65813. const Colour Colours::mediumorchid (0xffba55d3);
  65814. const Colour Colours::mediumpurple (0xff9370db);
  65815. const Colour Colours::mediumseagreen (0xff3cb371);
  65816. const Colour Colours::mediumslateblue (0xff7b68ee);
  65817. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65818. const Colour Colours::mediumturquoise (0xff48d1cc);
  65819. const Colour Colours::mediumvioletred (0xffc71585);
  65820. const Colour Colours::midnightblue (0xff191970);
  65821. const Colour Colours::mintcream (0xfff5fffa);
  65822. const Colour Colours::mistyrose (0xffffe4e1);
  65823. const Colour Colours::navajowhite (0xffffdead);
  65824. const Colour Colours::navy (0xff000080);
  65825. const Colour Colours::oldlace (0xfffdf5e6);
  65826. const Colour Colours::olive (0xff808000);
  65827. const Colour Colours::olivedrab (0xff6b8e23);
  65828. const Colour Colours::orange (0xffffa500);
  65829. const Colour Colours::orangered (0xffff4500);
  65830. const Colour Colours::orchid (0xffda70d6);
  65831. const Colour Colours::palegoldenrod (0xffeee8aa);
  65832. const Colour Colours::palegreen (0xff98fb98);
  65833. const Colour Colours::paleturquoise (0xffafeeee);
  65834. const Colour Colours::palevioletred (0xffdb7093);
  65835. const Colour Colours::papayawhip (0xffffefd5);
  65836. const Colour Colours::peachpuff (0xffffdab9);
  65837. const Colour Colours::peru (0xffcd853f);
  65838. const Colour Colours::pink (0xffffc0cb);
  65839. const Colour Colours::plum (0xffdda0dd);
  65840. const Colour Colours::powderblue (0xffb0e0e6);
  65841. const Colour Colours::purple (0xff800080);
  65842. const Colour Colours::red (0xffff0000);
  65843. const Colour Colours::rosybrown (0xffbc8f8f);
  65844. const Colour Colours::royalblue (0xff4169e1);
  65845. const Colour Colours::saddlebrown (0xff8b4513);
  65846. const Colour Colours::salmon (0xfffa8072);
  65847. const Colour Colours::sandybrown (0xfff4a460);
  65848. const Colour Colours::seagreen (0xff2e8b57);
  65849. const Colour Colours::seashell (0xfffff5ee);
  65850. const Colour Colours::sienna (0xffa0522d);
  65851. const Colour Colours::silver (0xffc0c0c0);
  65852. const Colour Colours::skyblue (0xff87ceeb);
  65853. const Colour Colours::slateblue (0xff6a5acd);
  65854. const Colour Colours::slategrey (0xff708090);
  65855. const Colour Colours::snow (0xfffffafa);
  65856. const Colour Colours::springgreen (0xff00ff7f);
  65857. const Colour Colours::steelblue (0xff4682b4);
  65858. const Colour Colours::tan (0xffd2b48c);
  65859. const Colour Colours::teal (0xff008080);
  65860. const Colour Colours::thistle (0xffd8bfd8);
  65861. const Colour Colours::tomato (0xffff6347);
  65862. const Colour Colours::turquoise (0xff40e0d0);
  65863. const Colour Colours::violet (0xffee82ee);
  65864. const Colour Colours::wheat (0xfff5deb3);
  65865. const Colour Colours::white (0xffffffff);
  65866. const Colour Colours::whitesmoke (0xfff5f5f5);
  65867. const Colour Colours::yellow (0xffffff00);
  65868. const Colour Colours::yellowgreen (0xff9acd32);
  65869. const Colour Colours::findColourForName (const String& colourName,
  65870. const Colour& defaultColour)
  65871. {
  65872. static const int presets[] =
  65873. {
  65874. // (first value is the string's hashcode, second is ARGB)
  65875. 0x05978fff, 0xff000000, /* black */
  65876. 0x06bdcc29, 0xffffffff, /* white */
  65877. 0x002e305a, 0xff0000ff, /* blue */
  65878. 0x00308adf, 0xff808080, /* grey */
  65879. 0x05e0cf03, 0xff008000, /* green */
  65880. 0x0001b891, 0xffff0000, /* red */
  65881. 0xd43c6474, 0xffffff00, /* yellow */
  65882. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65883. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65884. 0x002dcebc, 0xff00ffff, /* aqua */
  65885. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65886. 0x0590228f, 0xfff0ffff, /* azure */
  65887. 0x05947fe4, 0xfff5f5dc, /* beige */
  65888. 0xad388e35, 0xffffe4c4, /* bisque */
  65889. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65890. 0x39129959, 0xff8a2be2, /* blueviolet */
  65891. 0x059a8136, 0xffa52a2a, /* brown */
  65892. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65893. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65894. 0x6b748956, 0xff7fff00, /* chartreuse */
  65895. 0x2903623c, 0xffd2691e, /* chocolate */
  65896. 0x05a74431, 0xffff7f50, /* coral */
  65897. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65898. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65899. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65900. 0x002ed323, 0xff00ffff, /* cyan */
  65901. 0x67cc74d0, 0xff00008b, /* darkblue */
  65902. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65903. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65904. 0x67cecf55, 0xff555555, /* darkgrey */
  65905. 0x920b194d, 0xff006400, /* darkgreen */
  65906. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65907. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65908. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65909. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65910. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65911. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65912. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65913. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65914. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65915. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65916. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65917. 0xc8769375, 0xff9400d3, /* darkviolet */
  65918. 0x25832862, 0xffff1493, /* deeppink */
  65919. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65920. 0x634c8b67, 0xff696969, /* dimgrey */
  65921. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65922. 0xef19e3cb, 0xffb22222, /* firebrick */
  65923. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65924. 0xd086fd06, 0xff228b22, /* forestgreen */
  65925. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65926. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65927. 0x00308060, 0xffffd700, /* gold */
  65928. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65929. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65930. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65931. 0x41892743, 0xffff69b4, /* hotpink */
  65932. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65933. 0xb969fed2, 0xff4b0082, /* indigo */
  65934. 0x05fef6a9, 0xfffffff0, /* ivory */
  65935. 0x06149302, 0xfff0e68c, /* khaki */
  65936. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65937. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65938. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65939. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65940. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65941. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65942. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65943. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65944. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65945. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65946. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65947. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65948. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65949. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65950. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65951. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65952. 0x0032afd5, 0xff00ff00, /* lime */
  65953. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65954. 0x06234efa, 0xfffaf0e6, /* linen */
  65955. 0x316858a9, 0xffff00ff, /* magenta */
  65956. 0xbf8ca470, 0xff800000, /* maroon */
  65957. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65958. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65959. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65960. 0x07556b71, 0xff9370db, /* mediumpurple */
  65961. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65962. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65963. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65964. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65965. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65966. 0x168eb32a, 0xff191970, /* midnightblue */
  65967. 0x4306b960, 0xfff5fffa, /* mintcream */
  65968. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65969. 0xe97218a6, 0xffffdead, /* navajowhite */
  65970. 0x00337bb6, 0xff000080, /* navy */
  65971. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65972. 0x064ee1db, 0xff808000, /* olive */
  65973. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65974. 0xc3de262e, 0xffffa500, /* orange */
  65975. 0x58bebba3, 0xffff4500, /* orangered */
  65976. 0xc3def8a3, 0xffda70d6, /* orchid */
  65977. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65978. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65979. 0x74022737, 0xffafeeee, /* paleturquoise */
  65980. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65981. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65982. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65983. 0x003472f8, 0xffcd853f, /* peru */
  65984. 0x00348176, 0xffffc0cb, /* pink */
  65985. 0x00348d94, 0xffdda0dd, /* plum */
  65986. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65987. 0xc5c507bc, 0xff800080, /* purple */
  65988. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65989. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65990. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65991. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65992. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65993. 0x34636c14, 0xff2e8b57, /* seagreen */
  65994. 0x3507fb41, 0xfffff5ee, /* seashell */
  65995. 0xca348772, 0xffa0522d, /* sienna */
  65996. 0xca37d30d, 0xffc0c0c0, /* silver */
  65997. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65998. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65999. 0x44ab37f8, 0xff708090, /* slategrey */
  66000. 0x0035f183, 0xfffffafa, /* snow */
  66001. 0xd5440d16, 0xff00ff7f, /* springgreen */
  66002. 0x3e1524a5, 0xff4682b4, /* steelblue */
  66003. 0x0001bfa1, 0xffd2b48c, /* tan */
  66004. 0x0036425c, 0xff008080, /* teal */
  66005. 0xafc8858f, 0xffd8bfd8, /* thistle */
  66006. 0xcc41600a, 0xffff6347, /* tomato */
  66007. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  66008. 0xcf57947f, 0xffee82ee, /* violet */
  66009. 0x06bdbae7, 0xfff5deb3, /* wheat */
  66010. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  66011. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  66012. };
  66013. const int hash = colourName.trim().toLowerCase().hashCode();
  66014. for (int i = 0; i < numElementsInArray (presets); i += 2)
  66015. if (presets [i] == hash)
  66016. return Colour (presets [i + 1]);
  66017. return defaultColour;
  66018. }
  66019. END_JUCE_NAMESPACE
  66020. /*** End of inlined file: juce_Colours.cpp ***/
  66021. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  66022. BEGIN_JUCE_NAMESPACE
  66023. const int juce_edgeTableDefaultEdgesPerLine = 32;
  66024. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  66025. const Path& path, const AffineTransform& transform)
  66026. : bounds (bounds_),
  66027. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66028. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66029. needToCheckEmptinesss (true)
  66030. {
  66031. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  66032. int* t = table;
  66033. for (int i = bounds.getHeight(); --i >= 0;)
  66034. {
  66035. *t = 0;
  66036. t += lineStrideElements;
  66037. }
  66038. const int topLimit = bounds.getY() << 8;
  66039. const int heightLimit = bounds.getHeight() << 8;
  66040. const int leftLimit = bounds.getX() << 8;
  66041. const int rightLimit = bounds.getRight() << 8;
  66042. PathFlatteningIterator iter (path, transform);
  66043. while (iter.next())
  66044. {
  66045. int y1 = roundToInt (iter.y1 * 256.0f);
  66046. int y2 = roundToInt (iter.y2 * 256.0f);
  66047. if (y1 != y2)
  66048. {
  66049. y1 -= topLimit;
  66050. y2 -= topLimit;
  66051. const int startY = y1;
  66052. int direction = -1;
  66053. if (y1 > y2)
  66054. {
  66055. swapVariables (y1, y2);
  66056. direction = 1;
  66057. }
  66058. if (y1 < 0)
  66059. y1 = 0;
  66060. if (y2 > heightLimit)
  66061. y2 = heightLimit;
  66062. if (y1 < y2)
  66063. {
  66064. const double startX = 256.0f * iter.x1;
  66065. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  66066. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  66067. do
  66068. {
  66069. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  66070. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  66071. if (x < leftLimit)
  66072. x = leftLimit;
  66073. else if (x >= rightLimit)
  66074. x = rightLimit - 1;
  66075. addEdgePoint (x, y1 >> 8, direction * step);
  66076. y1 += step;
  66077. }
  66078. while (y1 < y2);
  66079. }
  66080. }
  66081. }
  66082. sanitiseLevels (path.isUsingNonZeroWinding());
  66083. }
  66084. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  66085. : bounds (rectangleToAdd),
  66086. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66087. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66088. needToCheckEmptinesss (true)
  66089. {
  66090. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66091. table[0] = 0;
  66092. const int x1 = rectangleToAdd.getX() << 8;
  66093. const int x2 = rectangleToAdd.getRight() << 8;
  66094. int* t = table;
  66095. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  66096. {
  66097. t[0] = 2;
  66098. t[1] = x1;
  66099. t[2] = 255;
  66100. t[3] = x2;
  66101. t[4] = 0;
  66102. t += lineStrideElements;
  66103. }
  66104. }
  66105. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  66106. : bounds (rectanglesToAdd.getBounds()),
  66107. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66108. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66109. needToCheckEmptinesss (true)
  66110. {
  66111. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66112. int* t = table;
  66113. for (int i = bounds.getHeight(); --i >= 0;)
  66114. {
  66115. *t = 0;
  66116. t += lineStrideElements;
  66117. }
  66118. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  66119. {
  66120. const Rectangle<int>* const r = iter.getRectangle();
  66121. const int x1 = r->getX() << 8;
  66122. const int x2 = r->getRight() << 8;
  66123. int y = r->getY() - bounds.getY();
  66124. for (int j = r->getHeight(); --j >= 0;)
  66125. {
  66126. addEdgePoint (x1, y, 255);
  66127. addEdgePoint (x2, y, -255);
  66128. ++y;
  66129. }
  66130. }
  66131. sanitiseLevels (true);
  66132. }
  66133. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  66134. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  66135. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  66136. 2 + (int) rectangleToAdd.getWidth(),
  66137. 2 + (int) rectangleToAdd.getHeight())),
  66138. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  66139. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  66140. needToCheckEmptinesss (true)
  66141. {
  66142. jassert (! rectangleToAdd.isEmpty());
  66143. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66144. table[0] = 0;
  66145. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  66146. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  66147. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  66148. jassert (y1 < 256);
  66149. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  66150. if (x2 <= x1 || y2 <= y1)
  66151. {
  66152. bounds.setHeight (0);
  66153. return;
  66154. }
  66155. int lineY = 0;
  66156. int* t = table;
  66157. if ((y1 >> 8) == (y2 >> 8))
  66158. {
  66159. t[0] = 2;
  66160. t[1] = x1;
  66161. t[2] = y2 - y1;
  66162. t[3] = x2;
  66163. t[4] = 0;
  66164. ++lineY;
  66165. t += lineStrideElements;
  66166. }
  66167. else
  66168. {
  66169. t[0] = 2;
  66170. t[1] = x1;
  66171. t[2] = 255 - (y1 & 255);
  66172. t[3] = x2;
  66173. t[4] = 0;
  66174. ++lineY;
  66175. t += lineStrideElements;
  66176. while (lineY < (y2 >> 8))
  66177. {
  66178. t[0] = 2;
  66179. t[1] = x1;
  66180. t[2] = 255;
  66181. t[3] = x2;
  66182. t[4] = 0;
  66183. ++lineY;
  66184. t += lineStrideElements;
  66185. }
  66186. jassert (lineY < bounds.getHeight());
  66187. t[0] = 2;
  66188. t[1] = x1;
  66189. t[2] = y2 & 255;
  66190. t[3] = x2;
  66191. t[4] = 0;
  66192. ++lineY;
  66193. t += lineStrideElements;
  66194. }
  66195. while (lineY < bounds.getHeight())
  66196. {
  66197. t[0] = 0;
  66198. t += lineStrideElements;
  66199. ++lineY;
  66200. }
  66201. }
  66202. EdgeTable::EdgeTable (const EdgeTable& other)
  66203. {
  66204. operator= (other);
  66205. }
  66206. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  66207. {
  66208. bounds = other.bounds;
  66209. maxEdgesPerLine = other.maxEdgesPerLine;
  66210. lineStrideElements = other.lineStrideElements;
  66211. needToCheckEmptinesss = other.needToCheckEmptinesss;
  66212. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  66213. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  66214. return *this;
  66215. }
  66216. EdgeTable::~EdgeTable()
  66217. {
  66218. }
  66219. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  66220. {
  66221. while (--numLines >= 0)
  66222. {
  66223. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  66224. src += srcLineStride;
  66225. dest += destLineStride;
  66226. }
  66227. }
  66228. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  66229. {
  66230. // Convert the table from relative windings to absolute levels..
  66231. int* lineStart = table;
  66232. for (int i = bounds.getHeight(); --i >= 0;)
  66233. {
  66234. int* line = lineStart;
  66235. lineStart += lineStrideElements;
  66236. int num = *line;
  66237. if (num == 0)
  66238. continue;
  66239. int level = 0;
  66240. if (useNonZeroWinding)
  66241. {
  66242. while (--num > 0)
  66243. {
  66244. line += 2;
  66245. level += *line;
  66246. int corrected = abs (level);
  66247. if (corrected >> 8)
  66248. corrected = 255;
  66249. *line = corrected;
  66250. }
  66251. }
  66252. else
  66253. {
  66254. while (--num > 0)
  66255. {
  66256. line += 2;
  66257. level += *line;
  66258. int corrected = abs (level);
  66259. if (corrected >> 8)
  66260. {
  66261. corrected &= 511;
  66262. if (corrected >> 8)
  66263. corrected = 511 - corrected;
  66264. }
  66265. *line = corrected;
  66266. }
  66267. }
  66268. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  66269. }
  66270. }
  66271. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  66272. {
  66273. if (newNumEdgesPerLine != maxEdgesPerLine)
  66274. {
  66275. maxEdgesPerLine = newNumEdgesPerLine;
  66276. jassert (bounds.getHeight() > 0);
  66277. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66278. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66279. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66280. table.swapWith (newTable);
  66281. lineStrideElements = newLineStrideElements;
  66282. }
  66283. }
  66284. void EdgeTable::optimiseTable() throw()
  66285. {
  66286. int maxLineElements = 0;
  66287. for (int i = bounds.getHeight(); --i >= 0;)
  66288. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66289. remapTableForNumEdges (maxLineElements);
  66290. }
  66291. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  66292. {
  66293. jassert (y >= 0 && y < bounds.getHeight());
  66294. int* line = table + lineStrideElements * y;
  66295. const int numPoints = line[0];
  66296. int n = numPoints << 1;
  66297. if (n > 0)
  66298. {
  66299. while (n > 0)
  66300. {
  66301. const int cx = line [n - 1];
  66302. if (cx <= x)
  66303. {
  66304. if (cx == x)
  66305. {
  66306. line [n] += winding;
  66307. return;
  66308. }
  66309. break;
  66310. }
  66311. n -= 2;
  66312. }
  66313. if (numPoints >= maxEdgesPerLine)
  66314. {
  66315. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66316. jassert (numPoints < maxEdgesPerLine);
  66317. line = table + lineStrideElements * y;
  66318. }
  66319. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66320. }
  66321. line [n + 1] = x;
  66322. line [n + 2] = winding;
  66323. line[0]++;
  66324. }
  66325. void EdgeTable::translate (float dx, const int dy) throw()
  66326. {
  66327. bounds.translate ((int) std::floor (dx), dy);
  66328. int* lineStart = table;
  66329. const int intDx = (int) (dx * 256.0f);
  66330. for (int i = bounds.getHeight(); --i >= 0;)
  66331. {
  66332. int* line = lineStart;
  66333. lineStart += lineStrideElements;
  66334. int num = *line++;
  66335. while (--num >= 0)
  66336. {
  66337. *line += intDx;
  66338. line += 2;
  66339. }
  66340. }
  66341. }
  66342. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  66343. {
  66344. jassert (y >= 0 && y < bounds.getHeight());
  66345. int* dest = table + lineStrideElements * y;
  66346. if (dest[0] == 0)
  66347. return;
  66348. int otherNumPoints = *otherLine;
  66349. if (otherNumPoints == 0)
  66350. {
  66351. *dest = 0;
  66352. return;
  66353. }
  66354. const int right = bounds.getRight() << 8;
  66355. // optimise for the common case where our line lies entirely within a
  66356. // single pair of points, as happens when clipping to a simple rect.
  66357. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66358. {
  66359. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66360. return;
  66361. }
  66362. ++otherLine;
  66363. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66364. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66365. memcpy (temp, dest, lineSizeBytes);
  66366. const int* src1 = temp;
  66367. int srcNum1 = *src1++;
  66368. int x1 = *src1++;
  66369. const int* src2 = otherLine;
  66370. int srcNum2 = otherNumPoints;
  66371. int x2 = *src2++;
  66372. int destIndex = 0, destTotal = 0;
  66373. int level1 = 0, level2 = 0;
  66374. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66375. while (srcNum1 > 0 && srcNum2 > 0)
  66376. {
  66377. int nextX;
  66378. if (x1 < x2)
  66379. {
  66380. nextX = x1;
  66381. level1 = *src1++;
  66382. x1 = *src1++;
  66383. --srcNum1;
  66384. }
  66385. else if (x1 == x2)
  66386. {
  66387. nextX = x1;
  66388. level1 = *src1++;
  66389. level2 = *src2++;
  66390. x1 = *src1++;
  66391. x2 = *src2++;
  66392. --srcNum1;
  66393. --srcNum2;
  66394. }
  66395. else
  66396. {
  66397. nextX = x2;
  66398. level2 = *src2++;
  66399. x2 = *src2++;
  66400. --srcNum2;
  66401. }
  66402. if (nextX > lastX)
  66403. {
  66404. if (nextX >= right)
  66405. break;
  66406. lastX = nextX;
  66407. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66408. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66409. if (nextLevel != lastLevel)
  66410. {
  66411. if (destTotal >= maxEdgesPerLine)
  66412. {
  66413. dest[0] = destTotal;
  66414. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66415. dest = table + lineStrideElements * y;
  66416. }
  66417. ++destTotal;
  66418. lastLevel = nextLevel;
  66419. dest[++destIndex] = nextX;
  66420. dest[++destIndex] = nextLevel;
  66421. }
  66422. }
  66423. }
  66424. if (lastLevel > 0)
  66425. {
  66426. if (destTotal >= maxEdgesPerLine)
  66427. {
  66428. dest[0] = destTotal;
  66429. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66430. dest = table + lineStrideElements * y;
  66431. }
  66432. ++destTotal;
  66433. dest[++destIndex] = right;
  66434. dest[++destIndex] = 0;
  66435. }
  66436. dest[0] = destTotal;
  66437. #if JUCE_DEBUG
  66438. int last = std::numeric_limits<int>::min();
  66439. for (int i = 0; i < dest[0]; ++i)
  66440. {
  66441. jassert (dest[i * 2 + 1] > last);
  66442. last = dest[i * 2 + 1];
  66443. }
  66444. jassert (dest [dest[0] * 2] == 0);
  66445. #endif
  66446. }
  66447. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66448. {
  66449. int* lastItem = dest + (dest[0] * 2 - 1);
  66450. if (x2 < lastItem[0])
  66451. {
  66452. if (x2 <= dest[1])
  66453. {
  66454. dest[0] = 0;
  66455. return;
  66456. }
  66457. while (x2 < lastItem[-2])
  66458. {
  66459. --(dest[0]);
  66460. lastItem -= 2;
  66461. }
  66462. lastItem[0] = x2;
  66463. lastItem[1] = 0;
  66464. }
  66465. if (x1 > dest[1])
  66466. {
  66467. while (lastItem[0] > x1)
  66468. lastItem -= 2;
  66469. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66470. if (itemsRemoved > 0)
  66471. {
  66472. dest[0] -= itemsRemoved;
  66473. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66474. }
  66475. dest[1] = x1;
  66476. }
  66477. }
  66478. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66479. {
  66480. const Rectangle<int> clipped (r.getIntersection (bounds));
  66481. if (clipped.isEmpty())
  66482. {
  66483. needToCheckEmptinesss = false;
  66484. bounds.setHeight (0);
  66485. }
  66486. else
  66487. {
  66488. const int top = clipped.getY() - bounds.getY();
  66489. const int bottom = clipped.getBottom() - bounds.getY();
  66490. if (bottom < bounds.getHeight())
  66491. bounds.setHeight (bottom);
  66492. if (clipped.getRight() < bounds.getRight())
  66493. bounds.setRight (clipped.getRight());
  66494. for (int i = top; --i >= 0;)
  66495. table [lineStrideElements * i] = 0;
  66496. if (clipped.getX() > bounds.getX())
  66497. {
  66498. const int x1 = clipped.getX() << 8;
  66499. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66500. int* line = table + lineStrideElements * top;
  66501. for (int i = bottom - top; --i >= 0;)
  66502. {
  66503. if (line[0] != 0)
  66504. clipEdgeTableLineToRange (line, x1, x2);
  66505. line += lineStrideElements;
  66506. }
  66507. }
  66508. needToCheckEmptinesss = true;
  66509. }
  66510. }
  66511. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66512. {
  66513. const Rectangle<int> clipped (r.getIntersection (bounds));
  66514. if (! clipped.isEmpty())
  66515. {
  66516. const int top = clipped.getY() - bounds.getY();
  66517. const int bottom = clipped.getBottom() - bounds.getY();
  66518. //XXX optimise here by shortening the table if it fills top or bottom
  66519. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66520. clipped.getX() << 8, 0,
  66521. clipped.getRight() << 8, 255,
  66522. std::numeric_limits<int>::max(), 0 };
  66523. for (int i = top; i < bottom; ++i)
  66524. intersectWithEdgeTableLine (i, rectLine);
  66525. needToCheckEmptinesss = true;
  66526. }
  66527. }
  66528. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66529. {
  66530. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66531. if (clipped.isEmpty())
  66532. {
  66533. needToCheckEmptinesss = false;
  66534. bounds.setHeight (0);
  66535. }
  66536. else
  66537. {
  66538. const int top = clipped.getY() - bounds.getY();
  66539. const int bottom = clipped.getBottom() - bounds.getY();
  66540. if (bottom < bounds.getHeight())
  66541. bounds.setHeight (bottom);
  66542. if (clipped.getRight() < bounds.getRight())
  66543. bounds.setRight (clipped.getRight());
  66544. int i = 0;
  66545. for (i = top; --i >= 0;)
  66546. table [lineStrideElements * i] = 0;
  66547. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66548. for (i = top; i < bottom; ++i)
  66549. {
  66550. intersectWithEdgeTableLine (i, otherLine);
  66551. otherLine += other.lineStrideElements;
  66552. }
  66553. needToCheckEmptinesss = true;
  66554. }
  66555. }
  66556. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66557. {
  66558. y -= bounds.getY();
  66559. if (y < 0 || y >= bounds.getHeight())
  66560. return;
  66561. needToCheckEmptinesss = true;
  66562. if (numPixels <= 0)
  66563. {
  66564. table [lineStrideElements * y] = 0;
  66565. return;
  66566. }
  66567. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66568. int destIndex = 0, lastLevel = 0;
  66569. while (--numPixels >= 0)
  66570. {
  66571. const int alpha = *mask;
  66572. mask += maskStride;
  66573. if (alpha != lastLevel)
  66574. {
  66575. tempLine[++destIndex] = (x << 8);
  66576. tempLine[++destIndex] = alpha;
  66577. lastLevel = alpha;
  66578. }
  66579. ++x;
  66580. }
  66581. if (lastLevel > 0)
  66582. {
  66583. tempLine[++destIndex] = (x << 8);
  66584. tempLine[++destIndex] = 0;
  66585. }
  66586. tempLine[0] = destIndex >> 1;
  66587. intersectWithEdgeTableLine (y, tempLine);
  66588. }
  66589. bool EdgeTable::isEmpty() throw()
  66590. {
  66591. if (needToCheckEmptinesss)
  66592. {
  66593. needToCheckEmptinesss = false;
  66594. int* t = table;
  66595. for (int i = bounds.getHeight(); --i >= 0;)
  66596. {
  66597. if (t[0] > 1)
  66598. return false;
  66599. t += lineStrideElements;
  66600. }
  66601. bounds.setHeight (0);
  66602. }
  66603. return bounds.getHeight() == 0;
  66604. }
  66605. END_JUCE_NAMESPACE
  66606. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66607. /*** Start of inlined file: juce_FillType.cpp ***/
  66608. BEGIN_JUCE_NAMESPACE
  66609. FillType::FillType() throw()
  66610. : colour (0xff000000), image (0)
  66611. {
  66612. }
  66613. FillType::FillType (const Colour& colour_) throw()
  66614. : colour (colour_), image (0)
  66615. {
  66616. }
  66617. FillType::FillType (const ColourGradient& gradient_)
  66618. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66619. {
  66620. }
  66621. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66622. : colour (0xff000000), image (image_), transform (transform_)
  66623. {
  66624. }
  66625. FillType::FillType (const FillType& other)
  66626. : colour (other.colour),
  66627. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66628. image (other.image), transform (other.transform)
  66629. {
  66630. }
  66631. FillType& FillType::operator= (const FillType& other)
  66632. {
  66633. if (this != &other)
  66634. {
  66635. colour = other.colour;
  66636. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66637. image = other.image;
  66638. transform = other.transform;
  66639. }
  66640. return *this;
  66641. }
  66642. FillType::~FillType() throw()
  66643. {
  66644. }
  66645. bool FillType::operator== (const FillType& other) const
  66646. {
  66647. return colour == other.colour && image == other.image
  66648. && transform == other.transform
  66649. && (gradient == other.gradient
  66650. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66651. }
  66652. bool FillType::operator!= (const FillType& other) const
  66653. {
  66654. return ! operator== (other);
  66655. }
  66656. void FillType::setColour (const Colour& newColour) throw()
  66657. {
  66658. gradient = 0;
  66659. image = Image::null;
  66660. colour = newColour;
  66661. }
  66662. void FillType::setGradient (const ColourGradient& newGradient)
  66663. {
  66664. if (gradient != 0)
  66665. {
  66666. *gradient = newGradient;
  66667. }
  66668. else
  66669. {
  66670. image = Image::null;
  66671. gradient = new ColourGradient (newGradient);
  66672. colour = Colours::black;
  66673. }
  66674. }
  66675. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66676. {
  66677. gradient = 0;
  66678. image = image_;
  66679. transform = transform_;
  66680. colour = Colours::black;
  66681. }
  66682. void FillType::setOpacity (const float newOpacity) throw()
  66683. {
  66684. colour = colour.withAlpha (newOpacity);
  66685. }
  66686. bool FillType::isInvisible() const throw()
  66687. {
  66688. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66689. }
  66690. END_JUCE_NAMESPACE
  66691. /*** End of inlined file: juce_FillType.cpp ***/
  66692. /*** Start of inlined file: juce_Graphics.cpp ***/
  66693. BEGIN_JUCE_NAMESPACE
  66694. template <typename Type>
  66695. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66696. {
  66697. const int maxVal = 0x3fffffff;
  66698. return (int) x >= -maxVal && (int) x <= maxVal
  66699. && (int) y >= -maxVal && (int) y <= maxVal
  66700. && (int) w >= -maxVal && (int) w <= maxVal
  66701. && (int) h >= -maxVal && (int) h <= maxVal;
  66702. }
  66703. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66704. {
  66705. }
  66706. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66707. {
  66708. }
  66709. Graphics::Graphics (const Image& imageToDrawOnto)
  66710. : context (imageToDrawOnto.createLowLevelContext()),
  66711. contextToDelete (context),
  66712. saveStatePending (false)
  66713. {
  66714. }
  66715. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66716. : context (internalContext),
  66717. saveStatePending (false)
  66718. {
  66719. }
  66720. Graphics::~Graphics()
  66721. {
  66722. }
  66723. void Graphics::resetToDefaultState()
  66724. {
  66725. saveStateIfPending();
  66726. context->setFill (FillType());
  66727. context->setFont (Font());
  66728. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66729. }
  66730. bool Graphics::isVectorDevice() const
  66731. {
  66732. return context->isVectorDevice();
  66733. }
  66734. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66735. {
  66736. saveStateIfPending();
  66737. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66738. }
  66739. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66740. {
  66741. saveStateIfPending();
  66742. return context->clipToRectangleList (clipRegion);
  66743. }
  66744. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66745. {
  66746. saveStateIfPending();
  66747. context->clipToPath (path, transform);
  66748. return ! context->isClipEmpty();
  66749. }
  66750. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66751. {
  66752. saveStateIfPending();
  66753. context->clipToImageAlpha (image, transform);
  66754. return ! context->isClipEmpty();
  66755. }
  66756. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66757. {
  66758. saveStateIfPending();
  66759. context->excludeClipRectangle (rectangleToExclude);
  66760. }
  66761. bool Graphics::isClipEmpty() const
  66762. {
  66763. return context->isClipEmpty();
  66764. }
  66765. const Rectangle<int> Graphics::getClipBounds() const
  66766. {
  66767. return context->getClipBounds();
  66768. }
  66769. void Graphics::saveState()
  66770. {
  66771. saveStateIfPending();
  66772. saveStatePending = true;
  66773. }
  66774. void Graphics::restoreState()
  66775. {
  66776. if (saveStatePending)
  66777. saveStatePending = false;
  66778. else
  66779. context->restoreState();
  66780. }
  66781. void Graphics::saveStateIfPending()
  66782. {
  66783. if (saveStatePending)
  66784. {
  66785. saveStatePending = false;
  66786. context->saveState();
  66787. }
  66788. }
  66789. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66790. {
  66791. saveStateIfPending();
  66792. context->setOrigin (newOriginX, newOriginY);
  66793. }
  66794. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66795. {
  66796. return context->clipRegionIntersects (area);
  66797. }
  66798. void Graphics::setColour (const Colour& newColour)
  66799. {
  66800. saveStateIfPending();
  66801. context->setFill (newColour);
  66802. }
  66803. void Graphics::setOpacity (const float newOpacity)
  66804. {
  66805. saveStateIfPending();
  66806. context->setOpacity (newOpacity);
  66807. }
  66808. void Graphics::setGradientFill (const ColourGradient& gradient)
  66809. {
  66810. setFillType (gradient);
  66811. }
  66812. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66813. {
  66814. saveStateIfPending();
  66815. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66816. context->setOpacity (opacity);
  66817. }
  66818. void Graphics::setFillType (const FillType& newFill)
  66819. {
  66820. saveStateIfPending();
  66821. context->setFill (newFill);
  66822. }
  66823. void Graphics::setFont (const Font& newFont)
  66824. {
  66825. saveStateIfPending();
  66826. context->setFont (newFont);
  66827. }
  66828. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66829. {
  66830. saveStateIfPending();
  66831. Font f (context->getFont());
  66832. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66833. context->setFont (f);
  66834. }
  66835. const Font Graphics::getCurrentFont() const
  66836. {
  66837. return context->getFont();
  66838. }
  66839. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66840. {
  66841. if (text.isNotEmpty()
  66842. && startX < context->getClipBounds().getRight())
  66843. {
  66844. GlyphArrangement arr;
  66845. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66846. arr.draw (*this);
  66847. }
  66848. }
  66849. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66850. {
  66851. if (text.isNotEmpty())
  66852. {
  66853. GlyphArrangement arr;
  66854. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66855. arr.draw (*this, transform);
  66856. }
  66857. }
  66858. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66859. {
  66860. if (text.isNotEmpty()
  66861. && startX < context->getClipBounds().getRight())
  66862. {
  66863. GlyphArrangement arr;
  66864. arr.addJustifiedText (context->getFont(), text,
  66865. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66866. Justification::left);
  66867. arr.draw (*this);
  66868. }
  66869. }
  66870. void Graphics::drawText (const String& text,
  66871. const int x, const int y, const int width, const int height,
  66872. const Justification& justificationType,
  66873. const bool useEllipsesIfTooBig) const
  66874. {
  66875. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66876. {
  66877. GlyphArrangement arr;
  66878. arr.addCurtailedLineOfText (context->getFont(), text,
  66879. 0.0f, 0.0f, (float) width,
  66880. useEllipsesIfTooBig);
  66881. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66882. (float) x, (float) y, (float) width, (float) height,
  66883. justificationType);
  66884. arr.draw (*this);
  66885. }
  66886. }
  66887. void Graphics::drawFittedText (const String& text,
  66888. const int x, const int y, const int width, const int height,
  66889. const Justification& justification,
  66890. const int maximumNumberOfLines,
  66891. const float minimumHorizontalScale) const
  66892. {
  66893. if (text.isNotEmpty()
  66894. && width > 0 && height > 0
  66895. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66896. {
  66897. GlyphArrangement arr;
  66898. arr.addFittedText (context->getFont(), text,
  66899. (float) x, (float) y, (float) width, (float) height,
  66900. justification,
  66901. maximumNumberOfLines,
  66902. minimumHorizontalScale);
  66903. arr.draw (*this);
  66904. }
  66905. }
  66906. void Graphics::fillRect (int x, int y, int width, int height) const
  66907. {
  66908. // passing in a silly number can cause maths problems in rendering!
  66909. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66910. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66911. }
  66912. void Graphics::fillRect (const Rectangle<int>& r) const
  66913. {
  66914. context->fillRect (r, false);
  66915. }
  66916. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66917. {
  66918. // passing in a silly number can cause maths problems in rendering!
  66919. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66920. Path p;
  66921. p.addRectangle (x, y, width, height);
  66922. fillPath (p);
  66923. }
  66924. void Graphics::setPixel (int x, int y) const
  66925. {
  66926. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66927. }
  66928. void Graphics::fillAll() const
  66929. {
  66930. fillRect (context->getClipBounds());
  66931. }
  66932. void Graphics::fillAll (const Colour& colourToUse) const
  66933. {
  66934. if (! colourToUse.isTransparent())
  66935. {
  66936. const Rectangle<int> clip (context->getClipBounds());
  66937. context->saveState();
  66938. context->setFill (colourToUse);
  66939. context->fillRect (clip, false);
  66940. context->restoreState();
  66941. }
  66942. }
  66943. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66944. {
  66945. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66946. context->fillPath (path, transform);
  66947. }
  66948. void Graphics::strokePath (const Path& path,
  66949. const PathStrokeType& strokeType,
  66950. const AffineTransform& transform) const
  66951. {
  66952. Path stroke;
  66953. strokeType.createStrokedPath (stroke, path, transform);
  66954. fillPath (stroke);
  66955. }
  66956. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66957. const int lineThickness) const
  66958. {
  66959. // passing in a silly number can cause maths problems in rendering!
  66960. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66961. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66962. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66963. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66964. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66965. }
  66966. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66967. {
  66968. // passing in a silly number can cause maths problems in rendering!
  66969. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66970. Path p;
  66971. p.addRectangle (x, y, width, lineThickness);
  66972. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66973. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66974. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66975. fillPath (p);
  66976. }
  66977. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66978. {
  66979. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66980. }
  66981. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66982. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66983. const bool useGradient, const bool sharpEdgeOnOutside) const
  66984. {
  66985. // passing in a silly number can cause maths problems in rendering!
  66986. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66987. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66988. {
  66989. context->saveState();
  66990. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66991. const float ramp = oldOpacity / bevelThickness;
  66992. for (int i = bevelThickness; --i >= 0;)
  66993. {
  66994. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66995. : oldOpacity;
  66996. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66997. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66998. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66999. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  67000. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  67001. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  67002. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  67003. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  67004. }
  67005. context->restoreState();
  67006. }
  67007. }
  67008. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  67009. {
  67010. // passing in a silly number can cause maths problems in rendering!
  67011. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67012. Path p;
  67013. p.addEllipse (x, y, width, height);
  67014. fillPath (p);
  67015. }
  67016. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  67017. const float lineThickness) const
  67018. {
  67019. // passing in a silly number can cause maths problems in rendering!
  67020. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67021. Path p;
  67022. p.addEllipse (x, y, width, height);
  67023. strokePath (p, PathStrokeType (lineThickness));
  67024. }
  67025. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  67026. {
  67027. // passing in a silly number can cause maths problems in rendering!
  67028. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67029. Path p;
  67030. p.addRoundedRectangle (x, y, width, height, cornerSize);
  67031. fillPath (p);
  67032. }
  67033. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  67034. {
  67035. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  67036. }
  67037. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  67038. const float cornerSize, const float lineThickness) const
  67039. {
  67040. // passing in a silly number can cause maths problems in rendering!
  67041. jassert (areCoordsSensibleNumbers (x, y, width, height));
  67042. Path p;
  67043. p.addRoundedRectangle (x, y, width, height, cornerSize);
  67044. strokePath (p, PathStrokeType (lineThickness));
  67045. }
  67046. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  67047. {
  67048. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  67049. }
  67050. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  67051. {
  67052. Path p;
  67053. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  67054. fillPath (p);
  67055. }
  67056. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  67057. const int checkWidth, const int checkHeight,
  67058. const Colour& colour1, const Colour& colour2) const
  67059. {
  67060. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  67061. if (checkWidth > 0 && checkHeight > 0)
  67062. {
  67063. context->saveState();
  67064. if (colour1 == colour2)
  67065. {
  67066. context->setFill (colour1);
  67067. context->fillRect (area, false);
  67068. }
  67069. else
  67070. {
  67071. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  67072. if (! clipped.isEmpty())
  67073. {
  67074. context->clipToRectangle (clipped);
  67075. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  67076. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  67077. const int startX = area.getX() + checkNumX * checkWidth;
  67078. const int startY = area.getY() + checkNumY * checkHeight;
  67079. const int right = clipped.getRight();
  67080. const int bottom = clipped.getBottom();
  67081. for (int i = 0; i < 2; ++i)
  67082. {
  67083. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  67084. int cy = i;
  67085. for (int y = startY; y < bottom; y += checkHeight)
  67086. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  67087. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  67088. }
  67089. }
  67090. }
  67091. context->restoreState();
  67092. }
  67093. }
  67094. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  67095. {
  67096. context->drawVerticalLine (x, top, bottom);
  67097. }
  67098. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  67099. {
  67100. context->drawHorizontalLine (y, left, right);
  67101. }
  67102. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  67103. {
  67104. context->drawLine (Line<float> (x1, y1, x2, y2));
  67105. }
  67106. void Graphics::drawLine (const float startX, const float startY,
  67107. const float endX, const float endY,
  67108. const float lineThickness) const
  67109. {
  67110. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  67111. }
  67112. void Graphics::drawLine (const Line<float>& line) const
  67113. {
  67114. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  67115. }
  67116. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  67117. {
  67118. Path p;
  67119. p.addLineSegment (line, lineThickness);
  67120. fillPath (p);
  67121. }
  67122. void Graphics::drawDashedLine (const float startX, const float startY,
  67123. const float endX, const float endY,
  67124. const float* const dashLengths,
  67125. const int numDashLengths,
  67126. const float lineThickness) const
  67127. {
  67128. const double dx = endX - startX;
  67129. const double dy = endY - startY;
  67130. const double totalLen = juce_hypot (dx, dy);
  67131. if (totalLen >= 0.5)
  67132. {
  67133. const double onePixAlpha = 1.0 / totalLen;
  67134. double alpha = 0.0;
  67135. float x = startX;
  67136. float y = startY;
  67137. int n = 0;
  67138. while (alpha < 1.0f)
  67139. {
  67140. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  67141. n = n % numDashLengths;
  67142. const float oldX = x;
  67143. const float oldY = y;
  67144. x = (float) (startX + dx * alpha);
  67145. y = (float) (startY + dy * alpha);
  67146. if ((n & 1) != 0)
  67147. {
  67148. if (lineThickness != 1.0f)
  67149. drawLine (oldX, oldY, x, y, lineThickness);
  67150. else
  67151. drawLine (oldX, oldY, x, y);
  67152. }
  67153. }
  67154. }
  67155. }
  67156. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  67157. {
  67158. saveStateIfPending();
  67159. context->setInterpolationQuality (newQuality);
  67160. }
  67161. void Graphics::drawImageAt (const Image& imageToDraw,
  67162. const int topLeftX, const int topLeftY,
  67163. const bool fillAlphaChannelWithCurrentBrush) const
  67164. {
  67165. const int imageW = imageToDraw.getWidth();
  67166. const int imageH = imageToDraw.getHeight();
  67167. drawImage (imageToDraw,
  67168. topLeftX, topLeftY, imageW, imageH,
  67169. 0, 0, imageW, imageH,
  67170. fillAlphaChannelWithCurrentBrush);
  67171. }
  67172. void Graphics::drawImageWithin (const Image& imageToDraw,
  67173. const int destX, const int destY,
  67174. const int destW, const int destH,
  67175. const RectanglePlacement& placementWithinTarget,
  67176. const bool fillAlphaChannelWithCurrentBrush) const
  67177. {
  67178. // passing in a silly number can cause maths problems in rendering!
  67179. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  67180. if (imageToDraw.isValid())
  67181. {
  67182. const int imageW = imageToDraw.getWidth();
  67183. const int imageH = imageToDraw.getHeight();
  67184. if (imageW > 0 && imageH > 0)
  67185. {
  67186. double newX = 0.0, newY = 0.0;
  67187. double newW = imageW;
  67188. double newH = imageH;
  67189. placementWithinTarget.applyTo (newX, newY, newW, newH,
  67190. destX, destY, destW, destH);
  67191. if (newW > 0 && newH > 0)
  67192. {
  67193. drawImage (imageToDraw,
  67194. roundToInt (newX), roundToInt (newY),
  67195. roundToInt (newW), roundToInt (newH),
  67196. 0, 0, imageW, imageH,
  67197. fillAlphaChannelWithCurrentBrush);
  67198. }
  67199. }
  67200. }
  67201. }
  67202. void Graphics::drawImage (const Image& imageToDraw,
  67203. int dx, int dy, int dw, int dh,
  67204. int sx, int sy, int sw, int sh,
  67205. const bool fillAlphaChannelWithCurrentBrush) const
  67206. {
  67207. // passing in a silly number can cause maths problems in rendering!
  67208. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  67209. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  67210. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  67211. {
  67212. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  67213. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  67214. .translated ((float) dx, (float) dy),
  67215. fillAlphaChannelWithCurrentBrush);
  67216. }
  67217. }
  67218. void Graphics::drawImageTransformed (const Image& imageToDraw,
  67219. const AffineTransform& transform,
  67220. const bool fillAlphaChannelWithCurrentBrush) const
  67221. {
  67222. if (imageToDraw.isValid() && ! context->isClipEmpty())
  67223. {
  67224. if (fillAlphaChannelWithCurrentBrush)
  67225. {
  67226. context->saveState();
  67227. context->clipToImageAlpha (imageToDraw, transform);
  67228. fillAll();
  67229. context->restoreState();
  67230. }
  67231. else
  67232. {
  67233. context->drawImage (imageToDraw, transform, false);
  67234. }
  67235. }
  67236. }
  67237. END_JUCE_NAMESPACE
  67238. /*** End of inlined file: juce_Graphics.cpp ***/
  67239. /*** Start of inlined file: juce_Justification.cpp ***/
  67240. BEGIN_JUCE_NAMESPACE
  67241. Justification::Justification (const Justification& other) throw()
  67242. : flags (other.flags)
  67243. {
  67244. }
  67245. Justification& Justification::operator= (const Justification& other) throw()
  67246. {
  67247. flags = other.flags;
  67248. return *this;
  67249. }
  67250. int Justification::getOnlyVerticalFlags() const throw()
  67251. {
  67252. return flags & (top | bottom | verticallyCentred);
  67253. }
  67254. int Justification::getOnlyHorizontalFlags() const throw()
  67255. {
  67256. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  67257. }
  67258. void Justification::applyToRectangle (int& x, int& y,
  67259. const int w, const int h,
  67260. const int spaceX, const int spaceY,
  67261. const int spaceW, const int spaceH) const throw()
  67262. {
  67263. if ((flags & horizontallyCentred) != 0)
  67264. x = spaceX + ((spaceW - w) >> 1);
  67265. else if ((flags & right) != 0)
  67266. x = spaceX + spaceW - w;
  67267. else
  67268. x = spaceX;
  67269. if ((flags & verticallyCentred) != 0)
  67270. y = spaceY + ((spaceH - h) >> 1);
  67271. else if ((flags & bottom) != 0)
  67272. y = spaceY + spaceH - h;
  67273. else
  67274. y = spaceY;
  67275. }
  67276. END_JUCE_NAMESPACE
  67277. /*** End of inlined file: juce_Justification.cpp ***/
  67278. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67279. BEGIN_JUCE_NAMESPACE
  67280. // this will throw an assertion if you try to draw something that's not
  67281. // possible in postscript
  67282. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67283. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67284. #define notPossibleInPostscriptAssert jassertfalse
  67285. #else
  67286. #define notPossibleInPostscriptAssert
  67287. #endif
  67288. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67289. const String& documentTitle,
  67290. const int totalWidth_,
  67291. const int totalHeight_)
  67292. : out (resultingPostScript),
  67293. totalWidth (totalWidth_),
  67294. totalHeight (totalHeight_),
  67295. needToClip (true)
  67296. {
  67297. stateStack.add (new SavedState());
  67298. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67299. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67300. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67301. "\n%%BoundingBox: 0 0 600 824"
  67302. "\n%%Pages: 0"
  67303. "\n%%Creator: Raw Material Software JUCE"
  67304. "\n%%Title: " << documentTitle <<
  67305. "\n%%CreationDate: none"
  67306. "\n%%LanguageLevel: 2"
  67307. "\n%%EndComments"
  67308. "\n%%BeginProlog"
  67309. "\n%%BeginResource: JRes"
  67310. "\n/bd {bind def} bind def"
  67311. "\n/c {setrgbcolor} bd"
  67312. "\n/m {moveto} bd"
  67313. "\n/l {lineto} bd"
  67314. "\n/rl {rlineto} bd"
  67315. "\n/ct {curveto} bd"
  67316. "\n/cp {closepath} bd"
  67317. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67318. "\n/doclip {initclip newpath} bd"
  67319. "\n/endclip {clip newpath} bd"
  67320. "\n%%EndResource"
  67321. "\n%%EndProlog"
  67322. "\n%%BeginSetup"
  67323. "\n%%EndSetup"
  67324. "\n%%Page: 1 1"
  67325. "\n%%BeginPageSetup"
  67326. "\n%%EndPageSetup\n\n"
  67327. << "40 800 translate\n"
  67328. << scale << ' ' << scale << " scale\n\n";
  67329. }
  67330. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67331. {
  67332. }
  67333. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67334. {
  67335. return true;
  67336. }
  67337. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67338. {
  67339. if (x != 0 || y != 0)
  67340. {
  67341. stateStack.getLast()->xOffset += x;
  67342. stateStack.getLast()->yOffset += y;
  67343. needToClip = true;
  67344. }
  67345. }
  67346. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67347. {
  67348. needToClip = true;
  67349. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67350. }
  67351. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67352. {
  67353. needToClip = true;
  67354. return stateStack.getLast()->clip.clipTo (clipRegion);
  67355. }
  67356. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67357. {
  67358. needToClip = true;
  67359. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67360. }
  67361. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67362. {
  67363. writeClip();
  67364. Path p (path);
  67365. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67366. writePath (p);
  67367. out << "clip\n";
  67368. }
  67369. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67370. {
  67371. needToClip = true;
  67372. jassertfalse; // xxx
  67373. }
  67374. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67375. {
  67376. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67377. }
  67378. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67379. {
  67380. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67381. -stateStack.getLast()->yOffset);
  67382. }
  67383. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67384. {
  67385. return stateStack.getLast()->clip.isEmpty();
  67386. }
  67387. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67388. : xOffset (0),
  67389. yOffset (0)
  67390. {
  67391. }
  67392. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67393. {
  67394. }
  67395. void LowLevelGraphicsPostScriptRenderer::saveState()
  67396. {
  67397. stateStack.add (new SavedState (*stateStack.getLast()));
  67398. }
  67399. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67400. {
  67401. jassert (stateStack.size() > 0);
  67402. if (stateStack.size() > 0)
  67403. stateStack.removeLast();
  67404. }
  67405. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67406. {
  67407. if (needToClip)
  67408. {
  67409. needToClip = false;
  67410. out << "doclip ";
  67411. int itemsOnLine = 0;
  67412. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67413. {
  67414. if (++itemsOnLine == 6)
  67415. {
  67416. itemsOnLine = 0;
  67417. out << '\n';
  67418. }
  67419. const Rectangle<int>& r = *i.getRectangle();
  67420. out << r.getX() << ' ' << -r.getY() << ' '
  67421. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67422. }
  67423. out << "endclip\n";
  67424. }
  67425. }
  67426. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67427. {
  67428. Colour c (Colours::white.overlaidWith (colour));
  67429. if (lastColour != c)
  67430. {
  67431. lastColour = c;
  67432. out << String (c.getFloatRed(), 3) << ' '
  67433. << String (c.getFloatGreen(), 3) << ' '
  67434. << String (c.getFloatBlue(), 3) << " c\n";
  67435. }
  67436. }
  67437. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67438. {
  67439. out << String (x, 2) << ' '
  67440. << String (-y, 2) << ' ';
  67441. }
  67442. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67443. {
  67444. out << "newpath ";
  67445. float lastX = 0.0f;
  67446. float lastY = 0.0f;
  67447. int itemsOnLine = 0;
  67448. Path::Iterator i (path);
  67449. while (i.next())
  67450. {
  67451. if (++itemsOnLine == 4)
  67452. {
  67453. itemsOnLine = 0;
  67454. out << '\n';
  67455. }
  67456. switch (i.elementType)
  67457. {
  67458. case Path::Iterator::startNewSubPath:
  67459. writeXY (i.x1, i.y1);
  67460. lastX = i.x1;
  67461. lastY = i.y1;
  67462. out << "m ";
  67463. break;
  67464. case Path::Iterator::lineTo:
  67465. writeXY (i.x1, i.y1);
  67466. lastX = i.x1;
  67467. lastY = i.y1;
  67468. out << "l ";
  67469. break;
  67470. case Path::Iterator::quadraticTo:
  67471. {
  67472. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67473. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67474. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67475. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67476. writeXY (cp1x, cp1y);
  67477. writeXY (cp2x, cp2y);
  67478. writeXY (i.x2, i.y2);
  67479. out << "ct ";
  67480. lastX = i.x2;
  67481. lastY = i.y2;
  67482. }
  67483. break;
  67484. case Path::Iterator::cubicTo:
  67485. writeXY (i.x1, i.y1);
  67486. writeXY (i.x2, i.y2);
  67487. writeXY (i.x3, i.y3);
  67488. out << "ct ";
  67489. lastX = i.x3;
  67490. lastY = i.y3;
  67491. break;
  67492. case Path::Iterator::closePath:
  67493. out << "cp ";
  67494. break;
  67495. default:
  67496. jassertfalse;
  67497. break;
  67498. }
  67499. }
  67500. out << '\n';
  67501. }
  67502. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67503. {
  67504. out << "[ "
  67505. << trans.mat00 << ' '
  67506. << trans.mat10 << ' '
  67507. << trans.mat01 << ' '
  67508. << trans.mat11 << ' '
  67509. << trans.mat02 << ' '
  67510. << trans.mat12 << " ] concat ";
  67511. }
  67512. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67513. {
  67514. stateStack.getLast()->fillType = fillType;
  67515. }
  67516. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67517. {
  67518. }
  67519. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67520. {
  67521. }
  67522. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67523. {
  67524. if (stateStack.getLast()->fillType.isColour())
  67525. {
  67526. writeClip();
  67527. writeColour (stateStack.getLast()->fillType.colour);
  67528. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67529. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67530. }
  67531. else
  67532. {
  67533. Path p;
  67534. p.addRectangle (r);
  67535. fillPath (p, AffineTransform::identity);
  67536. }
  67537. }
  67538. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67539. {
  67540. if (stateStack.getLast()->fillType.isColour())
  67541. {
  67542. writeClip();
  67543. Path p (path);
  67544. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67545. (float) stateStack.getLast()->yOffset));
  67546. writePath (p);
  67547. writeColour (stateStack.getLast()->fillType.colour);
  67548. out << "fill\n";
  67549. }
  67550. else if (stateStack.getLast()->fillType.isGradient())
  67551. {
  67552. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67553. // postscript can't do semi-transparent ones.
  67554. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67555. writeClip();
  67556. out << "gsave ";
  67557. {
  67558. Path p (path);
  67559. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67560. writePath (p);
  67561. out << "clip\n";
  67562. }
  67563. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67564. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67565. // time-being, this just fills it with the average colour..
  67566. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67567. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67568. out << "grestore\n";
  67569. }
  67570. }
  67571. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67572. const int sx, const int sy,
  67573. const int maxW, const int maxH) const
  67574. {
  67575. out << "{<\n";
  67576. const int w = jmin (maxW, im.getWidth());
  67577. const int h = jmin (maxH, im.getHeight());
  67578. int charsOnLine = 0;
  67579. const Image::BitmapData srcData (im, 0, 0, w, h);
  67580. Colour pixel;
  67581. for (int y = h; --y >= 0;)
  67582. {
  67583. for (int x = 0; x < w; ++x)
  67584. {
  67585. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67586. if (x >= sx && y >= sy)
  67587. {
  67588. if (im.isARGB())
  67589. {
  67590. PixelARGB p (*(const PixelARGB*) pixelData);
  67591. p.unpremultiply();
  67592. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67593. }
  67594. else if (im.isRGB())
  67595. {
  67596. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67597. }
  67598. else
  67599. {
  67600. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67601. }
  67602. }
  67603. else
  67604. {
  67605. pixel = Colours::transparentWhite;
  67606. }
  67607. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67608. out << String::toHexString (pixelValues, 3, 0);
  67609. charsOnLine += 3;
  67610. if (charsOnLine > 100)
  67611. {
  67612. out << '\n';
  67613. charsOnLine = 0;
  67614. }
  67615. }
  67616. }
  67617. out << "\n>}\n";
  67618. }
  67619. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67620. {
  67621. const int w = sourceImage.getWidth();
  67622. const int h = sourceImage.getHeight();
  67623. writeClip();
  67624. out << "gsave ";
  67625. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67626. .scaled (1.0f, -1.0f));
  67627. RectangleList imageClip;
  67628. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67629. out << "newpath ";
  67630. int itemsOnLine = 0;
  67631. for (RectangleList::Iterator i (imageClip); i.next();)
  67632. {
  67633. if (++itemsOnLine == 6)
  67634. {
  67635. out << '\n';
  67636. itemsOnLine = 0;
  67637. }
  67638. const Rectangle<int>& r = *i.getRectangle();
  67639. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67640. }
  67641. out << " clip newpath\n";
  67642. out << w << ' ' << h << " scale\n";
  67643. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67644. writeImage (sourceImage, 0, 0, w, h);
  67645. out << "false 3 colorimage grestore\n";
  67646. needToClip = true;
  67647. }
  67648. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67649. {
  67650. Path p;
  67651. p.addLineSegment (line, 1.0f);
  67652. fillPath (p, AffineTransform::identity);
  67653. }
  67654. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67655. {
  67656. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67657. }
  67658. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67659. {
  67660. drawLine (Line<float> (left, (float) y, right, (float) y));
  67661. }
  67662. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67663. {
  67664. stateStack.getLast()->font = newFont;
  67665. }
  67666. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67667. {
  67668. return stateStack.getLast()->font;
  67669. }
  67670. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67671. {
  67672. Path p;
  67673. Font& font = stateStack.getLast()->font;
  67674. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67675. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67676. }
  67677. END_JUCE_NAMESPACE
  67678. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67679. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67680. BEGIN_JUCE_NAMESPACE
  67681. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67682. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67683. #endif
  67684. #if JUCE_MSVC
  67685. #pragma warning (push)
  67686. #pragma warning (disable: 4127) // "expression is constant" warning
  67687. #if JUCE_DEBUG
  67688. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67689. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67690. #endif
  67691. #endif
  67692. namespace SoftwareRendererClasses
  67693. {
  67694. template <class PixelType, bool replaceExisting = false>
  67695. class SolidColourEdgeTableRenderer
  67696. {
  67697. public:
  67698. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67699. : data (data_),
  67700. sourceColour (colour)
  67701. {
  67702. if (sizeof (PixelType) == 3)
  67703. {
  67704. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67705. && sourceColour.getGreen() == sourceColour.getBlue();
  67706. filler[0].set (sourceColour);
  67707. filler[1].set (sourceColour);
  67708. filler[2].set (sourceColour);
  67709. filler[3].set (sourceColour);
  67710. }
  67711. }
  67712. forcedinline void setEdgeTableYPos (const int y) throw()
  67713. {
  67714. linePixels = (PixelType*) data.getLinePointer (y);
  67715. }
  67716. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67717. {
  67718. if (replaceExisting)
  67719. linePixels[x].set (sourceColour);
  67720. else
  67721. linePixels[x].blend (sourceColour, alphaLevel);
  67722. }
  67723. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67724. {
  67725. if (replaceExisting)
  67726. linePixels[x].set (sourceColour);
  67727. else
  67728. linePixels[x].blend (sourceColour);
  67729. }
  67730. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67731. {
  67732. PixelARGB p (sourceColour);
  67733. p.multiplyAlpha (alphaLevel);
  67734. PixelType* dest = linePixels + x;
  67735. if (replaceExisting || p.getAlpha() >= 0xff)
  67736. replaceLine (dest, p, width);
  67737. else
  67738. blendLine (dest, p, width);
  67739. }
  67740. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67741. {
  67742. PixelType* dest = linePixels + x;
  67743. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67744. replaceLine (dest, sourceColour, width);
  67745. else
  67746. blendLine (dest, sourceColour, width);
  67747. }
  67748. private:
  67749. const Image::BitmapData& data;
  67750. PixelType* linePixels;
  67751. PixelARGB sourceColour;
  67752. PixelRGB filler [4];
  67753. bool areRGBComponentsEqual;
  67754. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67755. {
  67756. do
  67757. {
  67758. dest->blend (colour);
  67759. ++dest;
  67760. } while (--width > 0);
  67761. }
  67762. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67763. {
  67764. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67765. {
  67766. memset (dest, colour.getRed(), width * 3);
  67767. }
  67768. else
  67769. {
  67770. if (width >> 5)
  67771. {
  67772. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67773. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67774. {
  67775. dest->set (colour);
  67776. ++dest;
  67777. --width;
  67778. }
  67779. while (width > 4)
  67780. {
  67781. int* d = reinterpret_cast<int*> (dest);
  67782. *d++ = intFiller[0];
  67783. *d++ = intFiller[1];
  67784. *d++ = intFiller[2];
  67785. dest = reinterpret_cast<PixelRGB*> (d);
  67786. width -= 4;
  67787. }
  67788. }
  67789. while (--width >= 0)
  67790. {
  67791. dest->set (colour);
  67792. ++dest;
  67793. }
  67794. }
  67795. }
  67796. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67797. {
  67798. memset (dest, colour.getAlpha(), width);
  67799. }
  67800. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67801. {
  67802. do
  67803. {
  67804. dest->set (colour);
  67805. ++dest;
  67806. } while (--width > 0);
  67807. }
  67808. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67809. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67810. };
  67811. class LinearGradientPixelGenerator
  67812. {
  67813. public:
  67814. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67815. : lookupTable (lookupTable_), numEntries (numEntries_)
  67816. {
  67817. jassert (numEntries_ >= 0);
  67818. Point<float> p1 (gradient.point1);
  67819. Point<float> p2 (gradient.point2);
  67820. if (! transform.isIdentity())
  67821. {
  67822. const Line<float> l (p2, p1);
  67823. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67824. p1.applyTransform (transform);
  67825. p2.applyTransform (transform);
  67826. p3.applyTransform (transform);
  67827. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67828. }
  67829. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67830. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67831. if (vertical)
  67832. {
  67833. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67834. start = roundToInt (p1.getY() * scale);
  67835. }
  67836. else if (horizontal)
  67837. {
  67838. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67839. start = roundToInt (p1.getX() * scale);
  67840. }
  67841. else
  67842. {
  67843. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67844. yTerm = p1.getY() - p1.getX() / grad;
  67845. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67846. grad *= scale;
  67847. }
  67848. }
  67849. forcedinline void setY (const int y) throw()
  67850. {
  67851. if (vertical)
  67852. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67853. else if (! horizontal)
  67854. start = roundToInt ((y - yTerm) * grad);
  67855. }
  67856. inline const PixelARGB getPixel (const int x) const throw()
  67857. {
  67858. return vertical ? linePix
  67859. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67860. }
  67861. private:
  67862. const PixelARGB* const lookupTable;
  67863. const int numEntries;
  67864. PixelARGB linePix;
  67865. int start, scale;
  67866. double grad, yTerm;
  67867. bool vertical, horizontal;
  67868. enum { numScaleBits = 12 };
  67869. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67870. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67871. };
  67872. class RadialGradientPixelGenerator
  67873. {
  67874. public:
  67875. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67876. const PixelARGB* const lookupTable_, const int numEntries_)
  67877. : lookupTable (lookupTable_),
  67878. numEntries (numEntries_),
  67879. gx1 (gradient.point1.getX()),
  67880. gy1 (gradient.point1.getY())
  67881. {
  67882. jassert (numEntries_ >= 0);
  67883. const Point<float> diff (gradient.point1 - gradient.point2);
  67884. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67885. invScale = numEntries / std::sqrt (maxDist);
  67886. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67887. }
  67888. forcedinline void setY (const int y) throw()
  67889. {
  67890. dy = y - gy1;
  67891. dy *= dy;
  67892. }
  67893. inline const PixelARGB getPixel (const int px) const throw()
  67894. {
  67895. double x = px - gx1;
  67896. x *= x;
  67897. x += dy;
  67898. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67899. }
  67900. protected:
  67901. const PixelARGB* const lookupTable;
  67902. const int numEntries;
  67903. const double gx1, gy1;
  67904. double maxDist, invScale, dy;
  67905. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67906. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67907. };
  67908. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67909. {
  67910. public:
  67911. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67912. const PixelARGB* const lookupTable_, const int numEntries_)
  67913. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67914. inverseTransform (transform.inverted())
  67915. {
  67916. tM10 = inverseTransform.mat10;
  67917. tM00 = inverseTransform.mat00;
  67918. }
  67919. forcedinline void setY (const int y) throw()
  67920. {
  67921. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67922. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67923. }
  67924. inline const PixelARGB getPixel (const int px) const throw()
  67925. {
  67926. double x = px;
  67927. const double y = tM10 * x + lineYM11;
  67928. x = tM00 * x + lineYM01;
  67929. x *= x;
  67930. x += y * y;
  67931. if (x >= maxDist)
  67932. return lookupTable [numEntries];
  67933. else
  67934. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67935. }
  67936. private:
  67937. double tM10, tM00, lineYM01, lineYM11;
  67938. const AffineTransform inverseTransform;
  67939. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67940. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67941. };
  67942. template <class PixelType, class GradientType>
  67943. class GradientEdgeTableRenderer : public GradientType
  67944. {
  67945. public:
  67946. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67947. const PixelARGB* const lookupTable_, const int numEntries_)
  67948. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67949. destData (destData_)
  67950. {
  67951. }
  67952. forcedinline void setEdgeTableYPos (const int y) throw()
  67953. {
  67954. linePixels = (PixelType*) destData.getLinePointer (y);
  67955. GradientType::setY (y);
  67956. }
  67957. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67958. {
  67959. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67960. }
  67961. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67962. {
  67963. linePixels[x].blend (GradientType::getPixel (x));
  67964. }
  67965. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67966. {
  67967. PixelType* dest = linePixels + x;
  67968. if (alphaLevel < 0xff)
  67969. {
  67970. do
  67971. {
  67972. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67973. } while (--width > 0);
  67974. }
  67975. else
  67976. {
  67977. do
  67978. {
  67979. (dest++)->blend (GradientType::getPixel (x++));
  67980. } while (--width > 0);
  67981. }
  67982. }
  67983. void handleEdgeTableLineFull (int x, int width) const throw()
  67984. {
  67985. PixelType* dest = linePixels + x;
  67986. do
  67987. {
  67988. (dest++)->blend (GradientType::getPixel (x++));
  67989. } while (--width > 0);
  67990. }
  67991. private:
  67992. const Image::BitmapData& destData;
  67993. PixelType* linePixels;
  67994. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67995. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67996. };
  67997. static forcedinline int safeModulo (int n, const int divisor) throw()
  67998. {
  67999. jassert (divisor > 0);
  68000. n %= divisor;
  68001. return (n < 0) ? (n + divisor) : n;
  68002. }
  68003. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  68004. class ImageFillEdgeTableRenderer
  68005. {
  68006. public:
  68007. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  68008. const Image::BitmapData& srcData_,
  68009. const int extraAlpha_,
  68010. const int x, const int y)
  68011. : destData (destData_),
  68012. srcData (srcData_),
  68013. extraAlpha (extraAlpha_ + 1),
  68014. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  68015. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  68016. {
  68017. }
  68018. forcedinline void setEdgeTableYPos (int y) throw()
  68019. {
  68020. linePixels = (DestPixelType*) destData.getLinePointer (y);
  68021. y -= yOffset;
  68022. if (repeatPattern)
  68023. {
  68024. jassert (y >= 0);
  68025. y %= srcData.height;
  68026. }
  68027. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  68028. }
  68029. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  68030. {
  68031. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  68032. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  68033. }
  68034. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  68035. {
  68036. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  68037. }
  68038. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  68039. {
  68040. DestPixelType* dest = linePixels + x;
  68041. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  68042. x -= xOffset;
  68043. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  68044. if (alphaLevel < 0xfe)
  68045. {
  68046. do
  68047. {
  68048. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  68049. } while (--width > 0);
  68050. }
  68051. else
  68052. {
  68053. if (repeatPattern)
  68054. {
  68055. do
  68056. {
  68057. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  68058. } while (--width > 0);
  68059. }
  68060. else
  68061. {
  68062. copyRow (dest, sourceLineStart + x, width);
  68063. }
  68064. }
  68065. }
  68066. void handleEdgeTableLineFull (int x, int width) const throw()
  68067. {
  68068. DestPixelType* dest = linePixels + x;
  68069. x -= xOffset;
  68070. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  68071. if (extraAlpha < 0xfe)
  68072. {
  68073. do
  68074. {
  68075. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  68076. } while (--width > 0);
  68077. }
  68078. else
  68079. {
  68080. if (repeatPattern)
  68081. {
  68082. do
  68083. {
  68084. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  68085. } while (--width > 0);
  68086. }
  68087. else
  68088. {
  68089. copyRow (dest, sourceLineStart + x, width);
  68090. }
  68091. }
  68092. }
  68093. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  68094. {
  68095. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  68096. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  68097. uint8* mask = (uint8*) (s + x - xOffset);
  68098. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  68099. mask += PixelARGB::indexA;
  68100. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  68101. }
  68102. private:
  68103. const Image::BitmapData& destData;
  68104. const Image::BitmapData& srcData;
  68105. const int extraAlpha, xOffset, yOffset;
  68106. DestPixelType* linePixels;
  68107. SrcPixelType* sourceLineStart;
  68108. template <class PixelType1, class PixelType2>
  68109. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  68110. {
  68111. do
  68112. {
  68113. dest++ ->blend (*src++);
  68114. } while (--width > 0);
  68115. }
  68116. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  68117. {
  68118. memcpy (dest, src, width * sizeof (PixelRGB));
  68119. }
  68120. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  68121. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  68122. };
  68123. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  68124. class TransformedImageFillEdgeTableRenderer
  68125. {
  68126. public:
  68127. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  68128. const Image::BitmapData& srcData_,
  68129. const AffineTransform& transform,
  68130. const int extraAlpha_,
  68131. const bool betterQuality_)
  68132. : interpolator (transform),
  68133. destData (destData_),
  68134. srcData (srcData_),
  68135. extraAlpha (extraAlpha_ + 1),
  68136. betterQuality (betterQuality_),
  68137. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  68138. pixelOffsetInt (betterQuality_ ? -128 : 0),
  68139. maxX (srcData_.width - 1),
  68140. maxY (srcData_.height - 1),
  68141. scratchSize (2048)
  68142. {
  68143. scratchBuffer.malloc (scratchSize);
  68144. }
  68145. ~TransformedImageFillEdgeTableRenderer()
  68146. {
  68147. }
  68148. forcedinline void setEdgeTableYPos (const int newY) throw()
  68149. {
  68150. y = newY;
  68151. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  68152. }
  68153. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  68154. {
  68155. alphaLevel *= extraAlpha;
  68156. alphaLevel >>= 8;
  68157. SrcPixelType p;
  68158. generate (&p, x, 1);
  68159. linePixels[x].blend (p, alphaLevel);
  68160. }
  68161. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  68162. {
  68163. SrcPixelType p;
  68164. generate (&p, x, 1);
  68165. linePixels[x].blend (p, extraAlpha);
  68166. }
  68167. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  68168. {
  68169. if (width > scratchSize)
  68170. {
  68171. scratchSize = width;
  68172. scratchBuffer.malloc (scratchSize);
  68173. }
  68174. SrcPixelType* span = scratchBuffer;
  68175. generate (span, x, width);
  68176. DestPixelType* dest = linePixels + x;
  68177. alphaLevel *= extraAlpha;
  68178. alphaLevel >>= 8;
  68179. if (alphaLevel < 0xfe)
  68180. {
  68181. do
  68182. {
  68183. dest++ ->blend (*span++, alphaLevel);
  68184. } while (--width > 0);
  68185. }
  68186. else
  68187. {
  68188. do
  68189. {
  68190. dest++ ->blend (*span++);
  68191. } while (--width > 0);
  68192. }
  68193. }
  68194. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  68195. {
  68196. handleEdgeTableLine (x, width, 255);
  68197. }
  68198. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  68199. {
  68200. if (width > scratchSize)
  68201. {
  68202. scratchSize = width;
  68203. scratchBuffer.malloc (scratchSize);
  68204. }
  68205. y = y_;
  68206. generate (scratchBuffer, x, width);
  68207. et.clipLineToMask (x, y_,
  68208. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  68209. sizeof (SrcPixelType), width);
  68210. }
  68211. private:
  68212. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  68213. {
  68214. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68215. do
  68216. {
  68217. int hiResX, hiResY;
  68218. this->interpolator.next (hiResX, hiResY);
  68219. hiResX += pixelOffsetInt;
  68220. hiResY += pixelOffsetInt;
  68221. int loResX = hiResX >> 8;
  68222. int loResY = hiResY >> 8;
  68223. if (repeatPattern)
  68224. {
  68225. loResX = safeModulo (loResX, srcData.width);
  68226. loResY = safeModulo (loResY, srcData.height);
  68227. }
  68228. if (betterQuality
  68229. && ((unsigned int) loResX) < (unsigned int) maxX
  68230. && ((unsigned int) loResY) < (unsigned int) maxY)
  68231. {
  68232. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  68233. hiResX &= 255;
  68234. hiResY &= 255;
  68235. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68236. uint32 weight = (256 - hiResX) * (256 - hiResY);
  68237. c[0] += weight * src[0];
  68238. c[1] += weight * src[1];
  68239. c[2] += weight * src[2];
  68240. c[3] += weight * src[3];
  68241. weight = hiResX * (256 - hiResY);
  68242. c[0] += weight * src[4];
  68243. c[1] += weight * src[5];
  68244. c[2] += weight * src[6];
  68245. c[3] += weight * src[7];
  68246. src += this->srcData.lineStride;
  68247. weight = (256 - hiResX) * hiResY;
  68248. c[0] += weight * src[0];
  68249. c[1] += weight * src[1];
  68250. c[2] += weight * src[2];
  68251. c[3] += weight * src[3];
  68252. weight = hiResX * hiResY;
  68253. c[0] += weight * src[4];
  68254. c[1] += weight * src[5];
  68255. c[2] += weight * src[6];
  68256. c[3] += weight * src[7];
  68257. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  68258. (uint8) (c[PixelARGB::indexR] >> 16),
  68259. (uint8) (c[PixelARGB::indexG] >> 16),
  68260. (uint8) (c[PixelARGB::indexB] >> 16));
  68261. }
  68262. else
  68263. {
  68264. if (! repeatPattern)
  68265. {
  68266. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68267. if (loResX < 0) loResX = 0;
  68268. if (loResY < 0) loResY = 0;
  68269. if (loResX > maxX) loResX = maxX;
  68270. if (loResY > maxY) loResY = maxY;
  68271. }
  68272. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  68273. }
  68274. ++dest;
  68275. } while (--numPixels > 0);
  68276. }
  68277. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  68278. {
  68279. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68280. do
  68281. {
  68282. int hiResX, hiResY;
  68283. this->interpolator.next (hiResX, hiResY);
  68284. hiResX += pixelOffsetInt;
  68285. hiResY += pixelOffsetInt;
  68286. int loResX = hiResX >> 8;
  68287. int loResY = hiResY >> 8;
  68288. if (repeatPattern)
  68289. {
  68290. loResX = safeModulo (loResX, srcData.width);
  68291. loResY = safeModulo (loResY, srcData.height);
  68292. }
  68293. if (betterQuality
  68294. && ((unsigned int) loResX) < (unsigned int) maxX
  68295. && ((unsigned int) loResY) < (unsigned int) maxY)
  68296. {
  68297. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68298. hiResX &= 255;
  68299. hiResY &= 255;
  68300. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68301. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  68302. c[0] += weight * src[0];
  68303. c[1] += weight * src[1];
  68304. c[2] += weight * src[2];
  68305. weight = hiResX * (256 - hiResY);
  68306. c[0] += weight * src[3];
  68307. c[1] += weight * src[4];
  68308. c[2] += weight * src[5];
  68309. src += this->srcData.lineStride;
  68310. weight = (256 - hiResX) * hiResY;
  68311. c[0] += weight * src[0];
  68312. c[1] += weight * src[1];
  68313. c[2] += weight * src[2];
  68314. weight = hiResX * hiResY;
  68315. c[0] += weight * src[3];
  68316. c[1] += weight * src[4];
  68317. c[2] += weight * src[5];
  68318. dest->setARGB ((uint8) 255,
  68319. (uint8) (c[PixelRGB::indexR] >> 16),
  68320. (uint8) (c[PixelRGB::indexG] >> 16),
  68321. (uint8) (c[PixelRGB::indexB] >> 16));
  68322. }
  68323. else
  68324. {
  68325. if (! repeatPattern)
  68326. {
  68327. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68328. if (loResX < 0) loResX = 0;
  68329. if (loResY < 0) loResY = 0;
  68330. if (loResX > maxX) loResX = maxX;
  68331. if (loResY > maxY) loResY = maxY;
  68332. }
  68333. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  68334. }
  68335. ++dest;
  68336. } while (--numPixels > 0);
  68337. }
  68338. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  68339. {
  68340. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68341. do
  68342. {
  68343. int hiResX, hiResY;
  68344. this->interpolator.next (hiResX, hiResY);
  68345. hiResX += pixelOffsetInt;
  68346. hiResY += pixelOffsetInt;
  68347. int loResX = hiResX >> 8;
  68348. int loResY = hiResY >> 8;
  68349. if (repeatPattern)
  68350. {
  68351. loResX = safeModulo (loResX, srcData.width);
  68352. loResY = safeModulo (loResY, srcData.height);
  68353. }
  68354. if (betterQuality
  68355. && ((unsigned int) loResX) < (unsigned int) maxX
  68356. && ((unsigned int) loResY) < (unsigned int) maxY)
  68357. {
  68358. hiResX &= 255;
  68359. hiResY &= 255;
  68360. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68361. uint32 c = 256 * 128;
  68362. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68363. c += src[1] * (hiResX * (256 - hiResY));
  68364. src += this->srcData.lineStride;
  68365. c += src[0] * ((256 - hiResX) * hiResY);
  68366. c += src[1] * (hiResX * hiResY);
  68367. *((uint8*) dest) = (uint8) c;
  68368. }
  68369. else
  68370. {
  68371. if (! repeatPattern)
  68372. {
  68373. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68374. if (loResX < 0) loResX = 0;
  68375. if (loResY < 0) loResY = 0;
  68376. if (loResX > maxX) loResX = maxX;
  68377. if (loResY > maxY) loResY = maxY;
  68378. }
  68379. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68380. }
  68381. ++dest;
  68382. } while (--numPixels > 0);
  68383. }
  68384. class TransformedImageSpanInterpolator
  68385. {
  68386. public:
  68387. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68388. : inverseTransform (transform.inverted())
  68389. {}
  68390. void setStartOfLine (float x, float y, const int numPixels) throw()
  68391. {
  68392. float x1 = x, y1 = y;
  68393. x += numPixels;
  68394. inverseTransform.transformPoints (x1, y1, x, y);
  68395. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68396. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68397. }
  68398. void next (int& x, int& y) throw()
  68399. {
  68400. x = xBresenham.n;
  68401. xBresenham.stepToNext();
  68402. y = yBresenham.n;
  68403. yBresenham.stepToNext();
  68404. }
  68405. private:
  68406. class BresenhamInterpolator
  68407. {
  68408. public:
  68409. BresenhamInterpolator() throw() {}
  68410. void set (const int n1, const int n2, const int numSteps_) throw()
  68411. {
  68412. numSteps = jmax (1, numSteps_);
  68413. step = (n2 - n1) / numSteps;
  68414. remainder = modulo = (n2 - n1) % numSteps;
  68415. n = n1;
  68416. if (modulo <= 0)
  68417. {
  68418. modulo += numSteps;
  68419. remainder += numSteps;
  68420. --step;
  68421. }
  68422. modulo -= numSteps;
  68423. }
  68424. forcedinline void stepToNext() throw()
  68425. {
  68426. modulo += remainder;
  68427. n += step;
  68428. if (modulo > 0)
  68429. {
  68430. modulo -= numSteps;
  68431. ++n;
  68432. }
  68433. }
  68434. int n;
  68435. private:
  68436. int numSteps, step, modulo, remainder;
  68437. };
  68438. const AffineTransform inverseTransform;
  68439. BresenhamInterpolator xBresenham, yBresenham;
  68440. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68441. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68442. };
  68443. TransformedImageSpanInterpolator interpolator;
  68444. const Image::BitmapData& destData;
  68445. const Image::BitmapData& srcData;
  68446. const int extraAlpha;
  68447. const bool betterQuality;
  68448. const float pixelOffset;
  68449. const int pixelOffsetInt, maxX, maxY;
  68450. int y;
  68451. DestPixelType* linePixels;
  68452. HeapBlock <SrcPixelType> scratchBuffer;
  68453. int scratchSize;
  68454. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68455. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68456. };
  68457. class ClipRegionBase : public ReferenceCountedObject
  68458. {
  68459. public:
  68460. ClipRegionBase() {}
  68461. virtual ~ClipRegionBase() {}
  68462. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68463. virtual const Ptr clone() const = 0;
  68464. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68465. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68466. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68467. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68468. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68469. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68470. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68471. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68472. virtual const Rectangle<int> getClipBounds() const = 0;
  68473. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68474. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68475. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68476. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68477. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68478. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68479. protected:
  68480. template <class Iterator>
  68481. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68482. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68483. {
  68484. switch (destData.pixelFormat)
  68485. {
  68486. case Image::ARGB:
  68487. switch (srcData.pixelFormat)
  68488. {
  68489. case Image::ARGB:
  68490. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68491. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68492. break;
  68493. case Image::RGB:
  68494. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68495. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68496. break;
  68497. default:
  68498. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68499. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68500. break;
  68501. }
  68502. break;
  68503. case Image::RGB:
  68504. switch (srcData.pixelFormat)
  68505. {
  68506. case Image::ARGB:
  68507. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68508. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68509. break;
  68510. case Image::RGB:
  68511. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68512. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68513. break;
  68514. default:
  68515. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68516. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68517. break;
  68518. }
  68519. break;
  68520. default:
  68521. switch (srcData.pixelFormat)
  68522. {
  68523. case Image::ARGB:
  68524. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68525. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68526. break;
  68527. case Image::RGB:
  68528. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68529. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68530. break;
  68531. default:
  68532. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68533. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68534. break;
  68535. }
  68536. break;
  68537. }
  68538. }
  68539. template <class Iterator>
  68540. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68541. {
  68542. switch (destData.pixelFormat)
  68543. {
  68544. case Image::ARGB:
  68545. switch (srcData.pixelFormat)
  68546. {
  68547. case Image::ARGB:
  68548. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68549. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68550. break;
  68551. case Image::RGB:
  68552. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68553. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68554. break;
  68555. default:
  68556. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68557. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68558. break;
  68559. }
  68560. break;
  68561. case Image::RGB:
  68562. switch (srcData.pixelFormat)
  68563. {
  68564. case Image::ARGB:
  68565. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68566. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68567. break;
  68568. case Image::RGB:
  68569. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68570. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68571. break;
  68572. default:
  68573. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68574. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68575. break;
  68576. }
  68577. break;
  68578. default:
  68579. switch (srcData.pixelFormat)
  68580. {
  68581. case Image::ARGB:
  68582. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68583. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68584. break;
  68585. case Image::RGB:
  68586. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68587. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68588. break;
  68589. default:
  68590. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68591. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68592. break;
  68593. }
  68594. break;
  68595. }
  68596. }
  68597. template <class Iterator, class DestPixelType>
  68598. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68599. {
  68600. jassert (destData.pixelStride == sizeof (DestPixelType));
  68601. if (replaceContents)
  68602. {
  68603. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68604. iter.iterate (r);
  68605. }
  68606. else
  68607. {
  68608. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68609. iter.iterate (r);
  68610. }
  68611. }
  68612. template <class Iterator, class DestPixelType>
  68613. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68614. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68615. {
  68616. jassert (destData.pixelStride == sizeof (DestPixelType));
  68617. if (g.isRadial)
  68618. {
  68619. if (isIdentity)
  68620. {
  68621. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68622. iter.iterate (renderer);
  68623. }
  68624. else
  68625. {
  68626. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68627. iter.iterate (renderer);
  68628. }
  68629. }
  68630. else
  68631. {
  68632. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68633. iter.iterate (renderer);
  68634. }
  68635. }
  68636. };
  68637. class ClipRegion_EdgeTable : public ClipRegionBase
  68638. {
  68639. public:
  68640. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68641. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68642. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68643. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68644. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68645. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68646. ~ClipRegion_EdgeTable() {}
  68647. const Ptr clone() const
  68648. {
  68649. return new ClipRegion_EdgeTable (*this);
  68650. }
  68651. const Ptr applyClipTo (const Ptr& target) const
  68652. {
  68653. return target->clipToEdgeTable (edgeTable);
  68654. }
  68655. const Ptr clipToRectangle (const Rectangle<int>& r)
  68656. {
  68657. edgeTable.clipToRectangle (r);
  68658. return edgeTable.isEmpty() ? 0 : this;
  68659. }
  68660. const Ptr clipToRectangleList (const RectangleList& r)
  68661. {
  68662. RectangleList inverse (edgeTable.getMaximumBounds());
  68663. if (inverse.subtract (r))
  68664. for (RectangleList::Iterator iter (inverse); iter.next();)
  68665. edgeTable.excludeRectangle (*iter.getRectangle());
  68666. return edgeTable.isEmpty() ? 0 : this;
  68667. }
  68668. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68669. {
  68670. edgeTable.excludeRectangle (r);
  68671. return edgeTable.isEmpty() ? 0 : this;
  68672. }
  68673. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68674. {
  68675. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68676. edgeTable.clipToEdgeTable (et);
  68677. return edgeTable.isEmpty() ? 0 : this;
  68678. }
  68679. const Ptr clipToEdgeTable (const EdgeTable& et)
  68680. {
  68681. edgeTable.clipToEdgeTable (et);
  68682. return edgeTable.isEmpty() ? 0 : this;
  68683. }
  68684. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68685. {
  68686. const Image::BitmapData srcData (image, false);
  68687. if (transform.isOnlyTranslation())
  68688. {
  68689. // If our translation doesn't involve any distortion, just use a simple blit..
  68690. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68691. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68692. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68693. {
  68694. const int imageX = ((tx + 128) >> 8);
  68695. const int imageY = ((ty + 128) >> 8);
  68696. if (image.getFormat() == Image::ARGB)
  68697. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68698. else
  68699. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68700. return edgeTable.isEmpty() ? 0 : this;
  68701. }
  68702. }
  68703. if (transform.isSingularity())
  68704. return 0;
  68705. {
  68706. Path p;
  68707. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68708. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68709. edgeTable.clipToEdgeTable (et2);
  68710. }
  68711. if (! edgeTable.isEmpty())
  68712. {
  68713. if (image.getFormat() == Image::ARGB)
  68714. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68715. else
  68716. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68717. }
  68718. return edgeTable.isEmpty() ? 0 : this;
  68719. }
  68720. bool clipRegionIntersects (const Rectangle<int>& r) const
  68721. {
  68722. return edgeTable.getMaximumBounds().intersects (r);
  68723. }
  68724. const Rectangle<int> getClipBounds() const
  68725. {
  68726. return edgeTable.getMaximumBounds();
  68727. }
  68728. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68729. {
  68730. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68731. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68732. if (! clipped.isEmpty())
  68733. {
  68734. ClipRegion_EdgeTable et (clipped);
  68735. et.edgeTable.clipToEdgeTable (edgeTable);
  68736. et.fillAllWithColour (destData, colour, replaceContents);
  68737. }
  68738. }
  68739. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68740. {
  68741. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68742. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68743. if (! clipped.isEmpty())
  68744. {
  68745. ClipRegion_EdgeTable et (clipped);
  68746. et.edgeTable.clipToEdgeTable (edgeTable);
  68747. et.fillAllWithColour (destData, colour, false);
  68748. }
  68749. }
  68750. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68751. {
  68752. switch (destData.pixelFormat)
  68753. {
  68754. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68755. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68756. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68757. }
  68758. }
  68759. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68760. {
  68761. HeapBlock <PixelARGB> lookupTable;
  68762. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68763. jassert (numLookupEntries > 0);
  68764. switch (destData.pixelFormat)
  68765. {
  68766. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68767. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68768. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68769. }
  68770. }
  68771. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68772. {
  68773. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68774. }
  68775. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68776. {
  68777. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68778. }
  68779. EdgeTable edgeTable;
  68780. private:
  68781. template <class SrcPixelType>
  68782. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68783. {
  68784. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68785. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68786. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68787. edgeTable.getMaximumBounds().getWidth());
  68788. }
  68789. template <class SrcPixelType>
  68790. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68791. {
  68792. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68793. edgeTable.clipToRectangle (r);
  68794. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68795. for (int y = 0; y < r.getHeight(); ++y)
  68796. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68797. }
  68798. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68799. };
  68800. class ClipRegion_RectangleList : public ClipRegionBase
  68801. {
  68802. public:
  68803. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68804. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68805. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68806. ~ClipRegion_RectangleList() {}
  68807. const Ptr clone() const
  68808. {
  68809. return new ClipRegion_RectangleList (*this);
  68810. }
  68811. const Ptr applyClipTo (const Ptr& target) const
  68812. {
  68813. return target->clipToRectangleList (clip);
  68814. }
  68815. const Ptr clipToRectangle (const Rectangle<int>& r)
  68816. {
  68817. clip.clipTo (r);
  68818. return clip.isEmpty() ? 0 : this;
  68819. }
  68820. const Ptr clipToRectangleList (const RectangleList& r)
  68821. {
  68822. clip.clipTo (r);
  68823. return clip.isEmpty() ? 0 : this;
  68824. }
  68825. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68826. {
  68827. clip.subtract (r);
  68828. return clip.isEmpty() ? 0 : this;
  68829. }
  68830. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68831. {
  68832. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68833. }
  68834. const Ptr clipToEdgeTable (const EdgeTable& et)
  68835. {
  68836. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68837. }
  68838. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68839. {
  68840. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68841. }
  68842. bool clipRegionIntersects (const Rectangle<int>& r) const
  68843. {
  68844. return clip.intersects (r);
  68845. }
  68846. const Rectangle<int> getClipBounds() const
  68847. {
  68848. return clip.getBounds();
  68849. }
  68850. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68851. {
  68852. SubRectangleIterator iter (clip, area);
  68853. switch (destData.pixelFormat)
  68854. {
  68855. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68856. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68857. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68858. }
  68859. }
  68860. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68861. {
  68862. SubRectangleIteratorFloat iter (clip, area);
  68863. switch (destData.pixelFormat)
  68864. {
  68865. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68866. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68867. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68868. }
  68869. }
  68870. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68871. {
  68872. switch (destData.pixelFormat)
  68873. {
  68874. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68875. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68876. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68877. }
  68878. }
  68879. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68880. {
  68881. HeapBlock <PixelARGB> lookupTable;
  68882. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68883. jassert (numLookupEntries > 0);
  68884. switch (destData.pixelFormat)
  68885. {
  68886. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68887. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68888. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68889. }
  68890. }
  68891. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68892. {
  68893. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68894. }
  68895. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68896. {
  68897. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68898. }
  68899. RectangleList clip;
  68900. template <class Renderer>
  68901. void iterate (Renderer& r) const throw()
  68902. {
  68903. RectangleList::Iterator iter (clip);
  68904. while (iter.next())
  68905. {
  68906. const Rectangle<int> rect (*iter.getRectangle());
  68907. const int x = rect.getX();
  68908. const int w = rect.getWidth();
  68909. jassert (w > 0);
  68910. const int bottom = rect.getBottom();
  68911. for (int y = rect.getY(); y < bottom; ++y)
  68912. {
  68913. r.setEdgeTableYPos (y);
  68914. r.handleEdgeTableLineFull (x, w);
  68915. }
  68916. }
  68917. }
  68918. private:
  68919. class SubRectangleIterator
  68920. {
  68921. public:
  68922. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68923. : clip (clip_), area (area_)
  68924. {
  68925. }
  68926. template <class Renderer>
  68927. void iterate (Renderer& r) const throw()
  68928. {
  68929. RectangleList::Iterator iter (clip);
  68930. while (iter.next())
  68931. {
  68932. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68933. if (! rect.isEmpty())
  68934. {
  68935. const int x = rect.getX();
  68936. const int w = rect.getWidth();
  68937. const int bottom = rect.getBottom();
  68938. for (int y = rect.getY(); y < bottom; ++y)
  68939. {
  68940. r.setEdgeTableYPos (y);
  68941. r.handleEdgeTableLineFull (x, w);
  68942. }
  68943. }
  68944. }
  68945. }
  68946. private:
  68947. const RectangleList& clip;
  68948. const Rectangle<int> area;
  68949. SubRectangleIterator (const SubRectangleIterator&);
  68950. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68951. };
  68952. class SubRectangleIteratorFloat
  68953. {
  68954. public:
  68955. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68956. : clip (clip_), area (area_)
  68957. {
  68958. }
  68959. template <class Renderer>
  68960. void iterate (Renderer& r) const throw()
  68961. {
  68962. int left = roundToInt (area.getX() * 256.0f);
  68963. int top = roundToInt (area.getY() * 256.0f);
  68964. int right = roundToInt (area.getRight() * 256.0f);
  68965. int bottom = roundToInt (area.getBottom() * 256.0f);
  68966. int totalTop, totalLeft, totalBottom, totalRight;
  68967. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68968. if ((top >> 8) == (bottom >> 8))
  68969. {
  68970. topAlpha = bottom - top;
  68971. bottomAlpha = 0;
  68972. totalTop = top >> 8;
  68973. totalBottom = bottom = top = totalTop + 1;
  68974. }
  68975. else
  68976. {
  68977. if ((top & 255) == 0)
  68978. {
  68979. topAlpha = 0;
  68980. top = totalTop = (top >> 8);
  68981. }
  68982. else
  68983. {
  68984. topAlpha = 255 - (top & 255);
  68985. totalTop = (top >> 8);
  68986. top = totalTop + 1;
  68987. }
  68988. bottomAlpha = bottom & 255;
  68989. bottom >>= 8;
  68990. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68991. }
  68992. if ((left >> 8) == (right >> 8))
  68993. {
  68994. leftAlpha = right - left;
  68995. rightAlpha = 0;
  68996. totalLeft = (left >> 8);
  68997. totalRight = right = left = totalLeft + 1;
  68998. }
  68999. else
  69000. {
  69001. if ((left & 255) == 0)
  69002. {
  69003. leftAlpha = 0;
  69004. left = totalLeft = (left >> 8);
  69005. }
  69006. else
  69007. {
  69008. leftAlpha = 255 - (left & 255);
  69009. totalLeft = (left >> 8);
  69010. left = totalLeft + 1;
  69011. }
  69012. rightAlpha = right & 255;
  69013. right >>= 8;
  69014. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  69015. }
  69016. RectangleList::Iterator iter (clip);
  69017. while (iter.next())
  69018. {
  69019. const int clipLeft = iter.getRectangle()->getX();
  69020. const int clipRight = iter.getRectangle()->getRight();
  69021. const int clipTop = iter.getRectangle()->getY();
  69022. const int clipBottom = iter.getRectangle()->getBottom();
  69023. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  69024. {
  69025. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  69026. {
  69027. if (topAlpha != 0 && totalTop >= clipTop)
  69028. {
  69029. r.setEdgeTableYPos (totalTop);
  69030. r.handleEdgeTablePixel (left, topAlpha);
  69031. }
  69032. const int endY = jmin (bottom, clipBottom);
  69033. for (int y = jmax (clipTop, top); y < endY; ++y)
  69034. {
  69035. r.setEdgeTableYPos (y);
  69036. r.handleEdgeTablePixelFull (left);
  69037. }
  69038. if (bottomAlpha != 0 && bottom < clipBottom)
  69039. {
  69040. r.setEdgeTableYPos (bottom);
  69041. r.handleEdgeTablePixel (left, bottomAlpha);
  69042. }
  69043. }
  69044. else
  69045. {
  69046. const int clippedLeft = jmax (left, clipLeft);
  69047. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  69048. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  69049. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  69050. if (topAlpha != 0 && totalTop >= clipTop)
  69051. {
  69052. r.setEdgeTableYPos (totalTop);
  69053. if (doLeftAlpha)
  69054. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  69055. if (clippedWidth > 0)
  69056. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  69057. if (doRightAlpha)
  69058. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  69059. }
  69060. const int endY = jmin (bottom, clipBottom);
  69061. for (int y = jmax (clipTop, top); y < endY; ++y)
  69062. {
  69063. r.setEdgeTableYPos (y);
  69064. if (doLeftAlpha)
  69065. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  69066. if (clippedWidth > 0)
  69067. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  69068. if (doRightAlpha)
  69069. r.handleEdgeTablePixel (right, rightAlpha);
  69070. }
  69071. if (bottomAlpha != 0 && bottom < clipBottom)
  69072. {
  69073. r.setEdgeTableYPos (bottom);
  69074. if (doLeftAlpha)
  69075. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  69076. if (clippedWidth > 0)
  69077. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  69078. if (doRightAlpha)
  69079. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  69080. }
  69081. }
  69082. }
  69083. }
  69084. }
  69085. private:
  69086. const RectangleList& clip;
  69087. const Rectangle<float>& area;
  69088. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  69089. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  69090. };
  69091. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  69092. };
  69093. }
  69094. class LowLevelGraphicsSoftwareRenderer::SavedState
  69095. {
  69096. public:
  69097. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  69098. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  69099. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  69100. {
  69101. }
  69102. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  69103. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  69104. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  69105. {
  69106. }
  69107. SavedState (const SavedState& other)
  69108. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  69109. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  69110. {
  69111. }
  69112. ~SavedState()
  69113. {
  69114. }
  69115. void setOrigin (const int x, const int y) throw()
  69116. {
  69117. xOffset += x;
  69118. yOffset += y;
  69119. }
  69120. bool clipToRectangle (const Rectangle<int>& r)
  69121. {
  69122. if (clip != 0)
  69123. {
  69124. cloneClipIfMultiplyReferenced();
  69125. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  69126. }
  69127. return clip != 0;
  69128. }
  69129. bool clipToRectangleList (const RectangleList& r)
  69130. {
  69131. if (clip != 0)
  69132. {
  69133. cloneClipIfMultiplyReferenced();
  69134. RectangleList offsetList (r);
  69135. offsetList.offsetAll (xOffset, yOffset);
  69136. clip = clip->clipToRectangleList (offsetList);
  69137. }
  69138. return clip != 0;
  69139. }
  69140. bool excludeClipRectangle (const Rectangle<int>& r)
  69141. {
  69142. if (clip != 0)
  69143. {
  69144. cloneClipIfMultiplyReferenced();
  69145. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  69146. }
  69147. return clip != 0;
  69148. }
  69149. void clipToPath (const Path& p, const AffineTransform& transform)
  69150. {
  69151. if (clip != 0)
  69152. {
  69153. cloneClipIfMultiplyReferenced();
  69154. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  69155. }
  69156. }
  69157. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  69158. {
  69159. if (clip != 0)
  69160. {
  69161. if (image.hasAlphaChannel())
  69162. {
  69163. cloneClipIfMultiplyReferenced();
  69164. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  69165. interpolationQuality != Graphics::lowResamplingQuality);
  69166. }
  69167. else
  69168. {
  69169. Path p;
  69170. p.addRectangle (image.getBounds());
  69171. clipToPath (p, t);
  69172. }
  69173. }
  69174. }
  69175. bool clipRegionIntersects (const Rectangle<int>& r) const
  69176. {
  69177. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  69178. }
  69179. const Rectangle<int> getClipBounds() const
  69180. {
  69181. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  69182. }
  69183. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  69184. {
  69185. if (clip != 0)
  69186. {
  69187. if (fillType.isColour())
  69188. {
  69189. Image::BitmapData destData (image, true);
  69190. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  69191. }
  69192. else
  69193. {
  69194. const Rectangle<int> totalClip (clip->getClipBounds());
  69195. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  69196. if (! clipped.isEmpty())
  69197. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  69198. }
  69199. }
  69200. }
  69201. void fillRect (Image& image, const Rectangle<float>& r)
  69202. {
  69203. if (clip != 0)
  69204. {
  69205. if (fillType.isColour())
  69206. {
  69207. Image::BitmapData destData (image, true);
  69208. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  69209. }
  69210. else
  69211. {
  69212. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  69213. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  69214. if (! clipped.isEmpty())
  69215. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  69216. }
  69217. }
  69218. }
  69219. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  69220. {
  69221. if (clip != 0)
  69222. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  69223. }
  69224. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  69225. {
  69226. if (clip != 0)
  69227. {
  69228. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69229. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69230. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69231. fillShape (image, shapeToFill, false);
  69232. }
  69233. }
  69234. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69235. {
  69236. jassert (clip != 0);
  69237. shapeToFill = clip->applyClipTo (shapeToFill);
  69238. if (shapeToFill != 0)
  69239. {
  69240. Image::BitmapData destData (image, true);
  69241. if (fillType.isGradient())
  69242. {
  69243. jassert (! replaceContents); // that option is just for solid colours
  69244. ColourGradient g2 (*(fillType.gradient));
  69245. g2.multiplyOpacity (fillType.getOpacity());
  69246. g2.point1.addXY (-0.5f, -0.5f);
  69247. g2.point2.addXY (-0.5f, -0.5f);
  69248. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  69249. const bool isIdentity = transform.isOnlyTranslation();
  69250. if (isIdentity)
  69251. {
  69252. // If our translation doesn't involve any distortion, we can speed it up..
  69253. g2.point1.applyTransform (transform);
  69254. g2.point2.applyTransform (transform);
  69255. transform = AffineTransform::identity;
  69256. }
  69257. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69258. }
  69259. else if (fillType.isTiledImage())
  69260. {
  69261. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  69262. }
  69263. else
  69264. {
  69265. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69266. }
  69267. }
  69268. }
  69269. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69270. {
  69271. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  69272. const Image::BitmapData destData (destImage, true);
  69273. const Image::BitmapData srcData (sourceImage, false);
  69274. const int alpha = fillType.colour.getAlpha();
  69275. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69276. if (transform.isOnlyTranslation())
  69277. {
  69278. // If our translation doesn't involve any distortion, just use a simple blit..
  69279. int tx = (int) (transform.getTranslationX() * 256.0f);
  69280. int ty = (int) (transform.getTranslationY() * 256.0f);
  69281. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69282. {
  69283. tx = ((tx + 128) >> 8);
  69284. ty = ((ty + 128) >> 8);
  69285. if (tiledFillClipRegion != 0)
  69286. {
  69287. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69288. }
  69289. else
  69290. {
  69291. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  69292. c = clip->applyClipTo (c);
  69293. if (c != 0)
  69294. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69295. }
  69296. return;
  69297. }
  69298. }
  69299. if (transform.isSingularity())
  69300. return;
  69301. if (tiledFillClipRegion != 0)
  69302. {
  69303. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69304. }
  69305. else
  69306. {
  69307. Path p;
  69308. p.addRectangle (sourceImage.getBounds());
  69309. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69310. c = c->clipToPath (p, transform);
  69311. if (c != 0)
  69312. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69313. }
  69314. }
  69315. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69316. int xOffset, yOffset;
  69317. Font font;
  69318. FillType fillType;
  69319. Graphics::ResamplingQuality interpolationQuality;
  69320. private:
  69321. void cloneClipIfMultiplyReferenced()
  69322. {
  69323. if (clip->getReferenceCount() > 1)
  69324. clip = clip->clone();
  69325. }
  69326. SavedState& operator= (const SavedState&);
  69327. };
  69328. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69329. : image (image_)
  69330. {
  69331. currentState = new SavedState (image_.getBounds(), 0, 0);
  69332. }
  69333. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69334. const RectangleList& initialClip)
  69335. : image (image_)
  69336. {
  69337. currentState = new SavedState (initialClip, xOffset, yOffset);
  69338. }
  69339. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69340. {
  69341. }
  69342. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69343. {
  69344. return false;
  69345. }
  69346. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69347. {
  69348. currentState->setOrigin (x, y);
  69349. }
  69350. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69351. {
  69352. return currentState->clipToRectangle (r);
  69353. }
  69354. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69355. {
  69356. return currentState->clipToRectangleList (clipRegion);
  69357. }
  69358. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69359. {
  69360. currentState->excludeClipRectangle (r);
  69361. }
  69362. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69363. {
  69364. currentState->clipToPath (path, transform);
  69365. }
  69366. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69367. {
  69368. currentState->clipToImageAlpha (sourceImage, transform);
  69369. }
  69370. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69371. {
  69372. return currentState->clipRegionIntersects (r);
  69373. }
  69374. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69375. {
  69376. return currentState->getClipBounds();
  69377. }
  69378. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69379. {
  69380. return currentState->clip == 0;
  69381. }
  69382. void LowLevelGraphicsSoftwareRenderer::saveState()
  69383. {
  69384. stateStack.add (new SavedState (*currentState));
  69385. }
  69386. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69387. {
  69388. SavedState* const top = stateStack.getLast();
  69389. if (top != 0)
  69390. {
  69391. currentState = top;
  69392. stateStack.removeLast (1, false);
  69393. }
  69394. else
  69395. {
  69396. jassertfalse; // trying to pop with an empty stack!
  69397. }
  69398. }
  69399. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69400. {
  69401. currentState->fillType = fillType;
  69402. }
  69403. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69404. {
  69405. currentState->fillType.setOpacity (newOpacity);
  69406. }
  69407. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69408. {
  69409. currentState->interpolationQuality = quality;
  69410. }
  69411. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69412. {
  69413. currentState->fillRect (image, r, replaceExistingContents);
  69414. }
  69415. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69416. {
  69417. currentState->fillPath (image, path, transform);
  69418. }
  69419. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69420. {
  69421. currentState->renderImage (image, sourceImage, transform,
  69422. fillEntireClipAsTiles ? currentState->clip : 0);
  69423. }
  69424. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69425. {
  69426. Path p;
  69427. p.addLineSegment (line, 1.0f);
  69428. fillPath (p, AffineTransform::identity);
  69429. }
  69430. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69431. {
  69432. if (bottom > top)
  69433. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69434. }
  69435. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69436. {
  69437. if (right > left)
  69438. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69439. }
  69440. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69441. {
  69442. public:
  69443. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69444. ~CachedGlyph() {}
  69445. void draw (SavedState& state, Image& image, const float x, const float y) const
  69446. {
  69447. if (edgeTable != 0)
  69448. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69449. }
  69450. void generate (const Font& newFont, const int glyphNumber)
  69451. {
  69452. font = newFont;
  69453. glyph = glyphNumber;
  69454. edgeTable = 0;
  69455. Path glyphPath;
  69456. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69457. if (! glyphPath.isEmpty())
  69458. {
  69459. const float fontHeight = font.getHeight();
  69460. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69461. #if JUCE_MAC || JUCE_IOS
  69462. .translated (0.0f, -0.5f)
  69463. #endif
  69464. );
  69465. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69466. glyphPath, transform);
  69467. }
  69468. }
  69469. int glyph, lastAccessCount;
  69470. Font font;
  69471. juce_UseDebuggingNewOperator
  69472. private:
  69473. ScopedPointer <EdgeTable> edgeTable;
  69474. CachedGlyph (const CachedGlyph&);
  69475. CachedGlyph& operator= (const CachedGlyph&);
  69476. };
  69477. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69478. {
  69479. public:
  69480. GlyphCache()
  69481. : accessCounter (0), hits (0), misses (0)
  69482. {
  69483. for (int i = 120; --i >= 0;)
  69484. glyphs.add (new CachedGlyph());
  69485. }
  69486. ~GlyphCache()
  69487. {
  69488. clearSingletonInstance();
  69489. }
  69490. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69491. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69492. {
  69493. ++accessCounter;
  69494. int oldestCounter = std::numeric_limits<int>::max();
  69495. CachedGlyph* oldest = 0;
  69496. for (int i = glyphs.size(); --i >= 0;)
  69497. {
  69498. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69499. if (glyph->glyph == glyphNumber && glyph->font == font)
  69500. {
  69501. ++hits;
  69502. glyph->lastAccessCount = accessCounter;
  69503. glyph->draw (state, image, x, y);
  69504. return;
  69505. }
  69506. if (glyph->lastAccessCount <= oldestCounter)
  69507. {
  69508. oldestCounter = glyph->lastAccessCount;
  69509. oldest = glyph;
  69510. }
  69511. }
  69512. if (hits + ++misses > (glyphs.size() << 4))
  69513. {
  69514. if (misses * 2 > hits)
  69515. {
  69516. for (int i = 32; --i >= 0;)
  69517. glyphs.add (new CachedGlyph());
  69518. }
  69519. hits = misses = 0;
  69520. oldest = glyphs.getLast();
  69521. }
  69522. jassert (oldest != 0);
  69523. oldest->lastAccessCount = accessCounter;
  69524. oldest->generate (font, glyphNumber);
  69525. oldest->draw (state, image, x, y);
  69526. }
  69527. juce_UseDebuggingNewOperator
  69528. private:
  69529. friend class OwnedArray <CachedGlyph>;
  69530. OwnedArray <CachedGlyph> glyphs;
  69531. int accessCounter, hits, misses;
  69532. GlyphCache (const GlyphCache&);
  69533. GlyphCache& operator= (const GlyphCache&);
  69534. };
  69535. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69536. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69537. {
  69538. currentState->font = newFont;
  69539. }
  69540. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69541. {
  69542. return currentState->font;
  69543. }
  69544. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69545. {
  69546. Font& f = currentState->font;
  69547. if (transform.isOnlyTranslation())
  69548. {
  69549. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69550. transform.getTranslationX(),
  69551. transform.getTranslationY());
  69552. }
  69553. else
  69554. {
  69555. Path p;
  69556. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69557. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69558. }
  69559. }
  69560. #if JUCE_MSVC
  69561. #pragma warning (pop)
  69562. #if JUCE_DEBUG
  69563. #pragma optimize ("", on) // resets optimisations to the project defaults
  69564. #endif
  69565. #endif
  69566. END_JUCE_NAMESPACE
  69567. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69568. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69569. BEGIN_JUCE_NAMESPACE
  69570. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69571. : flags (other.flags)
  69572. {
  69573. }
  69574. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69575. {
  69576. flags = other.flags;
  69577. return *this;
  69578. }
  69579. void RectanglePlacement::applyTo (double& x, double& y,
  69580. double& w, double& h,
  69581. const double dx, const double dy,
  69582. const double dw, const double dh) const throw()
  69583. {
  69584. if (w == 0 || h == 0)
  69585. return;
  69586. if ((flags & stretchToFit) != 0)
  69587. {
  69588. x = dx;
  69589. y = dy;
  69590. w = dw;
  69591. h = dh;
  69592. }
  69593. else
  69594. {
  69595. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69596. : jmin (dw / w, dh / h);
  69597. if ((flags & onlyReduceInSize) != 0)
  69598. scale = jmin (scale, 1.0);
  69599. if ((flags & onlyIncreaseInSize) != 0)
  69600. scale = jmax (scale, 1.0);
  69601. w *= scale;
  69602. h *= scale;
  69603. if ((flags & xLeft) != 0)
  69604. x = dx;
  69605. else if ((flags & xRight) != 0)
  69606. x = dx + dw - w;
  69607. else
  69608. x = dx + (dw - w) * 0.5;
  69609. if ((flags & yTop) != 0)
  69610. y = dy;
  69611. else if ((flags & yBottom) != 0)
  69612. y = dy + dh - h;
  69613. else
  69614. y = dy + (dh - h) * 0.5;
  69615. }
  69616. }
  69617. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  69618. float w, float h,
  69619. const float dx, const float dy,
  69620. const float dw, const float dh) const throw()
  69621. {
  69622. if (w == 0 || h == 0)
  69623. return AffineTransform::identity;
  69624. const float scaleX = dw / w;
  69625. const float scaleY = dh / h;
  69626. if ((flags & stretchToFit) != 0)
  69627. return AffineTransform::translation (-x, -y)
  69628. .scaled (scaleX, scaleY)
  69629. .translated (dx, dy);
  69630. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69631. : jmin (scaleX, scaleY);
  69632. if ((flags & onlyReduceInSize) != 0)
  69633. scale = jmin (scale, 1.0f);
  69634. if ((flags & onlyIncreaseInSize) != 0)
  69635. scale = jmax (scale, 1.0f);
  69636. w *= scale;
  69637. h *= scale;
  69638. float newX = dx;
  69639. if ((flags & xRight) != 0)
  69640. newX += dw - w; // right
  69641. else if ((flags & xLeft) == 0)
  69642. newX += (dw - w) / 2.0f; // centre
  69643. float newY = dy;
  69644. if ((flags & yBottom) != 0)
  69645. newY += dh - h; // bottom
  69646. else if ((flags & yTop) == 0)
  69647. newY += (dh - h) / 2.0f; // centre
  69648. return AffineTransform::translation (-x, -y)
  69649. .scaled (scale, scale)
  69650. .translated (newX, newY);
  69651. }
  69652. END_JUCE_NAMESPACE
  69653. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69654. /*** Start of inlined file: juce_Drawable.cpp ***/
  69655. BEGIN_JUCE_NAMESPACE
  69656. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69657. const AffineTransform& transform_,
  69658. const float opacity_) throw()
  69659. : g (g_),
  69660. transform (transform_),
  69661. opacity (opacity_)
  69662. {
  69663. }
  69664. Drawable::Drawable()
  69665. : parent (0)
  69666. {
  69667. }
  69668. Drawable::~Drawable()
  69669. {
  69670. }
  69671. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69672. {
  69673. render (RenderingContext (g, transform, opacity));
  69674. }
  69675. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69676. {
  69677. draw (g, opacity, AffineTransform::translation (x, y));
  69678. }
  69679. void Drawable::drawWithin (Graphics& g,
  69680. const int destX,
  69681. const int destY,
  69682. const int destW,
  69683. const int destH,
  69684. const RectanglePlacement& placement,
  69685. const float opacity) const
  69686. {
  69687. if (destW > 0 && destH > 0)
  69688. {
  69689. Rectangle<float> bounds (getBounds());
  69690. draw (g, opacity,
  69691. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  69692. (float) destX, (float) destY,
  69693. (float) destW, (float) destH));
  69694. }
  69695. }
  69696. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69697. {
  69698. Drawable* result = 0;
  69699. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69700. if (image.isValid())
  69701. {
  69702. DrawableImage* const di = new DrawableImage();
  69703. di->setImage (image);
  69704. result = di;
  69705. }
  69706. else
  69707. {
  69708. const String asString (String::createStringFromData (data, (int) numBytes));
  69709. XmlDocument doc (asString);
  69710. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69711. if (outer != 0 && outer->hasTagName ("svg"))
  69712. {
  69713. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69714. if (svg != 0)
  69715. result = Drawable::createFromSVG (*svg);
  69716. }
  69717. }
  69718. return result;
  69719. }
  69720. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69721. {
  69722. MemoryOutputStream mo;
  69723. mo.writeFromInputStream (dataSource, -1);
  69724. return createFromImageData (mo.getData(), mo.getDataSize());
  69725. }
  69726. Drawable* Drawable::createFromImageFile (const File& file)
  69727. {
  69728. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69729. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69730. }
  69731. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69732. {
  69733. return createChildFromValueTree (0, tree, imageProvider);
  69734. }
  69735. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69736. {
  69737. const Identifier type (tree.getType());
  69738. Drawable* d = 0;
  69739. if (type == DrawablePath::valueTreeType)
  69740. d = new DrawablePath();
  69741. else if (type == DrawableComposite::valueTreeType)
  69742. d = new DrawableComposite();
  69743. else if (type == DrawableImage::valueTreeType)
  69744. d = new DrawableImage();
  69745. else if (type == DrawableText::valueTreeType)
  69746. d = new DrawableText();
  69747. if (d != 0)
  69748. {
  69749. d->parent = parent;
  69750. d->refreshFromValueTree (tree, imageProvider);
  69751. }
  69752. return d;
  69753. }
  69754. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69755. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  69756. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  69757. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  69758. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  69759. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  69760. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  69761. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  69762. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  69763. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  69764. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69765. : state (state_)
  69766. {
  69767. }
  69768. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69769. {
  69770. }
  69771. const String Drawable::ValueTreeWrapperBase::getID() const
  69772. {
  69773. return state [idProperty];
  69774. }
  69775. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69776. {
  69777. if (newID.isEmpty())
  69778. state.removeProperty (idProperty, undoManager);
  69779. else
  69780. state.setProperty (idProperty, newID, undoManager);
  69781. }
  69782. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69783. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69784. {
  69785. const String newType (v[type].toString());
  69786. if (newType == "solid")
  69787. {
  69788. const String colourString (v [colour].toString());
  69789. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69790. : (uint32) colourString.getHexValue32()));
  69791. }
  69792. else if (newType == "gradient")
  69793. {
  69794. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69795. ColourGradient g;
  69796. if (gp1 != 0) *gp1 = p1;
  69797. if (gp2 != 0) *gp2 = p2;
  69798. if (gp3 != 0) *gp3 = p3;
  69799. g.point1 = p1.resolve (nameFinder);
  69800. g.point2 = p2.resolve (nameFinder);
  69801. g.isRadial = v[radial];
  69802. StringArray colourSteps;
  69803. colourSteps.addTokens (v[colours].toString(), false);
  69804. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69805. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69806. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69807. FillType fillType (g);
  69808. if (g.isRadial)
  69809. {
  69810. const Point<float> point3 (p3.resolve (nameFinder));
  69811. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69812. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69813. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69814. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69815. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69816. }
  69817. return fillType;
  69818. }
  69819. else if (newType == "image")
  69820. {
  69821. Image im;
  69822. if (imageProvider != 0)
  69823. im = imageProvider->getImageForIdentifier (v[imageId]);
  69824. FillType f (im, AffineTransform::identity);
  69825. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69826. return f;
  69827. }
  69828. jassertfalse;
  69829. return FillType();
  69830. }
  69831. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69832. {
  69833. const ColourGradient& g = *fillType.gradient;
  69834. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69835. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69836. return point3Source.transformedBy (fillType.transform);
  69837. }
  69838. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  69839. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69840. ImageProvider* imageProvider, UndoManager* const undoManager)
  69841. {
  69842. if (fillType.isColour())
  69843. {
  69844. v.setProperty (type, "solid", undoManager);
  69845. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69846. }
  69847. else if (fillType.isGradient())
  69848. {
  69849. v.setProperty (type, "gradient", undoManager);
  69850. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69851. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69852. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69853. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69854. String s;
  69855. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69856. s << ' ' << fillType.gradient->getColourPosition (i)
  69857. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69858. v.setProperty (colours, s.trimStart(), undoManager);
  69859. }
  69860. else if (fillType.isTiledImage())
  69861. {
  69862. v.setProperty (type, "image", undoManager);
  69863. if (imageProvider != 0)
  69864. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69865. if (fillType.getOpacity() < 1.0f)
  69866. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69867. else
  69868. v.removeProperty (imageOpacity, undoManager);
  69869. }
  69870. else
  69871. {
  69872. jassertfalse;
  69873. }
  69874. }
  69875. END_JUCE_NAMESPACE
  69876. /*** End of inlined file: juce_Drawable.cpp ***/
  69877. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69878. BEGIN_JUCE_NAMESPACE
  69879. DrawableComposite::DrawableComposite()
  69880. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69881. {
  69882. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69883. RelativeCoordinate (100.0),
  69884. RelativeCoordinate (0.0),
  69885. RelativeCoordinate (100.0)));
  69886. }
  69887. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69888. {
  69889. bounds = other.bounds;
  69890. for (int i = 0; i < other.drawables.size(); ++i)
  69891. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69892. markersX.addCopiesOf (other.markersX);
  69893. markersY.addCopiesOf (other.markersY);
  69894. }
  69895. DrawableComposite::~DrawableComposite()
  69896. {
  69897. }
  69898. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69899. {
  69900. if (drawable != 0)
  69901. {
  69902. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69903. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69904. drawables.insert (index, drawable);
  69905. drawable->parent = this;
  69906. }
  69907. }
  69908. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69909. {
  69910. insertDrawable (drawable.createCopy(), index);
  69911. }
  69912. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69913. {
  69914. drawables.remove (index, deleteDrawable);
  69915. }
  69916. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69917. {
  69918. for (int i = drawables.size(); --i >= 0;)
  69919. if (drawables.getUnchecked(i)->getName() == name)
  69920. return drawables.getUnchecked(i);
  69921. return 0;
  69922. }
  69923. void DrawableComposite::bringToFront (const int index)
  69924. {
  69925. if (index >= 0 && index < drawables.size() - 1)
  69926. drawables.move (index, -1);
  69927. }
  69928. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69929. {
  69930. bounds = newBoundingBox;
  69931. }
  69932. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69933. : name (other.name), position (other.position)
  69934. {
  69935. }
  69936. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69937. : name (name_), position (position_)
  69938. {
  69939. }
  69940. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69941. {
  69942. return name != other.name || position != other.position;
  69943. }
  69944. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69945. const char* const DrawableComposite::contentRightMarkerName ("right");
  69946. const char* const DrawableComposite::contentTopMarkerName ("top");
  69947. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69948. const RelativeRectangle DrawableComposite::getContentArea() const
  69949. {
  69950. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69951. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69952. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69953. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69954. }
  69955. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69956. {
  69957. setMarker (contentLeftMarkerName, true, newArea.left);
  69958. setMarker (contentRightMarkerName, true, newArea.right);
  69959. setMarker (contentTopMarkerName, false, newArea.top);
  69960. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69961. }
  69962. void DrawableComposite::resetBoundingBoxToContentArea()
  69963. {
  69964. const RelativeRectangle content (getContentArea());
  69965. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69966. RelativePoint (content.right, content.top),
  69967. RelativePoint (content.left, content.bottom)));
  69968. }
  69969. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69970. {
  69971. const Rectangle<float> bounds (getUntransformedBounds (false));
  69972. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69973. RelativeCoordinate (bounds.getRight()),
  69974. RelativeCoordinate (bounds.getY()),
  69975. RelativeCoordinate (bounds.getBottom())));
  69976. resetBoundingBoxToContentArea();
  69977. }
  69978. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69979. {
  69980. return (xAxis ? markersX : markersY).size();
  69981. }
  69982. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69983. {
  69984. return (xAxis ? markersX : markersY) [index];
  69985. }
  69986. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69987. {
  69988. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69989. for (int i = 0; i < markers.size(); ++i)
  69990. {
  69991. Marker* const m = markers.getUnchecked(i);
  69992. if (m->name == name)
  69993. {
  69994. if (m->position != position)
  69995. {
  69996. m->position = position;
  69997. invalidatePoints();
  69998. }
  69999. return;
  70000. }
  70001. }
  70002. (xAxis ? markersX : markersY).add (new Marker (name, position));
  70003. invalidatePoints();
  70004. }
  70005. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  70006. {
  70007. jassert (index >= 2);
  70008. if (index >= 2)
  70009. (xAxis ? markersX : markersY).remove (index);
  70010. }
  70011. const AffineTransform DrawableComposite::calculateTransform() const
  70012. {
  70013. Point<float> resolved[3];
  70014. bounds.resolveThreePoints (resolved, parent);
  70015. const Rectangle<float> content (getContentArea().resolve (parent));
  70016. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  70017. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  70018. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  70019. }
  70020. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  70021. {
  70022. if (drawables.size() > 0 && context.opacity > 0)
  70023. {
  70024. if (context.opacity >= 1.0f || drawables.size() == 1)
  70025. {
  70026. Drawable::RenderingContext contextCopy (context);
  70027. contextCopy.transform = calculateTransform().followedBy (context.transform);
  70028. for (int i = 0; i < drawables.size(); ++i)
  70029. drawables.getUnchecked(i)->render (contextCopy);
  70030. }
  70031. else
  70032. {
  70033. // To correctly render a whole composite layer with an overall transparency,
  70034. // we need to render everything opaquely into a temp buffer, then blend that
  70035. // with the target opacity...
  70036. const Rectangle<int> clipBounds (context.g.getClipBounds());
  70037. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  70038. {
  70039. Graphics tempG (tempImage);
  70040. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  70041. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  70042. render (tempContext);
  70043. }
  70044. context.g.setOpacity (context.opacity);
  70045. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  70046. }
  70047. }
  70048. }
  70049. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  70050. {
  70051. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  70052. int i;
  70053. for (i = 0; i < markersX.size(); ++i)
  70054. {
  70055. Marker* const m = markersX.getUnchecked(i);
  70056. if (m->name == symbol)
  70057. return m->position.getExpression();
  70058. }
  70059. for (i = 0; i < markersY.size(); ++i)
  70060. {
  70061. Marker* const m = markersY.getUnchecked(i);
  70062. if (m->name == symbol)
  70063. return m->position.getExpression();
  70064. }
  70065. return Expression::EvaluationContext::getSymbolValue (symbol, member);
  70066. }
  70067. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  70068. {
  70069. Rectangle<float> bounds;
  70070. int i;
  70071. for (i = 0; i < drawables.size(); ++i)
  70072. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  70073. if (includeMarkers)
  70074. {
  70075. if (markersX.size() > 0)
  70076. {
  70077. float minX = std::numeric_limits<float>::max();
  70078. float maxX = std::numeric_limits<float>::min();
  70079. for (i = markersX.size(); --i >= 0;)
  70080. {
  70081. const Marker* m = markersX.getUnchecked(i);
  70082. const float pos = (float) m->position.resolve (this);
  70083. minX = jmin (minX, pos);
  70084. maxX = jmax (maxX, pos);
  70085. }
  70086. if (minX <= maxX)
  70087. {
  70088. if (bounds.getHeight() > 0)
  70089. {
  70090. minX = jmin (minX, bounds.getX());
  70091. maxX = jmax (maxX, bounds.getRight());
  70092. }
  70093. bounds.setLeft (minX);
  70094. bounds.setWidth (maxX - minX);
  70095. }
  70096. }
  70097. if (markersY.size() > 0)
  70098. {
  70099. float minY = std::numeric_limits<float>::max();
  70100. float maxY = std::numeric_limits<float>::min();
  70101. for (i = markersY.size(); --i >= 0;)
  70102. {
  70103. const Marker* m = markersY.getUnchecked(i);
  70104. const float pos = (float) m->position.resolve (this);
  70105. minY = jmin (minY, pos);
  70106. maxY = jmax (maxY, pos);
  70107. }
  70108. if (minY <= maxY)
  70109. {
  70110. if (bounds.getHeight() > 0)
  70111. {
  70112. minY = jmin (minY, bounds.getY());
  70113. maxY = jmax (maxY, bounds.getBottom());
  70114. }
  70115. bounds.setTop (minY);
  70116. bounds.setHeight (maxY - minY);
  70117. }
  70118. }
  70119. }
  70120. return bounds;
  70121. }
  70122. const Rectangle<float> DrawableComposite::getBounds() const
  70123. {
  70124. return getUntransformedBounds (true).transformed (calculateTransform());
  70125. }
  70126. bool DrawableComposite::hitTest (float x, float y) const
  70127. {
  70128. calculateTransform().inverted().transformPoint (x, y);
  70129. for (int i = 0; i < drawables.size(); ++i)
  70130. if (drawables.getUnchecked(i)->hitTest (x, y))
  70131. return true;
  70132. return false;
  70133. }
  70134. Drawable* DrawableComposite::createCopy() const
  70135. {
  70136. return new DrawableComposite (*this);
  70137. }
  70138. void DrawableComposite::invalidatePoints()
  70139. {
  70140. for (int i = 0; i < drawables.size(); ++i)
  70141. drawables.getUnchecked(i)->invalidatePoints();
  70142. }
  70143. const Identifier DrawableComposite::valueTreeType ("Group");
  70144. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70145. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70146. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70147. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70148. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70149. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70150. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  70151. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  70152. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  70153. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70154. : ValueTreeWrapperBase (state_)
  70155. {
  70156. jassert (state.hasType (valueTreeType));
  70157. }
  70158. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70159. {
  70160. return state.getChildWithName (childGroupTag);
  70161. }
  70162. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70163. {
  70164. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70165. }
  70166. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  70167. {
  70168. return getChildList().getNumChildren();
  70169. }
  70170. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  70171. {
  70172. return getChildList().getChild (index);
  70173. }
  70174. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  70175. {
  70176. if (getID() == objectId)
  70177. return state;
  70178. if (! recursive)
  70179. {
  70180. return getChildList().getChildWithProperty (idProperty, objectId);
  70181. }
  70182. else
  70183. {
  70184. const ValueTree childList (getChildList());
  70185. for (int i = getNumDrawables(); --i >= 0;)
  70186. {
  70187. const ValueTree& child = childList.getChild (i);
  70188. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  70189. return child;
  70190. if (child.hasType (DrawableComposite::valueTreeType))
  70191. {
  70192. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  70193. if (v.isValid())
  70194. return v;
  70195. }
  70196. }
  70197. return ValueTree::invalid;
  70198. }
  70199. }
  70200. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  70201. {
  70202. return getChildList().indexOf (item);
  70203. }
  70204. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  70205. {
  70206. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  70207. }
  70208. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  70209. {
  70210. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  70211. }
  70212. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  70213. {
  70214. getChildList().removeChild (child, undoManager);
  70215. }
  70216. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70217. {
  70218. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70219. state.getProperty (topRight, "100, 0"),
  70220. state.getProperty (bottomLeft, "0, 100"));
  70221. }
  70222. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70223. {
  70224. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70225. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70226. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70227. }
  70228. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70229. {
  70230. const RelativeRectangle content (getContentArea());
  70231. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70232. RelativePoint (content.right, content.top),
  70233. RelativePoint (content.left, content.bottom)), undoManager);
  70234. }
  70235. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70236. {
  70237. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  70238. getMarker (true, getMarkerState (true, 1)).position,
  70239. getMarker (false, getMarkerState (false, 0)).position,
  70240. getMarker (false, getMarkerState (false, 1)).position);
  70241. }
  70242. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70243. {
  70244. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  70245. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  70246. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  70247. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70248. }
  70249. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70250. {
  70251. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70252. }
  70253. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70254. {
  70255. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70256. }
  70257. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70258. {
  70259. return getMarkerList (xAxis).getNumChildren();
  70260. }
  70261. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70262. {
  70263. return getMarkerList (xAxis).getChild (index);
  70264. }
  70265. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70266. {
  70267. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70268. }
  70269. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70270. {
  70271. return state.isAChildOf (getMarkerList (xAxis));
  70272. }
  70273. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70274. {
  70275. jassert (containsMarker (xAxis, state));
  70276. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70277. }
  70278. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70279. {
  70280. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70281. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70282. if (marker.isValid())
  70283. {
  70284. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70285. }
  70286. else
  70287. {
  70288. marker = ValueTree (markerTag);
  70289. marker.setProperty (nameProperty, m.name, 0);
  70290. marker.setProperty (posProperty, m.position.toString(), 0);
  70291. markerList.addChild (marker, -1, undoManager);
  70292. }
  70293. }
  70294. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70295. {
  70296. if (state [nameProperty].toString() != contentLeftMarkerName
  70297. && state [nameProperty].toString() != contentRightMarkerName
  70298. && state [nameProperty].toString() != contentTopMarkerName
  70299. && state [nameProperty].toString() != contentBottomMarkerName)
  70300. return getMarkerList (xAxis).removeChild (state, undoManager);
  70301. }
  70302. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70303. {
  70304. const ValueTreeWrapper wrapper (tree);
  70305. setName (wrapper.getID());
  70306. Rectangle<float> damage;
  70307. bool redrawAll = false;
  70308. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70309. if (bounds != newBounds)
  70310. {
  70311. redrawAll = true;
  70312. damage = getBounds();
  70313. bounds = newBounds;
  70314. }
  70315. const int numMarkersX = wrapper.getNumMarkers (true);
  70316. const int numMarkersY = wrapper.getNumMarkers (false);
  70317. // Remove deleted markers...
  70318. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70319. {
  70320. if (! redrawAll)
  70321. {
  70322. redrawAll = true;
  70323. damage = getBounds();
  70324. }
  70325. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70326. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70327. }
  70328. // Update markers and add new ones..
  70329. int i;
  70330. for (i = 0; i < numMarkersX; ++i)
  70331. {
  70332. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70333. Marker* m = markersX[i];
  70334. if (m == 0 || newMarker != *m)
  70335. {
  70336. if (! redrawAll)
  70337. {
  70338. redrawAll = true;
  70339. damage = getBounds();
  70340. }
  70341. if (m == 0)
  70342. markersX.add (new Marker (newMarker));
  70343. else
  70344. *m = newMarker;
  70345. }
  70346. }
  70347. for (i = 0; i < numMarkersY; ++i)
  70348. {
  70349. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70350. Marker* m = markersY[i];
  70351. if (m == 0 || newMarker != *m)
  70352. {
  70353. if (! redrawAll)
  70354. {
  70355. redrawAll = true;
  70356. damage = getBounds();
  70357. }
  70358. if (m == 0)
  70359. markersY.add (new Marker (newMarker));
  70360. else
  70361. *m = newMarker;
  70362. }
  70363. }
  70364. // Remove deleted drawables..
  70365. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70366. {
  70367. Drawable* const d = drawables.getUnchecked(i);
  70368. if (! redrawAll)
  70369. damage = damage.getUnion (d->getBounds());
  70370. d->parent = 0;
  70371. drawables.remove (i);
  70372. }
  70373. // Update drawables and add new ones..
  70374. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70375. {
  70376. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70377. Drawable* d = drawables[i];
  70378. if (d != 0)
  70379. {
  70380. if (newDrawable.hasType (d->getValueTreeType()))
  70381. {
  70382. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70383. if (! redrawAll)
  70384. damage = damage.getUnion (area);
  70385. }
  70386. else
  70387. {
  70388. if (! redrawAll)
  70389. damage = damage.getUnion (d->getBounds());
  70390. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70391. drawables.set (i, d);
  70392. if (! redrawAll)
  70393. damage = damage.getUnion (d->getBounds());
  70394. }
  70395. }
  70396. else
  70397. {
  70398. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70399. drawables.set (i, d);
  70400. if (! redrawAll)
  70401. damage = damage.getUnion (d->getBounds());
  70402. }
  70403. }
  70404. if (redrawAll)
  70405. damage = damage.getUnion (getBounds());
  70406. else if (! damage.isEmpty())
  70407. damage = damage.transformed (calculateTransform());
  70408. return damage;
  70409. }
  70410. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70411. {
  70412. ValueTree tree (valueTreeType);
  70413. ValueTreeWrapper v (tree);
  70414. v.setID (getName(), 0);
  70415. v.setBoundingBox (bounds, 0);
  70416. int i;
  70417. for (i = 0; i < drawables.size(); ++i)
  70418. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70419. for (i = 0; i < markersX.size(); ++i)
  70420. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70421. for (i = 0; i < markersY.size(); ++i)
  70422. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70423. return tree;
  70424. }
  70425. END_JUCE_NAMESPACE
  70426. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70427. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70428. BEGIN_JUCE_NAMESPACE
  70429. DrawableImage::DrawableImage()
  70430. : image (0),
  70431. opacity (1.0f),
  70432. overlayColour (0x00000000)
  70433. {
  70434. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70435. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70436. }
  70437. DrawableImage::DrawableImage (const DrawableImage& other)
  70438. : image (other.image),
  70439. opacity (other.opacity),
  70440. overlayColour (other.overlayColour),
  70441. bounds (other.bounds)
  70442. {
  70443. }
  70444. DrawableImage::~DrawableImage()
  70445. {
  70446. }
  70447. void DrawableImage::setImage (const Image& imageToUse)
  70448. {
  70449. image = imageToUse;
  70450. if (image.isValid())
  70451. {
  70452. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70453. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70454. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70455. }
  70456. }
  70457. void DrawableImage::setOpacity (const float newOpacity)
  70458. {
  70459. opacity = newOpacity;
  70460. }
  70461. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70462. {
  70463. overlayColour = newOverlayColour;
  70464. }
  70465. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70466. {
  70467. bounds = newBounds;
  70468. }
  70469. const AffineTransform DrawableImage::calculateTransform() const
  70470. {
  70471. if (image.isNull())
  70472. return AffineTransform::identity;
  70473. Point<float> resolved[3];
  70474. bounds.resolveThreePoints (resolved, parent);
  70475. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70476. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70477. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70478. tr.getX(), tr.getY(),
  70479. bl.getX(), bl.getY());
  70480. }
  70481. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70482. {
  70483. if (image.isValid())
  70484. {
  70485. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70486. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70487. {
  70488. context.g.setOpacity (context.opacity * opacity);
  70489. context.g.drawImageTransformed (image, t, false);
  70490. }
  70491. if (! overlayColour.isTransparent())
  70492. {
  70493. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70494. context.g.drawImageTransformed (image, t, true);
  70495. }
  70496. }
  70497. }
  70498. const Rectangle<float> DrawableImage::getBounds() const
  70499. {
  70500. if (image.isNull())
  70501. return Rectangle<float>();
  70502. return bounds.getBounds (parent);
  70503. }
  70504. bool DrawableImage::hitTest (float x, float y) const
  70505. {
  70506. if (image.isNull())
  70507. return false;
  70508. calculateTransform().inverted().transformPoint (x, y);
  70509. const int ix = roundToInt (x);
  70510. const int iy = roundToInt (y);
  70511. return ix >= 0
  70512. && iy >= 0
  70513. && ix < image.getWidth()
  70514. && iy < image.getHeight()
  70515. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70516. }
  70517. Drawable* DrawableImage::createCopy() const
  70518. {
  70519. return new DrawableImage (*this);
  70520. }
  70521. void DrawableImage::invalidatePoints()
  70522. {
  70523. }
  70524. const Identifier DrawableImage::valueTreeType ("Image");
  70525. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70526. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70527. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70528. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70529. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70530. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70531. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70532. : ValueTreeWrapperBase (state_)
  70533. {
  70534. jassert (state.hasType (valueTreeType));
  70535. }
  70536. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70537. {
  70538. return state [image];
  70539. }
  70540. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70541. {
  70542. return state.getPropertyAsValue (image, undoManager);
  70543. }
  70544. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70545. {
  70546. state.setProperty (image, newIdentifier, undoManager);
  70547. }
  70548. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70549. {
  70550. return (float) state.getProperty (opacity, 1.0);
  70551. }
  70552. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70553. {
  70554. if (! state.hasProperty (opacity))
  70555. state.setProperty (opacity, 1.0, undoManager);
  70556. return state.getPropertyAsValue (opacity, undoManager);
  70557. }
  70558. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70559. {
  70560. state.setProperty (opacity, newOpacity, undoManager);
  70561. }
  70562. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70563. {
  70564. return Colour (state [overlay].toString().getHexValue32());
  70565. }
  70566. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70567. {
  70568. if (newColour.isTransparent())
  70569. state.removeProperty (overlay, undoManager);
  70570. else
  70571. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70572. }
  70573. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70574. {
  70575. return state.getPropertyAsValue (overlay, undoManager);
  70576. }
  70577. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70578. {
  70579. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70580. state.getProperty (topRight, "100, 0"),
  70581. state.getProperty (bottomLeft, "0, 100"));
  70582. }
  70583. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70584. {
  70585. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70586. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70587. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70588. }
  70589. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70590. {
  70591. const ValueTreeWrapper controller (tree);
  70592. setName (controller.getID());
  70593. const float newOpacity = controller.getOpacity();
  70594. const Colour newOverlayColour (controller.getOverlayColour());
  70595. Image newImage;
  70596. const var imageIdentifier (controller.getImageIdentifier());
  70597. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70598. if (imageProvider != 0)
  70599. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70600. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70601. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70602. {
  70603. const Rectangle<float> damage (getBounds());
  70604. opacity = newOpacity;
  70605. overlayColour = newOverlayColour;
  70606. bounds = newBounds;
  70607. image = newImage;
  70608. return damage.getUnion (getBounds());
  70609. }
  70610. return Rectangle<float>();
  70611. }
  70612. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70613. {
  70614. ValueTree tree (valueTreeType);
  70615. ValueTreeWrapper v (tree);
  70616. v.setID (getName(), 0);
  70617. v.setOpacity (opacity, 0);
  70618. v.setOverlayColour (overlayColour, 0);
  70619. v.setBoundingBox (bounds, 0);
  70620. if (image.isValid())
  70621. {
  70622. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70623. if (imageProvider != 0)
  70624. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70625. }
  70626. return tree;
  70627. }
  70628. END_JUCE_NAMESPACE
  70629. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70630. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70631. BEGIN_JUCE_NAMESPACE
  70632. DrawablePath::DrawablePath()
  70633. : mainFill (Colours::black),
  70634. strokeFill (Colours::black),
  70635. strokeType (0.0f),
  70636. pathNeedsUpdating (true),
  70637. strokeNeedsUpdating (true)
  70638. {
  70639. }
  70640. DrawablePath::DrawablePath (const DrawablePath& other)
  70641. : mainFill (other.mainFill),
  70642. strokeFill (other.strokeFill),
  70643. strokeType (other.strokeType),
  70644. pathNeedsUpdating (true),
  70645. strokeNeedsUpdating (true)
  70646. {
  70647. if (other.relativePath != 0)
  70648. relativePath = new RelativePointPath (*other.relativePath);
  70649. else
  70650. path = other.path;
  70651. }
  70652. DrawablePath::~DrawablePath()
  70653. {
  70654. }
  70655. void DrawablePath::setPath (const Path& newPath)
  70656. {
  70657. path = newPath;
  70658. strokeNeedsUpdating = true;
  70659. }
  70660. void DrawablePath::setFill (const FillType& newFill)
  70661. {
  70662. mainFill = newFill;
  70663. }
  70664. void DrawablePath::setStrokeFill (const FillType& newFill)
  70665. {
  70666. strokeFill = newFill;
  70667. }
  70668. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  70669. {
  70670. strokeType = newStrokeType;
  70671. strokeNeedsUpdating = true;
  70672. }
  70673. void DrawablePath::setStrokeThickness (const float newThickness)
  70674. {
  70675. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70676. }
  70677. void DrawablePath::updatePath() const
  70678. {
  70679. if (pathNeedsUpdating)
  70680. {
  70681. pathNeedsUpdating = false;
  70682. if (relativePath != 0)
  70683. {
  70684. path.clear();
  70685. relativePath->createPath (path, parent);
  70686. strokeNeedsUpdating = true;
  70687. }
  70688. }
  70689. }
  70690. void DrawablePath::updateStroke() const
  70691. {
  70692. if (strokeNeedsUpdating)
  70693. {
  70694. strokeNeedsUpdating = false;
  70695. updatePath();
  70696. stroke.clear();
  70697. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  70698. }
  70699. }
  70700. const Path& DrawablePath::getPath() const
  70701. {
  70702. updatePath();
  70703. return path;
  70704. }
  70705. const Path& DrawablePath::getStrokePath() const
  70706. {
  70707. updateStroke();
  70708. return stroke;
  70709. }
  70710. bool DrawablePath::isStrokeVisible() const throw()
  70711. {
  70712. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  70713. }
  70714. void DrawablePath::invalidatePoints()
  70715. {
  70716. pathNeedsUpdating = true;
  70717. strokeNeedsUpdating = true;
  70718. }
  70719. void DrawablePath::render (const Drawable::RenderingContext& context) const
  70720. {
  70721. {
  70722. FillType f (mainFill);
  70723. if (f.isGradient())
  70724. f.gradient->multiplyOpacity (context.opacity);
  70725. else
  70726. f.setOpacity (f.getOpacity() * context.opacity);
  70727. f.transform = f.transform.followedBy (context.transform);
  70728. context.g.setFillType (f);
  70729. context.g.fillPath (getPath(), context.transform);
  70730. }
  70731. if (isStrokeVisible())
  70732. {
  70733. FillType f (strokeFill);
  70734. if (f.isGradient())
  70735. f.gradient->multiplyOpacity (context.opacity);
  70736. else
  70737. f.setOpacity (f.getOpacity() * context.opacity);
  70738. f.transform = f.transform.followedBy (context.transform);
  70739. context.g.setFillType (f);
  70740. context.g.fillPath (getStrokePath(), context.transform);
  70741. }
  70742. }
  70743. const Rectangle<float> DrawablePath::getBounds() const
  70744. {
  70745. if (isStrokeVisible())
  70746. return getStrokePath().getBounds();
  70747. else
  70748. return getPath().getBounds();
  70749. }
  70750. bool DrawablePath::hitTest (float x, float y) const
  70751. {
  70752. return getPath().contains (x, y)
  70753. || (isStrokeVisible() && getStrokePath().contains (x, y));
  70754. }
  70755. Drawable* DrawablePath::createCopy() const
  70756. {
  70757. return new DrawablePath (*this);
  70758. }
  70759. const Identifier DrawablePath::valueTreeType ("Path");
  70760. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  70761. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  70762. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  70763. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  70764. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  70765. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  70766. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70767. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70768. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70769. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70770. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70771. : ValueTreeWrapperBase (state_)
  70772. {
  70773. jassert (state.hasType (valueTreeType));
  70774. }
  70775. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70776. {
  70777. return state.getOrCreateChildWithName (path, 0);
  70778. }
  70779. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  70780. {
  70781. ValueTree v (state.getChildWithName (fill));
  70782. if (v.isValid())
  70783. return v;
  70784. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  70785. return getMainFillState();
  70786. }
  70787. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  70788. {
  70789. ValueTree v (state.getChildWithName (stroke));
  70790. if (v.isValid())
  70791. return v;
  70792. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  70793. return getStrokeFillState();
  70794. }
  70795. const FillType DrawablePath::ValueTreeWrapper::getMainFill (Expression::EvaluationContext* nameFinder,
  70796. ImageProvider* imageProvider) const
  70797. {
  70798. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  70799. }
  70800. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  70801. const RelativePoint* gp2, const RelativePoint* gp3,
  70802. ImageProvider* imageProvider, UndoManager* undoManager)
  70803. {
  70804. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  70805. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70806. }
  70807. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (Expression::EvaluationContext* nameFinder,
  70808. ImageProvider* imageProvider) const
  70809. {
  70810. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  70811. }
  70812. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  70813. const RelativePoint* gp2, const RelativePoint* gp3,
  70814. ImageProvider* imageProvider, UndoManager* undoManager)
  70815. {
  70816. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  70817. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70818. }
  70819. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  70820. {
  70821. const String jointStyleString (state [jointStyle].toString());
  70822. const String capStyleString (state [capStyle].toString());
  70823. return PathStrokeType (state [strokeWidth],
  70824. jointStyleString == "curved" ? PathStrokeType::curved
  70825. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70826. : PathStrokeType::mitered),
  70827. capStyleString == "square" ? PathStrokeType::square
  70828. : (capStyleString == "round" ? PathStrokeType::rounded
  70829. : PathStrokeType::butt));
  70830. }
  70831. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70832. {
  70833. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70834. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70835. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70836. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70837. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70838. }
  70839. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70840. {
  70841. return state [nonZeroWinding];
  70842. }
  70843. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70844. {
  70845. state.setProperty (nonZeroWinding, b, undoManager);
  70846. }
  70847. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70848. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70849. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70850. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70851. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70852. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70853. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70854. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70855. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70856. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70857. : state (state_)
  70858. {
  70859. }
  70860. DrawablePath::ValueTreeWrapper::Element::~Element()
  70861. {
  70862. }
  70863. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70864. {
  70865. return ValueTreeWrapper (state.getParent().getParent());
  70866. }
  70867. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70868. {
  70869. return Element (state.getSibling (-1));
  70870. }
  70871. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70872. {
  70873. const Identifier i (state.getType());
  70874. if (i == startSubPathElement || i == lineToElement) return 1;
  70875. if (i == quadraticToElement) return 2;
  70876. if (i == cubicToElement) return 3;
  70877. return 0;
  70878. }
  70879. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70880. {
  70881. jassert (index >= 0 && index < getNumControlPoints());
  70882. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70883. }
  70884. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70885. {
  70886. jassert (index >= 0 && index < getNumControlPoints());
  70887. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70888. }
  70889. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70890. {
  70891. jassert (index >= 0 && index < getNumControlPoints());
  70892. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70893. }
  70894. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70895. {
  70896. const Identifier i (state.getType());
  70897. if (i == startSubPathElement)
  70898. return getControlPoint (0);
  70899. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70900. return getPreviousElement().getEndPoint();
  70901. }
  70902. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70903. {
  70904. const Identifier i (state.getType());
  70905. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70906. if (i == quadraticToElement) return getControlPoint (1);
  70907. if (i == cubicToElement) return getControlPoint (2);
  70908. jassert (i == closeSubPathElement);
  70909. return RelativePoint();
  70910. }
  70911. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70912. {
  70913. const Identifier i (state.getType());
  70914. if (i == lineToElement || i == closeSubPathElement)
  70915. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70916. if (i == cubicToElement)
  70917. {
  70918. Path p;
  70919. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70920. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70921. return p.getLength();
  70922. }
  70923. if (i == quadraticToElement)
  70924. {
  70925. Path p;
  70926. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70927. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70928. return p.getLength();
  70929. }
  70930. jassert (i == startSubPathElement);
  70931. return 0;
  70932. }
  70933. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70934. {
  70935. return state [mode].toString();
  70936. }
  70937. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70938. {
  70939. if (state.hasType (cubicToElement))
  70940. state.setProperty (mode, newMode, undoManager);
  70941. }
  70942. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70943. {
  70944. const Identifier i (state.getType());
  70945. if (i == quadraticToElement || i == cubicToElement)
  70946. {
  70947. ValueTree newState (lineToElement);
  70948. Element e (newState);
  70949. e.setControlPoint (0, getEndPoint(), undoManager);
  70950. state = newState;
  70951. }
  70952. }
  70953. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70954. {
  70955. const Identifier i (state.getType());
  70956. if (i == lineToElement || i == quadraticToElement)
  70957. {
  70958. ValueTree newState (cubicToElement);
  70959. Element e (newState);
  70960. const RelativePoint start (getStartPoint());
  70961. const RelativePoint end (getEndPoint());
  70962. const Point<float> startResolved (start.resolve (nameFinder));
  70963. const Point<float> endResolved (end.resolve (nameFinder));
  70964. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70965. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70966. e.setControlPoint (2, end, undoManager);
  70967. state = newState;
  70968. }
  70969. }
  70970. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70971. {
  70972. const Identifier i (state.getType());
  70973. if (i != startSubPathElement)
  70974. {
  70975. ValueTree newState (startSubPathElement);
  70976. Element e (newState);
  70977. e.setControlPoint (0, getEndPoint(), undoManager);
  70978. state = newState;
  70979. }
  70980. }
  70981. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70982. {
  70983. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70984. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70985. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70986. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70987. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70988. return newCp1 + (newCp2 - newCp1) * proportion;
  70989. }
  70990. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70991. {
  70992. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70993. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70994. return mid1 + (mid2 - mid1) * proportion;
  70995. }
  70996. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70997. {
  70998. const Identifier i (state.getType());
  70999. float bestProp = 0;
  71000. if (i == cubicToElement)
  71001. {
  71002. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  71003. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  71004. float bestDistance = std::numeric_limits<float>::max();
  71005. for (int i = 110; --i >= 0;)
  71006. {
  71007. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  71008. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  71009. const float distance = centre.getDistanceFrom (targetPoint);
  71010. if (distance < bestDistance)
  71011. {
  71012. bestProp = prop;
  71013. bestDistance = distance;
  71014. }
  71015. }
  71016. }
  71017. else if (i == quadraticToElement)
  71018. {
  71019. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  71020. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  71021. float bestDistance = std::numeric_limits<float>::max();
  71022. for (int i = 110; --i >= 0;)
  71023. {
  71024. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  71025. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  71026. const float distance = centre.getDistanceFrom (targetPoint);
  71027. if (distance < bestDistance)
  71028. {
  71029. bestProp = prop;
  71030. bestDistance = distance;
  71031. }
  71032. }
  71033. }
  71034. else if (i == lineToElement)
  71035. {
  71036. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  71037. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  71038. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  71039. }
  71040. return bestProp;
  71041. }
  71042. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  71043. {
  71044. ValueTree newTree;
  71045. const Identifier i (state.getType());
  71046. if (i == cubicToElement)
  71047. {
  71048. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  71049. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  71050. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  71051. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  71052. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  71053. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  71054. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  71055. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  71056. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  71057. setControlPoint (0, mid1, undoManager);
  71058. setControlPoint (1, newCp1, undoManager);
  71059. setControlPoint (2, newCentre, undoManager);
  71060. setModeOfEndPoint (roundedMode, undoManager);
  71061. Element newElement (newTree = ValueTree (cubicToElement));
  71062. newElement.setControlPoint (0, newCp2, 0);
  71063. newElement.setControlPoint (1, mid3, 0);
  71064. newElement.setControlPoint (2, rp4, 0);
  71065. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71066. }
  71067. else if (i == quadraticToElement)
  71068. {
  71069. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  71070. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  71071. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  71072. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  71073. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  71074. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  71075. setControlPoint (0, mid1, undoManager);
  71076. setControlPoint (1, newCentre, undoManager);
  71077. setModeOfEndPoint (roundedMode, undoManager);
  71078. Element newElement (newTree = ValueTree (quadraticToElement));
  71079. newElement.setControlPoint (0, mid2, 0);
  71080. newElement.setControlPoint (1, rp3, 0);
  71081. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71082. }
  71083. else if (i == lineToElement)
  71084. {
  71085. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  71086. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  71087. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  71088. setControlPoint (0, newPoint, undoManager);
  71089. Element newElement (newTree = ValueTree (lineToElement));
  71090. newElement.setControlPoint (0, rp2, 0);
  71091. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  71092. }
  71093. else if (i == closeSubPathElement)
  71094. {
  71095. }
  71096. return newTree;
  71097. }
  71098. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  71099. {
  71100. state.getParent().removeChild (state, undoManager);
  71101. }
  71102. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  71103. {
  71104. Rectangle<float> damageRect;
  71105. ValueTreeWrapper v (tree);
  71106. setName (v.getID());
  71107. bool needsRedraw = false;
  71108. const FillType newFill (v.getMainFill (parent, imageProvider));
  71109. if (mainFill != newFill)
  71110. {
  71111. needsRedraw = true;
  71112. mainFill = newFill;
  71113. }
  71114. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  71115. if (strokeFill != newStrokeFill)
  71116. {
  71117. needsRedraw = true;
  71118. strokeFill = newStrokeFill;
  71119. }
  71120. const PathStrokeType newStroke (v.getStrokeType());
  71121. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  71122. Path newPath;
  71123. newRelativePath->createPath (newPath, parent);
  71124. if (! newRelativePath->containsAnyDynamicPoints())
  71125. newRelativePath = 0;
  71126. if (strokeType != newStroke || path != newPath)
  71127. {
  71128. damageRect = getBounds();
  71129. path.swapWithPath (newPath);
  71130. strokeNeedsUpdating = true;
  71131. strokeType = newStroke;
  71132. needsRedraw = true;
  71133. }
  71134. relativePath = newRelativePath;
  71135. if (needsRedraw)
  71136. damageRect = damageRect.getUnion (getBounds());
  71137. return damageRect;
  71138. }
  71139. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  71140. {
  71141. ValueTree tree (valueTreeType);
  71142. ValueTreeWrapper v (tree);
  71143. v.setID (getName(), 0);
  71144. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  71145. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  71146. v.setStrokeType (strokeType, 0);
  71147. if (relativePath != 0)
  71148. {
  71149. relativePath->writeTo (tree, 0);
  71150. }
  71151. else
  71152. {
  71153. RelativePointPath rp (path);
  71154. rp.writeTo (tree, 0);
  71155. }
  71156. return tree;
  71157. }
  71158. END_JUCE_NAMESPACE
  71159. /*** End of inlined file: juce_DrawablePath.cpp ***/
  71160. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71161. BEGIN_JUCE_NAMESPACE
  71162. DrawableText::DrawableText()
  71163. : colour (Colours::black),
  71164. justification (Justification::centredLeft)
  71165. {
  71166. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71167. RelativePoint (50.0f, 0.0f),
  71168. RelativePoint (0.0f, 20.0f)));
  71169. setFont (Font (15.0f), true);
  71170. }
  71171. DrawableText::DrawableText (const DrawableText& other)
  71172. : text (other.text),
  71173. font (other.font),
  71174. colour (other.colour),
  71175. justification (other.justification),
  71176. bounds (other.bounds),
  71177. fontSizeControlPoint (other.fontSizeControlPoint)
  71178. {
  71179. }
  71180. DrawableText::~DrawableText()
  71181. {
  71182. }
  71183. void DrawableText::setText (const String& newText)
  71184. {
  71185. text = newText;
  71186. }
  71187. void DrawableText::setColour (const Colour& newColour)
  71188. {
  71189. colour = newColour;
  71190. }
  71191. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71192. {
  71193. font = newFont;
  71194. if (applySizeAndScale)
  71195. {
  71196. Point<float> corners[3];
  71197. bounds.resolveThreePoints (corners, parent);
  71198. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  71199. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71200. }
  71201. }
  71202. void DrawableText::setJustification (const Justification& newJustification)
  71203. {
  71204. justification = newJustification;
  71205. }
  71206. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71207. {
  71208. bounds = newBounds;
  71209. }
  71210. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71211. {
  71212. fontSizeControlPoint = newPoint;
  71213. }
  71214. void DrawableText::render (const Drawable::RenderingContext& context) const
  71215. {
  71216. Point<float> points[3];
  71217. bounds.resolveThreePoints (points, parent);
  71218. const float w = Line<float> (points[0], points[1]).getLength();
  71219. const float h = Line<float> (points[0], points[2]).getLength();
  71220. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  71221. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  71222. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  71223. Font f (font);
  71224. f.setHeight (fontHeight);
  71225. f.setHorizontalScale (fontWidth / fontHeight);
  71226. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  71227. GlyphArrangement ga;
  71228. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  71229. ga.draw (context.g,
  71230. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71231. w, 0, points[1].getX(), points[1].getY(),
  71232. 0, h, points[2].getX(), points[2].getY())
  71233. .followedBy (context.transform));
  71234. }
  71235. const Rectangle<float> DrawableText::getBounds() const
  71236. {
  71237. return bounds.getBounds (parent);
  71238. }
  71239. bool DrawableText::hitTest (float x, float y) const
  71240. {
  71241. Path p;
  71242. bounds.getPath (p, parent);
  71243. return p.contains (x, y);
  71244. }
  71245. Drawable* DrawableText::createCopy() const
  71246. {
  71247. return new DrawableText (*this);
  71248. }
  71249. void DrawableText::invalidatePoints()
  71250. {
  71251. }
  71252. const Identifier DrawableText::valueTreeType ("Text");
  71253. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71254. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71255. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71256. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71257. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71258. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71259. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71260. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71261. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71262. : ValueTreeWrapperBase (state_)
  71263. {
  71264. jassert (state.hasType (valueTreeType));
  71265. }
  71266. const String DrawableText::ValueTreeWrapper::getText() const
  71267. {
  71268. return state [text].toString();
  71269. }
  71270. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71271. {
  71272. state.setProperty (text, newText, undoManager);
  71273. }
  71274. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71275. {
  71276. return state.getPropertyAsValue (text, undoManager);
  71277. }
  71278. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71279. {
  71280. return Colour::fromString (state [colour].toString());
  71281. }
  71282. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71283. {
  71284. state.setProperty (colour, newColour.toString(), undoManager);
  71285. }
  71286. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71287. {
  71288. return Justification ((int) state [justification]);
  71289. }
  71290. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71291. {
  71292. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71293. }
  71294. const Font DrawableText::ValueTreeWrapper::getFont() const
  71295. {
  71296. return Font::fromString (state [font]);
  71297. }
  71298. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71299. {
  71300. state.setProperty (font, newFont.toString(), undoManager);
  71301. }
  71302. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71303. {
  71304. return state.getPropertyAsValue (font, undoManager);
  71305. }
  71306. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71307. {
  71308. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71309. }
  71310. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71311. {
  71312. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71313. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71314. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71315. }
  71316. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71317. {
  71318. return state [fontSizeAnchor].toString();
  71319. }
  71320. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71321. {
  71322. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71323. }
  71324. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71325. {
  71326. ValueTreeWrapper v (tree);
  71327. setName (v.getID());
  71328. const RelativeParallelogram newBounds (v.getBoundingBox());
  71329. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71330. const Colour newColour (v.getColour());
  71331. const Justification newJustification (v.getJustification());
  71332. const String newText (v.getText());
  71333. const Font newFont (v.getFont());
  71334. if (text != newText || font != newFont || justification != newJustification
  71335. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71336. {
  71337. const Rectangle<float> damage (getBounds());
  71338. setBoundingBox (newBounds);
  71339. setFontSizeControlPoint (newFontPoint);
  71340. setColour (newColour);
  71341. setFont (newFont, false);
  71342. setJustification (newJustification);
  71343. setText (newText);
  71344. return damage.getUnion (getBounds());
  71345. }
  71346. return Rectangle<float>();
  71347. }
  71348. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71349. {
  71350. ValueTree tree (valueTreeType);
  71351. ValueTreeWrapper v (tree);
  71352. v.setID (getName(), 0);
  71353. v.setText (text, 0);
  71354. v.setFont (font, 0);
  71355. v.setJustification (justification, 0);
  71356. v.setColour (colour, 0);
  71357. v.setBoundingBox (bounds, 0);
  71358. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71359. return tree;
  71360. }
  71361. END_JUCE_NAMESPACE
  71362. /*** End of inlined file: juce_DrawableText.cpp ***/
  71363. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71364. BEGIN_JUCE_NAMESPACE
  71365. class SVGState
  71366. {
  71367. public:
  71368. SVGState (const XmlElement* const topLevel)
  71369. : topLevelXml (topLevel),
  71370. elementX (0), elementY (0),
  71371. width (512), height (512),
  71372. viewBoxW (0), viewBoxH (0)
  71373. {
  71374. }
  71375. ~SVGState()
  71376. {
  71377. }
  71378. Drawable* parseSVGElement (const XmlElement& xml)
  71379. {
  71380. if (! xml.hasTagName ("svg"))
  71381. return 0;
  71382. DrawableComposite* const drawable = new DrawableComposite();
  71383. drawable->setName (xml.getStringAttribute ("id"));
  71384. SVGState newState (*this);
  71385. if (xml.hasAttribute ("transform"))
  71386. newState.addTransform (xml);
  71387. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71388. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71389. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71390. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71391. if (xml.hasAttribute ("viewBox"))
  71392. {
  71393. const String viewParams (xml.getStringAttribute ("viewBox"));
  71394. int i = 0;
  71395. float vx, vy, vw, vh;
  71396. if (parseCoords (viewParams, vx, vy, i, true)
  71397. && parseCoords (viewParams, vw, vh, i, true)
  71398. && vw > 0
  71399. && vh > 0)
  71400. {
  71401. newState.viewBoxW = vw;
  71402. newState.viewBoxH = vh;
  71403. int placementFlags = 0;
  71404. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71405. if (aspect.containsIgnoreCase ("none"))
  71406. {
  71407. placementFlags = RectanglePlacement::stretchToFit;
  71408. }
  71409. else
  71410. {
  71411. if (aspect.containsIgnoreCase ("slice"))
  71412. placementFlags |= RectanglePlacement::fillDestination;
  71413. if (aspect.containsIgnoreCase ("xMin"))
  71414. placementFlags |= RectanglePlacement::xLeft;
  71415. else if (aspect.containsIgnoreCase ("xMax"))
  71416. placementFlags |= RectanglePlacement::xRight;
  71417. else
  71418. placementFlags |= RectanglePlacement::xMid;
  71419. if (aspect.containsIgnoreCase ("yMin"))
  71420. placementFlags |= RectanglePlacement::yTop;
  71421. else if (aspect.containsIgnoreCase ("yMax"))
  71422. placementFlags |= RectanglePlacement::yBottom;
  71423. else
  71424. placementFlags |= RectanglePlacement::yMid;
  71425. }
  71426. const RectanglePlacement placement (placementFlags);
  71427. newState.transform
  71428. = placement.getTransformToFit (vx, vy, vw, vh,
  71429. 0.0f, 0.0f, newState.width, newState.height)
  71430. .followedBy (newState.transform);
  71431. }
  71432. }
  71433. else
  71434. {
  71435. if (viewBoxW == 0)
  71436. newState.viewBoxW = newState.width;
  71437. if (viewBoxH == 0)
  71438. newState.viewBoxH = newState.height;
  71439. }
  71440. newState.parseSubElements (xml, drawable);
  71441. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71442. return drawable;
  71443. }
  71444. private:
  71445. const XmlElement* const topLevelXml;
  71446. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71447. AffineTransform transform;
  71448. String cssStyleText;
  71449. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71450. {
  71451. forEachXmlChildElement (xml, e)
  71452. {
  71453. Drawable* d = 0;
  71454. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71455. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71456. else if (e->hasTagName ("path")) d = parsePath (*e);
  71457. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71458. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71459. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71460. else if (e->hasTagName ("line")) d = parseLine (*e);
  71461. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71462. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71463. else if (e->hasTagName ("text")) d = parseText (*e);
  71464. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71465. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71466. parentDrawable->insertDrawable (d);
  71467. }
  71468. }
  71469. DrawableComposite* parseSwitch (const XmlElement& xml)
  71470. {
  71471. const XmlElement* const group = xml.getChildByName ("g");
  71472. if (group != 0)
  71473. return parseGroupElement (*group);
  71474. return 0;
  71475. }
  71476. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71477. {
  71478. DrawableComposite* const drawable = new DrawableComposite();
  71479. drawable->setName (xml.getStringAttribute ("id"));
  71480. if (xml.hasAttribute ("transform"))
  71481. {
  71482. SVGState newState (*this);
  71483. newState.addTransform (xml);
  71484. newState.parseSubElements (xml, drawable);
  71485. }
  71486. else
  71487. {
  71488. parseSubElements (xml, drawable);
  71489. }
  71490. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71491. return drawable;
  71492. }
  71493. Drawable* parsePath (const XmlElement& xml) const
  71494. {
  71495. const String d (xml.getStringAttribute ("d").trimStart());
  71496. Path path;
  71497. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71498. path.setUsingNonZeroWinding (false);
  71499. int index = 0;
  71500. float lastX = 0, lastY = 0;
  71501. float lastX2 = 0, lastY2 = 0;
  71502. juce_wchar lastCommandChar = 0;
  71503. bool isRelative = true;
  71504. bool carryOn = true;
  71505. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71506. while (d[index] != 0)
  71507. {
  71508. float x, y, x2, y2, x3, y3;
  71509. if (validCommandChars.containsChar (d[index]))
  71510. {
  71511. lastCommandChar = d [index++];
  71512. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71513. }
  71514. switch (lastCommandChar)
  71515. {
  71516. case 'M':
  71517. case 'm':
  71518. case 'L':
  71519. case 'l':
  71520. if (parseCoords (d, x, y, index, false))
  71521. {
  71522. if (isRelative)
  71523. {
  71524. x += lastX;
  71525. y += lastY;
  71526. }
  71527. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71528. {
  71529. path.startNewSubPath (x, y);
  71530. lastCommandChar = 'l';
  71531. }
  71532. else
  71533. path.lineTo (x, y);
  71534. lastX2 = lastX;
  71535. lastY2 = lastY;
  71536. lastX = x;
  71537. lastY = y;
  71538. }
  71539. else
  71540. {
  71541. ++index;
  71542. }
  71543. break;
  71544. case 'H':
  71545. case 'h':
  71546. if (parseCoord (d, x, index, false, true))
  71547. {
  71548. if (isRelative)
  71549. x += lastX;
  71550. path.lineTo (x, lastY);
  71551. lastX2 = lastX;
  71552. lastX = x;
  71553. }
  71554. else
  71555. {
  71556. ++index;
  71557. }
  71558. break;
  71559. case 'V':
  71560. case 'v':
  71561. if (parseCoord (d, y, index, false, false))
  71562. {
  71563. if (isRelative)
  71564. y += lastY;
  71565. path.lineTo (lastX, y);
  71566. lastY2 = lastY;
  71567. lastY = y;
  71568. }
  71569. else
  71570. {
  71571. ++index;
  71572. }
  71573. break;
  71574. case 'C':
  71575. case 'c':
  71576. if (parseCoords (d, x, y, index, false)
  71577. && parseCoords (d, x2, y2, index, false)
  71578. && parseCoords (d, x3, y3, index, false))
  71579. {
  71580. if (isRelative)
  71581. {
  71582. x += lastX;
  71583. y += lastY;
  71584. x2 += lastX;
  71585. y2 += lastY;
  71586. x3 += lastX;
  71587. y3 += lastY;
  71588. }
  71589. path.cubicTo (x, y, x2, y2, x3, y3);
  71590. lastX2 = x2;
  71591. lastY2 = y2;
  71592. lastX = x3;
  71593. lastY = y3;
  71594. }
  71595. else
  71596. {
  71597. ++index;
  71598. }
  71599. break;
  71600. case 'S':
  71601. case 's':
  71602. if (parseCoords (d, x, y, index, false)
  71603. && parseCoords (d, x3, y3, index, false))
  71604. {
  71605. if (isRelative)
  71606. {
  71607. x += lastX;
  71608. y += lastY;
  71609. x3 += lastX;
  71610. y3 += lastY;
  71611. }
  71612. x2 = lastX + (lastX - lastX2);
  71613. y2 = lastY + (lastY - lastY2);
  71614. path.cubicTo (x2, y2, x, y, x3, y3);
  71615. lastX2 = x;
  71616. lastY2 = y;
  71617. lastX = x3;
  71618. lastY = y3;
  71619. }
  71620. else
  71621. {
  71622. ++index;
  71623. }
  71624. break;
  71625. case 'Q':
  71626. case 'q':
  71627. if (parseCoords (d, x, y, index, false)
  71628. && parseCoords (d, x2, y2, index, false))
  71629. {
  71630. if (isRelative)
  71631. {
  71632. x += lastX;
  71633. y += lastY;
  71634. x2 += lastX;
  71635. y2 += lastY;
  71636. }
  71637. path.quadraticTo (x, y, x2, y2);
  71638. lastX2 = x;
  71639. lastY2 = y;
  71640. lastX = x2;
  71641. lastY = y2;
  71642. }
  71643. else
  71644. {
  71645. ++index;
  71646. }
  71647. break;
  71648. case 'T':
  71649. case 't':
  71650. if (parseCoords (d, x, y, index, false))
  71651. {
  71652. if (isRelative)
  71653. {
  71654. x += lastX;
  71655. y += lastY;
  71656. }
  71657. x2 = lastX + (lastX - lastX2);
  71658. y2 = lastY + (lastY - lastY2);
  71659. path.quadraticTo (x2, y2, x, y);
  71660. lastX2 = x2;
  71661. lastY2 = y2;
  71662. lastX = x;
  71663. lastY = y;
  71664. }
  71665. else
  71666. {
  71667. ++index;
  71668. }
  71669. break;
  71670. case 'A':
  71671. case 'a':
  71672. if (parseCoords (d, x, y, index, false))
  71673. {
  71674. String num;
  71675. if (parseNextNumber (d, num, index, false))
  71676. {
  71677. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71678. if (parseNextNumber (d, num, index, false))
  71679. {
  71680. const bool largeArc = num.getIntValue() != 0;
  71681. if (parseNextNumber (d, num, index, false))
  71682. {
  71683. const bool sweep = num.getIntValue() != 0;
  71684. if (parseCoords (d, x2, y2, index, false))
  71685. {
  71686. if (isRelative)
  71687. {
  71688. x2 += lastX;
  71689. y2 += lastY;
  71690. }
  71691. if (lastX != x2 || lastY != y2)
  71692. {
  71693. double centreX, centreY, startAngle, deltaAngle;
  71694. double rx = x, ry = y;
  71695. endpointToCentreParameters (lastX, lastY, x2, y2,
  71696. angle, largeArc, sweep,
  71697. rx, ry, centreX, centreY,
  71698. startAngle, deltaAngle);
  71699. path.addCentredArc ((float) centreX, (float) centreY,
  71700. (float) rx, (float) ry,
  71701. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71702. false);
  71703. path.lineTo (x2, y2);
  71704. }
  71705. lastX2 = lastX;
  71706. lastY2 = lastY;
  71707. lastX = x2;
  71708. lastY = y2;
  71709. }
  71710. }
  71711. }
  71712. }
  71713. }
  71714. else
  71715. {
  71716. ++index;
  71717. }
  71718. break;
  71719. case 'Z':
  71720. case 'z':
  71721. path.closeSubPath();
  71722. while (CharacterFunctions::isWhitespace (d [index]))
  71723. ++index;
  71724. break;
  71725. default:
  71726. carryOn = false;
  71727. break;
  71728. }
  71729. if (! carryOn)
  71730. break;
  71731. }
  71732. return parseShape (xml, path);
  71733. }
  71734. Drawable* parseRect (const XmlElement& xml) const
  71735. {
  71736. Path rect;
  71737. const bool hasRX = xml.hasAttribute ("rx");
  71738. const bool hasRY = xml.hasAttribute ("ry");
  71739. if (hasRX || hasRY)
  71740. {
  71741. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71742. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71743. if (! hasRX)
  71744. rx = ry;
  71745. else if (! hasRY)
  71746. ry = rx;
  71747. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71748. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71749. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71750. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71751. rx, ry);
  71752. }
  71753. else
  71754. {
  71755. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71756. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71757. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71758. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71759. }
  71760. return parseShape (xml, rect);
  71761. }
  71762. Drawable* parseCircle (const XmlElement& xml) const
  71763. {
  71764. Path circle;
  71765. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71766. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71767. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71768. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71769. return parseShape (xml, circle);
  71770. }
  71771. Drawable* parseEllipse (const XmlElement& xml) const
  71772. {
  71773. Path ellipse;
  71774. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71775. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71776. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71777. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71778. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71779. return parseShape (xml, ellipse);
  71780. }
  71781. Drawable* parseLine (const XmlElement& xml) const
  71782. {
  71783. Path line;
  71784. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71785. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71786. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71787. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71788. line.startNewSubPath (x1, y1);
  71789. line.lineTo (x2, y2);
  71790. return parseShape (xml, line);
  71791. }
  71792. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71793. {
  71794. const String points (xml.getStringAttribute ("points"));
  71795. Path path;
  71796. int index = 0;
  71797. float x, y;
  71798. if (parseCoords (points, x, y, index, true))
  71799. {
  71800. float firstX = x;
  71801. float firstY = y;
  71802. float lastX = 0, lastY = 0;
  71803. path.startNewSubPath (x, y);
  71804. while (parseCoords (points, x, y, index, true))
  71805. {
  71806. lastX = x;
  71807. lastY = y;
  71808. path.lineTo (x, y);
  71809. }
  71810. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71811. path.closeSubPath();
  71812. }
  71813. return parseShape (xml, path);
  71814. }
  71815. Drawable* parseShape (const XmlElement& xml, Path& path,
  71816. const bool shouldParseTransform = true) const
  71817. {
  71818. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71819. {
  71820. SVGState newState (*this);
  71821. newState.addTransform (xml);
  71822. return newState.parseShape (xml, path, false);
  71823. }
  71824. DrawablePath* dp = new DrawablePath();
  71825. dp->setName (xml.getStringAttribute ("id"));
  71826. dp->setFill (Colours::transparentBlack);
  71827. path.applyTransform (transform);
  71828. dp->setPath (path);
  71829. Path::Iterator iter (path);
  71830. bool containsClosedSubPath = false;
  71831. while (iter.next())
  71832. {
  71833. if (iter.elementType == Path::Iterator::closePath)
  71834. {
  71835. containsClosedSubPath = true;
  71836. break;
  71837. }
  71838. }
  71839. dp->setFill (getPathFillType (path,
  71840. getStyleAttribute (&xml, "fill"),
  71841. getStyleAttribute (&xml, "fill-opacity"),
  71842. getStyleAttribute (&xml, "opacity"),
  71843. containsClosedSubPath ? Colours::black
  71844. : Colours::transparentBlack));
  71845. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71846. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71847. {
  71848. dp->setStrokeFill (getPathFillType (path, strokeType,
  71849. getStyleAttribute (&xml, "stroke-opacity"),
  71850. getStyleAttribute (&xml, "opacity"),
  71851. Colours::transparentBlack));
  71852. dp->setStrokeType (getStrokeFor (&xml));
  71853. }
  71854. return dp;
  71855. }
  71856. const XmlElement* findLinkedElement (const XmlElement* e) const
  71857. {
  71858. const String id (e->getStringAttribute ("xlink:href"));
  71859. if (! id.startsWithChar ('#'))
  71860. return 0;
  71861. return findElementForId (topLevelXml, id.substring (1));
  71862. }
  71863. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71864. {
  71865. if (fillXml == 0)
  71866. return;
  71867. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71868. {
  71869. int index = 0;
  71870. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71871. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71872. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71873. double offset = e->getDoubleAttribute ("offset");
  71874. if (e->getStringAttribute ("offset").containsChar ('%'))
  71875. offset *= 0.01;
  71876. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71877. }
  71878. }
  71879. const FillType getPathFillType (const Path& path,
  71880. const String& fill,
  71881. const String& fillOpacity,
  71882. const String& overallOpacity,
  71883. const Colour& defaultColour) const
  71884. {
  71885. float opacity = 1.0f;
  71886. if (overallOpacity.isNotEmpty())
  71887. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71888. if (fillOpacity.isNotEmpty())
  71889. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71890. if (fill.startsWithIgnoreCase ("url"))
  71891. {
  71892. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71893. .upToLastOccurrenceOf (")", false, false).trim());
  71894. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71895. if (fillXml != 0
  71896. && (fillXml->hasTagName ("linearGradient")
  71897. || fillXml->hasTagName ("radialGradient")))
  71898. {
  71899. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71900. ColourGradient gradient;
  71901. addGradientStopsIn (gradient, inheritedFrom);
  71902. addGradientStopsIn (gradient, fillXml);
  71903. if (gradient.getNumColours() > 0)
  71904. {
  71905. gradient.addColour (0.0, gradient.getColour (0));
  71906. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71907. }
  71908. else
  71909. {
  71910. gradient.addColour (0.0, Colours::black);
  71911. gradient.addColour (1.0, Colours::black);
  71912. }
  71913. if (overallOpacity.isNotEmpty())
  71914. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71915. jassert (gradient.getNumColours() > 0);
  71916. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71917. float gradientWidth = viewBoxW;
  71918. float gradientHeight = viewBoxH;
  71919. float dx = 0.0f;
  71920. float dy = 0.0f;
  71921. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71922. if (! userSpace)
  71923. {
  71924. const Rectangle<float> bounds (path.getBounds());
  71925. dx = bounds.getX();
  71926. dy = bounds.getY();
  71927. gradientWidth = bounds.getWidth();
  71928. gradientHeight = bounds.getHeight();
  71929. }
  71930. if (gradient.isRadial)
  71931. {
  71932. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71933. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71934. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71935. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71936. //xxx (the fx, fy focal point isn't handled properly here..)
  71937. }
  71938. else
  71939. {
  71940. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71941. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71942. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71943. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71944. if (gradient.point1 == gradient.point2)
  71945. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71946. }
  71947. FillType type (gradient);
  71948. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71949. .followedBy (transform);
  71950. return type;
  71951. }
  71952. }
  71953. if (fill.equalsIgnoreCase ("none"))
  71954. return Colours::transparentBlack;
  71955. int i = 0;
  71956. const Colour colour (parseColour (fill, i, defaultColour));
  71957. return colour.withMultipliedAlpha (opacity);
  71958. }
  71959. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71960. {
  71961. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71962. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71963. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71964. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71965. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71966. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71967. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71968. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71969. if (join.equalsIgnoreCase ("round"))
  71970. joinStyle = PathStrokeType::curved;
  71971. else if (join.equalsIgnoreCase ("bevel"))
  71972. joinStyle = PathStrokeType::beveled;
  71973. if (cap.equalsIgnoreCase ("round"))
  71974. capStyle = PathStrokeType::rounded;
  71975. else if (cap.equalsIgnoreCase ("square"))
  71976. capStyle = PathStrokeType::square;
  71977. float ox = 0.0f, oy = 0.0f;
  71978. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71979. transform.transformPoints (ox, oy, x, y);
  71980. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71981. joinStyle, capStyle);
  71982. }
  71983. Drawable* parseText (const XmlElement& xml)
  71984. {
  71985. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71986. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71987. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71988. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71989. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71990. //xxx not done text yet!
  71991. forEachXmlChildElement (xml, e)
  71992. {
  71993. if (e->isTextElement())
  71994. {
  71995. const String text (e->getText());
  71996. Path path;
  71997. Drawable* s = parseShape (*e, path);
  71998. delete s; // xxx not finished!
  71999. }
  72000. else if (e->hasTagName ("tspan"))
  72001. {
  72002. Drawable* s = parseText (*e);
  72003. delete s; // xxx not finished!
  72004. }
  72005. }
  72006. return 0;
  72007. }
  72008. void addTransform (const XmlElement& xml)
  72009. {
  72010. transform = parseTransform (xml.getStringAttribute ("transform"))
  72011. .followedBy (transform);
  72012. }
  72013. bool parseCoord (const String& s, float& value, int& index,
  72014. const bool allowUnits, const bool isX) const
  72015. {
  72016. String number;
  72017. if (! parseNextNumber (s, number, index, allowUnits))
  72018. {
  72019. value = 0;
  72020. return false;
  72021. }
  72022. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  72023. return true;
  72024. }
  72025. bool parseCoords (const String& s, float& x, float& y,
  72026. int& index, const bool allowUnits) const
  72027. {
  72028. return parseCoord (s, x, index, allowUnits, true)
  72029. && parseCoord (s, y, index, allowUnits, false);
  72030. }
  72031. float getCoordLength (const String& s, const float sizeForProportions) const
  72032. {
  72033. float n = s.getFloatValue();
  72034. const int len = s.length();
  72035. if (len > 2)
  72036. {
  72037. const float dpi = 96.0f;
  72038. const juce_wchar n1 = s [len - 2];
  72039. const juce_wchar n2 = s [len - 1];
  72040. if (n1 == 'i' && n2 == 'n')
  72041. n *= dpi;
  72042. else if (n1 == 'm' && n2 == 'm')
  72043. n *= dpi / 25.4f;
  72044. else if (n1 == 'c' && n2 == 'm')
  72045. n *= dpi / 2.54f;
  72046. else if (n1 == 'p' && n2 == 'c')
  72047. n *= 15.0f;
  72048. else if (n2 == '%')
  72049. n *= 0.01f * sizeForProportions;
  72050. }
  72051. return n;
  72052. }
  72053. void getCoordList (Array <float>& coords, const String& list,
  72054. const bool allowUnits, const bool isX) const
  72055. {
  72056. int index = 0;
  72057. float value;
  72058. while (parseCoord (list, value, index, allowUnits, isX))
  72059. coords.add (value);
  72060. }
  72061. void parseCSSStyle (const XmlElement& xml)
  72062. {
  72063. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  72064. }
  72065. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  72066. const String& defaultValue = String::empty) const
  72067. {
  72068. if (xml->hasAttribute (attributeName))
  72069. return xml->getStringAttribute (attributeName, defaultValue);
  72070. const String styleAtt (xml->getStringAttribute ("style"));
  72071. if (styleAtt.isNotEmpty())
  72072. {
  72073. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  72074. if (value.isNotEmpty())
  72075. return value;
  72076. }
  72077. else if (xml->hasAttribute ("class"))
  72078. {
  72079. const String className ("." + xml->getStringAttribute ("class"));
  72080. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  72081. if (index < 0)
  72082. index = cssStyleText.indexOfIgnoreCase (className + "{");
  72083. if (index >= 0)
  72084. {
  72085. const int openBracket = cssStyleText.indexOfChar (index, '{');
  72086. if (openBracket > index)
  72087. {
  72088. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  72089. if (closeBracket > openBracket)
  72090. {
  72091. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  72092. if (value.isNotEmpty())
  72093. return value;
  72094. }
  72095. }
  72096. }
  72097. }
  72098. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72099. if (xml != 0)
  72100. return getStyleAttribute (xml, attributeName, defaultValue);
  72101. return defaultValue;
  72102. }
  72103. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72104. {
  72105. if (xml->hasAttribute (attributeName))
  72106. return xml->getStringAttribute (attributeName);
  72107. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72108. if (xml != 0)
  72109. return getInheritedAttribute (xml, attributeName);
  72110. return String::empty;
  72111. }
  72112. static bool isIdentifierChar (const juce_wchar c)
  72113. {
  72114. return CharacterFunctions::isLetter (c) || c == '-';
  72115. }
  72116. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72117. {
  72118. int i = 0;
  72119. for (;;)
  72120. {
  72121. i = list.indexOf (i, attributeName);
  72122. if (i < 0)
  72123. break;
  72124. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72125. && ! isIdentifierChar (list [i + attributeName.length()]))
  72126. {
  72127. i = list.indexOfChar (i, ':');
  72128. if (i < 0)
  72129. break;
  72130. int end = list.indexOfChar (i, ';');
  72131. if (end < 0)
  72132. end = 0x7ffff;
  72133. return list.substring (i + 1, end).trim();
  72134. }
  72135. ++i;
  72136. }
  72137. return defaultValue;
  72138. }
  72139. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  72140. {
  72141. const juce_wchar* const s = source;
  72142. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72143. ++index;
  72144. int start = index;
  72145. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  72146. ++index;
  72147. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  72148. ++index;
  72149. if ((s[index] == 'e' || s[index] == 'E')
  72150. && (CharacterFunctions::isDigit (s[index + 1])
  72151. || s[index + 1] == '-'
  72152. || s[index + 1] == '+'))
  72153. {
  72154. index += 2;
  72155. while (CharacterFunctions::isDigit (s[index]))
  72156. ++index;
  72157. }
  72158. if (allowUnits)
  72159. {
  72160. while (CharacterFunctions::isLetter (s[index]))
  72161. ++index;
  72162. }
  72163. if (index == start)
  72164. return false;
  72165. value = String (s + start, index - start);
  72166. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72167. ++index;
  72168. return true;
  72169. }
  72170. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72171. {
  72172. if (s [index] == '#')
  72173. {
  72174. uint32 hex [6];
  72175. zeromem (hex, sizeof (hex));
  72176. int numChars = 0;
  72177. for (int i = 6; --i >= 0;)
  72178. {
  72179. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72180. if (hexValue >= 0)
  72181. hex [numChars++] = hexValue;
  72182. else
  72183. break;
  72184. }
  72185. if (numChars <= 3)
  72186. return Colour ((uint8) (hex [0] * 0x11),
  72187. (uint8) (hex [1] * 0x11),
  72188. (uint8) (hex [2] * 0x11));
  72189. else
  72190. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72191. (uint8) ((hex [2] << 4) + hex [3]),
  72192. (uint8) ((hex [4] << 4) + hex [5]));
  72193. }
  72194. else if (s [index] == 'r'
  72195. && s [index + 1] == 'g'
  72196. && s [index + 2] == 'b')
  72197. {
  72198. const int openBracket = s.indexOfChar (index, '(');
  72199. const int closeBracket = s.indexOfChar (openBracket, ')');
  72200. if (openBracket >= 3 && closeBracket > openBracket)
  72201. {
  72202. index = closeBracket;
  72203. StringArray tokens;
  72204. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72205. tokens.trim();
  72206. tokens.removeEmptyStrings();
  72207. if (tokens[0].containsChar ('%'))
  72208. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72209. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72210. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72211. else
  72212. return Colour ((uint8) tokens[0].getIntValue(),
  72213. (uint8) tokens[1].getIntValue(),
  72214. (uint8) tokens[2].getIntValue());
  72215. }
  72216. }
  72217. return Colours::findColourForName (s, defaultColour);
  72218. }
  72219. static const AffineTransform parseTransform (String t)
  72220. {
  72221. AffineTransform result;
  72222. while (t.isNotEmpty())
  72223. {
  72224. StringArray tokens;
  72225. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72226. .upToFirstOccurrenceOf (")", false, false),
  72227. ", ", String::empty);
  72228. tokens.removeEmptyStrings (true);
  72229. float numbers [6];
  72230. for (int i = 0; i < 6; ++i)
  72231. numbers[i] = tokens[i].getFloatValue();
  72232. AffineTransform trans;
  72233. if (t.startsWithIgnoreCase ("matrix"))
  72234. {
  72235. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72236. numbers[1], numbers[3], numbers[5]);
  72237. }
  72238. else if (t.startsWithIgnoreCase ("translate"))
  72239. {
  72240. jassert (tokens.size() == 2);
  72241. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72242. }
  72243. else if (t.startsWithIgnoreCase ("scale"))
  72244. {
  72245. if (tokens.size() == 1)
  72246. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72247. else
  72248. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72249. }
  72250. else if (t.startsWithIgnoreCase ("rotate"))
  72251. {
  72252. if (tokens.size() != 3)
  72253. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72254. else
  72255. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72256. numbers[1], numbers[2]);
  72257. }
  72258. else if (t.startsWithIgnoreCase ("skewX"))
  72259. {
  72260. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72261. 0.0f, 1.0f, 0.0f);
  72262. }
  72263. else if (t.startsWithIgnoreCase ("skewY"))
  72264. {
  72265. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72266. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72267. }
  72268. result = trans.followedBy (result);
  72269. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72270. }
  72271. return result;
  72272. }
  72273. static void endpointToCentreParameters (const double x1, const double y1,
  72274. const double x2, const double y2,
  72275. const double angle,
  72276. const bool largeArc, const bool sweep,
  72277. double& rx, double& ry,
  72278. double& centreX, double& centreY,
  72279. double& startAngle, double& deltaAngle)
  72280. {
  72281. const double midX = (x1 - x2) * 0.5;
  72282. const double midY = (y1 - y2) * 0.5;
  72283. const double cosAngle = cos (angle);
  72284. const double sinAngle = sin (angle);
  72285. const double xp = cosAngle * midX + sinAngle * midY;
  72286. const double yp = cosAngle * midY - sinAngle * midX;
  72287. const double xp2 = xp * xp;
  72288. const double yp2 = yp * yp;
  72289. double rx2 = rx * rx;
  72290. double ry2 = ry * ry;
  72291. const double s = (xp2 / rx2) + (yp2 / ry2);
  72292. double c;
  72293. if (s <= 1.0)
  72294. {
  72295. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72296. / (( rx2 * yp2) + (ry2 * xp2))));
  72297. if (largeArc == sweep)
  72298. c = -c;
  72299. }
  72300. else
  72301. {
  72302. const double s2 = std::sqrt (s);
  72303. rx *= s2;
  72304. ry *= s2;
  72305. rx2 = rx * rx;
  72306. ry2 = ry * ry;
  72307. c = 0;
  72308. }
  72309. const double cpx = ((rx * yp) / ry) * c;
  72310. const double cpy = ((-ry * xp) / rx) * c;
  72311. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72312. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72313. const double ux = (xp - cpx) / rx;
  72314. const double uy = (yp - cpy) / ry;
  72315. const double vx = (-xp - cpx) / rx;
  72316. const double vy = (-yp - cpy) / ry;
  72317. const double length = juce_hypot (ux, uy);
  72318. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72319. if (uy < 0)
  72320. startAngle = -startAngle;
  72321. startAngle += double_Pi * 0.5;
  72322. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72323. / (length * juce_hypot (vx, vy))));
  72324. if ((ux * vy) - (uy * vx) < 0)
  72325. deltaAngle = -deltaAngle;
  72326. if (sweep)
  72327. {
  72328. if (deltaAngle < 0)
  72329. deltaAngle += double_Pi * 2.0;
  72330. }
  72331. else
  72332. {
  72333. if (deltaAngle > 0)
  72334. deltaAngle -= double_Pi * 2.0;
  72335. }
  72336. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72337. }
  72338. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72339. {
  72340. forEachXmlChildElement (*parent, e)
  72341. {
  72342. if (e->compareAttribute ("id", id))
  72343. return e;
  72344. const XmlElement* const found = findElementForId (e, id);
  72345. if (found != 0)
  72346. return found;
  72347. }
  72348. return 0;
  72349. }
  72350. SVGState& operator= (const SVGState&);
  72351. };
  72352. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72353. {
  72354. SVGState state (&svgDocument);
  72355. return state.parseSVGElement (svgDocument);
  72356. }
  72357. END_JUCE_NAMESPACE
  72358. /*** End of inlined file: juce_SVGParser.cpp ***/
  72359. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72360. BEGIN_JUCE_NAMESPACE
  72361. #if JUCE_MSVC && JUCE_DEBUG
  72362. #pragma optimize ("t", on)
  72363. #endif
  72364. DropShadowEffect::DropShadowEffect()
  72365. : offsetX (0),
  72366. offsetY (0),
  72367. radius (4),
  72368. opacity (0.6f)
  72369. {
  72370. }
  72371. DropShadowEffect::~DropShadowEffect()
  72372. {
  72373. }
  72374. void DropShadowEffect::setShadowProperties (const float newRadius,
  72375. const float newOpacity,
  72376. const int newShadowOffsetX,
  72377. const int newShadowOffsetY)
  72378. {
  72379. radius = jmax (1.1f, newRadius);
  72380. offsetX = newShadowOffsetX;
  72381. offsetY = newShadowOffsetY;
  72382. opacity = newOpacity;
  72383. }
  72384. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  72385. {
  72386. const int w = image.getWidth();
  72387. const int h = image.getHeight();
  72388. Image shadowImage (Image::SingleChannel, w, h, false);
  72389. const Image::BitmapData srcData (image, false);
  72390. const Image::BitmapData destData (shadowImage, true);
  72391. const int filter = roundToInt (63.0f / radius);
  72392. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72393. for (int x = w; --x >= 0;)
  72394. {
  72395. int shadowAlpha = 0;
  72396. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72397. uint8* shadowPix = destData.data + x;
  72398. for (int y = h; --y >= 0;)
  72399. {
  72400. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72401. *shadowPix = (uint8) shadowAlpha;
  72402. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72403. shadowPix += destData.lineStride;
  72404. }
  72405. }
  72406. for (int y = h; --y >= 0;)
  72407. {
  72408. int shadowAlpha = 0;
  72409. uint8* shadowPix = destData.getLinePointer (y);
  72410. for (int x = w; --x >= 0;)
  72411. {
  72412. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72413. *shadowPix++ = (uint8) shadowAlpha;
  72414. }
  72415. }
  72416. g.setColour (Colours::black.withAlpha (opacity));
  72417. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72418. g.setOpacity (1.0f);
  72419. g.drawImageAt (image, 0, 0);
  72420. }
  72421. #if JUCE_MSVC && JUCE_DEBUG
  72422. #pragma optimize ("", on) // resets optimisations to the project defaults
  72423. #endif
  72424. END_JUCE_NAMESPACE
  72425. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72426. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72427. BEGIN_JUCE_NAMESPACE
  72428. GlowEffect::GlowEffect()
  72429. : radius (2.0f),
  72430. colour (Colours::white)
  72431. {
  72432. }
  72433. GlowEffect::~GlowEffect()
  72434. {
  72435. }
  72436. void GlowEffect::setGlowProperties (const float newRadius,
  72437. const Colour& newColour)
  72438. {
  72439. radius = newRadius;
  72440. colour = newColour;
  72441. }
  72442. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72443. {
  72444. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72445. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72446. blurKernel.createGaussianBlur (radius);
  72447. blurKernel.rescaleAllValues (radius);
  72448. blurKernel.applyToImage (temp, image, image.getBounds());
  72449. g.setColour (colour);
  72450. g.drawImageAt (temp, 0, 0, true);
  72451. g.setOpacity (1.0f);
  72452. g.drawImageAt (image, 0, 0, false);
  72453. }
  72454. END_JUCE_NAMESPACE
  72455. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72456. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72457. BEGIN_JUCE_NAMESPACE
  72458. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72459. : opacity (opacity_)
  72460. {
  72461. }
  72462. ReduceOpacityEffect::~ReduceOpacityEffect()
  72463. {
  72464. }
  72465. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72466. {
  72467. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72468. }
  72469. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72470. {
  72471. g.setOpacity (opacity);
  72472. g.drawImageAt (image, 0, 0);
  72473. }
  72474. END_JUCE_NAMESPACE
  72475. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72476. /*** Start of inlined file: juce_Font.cpp ***/
  72477. BEGIN_JUCE_NAMESPACE
  72478. namespace FontValues
  72479. {
  72480. static float limitFontHeight (const float height) throw()
  72481. {
  72482. return jlimit (0.1f, 10000.0f, height);
  72483. }
  72484. static const float defaultFontHeight = 14.0f;
  72485. static String fallbackFont;
  72486. }
  72487. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72488. const float kerning_, const float ascent_, const int styleFlags_,
  72489. Typeface* const typeface_) throw()
  72490. : typefaceName (typefaceName_),
  72491. height (height_),
  72492. horizontalScale (horizontalScale_),
  72493. kerning (kerning_),
  72494. ascent (ascent_),
  72495. styleFlags (styleFlags_),
  72496. typeface (typeface_)
  72497. {
  72498. }
  72499. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72500. : typefaceName (other.typefaceName),
  72501. height (other.height),
  72502. horizontalScale (other.horizontalScale),
  72503. kerning (other.kerning),
  72504. ascent (other.ascent),
  72505. styleFlags (other.styleFlags),
  72506. typeface (other.typeface)
  72507. {
  72508. }
  72509. Font::Font() throw()
  72510. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72511. 1.0f, 0, 0, Font::plain, 0))
  72512. {
  72513. }
  72514. Font::Font (const float fontHeight, const int styleFlags_) throw()
  72515. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72516. 1.0f, 0, 0, styleFlags_, 0))
  72517. {
  72518. }
  72519. Font::Font (const String& typefaceName_,
  72520. const float fontHeight,
  72521. const int styleFlags_) throw()
  72522. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72523. 1.0f, 0, 0, styleFlags_, 0))
  72524. {
  72525. }
  72526. Font::Font (const Font& other) throw()
  72527. : font (other.font)
  72528. {
  72529. }
  72530. Font& Font::operator= (const Font& other) throw()
  72531. {
  72532. font = other.font;
  72533. return *this;
  72534. }
  72535. Font::~Font() throw()
  72536. {
  72537. }
  72538. Font::Font (const Typeface::Ptr& typeface) throw()
  72539. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72540. 1.0f, 0, 0, Font::plain, typeface))
  72541. {
  72542. }
  72543. bool Font::operator== (const Font& other) const throw()
  72544. {
  72545. return font == other.font
  72546. || (font->height == other.font->height
  72547. && font->styleFlags == other.font->styleFlags
  72548. && font->horizontalScale == other.font->horizontalScale
  72549. && font->kerning == other.font->kerning
  72550. && font->typefaceName == other.font->typefaceName);
  72551. }
  72552. bool Font::operator!= (const Font& other) const throw()
  72553. {
  72554. return ! operator== (other);
  72555. }
  72556. void Font::dupeInternalIfShared() throw()
  72557. {
  72558. if (font->getReferenceCount() > 1)
  72559. font = new SharedFontInternal (*font);
  72560. }
  72561. const String Font::getDefaultSansSerifFontName() throw()
  72562. {
  72563. static const String name ("<Sans-Serif>");
  72564. return name;
  72565. }
  72566. const String Font::getDefaultSerifFontName() throw()
  72567. {
  72568. static const String name ("<Serif>");
  72569. return name;
  72570. }
  72571. const String Font::getDefaultMonospacedFontName() throw()
  72572. {
  72573. static const String name ("<Monospaced>");
  72574. return name;
  72575. }
  72576. void Font::setTypefaceName (const String& faceName) throw()
  72577. {
  72578. if (faceName != font->typefaceName)
  72579. {
  72580. dupeInternalIfShared();
  72581. font->typefaceName = faceName;
  72582. font->typeface = 0;
  72583. font->ascent = 0;
  72584. }
  72585. }
  72586. const String Font::getFallbackFontName() throw()
  72587. {
  72588. return FontValues::fallbackFont;
  72589. }
  72590. void Font::setFallbackFontName (const String& name) throw()
  72591. {
  72592. FontValues::fallbackFont = name;
  72593. }
  72594. void Font::setHeight (float newHeight) throw()
  72595. {
  72596. newHeight = FontValues::limitFontHeight (newHeight);
  72597. if (font->height != newHeight)
  72598. {
  72599. dupeInternalIfShared();
  72600. font->height = newHeight;
  72601. }
  72602. }
  72603. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  72604. {
  72605. newHeight = FontValues::limitFontHeight (newHeight);
  72606. if (font->height != newHeight)
  72607. {
  72608. dupeInternalIfShared();
  72609. font->horizontalScale *= (font->height / newHeight);
  72610. font->height = newHeight;
  72611. }
  72612. }
  72613. void Font::setStyleFlags (const int newFlags) throw()
  72614. {
  72615. if (font->styleFlags != newFlags)
  72616. {
  72617. dupeInternalIfShared();
  72618. font->styleFlags = newFlags;
  72619. font->typeface = 0;
  72620. font->ascent = 0;
  72621. }
  72622. }
  72623. void Font::setSizeAndStyle (float newHeight,
  72624. const int newStyleFlags,
  72625. const float newHorizontalScale,
  72626. const float newKerningAmount) throw()
  72627. {
  72628. newHeight = FontValues::limitFontHeight (newHeight);
  72629. if (font->height != newHeight
  72630. || font->horizontalScale != newHorizontalScale
  72631. || font->kerning != newKerningAmount)
  72632. {
  72633. dupeInternalIfShared();
  72634. font->height = newHeight;
  72635. font->horizontalScale = newHorizontalScale;
  72636. font->kerning = newKerningAmount;
  72637. }
  72638. setStyleFlags (newStyleFlags);
  72639. }
  72640. void Font::setHorizontalScale (const float scaleFactor) throw()
  72641. {
  72642. dupeInternalIfShared();
  72643. font->horizontalScale = scaleFactor;
  72644. }
  72645. void Font::setExtraKerningFactor (const float extraKerning) throw()
  72646. {
  72647. dupeInternalIfShared();
  72648. font->kerning = extraKerning;
  72649. }
  72650. void Font::setBold (const bool shouldBeBold) throw()
  72651. {
  72652. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72653. : (font->styleFlags & ~bold));
  72654. }
  72655. bool Font::isBold() const throw()
  72656. {
  72657. return (font->styleFlags & bold) != 0;
  72658. }
  72659. void Font::setItalic (const bool shouldBeItalic) throw()
  72660. {
  72661. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72662. : (font->styleFlags & ~italic));
  72663. }
  72664. bool Font::isItalic() const throw()
  72665. {
  72666. return (font->styleFlags & italic) != 0;
  72667. }
  72668. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  72669. {
  72670. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72671. : (font->styleFlags & ~underlined));
  72672. }
  72673. bool Font::isUnderlined() const throw()
  72674. {
  72675. return (font->styleFlags & underlined) != 0;
  72676. }
  72677. float Font::getAscent() const throw()
  72678. {
  72679. if (font->ascent == 0)
  72680. font->ascent = getTypeface()->getAscent();
  72681. return font->height * font->ascent;
  72682. }
  72683. float Font::getDescent() const throw()
  72684. {
  72685. return font->height - getAscent();
  72686. }
  72687. int Font::getStringWidth (const String& text) const throw()
  72688. {
  72689. return roundToInt (getStringWidthFloat (text));
  72690. }
  72691. float Font::getStringWidthFloat (const String& text) const throw()
  72692. {
  72693. float w = getTypeface()->getStringWidth (text);
  72694. if (font->kerning != 0)
  72695. w += font->kerning * text.length();
  72696. return w * font->height * font->horizontalScale;
  72697. }
  72698. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  72699. {
  72700. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72701. const float scale = font->height * font->horizontalScale;
  72702. const int num = xOffsets.size();
  72703. if (num > 0)
  72704. {
  72705. float* const x = &(xOffsets.getReference(0));
  72706. if (font->kerning != 0)
  72707. {
  72708. for (int i = 0; i < num; ++i)
  72709. x[i] = (x[i] + i * font->kerning) * scale;
  72710. }
  72711. else
  72712. {
  72713. for (int i = 0; i < num; ++i)
  72714. x[i] *= scale;
  72715. }
  72716. }
  72717. }
  72718. void Font::findFonts (Array<Font>& destArray) throw()
  72719. {
  72720. const StringArray names (findAllTypefaceNames());
  72721. for (int i = 0; i < names.size(); ++i)
  72722. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72723. }
  72724. const String Font::toString() const
  72725. {
  72726. String s (getTypefaceName());
  72727. if (s == getDefaultSansSerifFontName())
  72728. s = String::empty;
  72729. else
  72730. s += "; ";
  72731. s += String (getHeight(), 1);
  72732. if (isBold())
  72733. s += " bold";
  72734. if (isItalic())
  72735. s += " italic";
  72736. return s;
  72737. }
  72738. const Font Font::fromString (const String& fontDescription)
  72739. {
  72740. String name;
  72741. const int separator = fontDescription.indexOfChar (';');
  72742. if (separator > 0)
  72743. name = fontDescription.substring (0, separator).trim();
  72744. if (name.isEmpty())
  72745. name = getDefaultSansSerifFontName();
  72746. String sizeAndStyle (fontDescription.substring (separator + 1));
  72747. float height = sizeAndStyle.getFloatValue();
  72748. if (height <= 0)
  72749. height = 10.0f;
  72750. int flags = Font::plain;
  72751. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72752. flags |= Font::bold;
  72753. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72754. flags |= Font::italic;
  72755. return Font (name, height, flags);
  72756. }
  72757. class TypefaceCache : public DeletedAtShutdown
  72758. {
  72759. public:
  72760. TypefaceCache (int numToCache = 10) throw()
  72761. : counter (1)
  72762. {
  72763. while (--numToCache >= 0)
  72764. faces.add (new CachedFace());
  72765. }
  72766. ~TypefaceCache()
  72767. {
  72768. clearSingletonInstance();
  72769. }
  72770. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72771. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  72772. {
  72773. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72774. const String faceName (font.getTypefaceName());
  72775. int i;
  72776. for (i = faces.size(); --i >= 0;)
  72777. {
  72778. CachedFace* const face = faces.getUnchecked(i);
  72779. if (face->flags == flags
  72780. && face->typefaceName == faceName)
  72781. {
  72782. face->lastUsageCount = ++counter;
  72783. return face->typeFace;
  72784. }
  72785. }
  72786. int replaceIndex = 0;
  72787. int bestLastUsageCount = std::numeric_limits<int>::max();
  72788. for (i = faces.size(); --i >= 0;)
  72789. {
  72790. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72791. if (bestLastUsageCount > lu)
  72792. {
  72793. bestLastUsageCount = lu;
  72794. replaceIndex = i;
  72795. }
  72796. }
  72797. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72798. face->typefaceName = faceName;
  72799. face->flags = flags;
  72800. face->lastUsageCount = ++counter;
  72801. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72802. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72803. return face->typeFace;
  72804. }
  72805. juce_UseDebuggingNewOperator
  72806. private:
  72807. struct CachedFace
  72808. {
  72809. CachedFace() throw()
  72810. : lastUsageCount (0), flags (-1)
  72811. {
  72812. }
  72813. String typefaceName;
  72814. int lastUsageCount;
  72815. int flags;
  72816. Typeface::Ptr typeFace;
  72817. };
  72818. int counter;
  72819. OwnedArray <CachedFace> faces;
  72820. TypefaceCache (const TypefaceCache&);
  72821. TypefaceCache& operator= (const TypefaceCache&);
  72822. };
  72823. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72824. Typeface* Font::getTypeface() const throw()
  72825. {
  72826. if (font->typeface == 0)
  72827. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72828. return font->typeface;
  72829. }
  72830. END_JUCE_NAMESPACE
  72831. /*** End of inlined file: juce_Font.cpp ***/
  72832. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72833. BEGIN_JUCE_NAMESPACE
  72834. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72835. const juce_wchar character_, const int glyph_)
  72836. : x (x_),
  72837. y (y_),
  72838. w (w_),
  72839. font (font_),
  72840. character (character_),
  72841. glyph (glyph_)
  72842. {
  72843. }
  72844. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72845. : x (other.x),
  72846. y (other.y),
  72847. w (other.w),
  72848. font (other.font),
  72849. character (other.character),
  72850. glyph (other.glyph)
  72851. {
  72852. }
  72853. void PositionedGlyph::draw (const Graphics& g) const
  72854. {
  72855. if (! isWhitespace())
  72856. {
  72857. g.getInternalContext()->setFont (font);
  72858. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72859. }
  72860. }
  72861. void PositionedGlyph::draw (const Graphics& g,
  72862. const AffineTransform& transform) const
  72863. {
  72864. if (! isWhitespace())
  72865. {
  72866. g.getInternalContext()->setFont (font);
  72867. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72868. .followedBy (transform));
  72869. }
  72870. }
  72871. void PositionedGlyph::createPath (Path& path) const
  72872. {
  72873. if (! isWhitespace())
  72874. {
  72875. Typeface* const t = font.getTypeface();
  72876. if (t != 0)
  72877. {
  72878. Path p;
  72879. t->getOutlineForGlyph (glyph, p);
  72880. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72881. .translated (x, y));
  72882. }
  72883. }
  72884. }
  72885. bool PositionedGlyph::hitTest (float px, float py) const
  72886. {
  72887. if (getBounds().contains (px, py) && ! isWhitespace())
  72888. {
  72889. Typeface* const t = font.getTypeface();
  72890. if (t != 0)
  72891. {
  72892. Path p;
  72893. t->getOutlineForGlyph (glyph, p);
  72894. AffineTransform::translation (-x, -y)
  72895. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72896. .transformPoint (px, py);
  72897. return p.contains (px, py);
  72898. }
  72899. }
  72900. return false;
  72901. }
  72902. void PositionedGlyph::moveBy (const float deltaX,
  72903. const float deltaY)
  72904. {
  72905. x += deltaX;
  72906. y += deltaY;
  72907. }
  72908. GlyphArrangement::GlyphArrangement()
  72909. {
  72910. glyphs.ensureStorageAllocated (128);
  72911. }
  72912. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72913. {
  72914. addGlyphArrangement (other);
  72915. }
  72916. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72917. {
  72918. if (this != &other)
  72919. {
  72920. clear();
  72921. addGlyphArrangement (other);
  72922. }
  72923. return *this;
  72924. }
  72925. GlyphArrangement::~GlyphArrangement()
  72926. {
  72927. }
  72928. void GlyphArrangement::clear()
  72929. {
  72930. glyphs.clear();
  72931. }
  72932. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72933. {
  72934. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72935. return *glyphs [index];
  72936. }
  72937. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72938. {
  72939. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72940. glyphs.addCopiesOf (other.glyphs);
  72941. }
  72942. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72943. {
  72944. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72945. }
  72946. void GlyphArrangement::addLineOfText (const Font& font,
  72947. const String& text,
  72948. const float xOffset,
  72949. const float yOffset)
  72950. {
  72951. addCurtailedLineOfText (font, text,
  72952. xOffset, yOffset,
  72953. 1.0e10f, false);
  72954. }
  72955. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72956. const String& text,
  72957. float xOffset,
  72958. const float yOffset,
  72959. const float maxWidthPixels,
  72960. const bool useEllipsis)
  72961. {
  72962. if (text.isNotEmpty())
  72963. {
  72964. Array <int> newGlyphs;
  72965. Array <float> xOffsets;
  72966. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72967. const int textLen = newGlyphs.size();
  72968. const juce_wchar* const unicodeText = text;
  72969. for (int i = 0; i < textLen; ++i)
  72970. {
  72971. const float thisX = xOffsets.getUnchecked (i);
  72972. const float nextX = xOffsets.getUnchecked (i + 1);
  72973. if (nextX > maxWidthPixels + 1.0f)
  72974. {
  72975. // curtail the string if it's too wide..
  72976. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72977. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72978. break;
  72979. }
  72980. else
  72981. {
  72982. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72983. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72984. }
  72985. }
  72986. }
  72987. }
  72988. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72989. const int startIndex, int endIndex)
  72990. {
  72991. int numDeleted = 0;
  72992. if (glyphs.size() > 0)
  72993. {
  72994. Array<int> dotGlyphs;
  72995. Array<float> dotXs;
  72996. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72997. const float dx = dotXs[1];
  72998. float xOffset = 0.0f, yOffset = 0.0f;
  72999. while (endIndex > startIndex)
  73000. {
  73001. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  73002. xOffset = pg->x;
  73003. yOffset = pg->y;
  73004. glyphs.remove (endIndex);
  73005. ++numDeleted;
  73006. if (xOffset + dx * 3 <= maxXPos)
  73007. break;
  73008. }
  73009. for (int i = 3; --i >= 0;)
  73010. {
  73011. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  73012. font, '.', dotGlyphs.getFirst()));
  73013. --numDeleted;
  73014. xOffset += dx;
  73015. if (xOffset > maxXPos)
  73016. break;
  73017. }
  73018. }
  73019. return numDeleted;
  73020. }
  73021. void GlyphArrangement::addJustifiedText (const Font& font,
  73022. const String& text,
  73023. float x, float y,
  73024. const float maxLineWidth,
  73025. const Justification& horizontalLayout)
  73026. {
  73027. int lineStartIndex = glyphs.size();
  73028. addLineOfText (font, text, x, y);
  73029. const float originalY = y;
  73030. while (lineStartIndex < glyphs.size())
  73031. {
  73032. int i = lineStartIndex;
  73033. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  73034. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  73035. ++i;
  73036. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  73037. int lastWordBreakIndex = -1;
  73038. while (i < glyphs.size())
  73039. {
  73040. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  73041. const juce_wchar c = pg->getCharacter();
  73042. if (c == '\r' || c == '\n')
  73043. {
  73044. ++i;
  73045. if (c == '\r' && i < glyphs.size()
  73046. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  73047. ++i;
  73048. break;
  73049. }
  73050. else if (pg->isWhitespace())
  73051. {
  73052. lastWordBreakIndex = i + 1;
  73053. }
  73054. else if (pg->getRight() - 0.0001f >= lineMaxX)
  73055. {
  73056. if (lastWordBreakIndex >= 0)
  73057. i = lastWordBreakIndex;
  73058. break;
  73059. }
  73060. ++i;
  73061. }
  73062. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  73063. float currentLineEndX = currentLineStartX;
  73064. for (int j = i; --j >= lineStartIndex;)
  73065. {
  73066. if (! glyphs.getUnchecked (j)->isWhitespace())
  73067. {
  73068. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  73069. break;
  73070. }
  73071. }
  73072. float deltaX = 0.0f;
  73073. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  73074. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  73075. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  73076. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  73077. else if (horizontalLayout.testFlags (Justification::right))
  73078. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  73079. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  73080. x + deltaX - currentLineStartX, y - originalY);
  73081. lineStartIndex = i;
  73082. y += font.getHeight();
  73083. }
  73084. }
  73085. void GlyphArrangement::addFittedText (const Font& f,
  73086. const String& text,
  73087. const float x, const float y,
  73088. const float width, const float height,
  73089. const Justification& layout,
  73090. int maximumLines,
  73091. const float minimumHorizontalScale)
  73092. {
  73093. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  73094. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  73095. if (text.containsAnyOf ("\r\n"))
  73096. {
  73097. GlyphArrangement ga;
  73098. ga.addJustifiedText (f, text, x, y, width, layout);
  73099. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73100. float dy = y - bb.getY();
  73101. if (layout.testFlags (Justification::verticallyCentred))
  73102. dy += (height - bb.getHeight()) * 0.5f;
  73103. else if (layout.testFlags (Justification::bottom))
  73104. dy += height - bb.getHeight();
  73105. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73106. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73107. for (int i = 0; i < ga.glyphs.size(); ++i)
  73108. glyphs.add (ga.glyphs.getUnchecked (i));
  73109. ga.glyphs.clear (false);
  73110. return;
  73111. }
  73112. int startIndex = glyphs.size();
  73113. addLineOfText (f, text.trim(), x, y);
  73114. if (glyphs.size() > startIndex)
  73115. {
  73116. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73117. - glyphs.getUnchecked (startIndex)->getLeft();
  73118. if (lineWidth <= 0)
  73119. return;
  73120. if (lineWidth * minimumHorizontalScale < width)
  73121. {
  73122. if (lineWidth > width)
  73123. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73124. width / lineWidth);
  73125. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73126. x, y, width, height, layout);
  73127. }
  73128. else if (maximumLines <= 1)
  73129. {
  73130. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73131. x, y, width, height, f, layout, minimumHorizontalScale);
  73132. }
  73133. else
  73134. {
  73135. Font font (f);
  73136. String txt (text.trim());
  73137. const int length = txt.length();
  73138. const int originalStartIndex = startIndex;
  73139. int numLines = 1;
  73140. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73141. maximumLines = 1;
  73142. maximumLines = jmin (maximumLines, length);
  73143. while (numLines < maximumLines)
  73144. {
  73145. ++numLines;
  73146. const float newFontHeight = height / (float) numLines;
  73147. if (newFontHeight < font.getHeight())
  73148. {
  73149. font.setHeight (jmax (8.0f, newFontHeight));
  73150. removeRangeOfGlyphs (startIndex, -1);
  73151. addLineOfText (font, txt, x, y);
  73152. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73153. - glyphs.getUnchecked (startIndex)->getLeft();
  73154. }
  73155. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73156. break;
  73157. }
  73158. if (numLines < 1)
  73159. numLines = 1;
  73160. float lineY = y;
  73161. float widthPerLine = lineWidth / numLines;
  73162. int lastLineStartIndex = 0;
  73163. for (int line = 0; line < numLines; ++line)
  73164. {
  73165. int i = startIndex;
  73166. lastLineStartIndex = i;
  73167. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73168. if (line == numLines - 1)
  73169. {
  73170. widthPerLine = width;
  73171. i = glyphs.size();
  73172. }
  73173. else
  73174. {
  73175. while (i < glyphs.size())
  73176. {
  73177. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73178. if (lineWidth > widthPerLine)
  73179. {
  73180. // got to a point where the line's too long, so skip forward to find a
  73181. // good place to break it..
  73182. const int searchStartIndex = i;
  73183. while (i < glyphs.size())
  73184. {
  73185. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73186. {
  73187. if (glyphs.getUnchecked (i)->isWhitespace()
  73188. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73189. {
  73190. ++i;
  73191. break;
  73192. }
  73193. }
  73194. else
  73195. {
  73196. // can't find a suitable break, so try looking backwards..
  73197. i = searchStartIndex;
  73198. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73199. {
  73200. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73201. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73202. {
  73203. i -= back - 1;
  73204. break;
  73205. }
  73206. }
  73207. break;
  73208. }
  73209. ++i;
  73210. }
  73211. break;
  73212. }
  73213. ++i;
  73214. }
  73215. int wsStart = i;
  73216. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73217. --wsStart;
  73218. int wsEnd = i;
  73219. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73220. ++wsEnd;
  73221. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73222. i = jmax (wsStart, startIndex + 1);
  73223. }
  73224. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73225. x, lineY, width, font.getHeight(), font,
  73226. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73227. minimumHorizontalScale);
  73228. startIndex = i;
  73229. lineY += font.getHeight();
  73230. if (startIndex >= glyphs.size())
  73231. break;
  73232. }
  73233. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73234. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73235. }
  73236. }
  73237. }
  73238. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73239. const float dx, const float dy)
  73240. {
  73241. jassert (startIndex >= 0);
  73242. if (dx != 0.0f || dy != 0.0f)
  73243. {
  73244. if (num < 0 || startIndex + num > glyphs.size())
  73245. num = glyphs.size() - startIndex;
  73246. while (--num >= 0)
  73247. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73248. }
  73249. }
  73250. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73251. const Justification& justification, float minimumHorizontalScale)
  73252. {
  73253. int numDeleted = 0;
  73254. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73255. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73256. if (lineWidth > w)
  73257. {
  73258. if (minimumHorizontalScale < 1.0f)
  73259. {
  73260. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73261. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73262. }
  73263. if (lineWidth > w)
  73264. {
  73265. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73266. numGlyphs -= numDeleted;
  73267. }
  73268. }
  73269. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73270. return numDeleted;
  73271. }
  73272. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73273. const float horizontalScaleFactor)
  73274. {
  73275. jassert (startIndex >= 0);
  73276. if (num < 0 || startIndex + num > glyphs.size())
  73277. num = glyphs.size() - startIndex;
  73278. if (num > 0)
  73279. {
  73280. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73281. while (--num >= 0)
  73282. {
  73283. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73284. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73285. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73286. pg->w *= horizontalScaleFactor;
  73287. }
  73288. }
  73289. }
  73290. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73291. {
  73292. jassert (startIndex >= 0);
  73293. if (num < 0 || startIndex + num > glyphs.size())
  73294. num = glyphs.size() - startIndex;
  73295. Rectangle<float> result;
  73296. while (--num >= 0)
  73297. {
  73298. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73299. if (includeWhitespace || ! pg->isWhitespace())
  73300. result = result.getUnion (pg->getBounds());
  73301. }
  73302. return result;
  73303. }
  73304. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73305. const float x, const float y, const float width, const float height,
  73306. const Justification& justification)
  73307. {
  73308. jassert (num >= 0 && startIndex >= 0);
  73309. if (glyphs.size() > 0 && num > 0)
  73310. {
  73311. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73312. | Justification::horizontallyCentred)));
  73313. float deltaX = 0.0f;
  73314. if (justification.testFlags (Justification::horizontallyJustified))
  73315. deltaX = x - bb.getX();
  73316. else if (justification.testFlags (Justification::horizontallyCentred))
  73317. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73318. else if (justification.testFlags (Justification::right))
  73319. deltaX = (x + width) - bb.getRight();
  73320. else
  73321. deltaX = x - bb.getX();
  73322. float deltaY = 0.0f;
  73323. if (justification.testFlags (Justification::top))
  73324. deltaY = y - bb.getY();
  73325. else if (justification.testFlags (Justification::bottom))
  73326. deltaY = (y + height) - bb.getBottom();
  73327. else
  73328. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73329. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73330. if (justification.testFlags (Justification::horizontallyJustified))
  73331. {
  73332. int lineStart = 0;
  73333. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73334. int i;
  73335. for (i = 0; i < num; ++i)
  73336. {
  73337. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73338. if (glyphY != baseY)
  73339. {
  73340. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73341. lineStart = i;
  73342. baseY = glyphY;
  73343. }
  73344. }
  73345. if (i > lineStart)
  73346. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73347. }
  73348. }
  73349. }
  73350. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73351. {
  73352. if (start + num < glyphs.size()
  73353. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73354. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73355. {
  73356. int numSpaces = 0;
  73357. int spacesAtEnd = 0;
  73358. for (int i = 0; i < num; ++i)
  73359. {
  73360. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73361. {
  73362. ++spacesAtEnd;
  73363. ++numSpaces;
  73364. }
  73365. else
  73366. {
  73367. spacesAtEnd = 0;
  73368. }
  73369. }
  73370. numSpaces -= spacesAtEnd;
  73371. if (numSpaces > 0)
  73372. {
  73373. const float startX = glyphs.getUnchecked (start)->getLeft();
  73374. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73375. const float extraPaddingBetweenWords
  73376. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73377. float deltaX = 0.0f;
  73378. for (int i = 0; i < num; ++i)
  73379. {
  73380. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73381. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73382. deltaX += extraPaddingBetweenWords;
  73383. }
  73384. }
  73385. }
  73386. }
  73387. void GlyphArrangement::draw (const Graphics& g) const
  73388. {
  73389. for (int i = 0; i < glyphs.size(); ++i)
  73390. {
  73391. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73392. if (pg->font.isUnderlined())
  73393. {
  73394. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73395. float nextX = pg->x + pg->w;
  73396. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73397. nextX = glyphs.getUnchecked (i + 1)->x;
  73398. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73399. nextX - pg->x, lineThickness);
  73400. }
  73401. pg->draw (g);
  73402. }
  73403. }
  73404. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73405. {
  73406. for (int i = 0; i < glyphs.size(); ++i)
  73407. {
  73408. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73409. if (pg->font.isUnderlined())
  73410. {
  73411. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73412. float nextX = pg->x + pg->w;
  73413. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73414. nextX = glyphs.getUnchecked (i + 1)->x;
  73415. Path p;
  73416. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73417. nextX, pg->y + lineThickness * 2.0f),
  73418. lineThickness);
  73419. g.fillPath (p, transform);
  73420. }
  73421. pg->draw (g, transform);
  73422. }
  73423. }
  73424. void GlyphArrangement::createPath (Path& path) const
  73425. {
  73426. for (int i = 0; i < glyphs.size(); ++i)
  73427. glyphs.getUnchecked (i)->createPath (path);
  73428. }
  73429. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73430. {
  73431. for (int i = 0; i < glyphs.size(); ++i)
  73432. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73433. return i;
  73434. return -1;
  73435. }
  73436. END_JUCE_NAMESPACE
  73437. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73438. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73439. BEGIN_JUCE_NAMESPACE
  73440. class TextLayout::Token
  73441. {
  73442. public:
  73443. String text;
  73444. Font font;
  73445. int x, y, w, h;
  73446. int line, lineHeight;
  73447. bool isWhitespace, isNewLine;
  73448. Token (const String& t,
  73449. const Font& f,
  73450. const bool isWhitespace_)
  73451. : text (t),
  73452. font (f),
  73453. x(0),
  73454. y(0),
  73455. isWhitespace (isWhitespace_)
  73456. {
  73457. w = font.getStringWidth (t);
  73458. h = roundToInt (f.getHeight());
  73459. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73460. }
  73461. Token (const Token& other)
  73462. : text (other.text),
  73463. font (other.font),
  73464. x (other.x),
  73465. y (other.y),
  73466. w (other.w),
  73467. h (other.h),
  73468. line (other.line),
  73469. lineHeight (other.lineHeight),
  73470. isWhitespace (other.isWhitespace),
  73471. isNewLine (other.isNewLine)
  73472. {
  73473. }
  73474. ~Token()
  73475. {
  73476. }
  73477. void draw (Graphics& g,
  73478. const int xOffset,
  73479. const int yOffset)
  73480. {
  73481. if (! isWhitespace)
  73482. {
  73483. g.setFont (font);
  73484. g.drawSingleLineText (text.trimEnd(),
  73485. xOffset + x,
  73486. yOffset + y + (lineHeight - h)
  73487. + roundToInt (font.getAscent()));
  73488. }
  73489. }
  73490. juce_UseDebuggingNewOperator
  73491. };
  73492. TextLayout::TextLayout()
  73493. : totalLines (0)
  73494. {
  73495. tokens.ensureStorageAllocated (64);
  73496. }
  73497. TextLayout::TextLayout (const String& text, const Font& font)
  73498. : totalLines (0)
  73499. {
  73500. tokens.ensureStorageAllocated (64);
  73501. appendText (text, font);
  73502. }
  73503. TextLayout::TextLayout (const TextLayout& other)
  73504. : totalLines (0)
  73505. {
  73506. *this = other;
  73507. }
  73508. TextLayout& TextLayout::operator= (const TextLayout& other)
  73509. {
  73510. if (this != &other)
  73511. {
  73512. clear();
  73513. totalLines = other.totalLines;
  73514. tokens.addCopiesOf (other.tokens);
  73515. }
  73516. return *this;
  73517. }
  73518. TextLayout::~TextLayout()
  73519. {
  73520. clear();
  73521. }
  73522. void TextLayout::clear()
  73523. {
  73524. tokens.clear();
  73525. totalLines = 0;
  73526. }
  73527. void TextLayout::appendText (const String& text, const Font& font)
  73528. {
  73529. const juce_wchar* t = text;
  73530. String currentString;
  73531. int lastCharType = 0;
  73532. for (;;)
  73533. {
  73534. const juce_wchar c = *t++;
  73535. if (c == 0)
  73536. break;
  73537. int charType;
  73538. if (c == '\r' || c == '\n')
  73539. {
  73540. charType = 0;
  73541. }
  73542. else if (CharacterFunctions::isWhitespace (c))
  73543. {
  73544. charType = 2;
  73545. }
  73546. else
  73547. {
  73548. charType = 1;
  73549. }
  73550. if (charType == 0 || charType != lastCharType)
  73551. {
  73552. if (currentString.isNotEmpty())
  73553. {
  73554. tokens.add (new Token (currentString, font,
  73555. lastCharType == 2 || lastCharType == 0));
  73556. }
  73557. currentString = String::charToString (c);
  73558. if (c == '\r' && *t == '\n')
  73559. currentString += *t++;
  73560. }
  73561. else
  73562. {
  73563. currentString += c;
  73564. }
  73565. lastCharType = charType;
  73566. }
  73567. if (currentString.isNotEmpty())
  73568. tokens.add (new Token (currentString, font, lastCharType == 2));
  73569. }
  73570. void TextLayout::setText (const String& text, const Font& font)
  73571. {
  73572. clear();
  73573. appendText (text, font);
  73574. }
  73575. void TextLayout::layout (int maxWidth,
  73576. const Justification& justification,
  73577. const bool attemptToBalanceLineLengths)
  73578. {
  73579. if (attemptToBalanceLineLengths)
  73580. {
  73581. const int originalW = maxWidth;
  73582. int bestWidth = maxWidth;
  73583. float bestLineProportion = 0.0f;
  73584. while (maxWidth > originalW / 2)
  73585. {
  73586. layout (maxWidth, justification, false);
  73587. if (getNumLines() <= 1)
  73588. return;
  73589. const int lastLineW = getLineWidth (getNumLines() - 1);
  73590. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73591. const float prop = lastLineW / (float) lastButOneLineW;
  73592. if (prop > 0.9f)
  73593. return;
  73594. if (prop > bestLineProportion)
  73595. {
  73596. bestLineProportion = prop;
  73597. bestWidth = maxWidth;
  73598. }
  73599. maxWidth -= 10;
  73600. }
  73601. layout (bestWidth, justification, false);
  73602. }
  73603. else
  73604. {
  73605. int x = 0;
  73606. int y = 0;
  73607. int h = 0;
  73608. totalLines = 0;
  73609. int i;
  73610. for (i = 0; i < tokens.size(); ++i)
  73611. {
  73612. Token* const t = tokens.getUnchecked(i);
  73613. t->x = x;
  73614. t->y = y;
  73615. t->line = totalLines;
  73616. x += t->w;
  73617. h = jmax (h, t->h);
  73618. const Token* nextTok = tokens [i + 1];
  73619. if (nextTok == 0)
  73620. break;
  73621. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73622. {
  73623. // finished a line, so go back and update the heights of the things on it
  73624. for (int j = i; j >= 0; --j)
  73625. {
  73626. Token* const tok = tokens.getUnchecked(j);
  73627. if (tok->line == totalLines)
  73628. tok->lineHeight = h;
  73629. else
  73630. break;
  73631. }
  73632. x = 0;
  73633. y += h;
  73634. h = 0;
  73635. ++totalLines;
  73636. }
  73637. }
  73638. // finished a line, so go back and update the heights of the things on it
  73639. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73640. {
  73641. Token* const t = tokens.getUnchecked(j);
  73642. if (t->line == totalLines)
  73643. t->lineHeight = h;
  73644. else
  73645. break;
  73646. }
  73647. ++totalLines;
  73648. if (! justification.testFlags (Justification::left))
  73649. {
  73650. int totalW = getWidth();
  73651. for (i = totalLines; --i >= 0;)
  73652. {
  73653. const int lineW = getLineWidth (i);
  73654. int dx = 0;
  73655. if (justification.testFlags (Justification::horizontallyCentred))
  73656. dx = (totalW - lineW) / 2;
  73657. else if (justification.testFlags (Justification::right))
  73658. dx = totalW - lineW;
  73659. for (int j = tokens.size(); --j >= 0;)
  73660. {
  73661. Token* const t = tokens.getUnchecked(j);
  73662. if (t->line == i)
  73663. t->x += dx;
  73664. }
  73665. }
  73666. }
  73667. }
  73668. }
  73669. int TextLayout::getLineWidth (const int lineNumber) const
  73670. {
  73671. int maxW = 0;
  73672. for (int i = tokens.size(); --i >= 0;)
  73673. {
  73674. const Token* const t = tokens.getUnchecked(i);
  73675. if (t->line == lineNumber && ! t->isWhitespace)
  73676. maxW = jmax (maxW, t->x + t->w);
  73677. }
  73678. return maxW;
  73679. }
  73680. int TextLayout::getWidth() const
  73681. {
  73682. int maxW = 0;
  73683. for (int i = tokens.size(); --i >= 0;)
  73684. {
  73685. const Token* const t = tokens.getUnchecked(i);
  73686. if (! t->isWhitespace)
  73687. maxW = jmax (maxW, t->x + t->w);
  73688. }
  73689. return maxW;
  73690. }
  73691. int TextLayout::getHeight() const
  73692. {
  73693. int maxH = 0;
  73694. for (int i = tokens.size(); --i >= 0;)
  73695. {
  73696. const Token* const t = tokens.getUnchecked(i);
  73697. if (! t->isWhitespace)
  73698. maxH = jmax (maxH, t->y + t->h);
  73699. }
  73700. return maxH;
  73701. }
  73702. void TextLayout::draw (Graphics& g,
  73703. const int xOffset,
  73704. const int yOffset) const
  73705. {
  73706. for (int i = tokens.size(); --i >= 0;)
  73707. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73708. }
  73709. void TextLayout::drawWithin (Graphics& g,
  73710. int x, int y, int w, int h,
  73711. const Justification& justification) const
  73712. {
  73713. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73714. x, y, w, h);
  73715. draw (g, x, y);
  73716. }
  73717. END_JUCE_NAMESPACE
  73718. /*** End of inlined file: juce_TextLayout.cpp ***/
  73719. /*** Start of inlined file: juce_Typeface.cpp ***/
  73720. BEGIN_JUCE_NAMESPACE
  73721. Typeface::Typeface (const String& name_) throw()
  73722. : name (name_)
  73723. {
  73724. }
  73725. Typeface::~Typeface()
  73726. {
  73727. }
  73728. class CustomTypeface::GlyphInfo
  73729. {
  73730. public:
  73731. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73732. : character (character_), path (path_), width (width_)
  73733. {
  73734. }
  73735. ~GlyphInfo() throw()
  73736. {
  73737. }
  73738. struct KerningPair
  73739. {
  73740. juce_wchar character2;
  73741. float kerningAmount;
  73742. };
  73743. void addKerningPair (const juce_wchar subsequentCharacter,
  73744. const float extraKerningAmount) throw()
  73745. {
  73746. KerningPair kp;
  73747. kp.character2 = subsequentCharacter;
  73748. kp.kerningAmount = extraKerningAmount;
  73749. kerningPairs.add (kp);
  73750. }
  73751. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73752. {
  73753. if (subsequentCharacter != 0)
  73754. {
  73755. for (int i = kerningPairs.size(); --i >= 0;)
  73756. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73757. return width + kerningPairs.getReference(i).kerningAmount;
  73758. }
  73759. return width;
  73760. }
  73761. const juce_wchar character;
  73762. const Path path;
  73763. float width;
  73764. Array <KerningPair> kerningPairs;
  73765. juce_UseDebuggingNewOperator
  73766. private:
  73767. GlyphInfo (const GlyphInfo&);
  73768. GlyphInfo& operator= (const GlyphInfo&);
  73769. };
  73770. CustomTypeface::CustomTypeface()
  73771. : Typeface (String::empty)
  73772. {
  73773. clear();
  73774. }
  73775. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73776. : Typeface (String::empty)
  73777. {
  73778. clear();
  73779. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73780. BufferedInputStream in (&gzin, 32768, false);
  73781. name = in.readString();
  73782. isBold = in.readBool();
  73783. isItalic = in.readBool();
  73784. ascent = in.readFloat();
  73785. defaultCharacter = (juce_wchar) in.readShort();
  73786. int i, numChars = in.readInt();
  73787. for (i = 0; i < numChars; ++i)
  73788. {
  73789. const juce_wchar c = (juce_wchar) in.readShort();
  73790. const float width = in.readFloat();
  73791. Path p;
  73792. p.loadPathFromStream (in);
  73793. addGlyph (c, p, width);
  73794. }
  73795. const int numKerningPairs = in.readInt();
  73796. for (i = 0; i < numKerningPairs; ++i)
  73797. {
  73798. const juce_wchar char1 = (juce_wchar) in.readShort();
  73799. const juce_wchar char2 = (juce_wchar) in.readShort();
  73800. addKerningPair (char1, char2, in.readFloat());
  73801. }
  73802. }
  73803. CustomTypeface::~CustomTypeface()
  73804. {
  73805. }
  73806. void CustomTypeface::clear()
  73807. {
  73808. defaultCharacter = 0;
  73809. ascent = 1.0f;
  73810. isBold = isItalic = false;
  73811. zeromem (lookupTable, sizeof (lookupTable));
  73812. glyphs.clear();
  73813. }
  73814. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73815. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73816. {
  73817. name = name_;
  73818. defaultCharacter = defaultCharacter_;
  73819. ascent = ascent_;
  73820. isBold = isBold_;
  73821. isItalic = isItalic_;
  73822. }
  73823. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73824. {
  73825. // Check that you're not trying to add the same character twice..
  73826. jassert (findGlyph (character, false) == 0);
  73827. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73828. lookupTable [character] = (short) glyphs.size();
  73829. glyphs.add (new GlyphInfo (character, path, width));
  73830. }
  73831. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73832. {
  73833. if (extraAmount != 0)
  73834. {
  73835. GlyphInfo* const g = findGlyph (char1, true);
  73836. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73837. if (g != 0)
  73838. g->addKerningPair (char2, extraAmount);
  73839. }
  73840. }
  73841. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73842. {
  73843. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73844. return glyphs [(int) lookupTable [(int) character]];
  73845. for (int i = 0; i < glyphs.size(); ++i)
  73846. {
  73847. GlyphInfo* const g = glyphs.getUnchecked(i);
  73848. if (g->character == character)
  73849. return g;
  73850. }
  73851. if (loadIfNeeded && loadGlyphIfPossible (character))
  73852. return findGlyph (character, false);
  73853. return 0;
  73854. }
  73855. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73856. {
  73857. GlyphInfo* glyph = findGlyph (character, true);
  73858. if (glyph == 0)
  73859. {
  73860. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73861. glyph = findGlyph (L' ', true);
  73862. if (glyph == 0)
  73863. {
  73864. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73865. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73866. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73867. {
  73868. //xxx
  73869. }
  73870. if (glyph == 0)
  73871. glyph = findGlyph (defaultCharacter, true);
  73872. }
  73873. }
  73874. return glyph;
  73875. }
  73876. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73877. {
  73878. return false;
  73879. }
  73880. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73881. {
  73882. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73883. for (int i = 0; i < numCharacters; ++i)
  73884. {
  73885. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73886. Array <int> glyphIndexes;
  73887. Array <float> offsets;
  73888. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73889. const int glyphIndex = glyphIndexes.getFirst();
  73890. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73891. {
  73892. const float glyphWidth = offsets[1];
  73893. Path p;
  73894. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73895. addGlyph (c, p, glyphWidth);
  73896. for (int j = glyphs.size() - 1; --j >= 0;)
  73897. {
  73898. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73899. glyphIndexes.clearQuick();
  73900. offsets.clearQuick();
  73901. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73902. if (offsets.size() > 1)
  73903. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73904. }
  73905. }
  73906. }
  73907. }
  73908. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73909. {
  73910. GZIPCompressorOutputStream out (&outputStream);
  73911. out.writeString (name);
  73912. out.writeBool (isBold);
  73913. out.writeBool (isItalic);
  73914. out.writeFloat (ascent);
  73915. out.writeShort ((short) (unsigned short) defaultCharacter);
  73916. out.writeInt (glyphs.size());
  73917. int i, numKerningPairs = 0;
  73918. for (i = 0; i < glyphs.size(); ++i)
  73919. {
  73920. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73921. out.writeShort ((short) (unsigned short) g->character);
  73922. out.writeFloat (g->width);
  73923. g->path.writePathToStream (out);
  73924. numKerningPairs += g->kerningPairs.size();
  73925. }
  73926. out.writeInt (numKerningPairs);
  73927. for (i = 0; i < glyphs.size(); ++i)
  73928. {
  73929. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73930. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73931. {
  73932. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73933. out.writeShort ((short) (unsigned short) g->character);
  73934. out.writeShort ((short) (unsigned short) p.character2);
  73935. out.writeFloat (p.kerningAmount);
  73936. }
  73937. }
  73938. return true;
  73939. }
  73940. float CustomTypeface::getAscent() const
  73941. {
  73942. return ascent;
  73943. }
  73944. float CustomTypeface::getDescent() const
  73945. {
  73946. return 1.0f - ascent;
  73947. }
  73948. float CustomTypeface::getStringWidth (const String& text)
  73949. {
  73950. float x = 0;
  73951. const juce_wchar* t = text;
  73952. while (*t != 0)
  73953. {
  73954. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73955. if (glyph != 0)
  73956. x += glyph->getHorizontalSpacing (*t);
  73957. }
  73958. return x;
  73959. }
  73960. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73961. {
  73962. xOffsets.add (0);
  73963. float x = 0;
  73964. const juce_wchar* t = text;
  73965. while (*t != 0)
  73966. {
  73967. const juce_wchar c = *t++;
  73968. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73969. if (glyph != 0)
  73970. {
  73971. x += glyph->getHorizontalSpacing (*t);
  73972. resultGlyphs.add ((int) glyph->character);
  73973. xOffsets.add (x);
  73974. }
  73975. }
  73976. }
  73977. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73978. {
  73979. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73980. if (glyph != 0)
  73981. {
  73982. path = glyph->path;
  73983. return true;
  73984. }
  73985. return false;
  73986. }
  73987. END_JUCE_NAMESPACE
  73988. /*** End of inlined file: juce_Typeface.cpp ***/
  73989. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73990. BEGIN_JUCE_NAMESPACE
  73991. AffineTransform::AffineTransform() throw()
  73992. : mat00 (1.0f),
  73993. mat01 (0),
  73994. mat02 (0),
  73995. mat10 (0),
  73996. mat11 (1.0f),
  73997. mat12 (0)
  73998. {
  73999. }
  74000. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  74001. : mat00 (other.mat00),
  74002. mat01 (other.mat01),
  74003. mat02 (other.mat02),
  74004. mat10 (other.mat10),
  74005. mat11 (other.mat11),
  74006. mat12 (other.mat12)
  74007. {
  74008. }
  74009. AffineTransform::AffineTransform (const float mat00_,
  74010. const float mat01_,
  74011. const float mat02_,
  74012. const float mat10_,
  74013. const float mat11_,
  74014. const float mat12_) throw()
  74015. : mat00 (mat00_),
  74016. mat01 (mat01_),
  74017. mat02 (mat02_),
  74018. mat10 (mat10_),
  74019. mat11 (mat11_),
  74020. mat12 (mat12_)
  74021. {
  74022. }
  74023. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  74024. {
  74025. mat00 = other.mat00;
  74026. mat01 = other.mat01;
  74027. mat02 = other.mat02;
  74028. mat10 = other.mat10;
  74029. mat11 = other.mat11;
  74030. mat12 = other.mat12;
  74031. return *this;
  74032. }
  74033. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  74034. {
  74035. return mat00 == other.mat00
  74036. && mat01 == other.mat01
  74037. && mat02 == other.mat02
  74038. && mat10 == other.mat10
  74039. && mat11 == other.mat11
  74040. && mat12 == other.mat12;
  74041. }
  74042. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  74043. {
  74044. return ! operator== (other);
  74045. }
  74046. bool AffineTransform::isIdentity() const throw()
  74047. {
  74048. return (mat01 == 0)
  74049. && (mat02 == 0)
  74050. && (mat10 == 0)
  74051. && (mat12 == 0)
  74052. && (mat00 == 1.0f)
  74053. && (mat11 == 1.0f);
  74054. }
  74055. const AffineTransform AffineTransform::identity;
  74056. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  74057. {
  74058. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  74059. other.mat00 * mat01 + other.mat01 * mat11,
  74060. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  74061. other.mat10 * mat00 + other.mat11 * mat10,
  74062. other.mat10 * mat01 + other.mat11 * mat11,
  74063. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  74064. }
  74065. const AffineTransform AffineTransform::followedBy (const float omat00,
  74066. const float omat01,
  74067. const float omat02,
  74068. const float omat10,
  74069. const float omat11,
  74070. const float omat12) const throw()
  74071. {
  74072. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  74073. omat00 * mat01 + omat01 * mat11,
  74074. omat00 * mat02 + omat01 * mat12 + omat02,
  74075. omat10 * mat00 + omat11 * mat10,
  74076. omat10 * mat01 + omat11 * mat11,
  74077. omat10 * mat02 + omat11 * mat12 + omat12);
  74078. }
  74079. const AffineTransform AffineTransform::translated (const float dx,
  74080. const float dy) const throw()
  74081. {
  74082. return AffineTransform (mat00, mat01, mat02 + dx,
  74083. mat10, mat11, mat12 + dy);
  74084. }
  74085. const AffineTransform AffineTransform::translation (const float dx,
  74086. const float dy) throw()
  74087. {
  74088. return AffineTransform (1.0f, 0, dx,
  74089. 0, 1.0f, dy);
  74090. }
  74091. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  74092. {
  74093. const float cosRad = std::cos (rad);
  74094. const float sinRad = std::sin (rad);
  74095. return followedBy (cosRad, -sinRad, 0,
  74096. sinRad, cosRad, 0);
  74097. }
  74098. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74099. {
  74100. const float cosRad = std::cos (rad);
  74101. const float sinRad = std::sin (rad);
  74102. return AffineTransform (cosRad, -sinRad, 0,
  74103. sinRad, cosRad, 0);
  74104. }
  74105. const AffineTransform AffineTransform::rotated (const float angle,
  74106. const float pivotX,
  74107. const float pivotY) const throw()
  74108. {
  74109. return translated (-pivotX, -pivotY)
  74110. .rotated (angle)
  74111. .translated (pivotX, pivotY);
  74112. }
  74113. const AffineTransform AffineTransform::rotation (const float angle,
  74114. const float pivotX,
  74115. const float pivotY) throw()
  74116. {
  74117. return translation (-pivotX, -pivotY)
  74118. .rotated (angle)
  74119. .translated (pivotX, pivotY);
  74120. }
  74121. const AffineTransform AffineTransform::scaled (const float factorX,
  74122. const float factorY) const throw()
  74123. {
  74124. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74125. factorY * mat10, factorY * mat11, factorY * mat12);
  74126. }
  74127. const AffineTransform AffineTransform::scale (const float factorX,
  74128. const float factorY) throw()
  74129. {
  74130. return AffineTransform (factorX, 0, 0,
  74131. 0, factorY, 0);
  74132. }
  74133. const AffineTransform AffineTransform::sheared (const float shearX,
  74134. const float shearY) const throw()
  74135. {
  74136. return followedBy (1.0f, shearX, 0,
  74137. shearY, 1.0f, 0);
  74138. }
  74139. const AffineTransform AffineTransform::inverted() const throw()
  74140. {
  74141. double determinant = (mat00 * mat11 - mat10 * mat01);
  74142. if (determinant != 0.0)
  74143. {
  74144. determinant = 1.0 / determinant;
  74145. const float dst00 = (float) (mat11 * determinant);
  74146. const float dst10 = (float) (-mat10 * determinant);
  74147. const float dst01 = (float) (-mat01 * determinant);
  74148. const float dst11 = (float) (mat00 * determinant);
  74149. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74150. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74151. }
  74152. else
  74153. {
  74154. // singularity..
  74155. return *this;
  74156. }
  74157. }
  74158. bool AffineTransform::isSingularity() const throw()
  74159. {
  74160. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  74161. }
  74162. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74163. const float x10, const float y10,
  74164. const float x01, const float y01) throw()
  74165. {
  74166. return AffineTransform (x10 - x00, x01 - x00, x00,
  74167. y10 - y00, y01 - y00, y00);
  74168. }
  74169. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74170. const float sx2, const float sy2, const float tx2, const float ty2,
  74171. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74172. {
  74173. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74174. .inverted()
  74175. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74176. }
  74177. bool AffineTransform::isOnlyTranslation() const throw()
  74178. {
  74179. return (mat01 == 0)
  74180. && (mat10 == 0)
  74181. && (mat00 == 1.0f)
  74182. && (mat11 == 1.0f);
  74183. }
  74184. END_JUCE_NAMESPACE
  74185. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74186. /*** Start of inlined file: juce_BorderSize.cpp ***/
  74187. BEGIN_JUCE_NAMESPACE
  74188. BorderSize::BorderSize() throw()
  74189. : top (0),
  74190. left (0),
  74191. bottom (0),
  74192. right (0)
  74193. {
  74194. }
  74195. BorderSize::BorderSize (const BorderSize& other) throw()
  74196. : top (other.top),
  74197. left (other.left),
  74198. bottom (other.bottom),
  74199. right (other.right)
  74200. {
  74201. }
  74202. BorderSize::BorderSize (const int topGap,
  74203. const int leftGap,
  74204. const int bottomGap,
  74205. const int rightGap) throw()
  74206. : top (topGap),
  74207. left (leftGap),
  74208. bottom (bottomGap),
  74209. right (rightGap)
  74210. {
  74211. }
  74212. BorderSize::BorderSize (const int allGaps) throw()
  74213. : top (allGaps),
  74214. left (allGaps),
  74215. bottom (allGaps),
  74216. right (allGaps)
  74217. {
  74218. }
  74219. BorderSize::~BorderSize() throw()
  74220. {
  74221. }
  74222. void BorderSize::setTop (const int newTopGap) throw()
  74223. {
  74224. top = newTopGap;
  74225. }
  74226. void BorderSize::setLeft (const int newLeftGap) throw()
  74227. {
  74228. left = newLeftGap;
  74229. }
  74230. void BorderSize::setBottom (const int newBottomGap) throw()
  74231. {
  74232. bottom = newBottomGap;
  74233. }
  74234. void BorderSize::setRight (const int newRightGap) throw()
  74235. {
  74236. right = newRightGap;
  74237. }
  74238. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74239. {
  74240. return Rectangle<int> (r.getX() + left,
  74241. r.getY() + top,
  74242. r.getWidth() - (left + right),
  74243. r.getHeight() - (top + bottom));
  74244. }
  74245. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74246. {
  74247. r.setBounds (r.getX() + left,
  74248. r.getY() + top,
  74249. r.getWidth() - (left + right),
  74250. r.getHeight() - (top + bottom));
  74251. }
  74252. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74253. {
  74254. return Rectangle<int> (r.getX() - left,
  74255. r.getY() - top,
  74256. r.getWidth() + (left + right),
  74257. r.getHeight() + (top + bottom));
  74258. }
  74259. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74260. {
  74261. r.setBounds (r.getX() - left,
  74262. r.getY() - top,
  74263. r.getWidth() + (left + right),
  74264. r.getHeight() + (top + bottom));
  74265. }
  74266. bool BorderSize::operator== (const BorderSize& other) const throw()
  74267. {
  74268. return top == other.top
  74269. && left == other.left
  74270. && bottom == other.bottom
  74271. && right == other.right;
  74272. }
  74273. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74274. {
  74275. return ! operator== (other);
  74276. }
  74277. END_JUCE_NAMESPACE
  74278. /*** End of inlined file: juce_BorderSize.cpp ***/
  74279. /*** Start of inlined file: juce_Path.cpp ***/
  74280. BEGIN_JUCE_NAMESPACE
  74281. // tests that some co-ords aren't NaNs
  74282. #define CHECK_COORDS_ARE_VALID(x, y) \
  74283. jassert (x == x && y == y);
  74284. namespace PathHelpers
  74285. {
  74286. static const float ellipseAngularIncrement = 0.05f;
  74287. static const String nextToken (const juce_wchar*& t)
  74288. {
  74289. while (CharacterFunctions::isWhitespace (*t))
  74290. ++t;
  74291. const juce_wchar* const start = t;
  74292. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74293. ++t;
  74294. return String (start, (int) (t - start));
  74295. }
  74296. }
  74297. const float Path::lineMarker = 100001.0f;
  74298. const float Path::moveMarker = 100002.0f;
  74299. const float Path::quadMarker = 100003.0f;
  74300. const float Path::cubicMarker = 100004.0f;
  74301. const float Path::closeSubPathMarker = 100005.0f;
  74302. Path::Path()
  74303. : numElements (0),
  74304. pathXMin (0),
  74305. pathXMax (0),
  74306. pathYMin (0),
  74307. pathYMax (0),
  74308. useNonZeroWinding (true)
  74309. {
  74310. }
  74311. Path::~Path()
  74312. {
  74313. }
  74314. Path::Path (const Path& other)
  74315. : numElements (other.numElements),
  74316. pathXMin (other.pathXMin),
  74317. pathXMax (other.pathXMax),
  74318. pathYMin (other.pathYMin),
  74319. pathYMax (other.pathYMax),
  74320. useNonZeroWinding (other.useNonZeroWinding)
  74321. {
  74322. if (numElements > 0)
  74323. {
  74324. data.setAllocatedSize ((int) numElements);
  74325. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74326. }
  74327. }
  74328. Path& Path::operator= (const Path& other)
  74329. {
  74330. if (this != &other)
  74331. {
  74332. data.ensureAllocatedSize ((int) other.numElements);
  74333. numElements = other.numElements;
  74334. pathXMin = other.pathXMin;
  74335. pathXMax = other.pathXMax;
  74336. pathYMin = other.pathYMin;
  74337. pathYMax = other.pathYMax;
  74338. useNonZeroWinding = other.useNonZeroWinding;
  74339. if (numElements > 0)
  74340. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74341. }
  74342. return *this;
  74343. }
  74344. bool Path::operator== (const Path& other) const throw()
  74345. {
  74346. return ! operator!= (other);
  74347. }
  74348. bool Path::operator!= (const Path& other) const throw()
  74349. {
  74350. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74351. return true;
  74352. for (size_t i = 0; i < numElements; ++i)
  74353. if (data.elements[i] != other.data.elements[i])
  74354. return true;
  74355. return false;
  74356. }
  74357. void Path::clear() throw()
  74358. {
  74359. numElements = 0;
  74360. pathXMin = 0;
  74361. pathYMin = 0;
  74362. pathYMax = 0;
  74363. pathXMax = 0;
  74364. }
  74365. void Path::swapWithPath (Path& other) throw()
  74366. {
  74367. data.swapWith (other.data);
  74368. swapVariables <size_t> (numElements, other.numElements);
  74369. swapVariables <float> (pathXMin, other.pathXMin);
  74370. swapVariables <float> (pathXMax, other.pathXMax);
  74371. swapVariables <float> (pathYMin, other.pathYMin);
  74372. swapVariables <float> (pathYMax, other.pathYMax);
  74373. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74374. }
  74375. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74376. {
  74377. useNonZeroWinding = isNonZero;
  74378. }
  74379. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74380. const bool preserveProportions) throw()
  74381. {
  74382. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74383. }
  74384. bool Path::isEmpty() const throw()
  74385. {
  74386. size_t i = 0;
  74387. while (i < numElements)
  74388. {
  74389. const float type = data.elements [i++];
  74390. if (type == moveMarker)
  74391. {
  74392. i += 2;
  74393. }
  74394. else if (type == lineMarker
  74395. || type == quadMarker
  74396. || type == cubicMarker)
  74397. {
  74398. return false;
  74399. }
  74400. }
  74401. return true;
  74402. }
  74403. const Rectangle<float> Path::getBounds() const throw()
  74404. {
  74405. return Rectangle<float> (pathXMin, pathYMin,
  74406. pathXMax - pathXMin,
  74407. pathYMax - pathYMin);
  74408. }
  74409. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74410. {
  74411. return getBounds().transformed (transform);
  74412. }
  74413. void Path::startNewSubPath (const float x, const float y)
  74414. {
  74415. CHECK_COORDS_ARE_VALID (x, y);
  74416. if (numElements == 0)
  74417. {
  74418. pathXMin = pathXMax = x;
  74419. pathYMin = pathYMax = y;
  74420. }
  74421. else
  74422. {
  74423. pathXMin = jmin (pathXMin, x);
  74424. pathXMax = jmax (pathXMax, x);
  74425. pathYMin = jmin (pathYMin, y);
  74426. pathYMax = jmax (pathYMax, y);
  74427. }
  74428. data.ensureAllocatedSize ((int) numElements + 3);
  74429. data.elements [numElements++] = moveMarker;
  74430. data.elements [numElements++] = x;
  74431. data.elements [numElements++] = y;
  74432. }
  74433. void Path::startNewSubPath (const Point<float>& start)
  74434. {
  74435. startNewSubPath (start.getX(), start.getY());
  74436. }
  74437. void Path::lineTo (const float x, const float y)
  74438. {
  74439. CHECK_COORDS_ARE_VALID (x, y);
  74440. if (numElements == 0)
  74441. startNewSubPath (0, 0);
  74442. data.ensureAllocatedSize ((int) numElements + 3);
  74443. data.elements [numElements++] = lineMarker;
  74444. data.elements [numElements++] = x;
  74445. data.elements [numElements++] = y;
  74446. pathXMin = jmin (pathXMin, x);
  74447. pathXMax = jmax (pathXMax, x);
  74448. pathYMin = jmin (pathYMin, y);
  74449. pathYMax = jmax (pathYMax, y);
  74450. }
  74451. void Path::lineTo (const Point<float>& end)
  74452. {
  74453. lineTo (end.getX(), end.getY());
  74454. }
  74455. void Path::quadraticTo (const float x1, const float y1,
  74456. const float x2, const float y2)
  74457. {
  74458. CHECK_COORDS_ARE_VALID (x1, y1);
  74459. CHECK_COORDS_ARE_VALID (x2, y2);
  74460. if (numElements == 0)
  74461. startNewSubPath (0, 0);
  74462. data.ensureAllocatedSize ((int) numElements + 5);
  74463. data.elements [numElements++] = quadMarker;
  74464. data.elements [numElements++] = x1;
  74465. data.elements [numElements++] = y1;
  74466. data.elements [numElements++] = x2;
  74467. data.elements [numElements++] = y2;
  74468. pathXMin = jmin (pathXMin, x1, x2);
  74469. pathXMax = jmax (pathXMax, x1, x2);
  74470. pathYMin = jmin (pathYMin, y1, y2);
  74471. pathYMax = jmax (pathYMax, y1, y2);
  74472. }
  74473. void Path::quadraticTo (const Point<float>& controlPoint,
  74474. const Point<float>& endPoint)
  74475. {
  74476. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74477. endPoint.getX(), endPoint.getY());
  74478. }
  74479. void Path::cubicTo (const float x1, const float y1,
  74480. const float x2, const float y2,
  74481. const float x3, const float y3)
  74482. {
  74483. CHECK_COORDS_ARE_VALID (x1, y1);
  74484. CHECK_COORDS_ARE_VALID (x2, y2);
  74485. CHECK_COORDS_ARE_VALID (x3, y3);
  74486. if (numElements == 0)
  74487. startNewSubPath (0, 0);
  74488. data.ensureAllocatedSize ((int) numElements + 7);
  74489. data.elements [numElements++] = cubicMarker;
  74490. data.elements [numElements++] = x1;
  74491. data.elements [numElements++] = y1;
  74492. data.elements [numElements++] = x2;
  74493. data.elements [numElements++] = y2;
  74494. data.elements [numElements++] = x3;
  74495. data.elements [numElements++] = y3;
  74496. pathXMin = jmin (pathXMin, x1, x2, x3);
  74497. pathXMax = jmax (pathXMax, x1, x2, x3);
  74498. pathYMin = jmin (pathYMin, y1, y2, y3);
  74499. pathYMax = jmax (pathYMax, y1, y2, y3);
  74500. }
  74501. void Path::cubicTo (const Point<float>& controlPoint1,
  74502. const Point<float>& controlPoint2,
  74503. const Point<float>& endPoint)
  74504. {
  74505. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74506. controlPoint2.getX(), controlPoint2.getY(),
  74507. endPoint.getX(), endPoint.getY());
  74508. }
  74509. void Path::closeSubPath()
  74510. {
  74511. if (numElements > 0
  74512. && data.elements [numElements - 1] != closeSubPathMarker)
  74513. {
  74514. data.ensureAllocatedSize ((int) numElements + 1);
  74515. data.elements [numElements++] = closeSubPathMarker;
  74516. }
  74517. }
  74518. const Point<float> Path::getCurrentPosition() const
  74519. {
  74520. size_t i = numElements - 1;
  74521. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74522. {
  74523. while (i >= 0)
  74524. {
  74525. if (data.elements[i] == moveMarker)
  74526. {
  74527. i += 2;
  74528. break;
  74529. }
  74530. --i;
  74531. }
  74532. }
  74533. if (i > 0)
  74534. return Point<float> (data.elements [i - 1], data.elements [i]);
  74535. return Point<float>();
  74536. }
  74537. void Path::addRectangle (const float x, const float y,
  74538. const float w, const float h)
  74539. {
  74540. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74541. if (w < 0)
  74542. swapVariables (x1, x2);
  74543. if (h < 0)
  74544. swapVariables (y1, y2);
  74545. data.ensureAllocatedSize ((int) numElements + 13);
  74546. if (numElements == 0)
  74547. {
  74548. pathXMin = x1;
  74549. pathXMax = x2;
  74550. pathYMin = y1;
  74551. pathYMax = y2;
  74552. }
  74553. else
  74554. {
  74555. pathXMin = jmin (pathXMin, x1);
  74556. pathXMax = jmax (pathXMax, x2);
  74557. pathYMin = jmin (pathYMin, y1);
  74558. pathYMax = jmax (pathYMax, y2);
  74559. }
  74560. data.elements [numElements++] = moveMarker;
  74561. data.elements [numElements++] = x1;
  74562. data.elements [numElements++] = y2;
  74563. data.elements [numElements++] = lineMarker;
  74564. data.elements [numElements++] = x1;
  74565. data.elements [numElements++] = y1;
  74566. data.elements [numElements++] = lineMarker;
  74567. data.elements [numElements++] = x2;
  74568. data.elements [numElements++] = y1;
  74569. data.elements [numElements++] = lineMarker;
  74570. data.elements [numElements++] = x2;
  74571. data.elements [numElements++] = y2;
  74572. data.elements [numElements++] = closeSubPathMarker;
  74573. }
  74574. void Path::addRoundedRectangle (const float x, const float y,
  74575. const float w, const float h,
  74576. float csx,
  74577. float csy)
  74578. {
  74579. csx = jmin (csx, w * 0.5f);
  74580. csy = jmin (csy, h * 0.5f);
  74581. const float cs45x = csx * 0.45f;
  74582. const float cs45y = csy * 0.45f;
  74583. const float x2 = x + w;
  74584. const float y2 = y + h;
  74585. startNewSubPath (x + csx, y);
  74586. lineTo (x2 - csx, y);
  74587. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74588. lineTo (x2, y2 - csy);
  74589. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74590. lineTo (x + csx, y2);
  74591. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74592. lineTo (x, y + csy);
  74593. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74594. closeSubPath();
  74595. }
  74596. void Path::addRoundedRectangle (const float x, const float y,
  74597. const float w, const float h,
  74598. float cs)
  74599. {
  74600. addRoundedRectangle (x, y, w, h, cs, cs);
  74601. }
  74602. void Path::addTriangle (const float x1, const float y1,
  74603. const float x2, const float y2,
  74604. const float x3, const float y3)
  74605. {
  74606. startNewSubPath (x1, y1);
  74607. lineTo (x2, y2);
  74608. lineTo (x3, y3);
  74609. closeSubPath();
  74610. }
  74611. void Path::addQuadrilateral (const float x1, const float y1,
  74612. const float x2, const float y2,
  74613. const float x3, const float y3,
  74614. const float x4, const float y4)
  74615. {
  74616. startNewSubPath (x1, y1);
  74617. lineTo (x2, y2);
  74618. lineTo (x3, y3);
  74619. lineTo (x4, y4);
  74620. closeSubPath();
  74621. }
  74622. void Path::addEllipse (const float x, const float y,
  74623. const float w, const float h)
  74624. {
  74625. const float hw = w * 0.5f;
  74626. const float hw55 = hw * 0.55f;
  74627. const float hh = h * 0.5f;
  74628. const float hh45 = hh * 0.55f;
  74629. const float cx = x + hw;
  74630. const float cy = y + hh;
  74631. startNewSubPath (cx, cy - hh);
  74632. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  74633. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  74634. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  74635. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  74636. closeSubPath();
  74637. }
  74638. void Path::addArc (const float x, const float y,
  74639. const float w, const float h,
  74640. const float fromRadians,
  74641. const float toRadians,
  74642. const bool startAsNewSubPath)
  74643. {
  74644. const float radiusX = w / 2.0f;
  74645. const float radiusY = h / 2.0f;
  74646. addCentredArc (x + radiusX,
  74647. y + radiusY,
  74648. radiusX, radiusY,
  74649. 0.0f,
  74650. fromRadians, toRadians,
  74651. startAsNewSubPath);
  74652. }
  74653. void Path::addCentredArc (const float centreX, const float centreY,
  74654. const float radiusX, const float radiusY,
  74655. const float rotationOfEllipse,
  74656. const float fromRadians,
  74657. const float toRadians,
  74658. const bool startAsNewSubPath)
  74659. {
  74660. if (radiusX > 0.0f && radiusY > 0.0f)
  74661. {
  74662. const Point<float> centre (centreX, centreY);
  74663. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74664. float angle = fromRadians;
  74665. if (startAsNewSubPath)
  74666. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74667. if (fromRadians < toRadians)
  74668. {
  74669. if (startAsNewSubPath)
  74670. angle += PathHelpers::ellipseAngularIncrement;
  74671. while (angle < toRadians)
  74672. {
  74673. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74674. angle += PathHelpers::ellipseAngularIncrement;
  74675. }
  74676. }
  74677. else
  74678. {
  74679. if (startAsNewSubPath)
  74680. angle -= PathHelpers::ellipseAngularIncrement;
  74681. while (angle > toRadians)
  74682. {
  74683. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74684. angle -= PathHelpers::ellipseAngularIncrement;
  74685. }
  74686. }
  74687. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74688. }
  74689. }
  74690. void Path::addPieSegment (const float x, const float y,
  74691. const float width, const float height,
  74692. const float fromRadians,
  74693. const float toRadians,
  74694. const float innerCircleProportionalSize)
  74695. {
  74696. float radiusX = width * 0.5f;
  74697. float radiusY = height * 0.5f;
  74698. const Point<float> centre (x + radiusX, y + radiusY);
  74699. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74700. addArc (x, y, width, height, fromRadians, toRadians);
  74701. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74702. {
  74703. closeSubPath();
  74704. if (innerCircleProportionalSize > 0)
  74705. {
  74706. radiusX *= innerCircleProportionalSize;
  74707. radiusY *= innerCircleProportionalSize;
  74708. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74709. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74710. }
  74711. }
  74712. else
  74713. {
  74714. if (innerCircleProportionalSize > 0)
  74715. {
  74716. radiusX *= innerCircleProportionalSize;
  74717. radiusY *= innerCircleProportionalSize;
  74718. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74719. }
  74720. else
  74721. {
  74722. lineTo (centre);
  74723. }
  74724. }
  74725. closeSubPath();
  74726. }
  74727. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74728. {
  74729. const Line<float> reversed (line.reversed());
  74730. lineThickness *= 0.5f;
  74731. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74732. lineTo (line.getPointAlongLine (0, -lineThickness));
  74733. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74734. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74735. closeSubPath();
  74736. }
  74737. void Path::addArrow (const Line<float>& line, float lineThickness,
  74738. float arrowheadWidth, float arrowheadLength)
  74739. {
  74740. const Line<float> reversed (line.reversed());
  74741. lineThickness *= 0.5f;
  74742. arrowheadWidth *= 0.5f;
  74743. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74744. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74745. lineTo (line.getPointAlongLine (0, -lineThickness));
  74746. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74747. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74748. lineTo (line.getEnd());
  74749. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74750. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74751. closeSubPath();
  74752. }
  74753. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74754. const float radius, const float startAngle)
  74755. {
  74756. jassert (numberOfSides > 1); // this would be silly.
  74757. if (numberOfSides > 1)
  74758. {
  74759. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74760. for (int i = 0; i < numberOfSides; ++i)
  74761. {
  74762. const float angle = startAngle + i * angleBetweenPoints;
  74763. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74764. if (i == 0)
  74765. startNewSubPath (p);
  74766. else
  74767. lineTo (p);
  74768. }
  74769. closeSubPath();
  74770. }
  74771. }
  74772. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74773. const float innerRadius, const float outerRadius, const float startAngle)
  74774. {
  74775. jassert (numberOfPoints > 1); // this would be silly.
  74776. if (numberOfPoints > 1)
  74777. {
  74778. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74779. for (int i = 0; i < numberOfPoints; ++i)
  74780. {
  74781. const float angle = startAngle + i * angleBetweenPoints;
  74782. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74783. if (i == 0)
  74784. startNewSubPath (p);
  74785. else
  74786. lineTo (p);
  74787. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74788. }
  74789. closeSubPath();
  74790. }
  74791. }
  74792. void Path::addBubble (float x, float y,
  74793. float w, float h,
  74794. float cs,
  74795. float tipX,
  74796. float tipY,
  74797. int whichSide,
  74798. float arrowPos,
  74799. float arrowWidth)
  74800. {
  74801. if (w > 1.0f && h > 1.0f)
  74802. {
  74803. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74804. const float cs2 = 2.0f * cs;
  74805. startNewSubPath (x + cs, y);
  74806. if (whichSide == 0)
  74807. {
  74808. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74809. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74810. lineTo (arrowX1, y);
  74811. lineTo (tipX, tipY);
  74812. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74813. }
  74814. lineTo (x + w - cs, y);
  74815. if (cs > 0.0f)
  74816. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74817. if (whichSide == 3)
  74818. {
  74819. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74820. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74821. lineTo (x + w, arrowY1);
  74822. lineTo (tipX, tipY);
  74823. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74824. }
  74825. lineTo (x + w, y + h - cs);
  74826. if (cs > 0.0f)
  74827. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74828. if (whichSide == 2)
  74829. {
  74830. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74831. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74832. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74833. lineTo (tipX, tipY);
  74834. lineTo (arrowX1, y + h);
  74835. }
  74836. lineTo (x + cs, y + h);
  74837. if (cs > 0.0f)
  74838. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74839. if (whichSide == 1)
  74840. {
  74841. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74842. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74843. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74844. lineTo (tipX, tipY);
  74845. lineTo (x, arrowY1);
  74846. }
  74847. lineTo (x, y + cs);
  74848. if (cs > 0.0f)
  74849. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74850. closeSubPath();
  74851. }
  74852. }
  74853. void Path::addPath (const Path& other)
  74854. {
  74855. size_t i = 0;
  74856. while (i < other.numElements)
  74857. {
  74858. const float type = other.data.elements [i++];
  74859. if (type == moveMarker)
  74860. {
  74861. startNewSubPath (other.data.elements [i],
  74862. other.data.elements [i + 1]);
  74863. i += 2;
  74864. }
  74865. else if (type == lineMarker)
  74866. {
  74867. lineTo (other.data.elements [i],
  74868. other.data.elements [i + 1]);
  74869. i += 2;
  74870. }
  74871. else if (type == quadMarker)
  74872. {
  74873. quadraticTo (other.data.elements [i],
  74874. other.data.elements [i + 1],
  74875. other.data.elements [i + 2],
  74876. other.data.elements [i + 3]);
  74877. i += 4;
  74878. }
  74879. else if (type == cubicMarker)
  74880. {
  74881. cubicTo (other.data.elements [i],
  74882. other.data.elements [i + 1],
  74883. other.data.elements [i + 2],
  74884. other.data.elements [i + 3],
  74885. other.data.elements [i + 4],
  74886. other.data.elements [i + 5]);
  74887. i += 6;
  74888. }
  74889. else if (type == closeSubPathMarker)
  74890. {
  74891. closeSubPath();
  74892. }
  74893. else
  74894. {
  74895. // something's gone wrong with the element list!
  74896. jassertfalse;
  74897. }
  74898. }
  74899. }
  74900. void Path::addPath (const Path& other,
  74901. const AffineTransform& transformToApply)
  74902. {
  74903. size_t i = 0;
  74904. while (i < other.numElements)
  74905. {
  74906. const float type = other.data.elements [i++];
  74907. if (type == closeSubPathMarker)
  74908. {
  74909. closeSubPath();
  74910. }
  74911. else
  74912. {
  74913. float x = other.data.elements [i++];
  74914. float y = other.data.elements [i++];
  74915. transformToApply.transformPoint (x, y);
  74916. if (type == moveMarker)
  74917. {
  74918. startNewSubPath (x, y);
  74919. }
  74920. else if (type == lineMarker)
  74921. {
  74922. lineTo (x, y);
  74923. }
  74924. else if (type == quadMarker)
  74925. {
  74926. float x2 = other.data.elements [i++];
  74927. float y2 = other.data.elements [i++];
  74928. transformToApply.transformPoint (x2, y2);
  74929. quadraticTo (x, y, x2, y2);
  74930. }
  74931. else if (type == cubicMarker)
  74932. {
  74933. float x2 = other.data.elements [i++];
  74934. float y2 = other.data.elements [i++];
  74935. float x3 = other.data.elements [i++];
  74936. float y3 = other.data.elements [i++];
  74937. transformToApply.transformPoints (x2, y2, x3, y3);
  74938. cubicTo (x, y, x2, y2, x3, y3);
  74939. }
  74940. else
  74941. {
  74942. // something's gone wrong with the element list!
  74943. jassertfalse;
  74944. }
  74945. }
  74946. }
  74947. }
  74948. void Path::applyTransform (const AffineTransform& transform) throw()
  74949. {
  74950. size_t i = 0;
  74951. pathYMin = pathXMin = 0;
  74952. pathYMax = pathXMax = 0;
  74953. bool setMaxMin = false;
  74954. while (i < numElements)
  74955. {
  74956. const float type = data.elements [i++];
  74957. if (type == moveMarker)
  74958. {
  74959. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74960. if (setMaxMin)
  74961. {
  74962. pathXMin = jmin (pathXMin, data.elements [i]);
  74963. pathXMax = jmax (pathXMax, data.elements [i]);
  74964. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74965. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74966. }
  74967. else
  74968. {
  74969. pathXMin = pathXMax = data.elements [i];
  74970. pathYMin = pathYMax = data.elements [i + 1];
  74971. setMaxMin = true;
  74972. }
  74973. i += 2;
  74974. }
  74975. else if (type == lineMarker)
  74976. {
  74977. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74978. pathXMin = jmin (pathXMin, data.elements [i]);
  74979. pathXMax = jmax (pathXMax, data.elements [i]);
  74980. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74981. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74982. i += 2;
  74983. }
  74984. else if (type == quadMarker)
  74985. {
  74986. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74987. data.elements [i + 2], data.elements [i + 3]);
  74988. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74989. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74990. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74991. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74992. i += 4;
  74993. }
  74994. else if (type == cubicMarker)
  74995. {
  74996. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74997. data.elements [i + 2], data.elements [i + 3],
  74998. data.elements [i + 4], data.elements [i + 5]);
  74999. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  75000. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  75001. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  75002. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  75003. i += 6;
  75004. }
  75005. }
  75006. }
  75007. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  75008. const float w, const float h,
  75009. const bool preserveProportions,
  75010. const Justification& justification) const
  75011. {
  75012. Rectangle<float> bounds (getBounds());
  75013. if (preserveProportions)
  75014. {
  75015. if (w <= 0 || h <= 0 || bounds.isEmpty())
  75016. return AffineTransform::identity;
  75017. float newW, newH;
  75018. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  75019. if (srcRatio > h / w)
  75020. {
  75021. newW = h / srcRatio;
  75022. newH = h;
  75023. }
  75024. else
  75025. {
  75026. newW = w;
  75027. newH = w * srcRatio;
  75028. }
  75029. float newXCentre = x;
  75030. float newYCentre = y;
  75031. if (justification.testFlags (Justification::left))
  75032. newXCentre += newW * 0.5f;
  75033. else if (justification.testFlags (Justification::right))
  75034. newXCentre += w - newW * 0.5f;
  75035. else
  75036. newXCentre += w * 0.5f;
  75037. if (justification.testFlags (Justification::top))
  75038. newYCentre += newH * 0.5f;
  75039. else if (justification.testFlags (Justification::bottom))
  75040. newYCentre += h - newH * 0.5f;
  75041. else
  75042. newYCentre += h * 0.5f;
  75043. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  75044. bounds.getHeight() * -0.5f - bounds.getY())
  75045. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  75046. .translated (newXCentre, newYCentre);
  75047. }
  75048. else
  75049. {
  75050. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  75051. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  75052. .translated (x, y);
  75053. }
  75054. }
  75055. bool Path::contains (const float x, const float y, const float tolerence) const
  75056. {
  75057. if (x <= pathXMin || x >= pathXMax
  75058. || y <= pathYMin || y >= pathYMax)
  75059. return false;
  75060. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  75061. int positiveCrossings = 0;
  75062. int negativeCrossings = 0;
  75063. while (i.next())
  75064. {
  75065. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  75066. {
  75067. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  75068. if (intersectX <= x)
  75069. {
  75070. if (i.y1 < i.y2)
  75071. ++positiveCrossings;
  75072. else
  75073. ++negativeCrossings;
  75074. }
  75075. }
  75076. }
  75077. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  75078. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  75079. }
  75080. bool Path::contains (const Point<float>& point, const float tolerence) const
  75081. {
  75082. return contains (point.getX(), point.getY(), tolerence);
  75083. }
  75084. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  75085. {
  75086. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  75087. Point<float> intersection;
  75088. while (i.next())
  75089. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75090. return true;
  75091. return false;
  75092. }
  75093. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  75094. {
  75095. Line<float> result (line);
  75096. const bool startInside = contains (line.getStart());
  75097. const bool endInside = contains (line.getEnd());
  75098. if (startInside == endInside)
  75099. {
  75100. if (keepSectionOutsidePath == startInside)
  75101. result = Line<float>();
  75102. }
  75103. else
  75104. {
  75105. PathFlatteningIterator i (*this, AffineTransform::identity);
  75106. Point<float> intersection;
  75107. while (i.next())
  75108. {
  75109. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75110. {
  75111. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  75112. result.setStart (intersection);
  75113. else
  75114. result.setEnd (intersection);
  75115. }
  75116. }
  75117. }
  75118. return result;
  75119. }
  75120. float Path::getLength (const AffineTransform& transform) const
  75121. {
  75122. float length = 0;
  75123. PathFlatteningIterator i (*this, transform);
  75124. while (i.next())
  75125. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  75126. return length;
  75127. }
  75128. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  75129. {
  75130. PathFlatteningIterator i (*this, transform);
  75131. while (i.next())
  75132. {
  75133. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75134. const float lineLength = line.getLength();
  75135. if (distanceFromStart <= lineLength)
  75136. return line.getPointAlongLine (distanceFromStart);
  75137. distanceFromStart -= lineLength;
  75138. }
  75139. return Point<float> (i.x2, i.y2);
  75140. }
  75141. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75142. const AffineTransform& transform) const
  75143. {
  75144. PathFlatteningIterator i (*this, transform);
  75145. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75146. float length = 0;
  75147. Point<float> pointOnLine;
  75148. while (i.next())
  75149. {
  75150. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75151. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75152. if (distance < bestDistance)
  75153. {
  75154. bestDistance = distance;
  75155. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75156. pointOnPath = pointOnLine;
  75157. }
  75158. length += line.getLength();
  75159. }
  75160. return bestPosition;
  75161. }
  75162. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75163. {
  75164. if (cornerRadius <= 0.01f)
  75165. return *this;
  75166. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75167. size_t n = 0;
  75168. bool lastWasLine = false, firstWasLine = false;
  75169. Path p;
  75170. while (n < numElements)
  75171. {
  75172. const float type = data.elements [n++];
  75173. if (type == moveMarker)
  75174. {
  75175. indexOfPathStart = p.numElements;
  75176. indexOfPathStartThis = n - 1;
  75177. const float x = data.elements [n++];
  75178. const float y = data.elements [n++];
  75179. p.startNewSubPath (x, y);
  75180. lastWasLine = false;
  75181. firstWasLine = (data.elements [n] == lineMarker);
  75182. }
  75183. else if (type == lineMarker || type == closeSubPathMarker)
  75184. {
  75185. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75186. if (type == lineMarker)
  75187. {
  75188. endX = data.elements [n++];
  75189. endY = data.elements [n++];
  75190. if (n > 8)
  75191. {
  75192. startX = data.elements [n - 8];
  75193. startY = data.elements [n - 7];
  75194. joinX = data.elements [n - 5];
  75195. joinY = data.elements [n - 4];
  75196. }
  75197. }
  75198. else
  75199. {
  75200. endX = data.elements [indexOfPathStartThis + 1];
  75201. endY = data.elements [indexOfPathStartThis + 2];
  75202. if (n > 6)
  75203. {
  75204. startX = data.elements [n - 6];
  75205. startY = data.elements [n - 5];
  75206. joinX = data.elements [n - 3];
  75207. joinY = data.elements [n - 2];
  75208. }
  75209. }
  75210. if (lastWasLine)
  75211. {
  75212. const double len1 = juce_hypot (startX - joinX,
  75213. startY - joinY);
  75214. if (len1 > 0)
  75215. {
  75216. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75217. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75218. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75219. }
  75220. const double len2 = juce_hypot (endX - joinX,
  75221. endY - joinY);
  75222. if (len2 > 0)
  75223. {
  75224. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75225. p.quadraticTo (joinX, joinY,
  75226. (float) (joinX + (endX - joinX) * propNeeded),
  75227. (float) (joinY + (endY - joinY) * propNeeded));
  75228. }
  75229. p.lineTo (endX, endY);
  75230. }
  75231. else if (type == lineMarker)
  75232. {
  75233. p.lineTo (endX, endY);
  75234. lastWasLine = true;
  75235. }
  75236. if (type == closeSubPathMarker)
  75237. {
  75238. if (firstWasLine)
  75239. {
  75240. startX = data.elements [n - 3];
  75241. startY = data.elements [n - 2];
  75242. joinX = endX;
  75243. joinY = endY;
  75244. endX = data.elements [indexOfPathStartThis + 4];
  75245. endY = data.elements [indexOfPathStartThis + 5];
  75246. const double len1 = juce_hypot (startX - joinX,
  75247. startY - joinY);
  75248. if (len1 > 0)
  75249. {
  75250. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75251. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75252. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75253. }
  75254. const double len2 = juce_hypot (endX - joinX,
  75255. endY - joinY);
  75256. if (len2 > 0)
  75257. {
  75258. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75259. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75260. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75261. p.quadraticTo (joinX, joinY, endX, endY);
  75262. p.data.elements [indexOfPathStart + 1] = endX;
  75263. p.data.elements [indexOfPathStart + 2] = endY;
  75264. }
  75265. }
  75266. p.closeSubPath();
  75267. }
  75268. }
  75269. else if (type == quadMarker)
  75270. {
  75271. lastWasLine = false;
  75272. const float x1 = data.elements [n++];
  75273. const float y1 = data.elements [n++];
  75274. const float x2 = data.elements [n++];
  75275. const float y2 = data.elements [n++];
  75276. p.quadraticTo (x1, y1, x2, y2);
  75277. }
  75278. else if (type == cubicMarker)
  75279. {
  75280. lastWasLine = false;
  75281. const float x1 = data.elements [n++];
  75282. const float y1 = data.elements [n++];
  75283. const float x2 = data.elements [n++];
  75284. const float y2 = data.elements [n++];
  75285. const float x3 = data.elements [n++];
  75286. const float y3 = data.elements [n++];
  75287. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75288. }
  75289. }
  75290. return p;
  75291. }
  75292. void Path::loadPathFromStream (InputStream& source)
  75293. {
  75294. while (! source.isExhausted())
  75295. {
  75296. switch (source.readByte())
  75297. {
  75298. case 'm':
  75299. {
  75300. const float x = source.readFloat();
  75301. const float y = source.readFloat();
  75302. startNewSubPath (x, y);
  75303. break;
  75304. }
  75305. case 'l':
  75306. {
  75307. const float x = source.readFloat();
  75308. const float y = source.readFloat();
  75309. lineTo (x, y);
  75310. break;
  75311. }
  75312. case 'q':
  75313. {
  75314. const float x1 = source.readFloat();
  75315. const float y1 = source.readFloat();
  75316. const float x2 = source.readFloat();
  75317. const float y2 = source.readFloat();
  75318. quadraticTo (x1, y1, x2, y2);
  75319. break;
  75320. }
  75321. case 'b':
  75322. {
  75323. const float x1 = source.readFloat();
  75324. const float y1 = source.readFloat();
  75325. const float x2 = source.readFloat();
  75326. const float y2 = source.readFloat();
  75327. const float x3 = source.readFloat();
  75328. const float y3 = source.readFloat();
  75329. cubicTo (x1, y1, x2, y2, x3, y3);
  75330. break;
  75331. }
  75332. case 'c':
  75333. closeSubPath();
  75334. break;
  75335. case 'n':
  75336. useNonZeroWinding = true;
  75337. break;
  75338. case 'z':
  75339. useNonZeroWinding = false;
  75340. break;
  75341. case 'e':
  75342. return; // end of path marker
  75343. default:
  75344. jassertfalse; // illegal char in the stream
  75345. break;
  75346. }
  75347. }
  75348. }
  75349. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75350. {
  75351. MemoryInputStream in (pathData, numberOfBytes, false);
  75352. loadPathFromStream (in);
  75353. }
  75354. void Path::writePathToStream (OutputStream& dest) const
  75355. {
  75356. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75357. size_t i = 0;
  75358. while (i < numElements)
  75359. {
  75360. const float type = data.elements [i++];
  75361. if (type == moveMarker)
  75362. {
  75363. dest.writeByte ('m');
  75364. dest.writeFloat (data.elements [i++]);
  75365. dest.writeFloat (data.elements [i++]);
  75366. }
  75367. else if (type == lineMarker)
  75368. {
  75369. dest.writeByte ('l');
  75370. dest.writeFloat (data.elements [i++]);
  75371. dest.writeFloat (data.elements [i++]);
  75372. }
  75373. else if (type == quadMarker)
  75374. {
  75375. dest.writeByte ('q');
  75376. dest.writeFloat (data.elements [i++]);
  75377. dest.writeFloat (data.elements [i++]);
  75378. dest.writeFloat (data.elements [i++]);
  75379. dest.writeFloat (data.elements [i++]);
  75380. }
  75381. else if (type == cubicMarker)
  75382. {
  75383. dest.writeByte ('b');
  75384. dest.writeFloat (data.elements [i++]);
  75385. dest.writeFloat (data.elements [i++]);
  75386. dest.writeFloat (data.elements [i++]);
  75387. dest.writeFloat (data.elements [i++]);
  75388. dest.writeFloat (data.elements [i++]);
  75389. dest.writeFloat (data.elements [i++]);
  75390. }
  75391. else if (type == closeSubPathMarker)
  75392. {
  75393. dest.writeByte ('c');
  75394. }
  75395. }
  75396. dest.writeByte ('e'); // marks the end-of-path
  75397. }
  75398. const String Path::toString() const
  75399. {
  75400. MemoryOutputStream s (2048);
  75401. if (! useNonZeroWinding)
  75402. s << 'a';
  75403. size_t i = 0;
  75404. float lastMarker = 0.0f;
  75405. while (i < numElements)
  75406. {
  75407. const float marker = data.elements [i++];
  75408. char markerChar = 0;
  75409. int numCoords = 0;
  75410. if (marker == moveMarker)
  75411. {
  75412. markerChar = 'm';
  75413. numCoords = 2;
  75414. }
  75415. else if (marker == lineMarker)
  75416. {
  75417. markerChar = 'l';
  75418. numCoords = 2;
  75419. }
  75420. else if (marker == quadMarker)
  75421. {
  75422. markerChar = 'q';
  75423. numCoords = 4;
  75424. }
  75425. else if (marker == cubicMarker)
  75426. {
  75427. markerChar = 'c';
  75428. numCoords = 6;
  75429. }
  75430. else
  75431. {
  75432. jassert (marker == closeSubPathMarker);
  75433. markerChar = 'z';
  75434. }
  75435. if (marker != lastMarker)
  75436. {
  75437. if (s.getDataSize() != 0)
  75438. s << ' ';
  75439. s << markerChar;
  75440. lastMarker = marker;
  75441. }
  75442. while (--numCoords >= 0 && i < numElements)
  75443. {
  75444. String coord (data.elements [i++], 3);
  75445. while (coord.endsWithChar ('0') && coord != "0")
  75446. coord = coord.dropLastCharacters (1);
  75447. if (coord.endsWithChar ('.'))
  75448. coord = coord.dropLastCharacters (1);
  75449. if (s.getDataSize() != 0)
  75450. s << ' ';
  75451. s << coord;
  75452. }
  75453. }
  75454. return s.toUTF8();
  75455. }
  75456. void Path::restoreFromString (const String& stringVersion)
  75457. {
  75458. clear();
  75459. setUsingNonZeroWinding (true);
  75460. const juce_wchar* t = stringVersion;
  75461. juce_wchar marker = 'm';
  75462. int numValues = 2;
  75463. float values [6];
  75464. for (;;)
  75465. {
  75466. const String token (PathHelpers::nextToken (t));
  75467. const juce_wchar firstChar = token[0];
  75468. int startNum = 0;
  75469. if (firstChar == 0)
  75470. break;
  75471. if (firstChar == 'm' || firstChar == 'l')
  75472. {
  75473. marker = firstChar;
  75474. numValues = 2;
  75475. }
  75476. else if (firstChar == 'q')
  75477. {
  75478. marker = firstChar;
  75479. numValues = 4;
  75480. }
  75481. else if (firstChar == 'c')
  75482. {
  75483. marker = firstChar;
  75484. numValues = 6;
  75485. }
  75486. else if (firstChar == 'z')
  75487. {
  75488. marker = firstChar;
  75489. numValues = 0;
  75490. }
  75491. else if (firstChar == 'a')
  75492. {
  75493. setUsingNonZeroWinding (false);
  75494. continue;
  75495. }
  75496. else
  75497. {
  75498. ++startNum;
  75499. values [0] = token.getFloatValue();
  75500. }
  75501. for (int i = startNum; i < numValues; ++i)
  75502. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75503. switch (marker)
  75504. {
  75505. case 'm': startNewSubPath (values[0], values[1]); break;
  75506. case 'l': lineTo (values[0], values[1]); break;
  75507. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75508. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75509. case 'z': closeSubPath(); break;
  75510. default: jassertfalse; break; // illegal string format?
  75511. }
  75512. }
  75513. }
  75514. Path::Iterator::Iterator (const Path& path_)
  75515. : path (path_),
  75516. index (0)
  75517. {
  75518. }
  75519. Path::Iterator::~Iterator()
  75520. {
  75521. }
  75522. bool Path::Iterator::next()
  75523. {
  75524. const float* const elements = path.data.elements;
  75525. if (index < path.numElements)
  75526. {
  75527. const float type = elements [index++];
  75528. if (type == moveMarker)
  75529. {
  75530. elementType = startNewSubPath;
  75531. x1 = elements [index++];
  75532. y1 = elements [index++];
  75533. }
  75534. else if (type == lineMarker)
  75535. {
  75536. elementType = lineTo;
  75537. x1 = elements [index++];
  75538. y1 = elements [index++];
  75539. }
  75540. else if (type == quadMarker)
  75541. {
  75542. elementType = quadraticTo;
  75543. x1 = elements [index++];
  75544. y1 = elements [index++];
  75545. x2 = elements [index++];
  75546. y2 = elements [index++];
  75547. }
  75548. else if (type == cubicMarker)
  75549. {
  75550. elementType = cubicTo;
  75551. x1 = elements [index++];
  75552. y1 = elements [index++];
  75553. x2 = elements [index++];
  75554. y2 = elements [index++];
  75555. x3 = elements [index++];
  75556. y3 = elements [index++];
  75557. }
  75558. else if (type == closeSubPathMarker)
  75559. {
  75560. elementType = closePath;
  75561. }
  75562. return true;
  75563. }
  75564. return false;
  75565. }
  75566. END_JUCE_NAMESPACE
  75567. /*** End of inlined file: juce_Path.cpp ***/
  75568. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75569. BEGIN_JUCE_NAMESPACE
  75570. #if JUCE_MSVC && JUCE_DEBUG
  75571. #pragma optimize ("t", on)
  75572. #endif
  75573. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75574. const AffineTransform& transform_,
  75575. float tolerence_)
  75576. : x2 (0),
  75577. y2 (0),
  75578. closesSubPath (false),
  75579. subPathIndex (-1),
  75580. path (path_),
  75581. transform (transform_),
  75582. points (path_.data.elements),
  75583. tolerence (tolerence_ * tolerence_),
  75584. subPathCloseX (0),
  75585. subPathCloseY (0),
  75586. isIdentityTransform (transform_.isIdentity()),
  75587. stackBase (32),
  75588. index (0),
  75589. stackSize (32)
  75590. {
  75591. stackPos = stackBase;
  75592. }
  75593. PathFlatteningIterator::~PathFlatteningIterator()
  75594. {
  75595. }
  75596. bool PathFlatteningIterator::next()
  75597. {
  75598. x1 = x2;
  75599. y1 = y2;
  75600. float x3 = 0;
  75601. float y3 = 0;
  75602. float x4 = 0;
  75603. float y4 = 0;
  75604. float type;
  75605. for (;;)
  75606. {
  75607. if (stackPos == stackBase)
  75608. {
  75609. if (index >= path.numElements)
  75610. {
  75611. return false;
  75612. }
  75613. else
  75614. {
  75615. type = points [index++];
  75616. if (type != Path::closeSubPathMarker)
  75617. {
  75618. x2 = points [index++];
  75619. y2 = points [index++];
  75620. if (type == Path::quadMarker)
  75621. {
  75622. x3 = points [index++];
  75623. y3 = points [index++];
  75624. if (! isIdentityTransform)
  75625. transform.transformPoints (x2, y2, x3, y3);
  75626. }
  75627. else if (type == Path::cubicMarker)
  75628. {
  75629. x3 = points [index++];
  75630. y3 = points [index++];
  75631. x4 = points [index++];
  75632. y4 = points [index++];
  75633. if (! isIdentityTransform)
  75634. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75635. }
  75636. else
  75637. {
  75638. if (! isIdentityTransform)
  75639. transform.transformPoint (x2, y2);
  75640. }
  75641. }
  75642. }
  75643. }
  75644. else
  75645. {
  75646. type = *--stackPos;
  75647. if (type != Path::closeSubPathMarker)
  75648. {
  75649. x2 = *--stackPos;
  75650. y2 = *--stackPos;
  75651. if (type == Path::quadMarker)
  75652. {
  75653. x3 = *--stackPos;
  75654. y3 = *--stackPos;
  75655. }
  75656. else if (type == Path::cubicMarker)
  75657. {
  75658. x3 = *--stackPos;
  75659. y3 = *--stackPos;
  75660. x4 = *--stackPos;
  75661. y4 = *--stackPos;
  75662. }
  75663. }
  75664. }
  75665. if (type == Path::lineMarker)
  75666. {
  75667. ++subPathIndex;
  75668. closesSubPath = (stackPos == stackBase)
  75669. && (index < path.numElements)
  75670. && (points [index] == Path::closeSubPathMarker)
  75671. && x2 == subPathCloseX
  75672. && y2 == subPathCloseY;
  75673. return true;
  75674. }
  75675. else if (type == Path::quadMarker)
  75676. {
  75677. const size_t offset = (size_t) (stackPos - stackBase);
  75678. if (offset >= stackSize - 10)
  75679. {
  75680. stackSize <<= 1;
  75681. stackBase.realloc (stackSize);
  75682. stackPos = stackBase + offset;
  75683. }
  75684. const float dx1 = x1 - x2;
  75685. const float dy1 = y1 - y2;
  75686. const float dx2 = x2 - x3;
  75687. const float dy2 = y2 - y3;
  75688. const float m1x = (x1 + x2) * 0.5f;
  75689. const float m1y = (y1 + y2) * 0.5f;
  75690. const float m2x = (x2 + x3) * 0.5f;
  75691. const float m2y = (y2 + y3) * 0.5f;
  75692. const float m3x = (m1x + m2x) * 0.5f;
  75693. const float m3y = (m1y + m2y) * 0.5f;
  75694. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75695. {
  75696. *stackPos++ = y3;
  75697. *stackPos++ = x3;
  75698. *stackPos++ = m2y;
  75699. *stackPos++ = m2x;
  75700. *stackPos++ = Path::quadMarker;
  75701. *stackPos++ = m3y;
  75702. *stackPos++ = m3x;
  75703. *stackPos++ = m1y;
  75704. *stackPos++ = m1x;
  75705. *stackPos++ = Path::quadMarker;
  75706. }
  75707. else
  75708. {
  75709. *stackPos++ = y3;
  75710. *stackPos++ = x3;
  75711. *stackPos++ = Path::lineMarker;
  75712. *stackPos++ = m3y;
  75713. *stackPos++ = m3x;
  75714. *stackPos++ = Path::lineMarker;
  75715. }
  75716. jassert (stackPos < stackBase + stackSize);
  75717. }
  75718. else if (type == Path::cubicMarker)
  75719. {
  75720. const size_t offset = (size_t) (stackPos - stackBase);
  75721. if (offset >= stackSize - 16)
  75722. {
  75723. stackSize <<= 1;
  75724. stackBase.realloc (stackSize);
  75725. stackPos = stackBase + offset;
  75726. }
  75727. const float dx1 = x1 - x2;
  75728. const float dy1 = y1 - y2;
  75729. const float dx2 = x2 - x3;
  75730. const float dy2 = y2 - y3;
  75731. const float dx3 = x3 - x4;
  75732. const float dy3 = y3 - y4;
  75733. const float m1x = (x1 + x2) * 0.5f;
  75734. const float m1y = (y1 + y2) * 0.5f;
  75735. const float m2x = (x3 + x2) * 0.5f;
  75736. const float m2y = (y3 + y2) * 0.5f;
  75737. const float m3x = (x3 + x4) * 0.5f;
  75738. const float m3y = (y3 + y4) * 0.5f;
  75739. const float m4x = (m1x + m2x) * 0.5f;
  75740. const float m4y = (m1y + m2y) * 0.5f;
  75741. const float m5x = (m3x + m2x) * 0.5f;
  75742. const float m5y = (m3y + m2y) * 0.5f;
  75743. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75744. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75745. {
  75746. *stackPos++ = y4;
  75747. *stackPos++ = x4;
  75748. *stackPos++ = m3y;
  75749. *stackPos++ = m3x;
  75750. *stackPos++ = m5y;
  75751. *stackPos++ = m5x;
  75752. *stackPos++ = Path::cubicMarker;
  75753. *stackPos++ = (m4y + m5y) * 0.5f;
  75754. *stackPos++ = (m4x + m5x) * 0.5f;
  75755. *stackPos++ = m4y;
  75756. *stackPos++ = m4x;
  75757. *stackPos++ = m1y;
  75758. *stackPos++ = m1x;
  75759. *stackPos++ = Path::cubicMarker;
  75760. }
  75761. else
  75762. {
  75763. *stackPos++ = y4;
  75764. *stackPos++ = x4;
  75765. *stackPos++ = Path::lineMarker;
  75766. *stackPos++ = m5y;
  75767. *stackPos++ = m5x;
  75768. *stackPos++ = Path::lineMarker;
  75769. *stackPos++ = m4y;
  75770. *stackPos++ = m4x;
  75771. *stackPos++ = Path::lineMarker;
  75772. }
  75773. }
  75774. else if (type == Path::closeSubPathMarker)
  75775. {
  75776. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75777. {
  75778. x1 = x2;
  75779. y1 = y2;
  75780. x2 = subPathCloseX;
  75781. y2 = subPathCloseY;
  75782. closesSubPath = true;
  75783. return true;
  75784. }
  75785. }
  75786. else
  75787. {
  75788. jassert (type == Path::moveMarker);
  75789. subPathIndex = -1;
  75790. subPathCloseX = x1 = x2;
  75791. subPathCloseY = y1 = y2;
  75792. }
  75793. }
  75794. }
  75795. #if JUCE_MSVC && JUCE_DEBUG
  75796. #pragma optimize ("", on) // resets optimisations to the project defaults
  75797. #endif
  75798. END_JUCE_NAMESPACE
  75799. /*** End of inlined file: juce_PathIterator.cpp ***/
  75800. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75801. BEGIN_JUCE_NAMESPACE
  75802. PathStrokeType::PathStrokeType (const float strokeThickness,
  75803. const JointStyle jointStyle_,
  75804. const EndCapStyle endStyle_) throw()
  75805. : thickness (strokeThickness),
  75806. jointStyle (jointStyle_),
  75807. endStyle (endStyle_)
  75808. {
  75809. }
  75810. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75811. : thickness (other.thickness),
  75812. jointStyle (other.jointStyle),
  75813. endStyle (other.endStyle)
  75814. {
  75815. }
  75816. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75817. {
  75818. thickness = other.thickness;
  75819. jointStyle = other.jointStyle;
  75820. endStyle = other.endStyle;
  75821. return *this;
  75822. }
  75823. PathStrokeType::~PathStrokeType() throw()
  75824. {
  75825. }
  75826. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75827. {
  75828. return thickness == other.thickness
  75829. && jointStyle == other.jointStyle
  75830. && endStyle == other.endStyle;
  75831. }
  75832. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75833. {
  75834. return ! operator== (other);
  75835. }
  75836. namespace PathStrokeHelpers
  75837. {
  75838. static bool lineIntersection (const float x1, const float y1,
  75839. const float x2, const float y2,
  75840. const float x3, const float y3,
  75841. const float x4, const float y4,
  75842. float& intersectionX,
  75843. float& intersectionY,
  75844. float& distanceBeyondLine1EndSquared) throw()
  75845. {
  75846. if (x2 != x3 || y2 != y3)
  75847. {
  75848. const float dx1 = x2 - x1;
  75849. const float dy1 = y2 - y1;
  75850. const float dx2 = x4 - x3;
  75851. const float dy2 = y4 - y3;
  75852. const float divisor = dx1 * dy2 - dx2 * dy1;
  75853. if (divisor == 0)
  75854. {
  75855. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75856. {
  75857. if (dy1 == 0 && dy2 != 0)
  75858. {
  75859. const float along = (y1 - y3) / dy2;
  75860. intersectionX = x3 + along * dx2;
  75861. intersectionY = y1;
  75862. distanceBeyondLine1EndSquared = intersectionX - x2;
  75863. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75864. if ((x2 > x1) == (intersectionX < x2))
  75865. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75866. return along >= 0 && along <= 1.0f;
  75867. }
  75868. else if (dy2 == 0 && dy1 != 0)
  75869. {
  75870. const float along = (y3 - y1) / dy1;
  75871. intersectionX = x1 + along * dx1;
  75872. intersectionY = y3;
  75873. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75874. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75875. if (along < 1.0f)
  75876. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75877. return along >= 0 && along <= 1.0f;
  75878. }
  75879. else if (dx1 == 0 && dx2 != 0)
  75880. {
  75881. const float along = (x1 - x3) / dx2;
  75882. intersectionX = x1;
  75883. intersectionY = y3 + along * dy2;
  75884. distanceBeyondLine1EndSquared = intersectionY - y2;
  75885. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75886. if ((y2 > y1) == (intersectionY < y2))
  75887. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75888. return along >= 0 && along <= 1.0f;
  75889. }
  75890. else if (dx2 == 0 && dx1 != 0)
  75891. {
  75892. const float along = (x3 - x1) / dx1;
  75893. intersectionX = x3;
  75894. intersectionY = y1 + along * dy1;
  75895. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75896. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75897. if (along < 1.0f)
  75898. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75899. return along >= 0 && along <= 1.0f;
  75900. }
  75901. }
  75902. intersectionX = 0.5f * (x2 + x3);
  75903. intersectionY = 0.5f * (y2 + y3);
  75904. distanceBeyondLine1EndSquared = 0.0f;
  75905. return false;
  75906. }
  75907. else
  75908. {
  75909. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75910. intersectionX = x1 + along1 * dx1;
  75911. intersectionY = y1 + along1 * dy1;
  75912. if (along1 >= 0 && along1 <= 1.0f)
  75913. {
  75914. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75915. if (along2 >= 0 && along2 <= divisor)
  75916. {
  75917. distanceBeyondLine1EndSquared = 0.0f;
  75918. return true;
  75919. }
  75920. }
  75921. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75922. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75923. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75924. if (along1 < 1.0f)
  75925. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75926. return false;
  75927. }
  75928. }
  75929. intersectionX = x2;
  75930. intersectionY = y2;
  75931. distanceBeyondLine1EndSquared = 0.0f;
  75932. return true;
  75933. }
  75934. static void addEdgeAndJoint (Path& destPath,
  75935. const PathStrokeType::JointStyle style,
  75936. const float maxMiterExtensionSquared, const float width,
  75937. const float x1, const float y1,
  75938. const float x2, const float y2,
  75939. const float x3, const float y3,
  75940. const float x4, const float y4,
  75941. const float midX, const float midY)
  75942. {
  75943. if (style == PathStrokeType::beveled
  75944. || (x3 == x4 && y3 == y4)
  75945. || (x1 == x2 && y1 == y2))
  75946. {
  75947. destPath.lineTo (x2, y2);
  75948. destPath.lineTo (x3, y3);
  75949. }
  75950. else
  75951. {
  75952. float jx, jy, distanceBeyondLine1EndSquared;
  75953. // if they intersect, use this point..
  75954. if (lineIntersection (x1, y1, x2, y2,
  75955. x3, y3, x4, y4,
  75956. jx, jy, distanceBeyondLine1EndSquared))
  75957. {
  75958. destPath.lineTo (jx, jy);
  75959. }
  75960. else
  75961. {
  75962. if (style == PathStrokeType::mitered)
  75963. {
  75964. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75965. && distanceBeyondLine1EndSquared > 0.0f)
  75966. {
  75967. destPath.lineTo (jx, jy);
  75968. }
  75969. else
  75970. {
  75971. // the end sticks out too far, so just use a blunt joint
  75972. destPath.lineTo (x2, y2);
  75973. destPath.lineTo (x3, y3);
  75974. }
  75975. }
  75976. else
  75977. {
  75978. // curved joints
  75979. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75980. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75981. const float angleIncrement = 0.1f;
  75982. destPath.lineTo (x2, y2);
  75983. if (std::abs (angle1 - angle2) > angleIncrement)
  75984. {
  75985. if (angle2 > angle1 + float_Pi
  75986. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75987. {
  75988. if (angle2 > angle1)
  75989. angle2 -= float_Pi * 2.0f;
  75990. jassert (angle1 <= angle2 + float_Pi);
  75991. angle1 -= angleIncrement;
  75992. while (angle1 > angle2)
  75993. {
  75994. destPath.lineTo (midX + width * std::sin (angle1),
  75995. midY + width * std::cos (angle1));
  75996. angle1 -= angleIncrement;
  75997. }
  75998. }
  75999. else
  76000. {
  76001. if (angle1 > angle2)
  76002. angle1 -= float_Pi * 2.0f;
  76003. jassert (angle1 >= angle2 - float_Pi);
  76004. angle1 += angleIncrement;
  76005. while (angle1 < angle2)
  76006. {
  76007. destPath.lineTo (midX + width * std::sin (angle1),
  76008. midY + width * std::cos (angle1));
  76009. angle1 += angleIncrement;
  76010. }
  76011. }
  76012. }
  76013. destPath.lineTo (x3, y3);
  76014. }
  76015. }
  76016. }
  76017. }
  76018. static void addLineEnd (Path& destPath,
  76019. const PathStrokeType::EndCapStyle style,
  76020. const float x1, const float y1,
  76021. const float x2, const float y2,
  76022. const float width)
  76023. {
  76024. if (style == PathStrokeType::butt)
  76025. {
  76026. destPath.lineTo (x2, y2);
  76027. }
  76028. else
  76029. {
  76030. float offx1, offy1, offx2, offy2;
  76031. float dx = x2 - x1;
  76032. float dy = y2 - y1;
  76033. const float len = juce_hypotf (dx, dy);
  76034. if (len == 0)
  76035. {
  76036. offx1 = offx2 = x1;
  76037. offy1 = offy2 = y1;
  76038. }
  76039. else
  76040. {
  76041. const float offset = width / len;
  76042. dx *= offset;
  76043. dy *= offset;
  76044. offx1 = x1 + dy;
  76045. offy1 = y1 - dx;
  76046. offx2 = x2 + dy;
  76047. offy2 = y2 - dx;
  76048. }
  76049. if (style == PathStrokeType::square)
  76050. {
  76051. // sqaure ends
  76052. destPath.lineTo (offx1, offy1);
  76053. destPath.lineTo (offx2, offy2);
  76054. destPath.lineTo (x2, y2);
  76055. }
  76056. else
  76057. {
  76058. // rounded ends
  76059. const float midx = (offx1 + offx2) * 0.5f;
  76060. const float midy = (offy1 + offy2) * 0.5f;
  76061. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  76062. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  76063. midx, midy);
  76064. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  76065. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  76066. x2, y2);
  76067. }
  76068. }
  76069. }
  76070. struct Arrowhead
  76071. {
  76072. float startWidth, startLength;
  76073. float endWidth, endLength;
  76074. };
  76075. static void addArrowhead (Path& destPath,
  76076. const float x1, const float y1,
  76077. const float x2, const float y2,
  76078. const float tipX, const float tipY,
  76079. const float width,
  76080. const float arrowheadWidth)
  76081. {
  76082. Line<float> line (x1, y1, x2, y2);
  76083. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  76084. destPath.lineTo (tipX, tipY);
  76085. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  76086. destPath.lineTo (x2, y2);
  76087. }
  76088. struct LineSection
  76089. {
  76090. float x1, y1, x2, y2; // original line
  76091. float lx1, ly1, lx2, ly2; // the left-hand stroke
  76092. float rx1, ry1, rx2, ry2; // the right-hand stroke
  76093. };
  76094. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  76095. {
  76096. while (amountAtEnd > 0 && subPath.size() > 0)
  76097. {
  76098. LineSection& l = subPath.getReference (subPath.size() - 1);
  76099. float dx = l.rx2 - l.rx1;
  76100. float dy = l.ry2 - l.ry1;
  76101. const float len = juce_hypotf (dx, dy);
  76102. if (len <= amountAtEnd && subPath.size() > 1)
  76103. {
  76104. LineSection& prev = subPath.getReference (subPath.size() - 2);
  76105. prev.x2 = l.x2;
  76106. prev.y2 = l.y2;
  76107. subPath.removeLast();
  76108. amountAtEnd -= len;
  76109. }
  76110. else
  76111. {
  76112. const float prop = jmin (0.9999f, amountAtEnd / len);
  76113. dx *= prop;
  76114. dy *= prop;
  76115. l.rx1 += dx;
  76116. l.ry1 += dy;
  76117. l.lx2 += dx;
  76118. l.ly2 += dy;
  76119. break;
  76120. }
  76121. }
  76122. while (amountAtStart > 0 && subPath.size() > 0)
  76123. {
  76124. LineSection& l = subPath.getReference (0);
  76125. float dx = l.rx2 - l.rx1;
  76126. float dy = l.ry2 - l.ry1;
  76127. const float len = juce_hypotf (dx, dy);
  76128. if (len <= amountAtStart && subPath.size() > 1)
  76129. {
  76130. LineSection& next = subPath.getReference (1);
  76131. next.x1 = l.x1;
  76132. next.y1 = l.y1;
  76133. subPath.remove (0);
  76134. amountAtStart -= len;
  76135. }
  76136. else
  76137. {
  76138. const float prop = jmin (0.9999f, amountAtStart / len);
  76139. dx *= prop;
  76140. dy *= prop;
  76141. l.rx2 -= dx;
  76142. l.ry2 -= dy;
  76143. l.lx1 -= dx;
  76144. l.ly1 -= dy;
  76145. break;
  76146. }
  76147. }
  76148. }
  76149. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76150. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76151. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76152. const Arrowhead* const arrowhead)
  76153. {
  76154. jassert (subPath.size() > 0);
  76155. if (arrowhead != 0)
  76156. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76157. const LineSection& firstLine = subPath.getReference (0);
  76158. float lastX1 = firstLine.lx1;
  76159. float lastY1 = firstLine.ly1;
  76160. float lastX2 = firstLine.lx2;
  76161. float lastY2 = firstLine.ly2;
  76162. if (isClosed)
  76163. {
  76164. destPath.startNewSubPath (lastX1, lastY1);
  76165. }
  76166. else
  76167. {
  76168. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76169. if (arrowhead != 0)
  76170. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76171. width, arrowhead->startWidth);
  76172. else
  76173. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76174. }
  76175. int i;
  76176. for (i = 1; i < subPath.size(); ++i)
  76177. {
  76178. const LineSection& l = subPath.getReference (i);
  76179. addEdgeAndJoint (destPath, jointStyle,
  76180. maxMiterExtensionSquared, width,
  76181. lastX1, lastY1, lastX2, lastY2,
  76182. l.lx1, l.ly1, l.lx2, l.ly2,
  76183. l.x1, l.y1);
  76184. lastX1 = l.lx1;
  76185. lastY1 = l.ly1;
  76186. lastX2 = l.lx2;
  76187. lastY2 = l.ly2;
  76188. }
  76189. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76190. if (isClosed)
  76191. {
  76192. const LineSection& l = subPath.getReference (0);
  76193. addEdgeAndJoint (destPath, jointStyle,
  76194. maxMiterExtensionSquared, width,
  76195. lastX1, lastY1, lastX2, lastY2,
  76196. l.lx1, l.ly1, l.lx2, l.ly2,
  76197. l.x1, l.y1);
  76198. destPath.closeSubPath();
  76199. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76200. }
  76201. else
  76202. {
  76203. destPath.lineTo (lastX2, lastY2);
  76204. if (arrowhead != 0)
  76205. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76206. width, arrowhead->endWidth);
  76207. else
  76208. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76209. }
  76210. lastX1 = lastLine.rx1;
  76211. lastY1 = lastLine.ry1;
  76212. lastX2 = lastLine.rx2;
  76213. lastY2 = lastLine.ry2;
  76214. for (i = subPath.size() - 1; --i >= 0;)
  76215. {
  76216. const LineSection& l = subPath.getReference (i);
  76217. addEdgeAndJoint (destPath, jointStyle,
  76218. maxMiterExtensionSquared, width,
  76219. lastX1, lastY1, lastX2, lastY2,
  76220. l.rx1, l.ry1, l.rx2, l.ry2,
  76221. l.x2, l.y2);
  76222. lastX1 = l.rx1;
  76223. lastY1 = l.ry1;
  76224. lastX2 = l.rx2;
  76225. lastY2 = l.ry2;
  76226. }
  76227. if (isClosed)
  76228. {
  76229. addEdgeAndJoint (destPath, jointStyle,
  76230. maxMiterExtensionSquared, width,
  76231. lastX1, lastY1, lastX2, lastY2,
  76232. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76233. lastLine.x2, lastLine.y2);
  76234. }
  76235. else
  76236. {
  76237. // do the last line
  76238. destPath.lineTo (lastX2, lastY2);
  76239. }
  76240. destPath.closeSubPath();
  76241. }
  76242. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76243. const PathStrokeType::EndCapStyle endStyle,
  76244. Path& destPath, const Path& source,
  76245. const AffineTransform& transform,
  76246. const float extraAccuracy, const Arrowhead* const arrowhead)
  76247. {
  76248. if (thickness <= 0)
  76249. {
  76250. destPath.clear();
  76251. return;
  76252. }
  76253. const Path* sourcePath = &source;
  76254. Path temp;
  76255. if (sourcePath == &destPath)
  76256. {
  76257. destPath.swapWithPath (temp);
  76258. sourcePath = &temp;
  76259. }
  76260. else
  76261. {
  76262. destPath.clear();
  76263. }
  76264. destPath.setUsingNonZeroWinding (true);
  76265. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76266. const float width = 0.5f * thickness;
  76267. // Iterate the path, creating a list of the
  76268. // left/right-hand lines along either side of it...
  76269. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76270. Array <LineSection> subPath;
  76271. subPath.ensureStorageAllocated (512);
  76272. LineSection l;
  76273. l.x1 = 0;
  76274. l.y1 = 0;
  76275. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76276. while (it.next())
  76277. {
  76278. if (it.subPathIndex == 0)
  76279. {
  76280. if (subPath.size() > 0)
  76281. {
  76282. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76283. subPath.clearQuick();
  76284. }
  76285. l.x1 = it.x1;
  76286. l.y1 = it.y1;
  76287. }
  76288. l.x2 = it.x2;
  76289. l.y2 = it.y2;
  76290. float dx = l.x2 - l.x1;
  76291. float dy = l.y2 - l.y1;
  76292. const float hypotSquared = dx*dx + dy*dy;
  76293. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76294. {
  76295. const float len = std::sqrt (hypotSquared);
  76296. if (len == 0)
  76297. {
  76298. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76299. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76300. }
  76301. else
  76302. {
  76303. const float offset = width / len;
  76304. dx *= offset;
  76305. dy *= offset;
  76306. l.rx2 = l.x1 - dy;
  76307. l.ry2 = l.y1 + dx;
  76308. l.lx1 = l.x1 + dy;
  76309. l.ly1 = l.y1 - dx;
  76310. l.lx2 = l.x2 + dy;
  76311. l.ly2 = l.y2 - dx;
  76312. l.rx1 = l.x2 - dy;
  76313. l.ry1 = l.y2 + dx;
  76314. }
  76315. subPath.add (l);
  76316. if (it.closesSubPath)
  76317. {
  76318. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76319. subPath.clearQuick();
  76320. }
  76321. else
  76322. {
  76323. l.x1 = it.x2;
  76324. l.y1 = it.y2;
  76325. }
  76326. }
  76327. }
  76328. if (subPath.size() > 0)
  76329. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76330. }
  76331. }
  76332. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76333. const AffineTransform& transform, const float extraAccuracy) const
  76334. {
  76335. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76336. transform, extraAccuracy, 0);
  76337. }
  76338. void PathStrokeType::createDashedStroke (Path& destPath,
  76339. const Path& sourcePath,
  76340. const float* dashLengths,
  76341. int numDashLengths,
  76342. const AffineTransform& transform,
  76343. const float extraAccuracy) const
  76344. {
  76345. if (thickness <= 0)
  76346. return;
  76347. // this should really be an even number..
  76348. jassert ((numDashLengths & 1) == 0);
  76349. Path newDestPath;
  76350. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76351. bool first = true;
  76352. int dashNum = 0;
  76353. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76354. float dx = 0.0f, dy = 0.0f;
  76355. for (;;)
  76356. {
  76357. const bool isSolid = ((dashNum & 1) == 0);
  76358. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76359. jassert (dashLen > 0); // must be a positive increment!
  76360. if (dashLen <= 0)
  76361. break;
  76362. pos += dashLen;
  76363. while (pos > lineEndPos)
  76364. {
  76365. if (! it.next())
  76366. {
  76367. if (isSolid && ! first)
  76368. newDestPath.lineTo (it.x2, it.y2);
  76369. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76370. return;
  76371. }
  76372. if (isSolid && ! first)
  76373. newDestPath.lineTo (it.x1, it.y1);
  76374. else
  76375. newDestPath.startNewSubPath (it.x1, it.y1);
  76376. dx = it.x2 - it.x1;
  76377. dy = it.y2 - it.y1;
  76378. lineLen = juce_hypotf (dx, dy);
  76379. lineEndPos += lineLen;
  76380. first = it.closesSubPath;
  76381. }
  76382. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76383. if (isSolid)
  76384. newDestPath.lineTo (it.x1 + dx * alpha,
  76385. it.y1 + dy * alpha);
  76386. else
  76387. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76388. it.y1 + dy * alpha);
  76389. }
  76390. }
  76391. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76392. const Path& sourcePath,
  76393. const float arrowheadStartWidth, const float arrowheadStartLength,
  76394. const float arrowheadEndWidth, const float arrowheadEndLength,
  76395. const AffineTransform& transform,
  76396. const float extraAccuracy) const
  76397. {
  76398. PathStrokeHelpers::Arrowhead head;
  76399. head.startWidth = arrowheadStartWidth;
  76400. head.startLength = arrowheadStartLength;
  76401. head.endWidth = arrowheadEndWidth;
  76402. head.endLength = arrowheadEndLength;
  76403. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76404. destPath, sourcePath, transform, extraAccuracy, &head);
  76405. }
  76406. END_JUCE_NAMESPACE
  76407. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76408. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76409. BEGIN_JUCE_NAMESPACE
  76410. PositionedRectangle::PositionedRectangle() throw()
  76411. : x (0.0),
  76412. y (0.0),
  76413. w (0.0),
  76414. h (0.0),
  76415. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76416. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76417. wMode (absoluteSize),
  76418. hMode (absoluteSize)
  76419. {
  76420. }
  76421. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76422. : x (other.x),
  76423. y (other.y),
  76424. w (other.w),
  76425. h (other.h),
  76426. xMode (other.xMode),
  76427. yMode (other.yMode),
  76428. wMode (other.wMode),
  76429. hMode (other.hMode)
  76430. {
  76431. }
  76432. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76433. {
  76434. x = other.x;
  76435. y = other.y;
  76436. w = other.w;
  76437. h = other.h;
  76438. xMode = other.xMode;
  76439. yMode = other.yMode;
  76440. wMode = other.wMode;
  76441. hMode = other.hMode;
  76442. return *this;
  76443. }
  76444. PositionedRectangle::~PositionedRectangle() throw()
  76445. {
  76446. }
  76447. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76448. {
  76449. return x == other.x
  76450. && y == other.y
  76451. && w == other.w
  76452. && h == other.h
  76453. && xMode == other.xMode
  76454. && yMode == other.yMode
  76455. && wMode == other.wMode
  76456. && hMode == other.hMode;
  76457. }
  76458. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76459. {
  76460. return ! operator== (other);
  76461. }
  76462. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76463. {
  76464. StringArray tokens;
  76465. tokens.addTokens (stringVersion, false);
  76466. decodePosString (tokens [0], xMode, x);
  76467. decodePosString (tokens [1], yMode, y);
  76468. decodeSizeString (tokens [2], wMode, w);
  76469. decodeSizeString (tokens [3], hMode, h);
  76470. }
  76471. const String PositionedRectangle::toString() const throw()
  76472. {
  76473. String s;
  76474. s.preallocateStorage (12);
  76475. addPosDescription (s, xMode, x);
  76476. s << ' ';
  76477. addPosDescription (s, yMode, y);
  76478. s << ' ';
  76479. addSizeDescription (s, wMode, w);
  76480. s << ' ';
  76481. addSizeDescription (s, hMode, h);
  76482. return s;
  76483. }
  76484. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76485. {
  76486. jassert (! target.isEmpty());
  76487. double x_, y_, w_, h_;
  76488. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76489. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76490. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76491. roundToInt (w_), roundToInt (h_));
  76492. }
  76493. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76494. double& x_, double& y_,
  76495. double& w_, double& h_) const throw()
  76496. {
  76497. jassert (! target.isEmpty());
  76498. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76499. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76500. }
  76501. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76502. {
  76503. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76504. }
  76505. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76506. const Rectangle<int>& target) throw()
  76507. {
  76508. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76509. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76510. }
  76511. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76512. const double newW, const double newH,
  76513. const Rectangle<int>& target) throw()
  76514. {
  76515. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76516. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76517. }
  76518. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76519. {
  76520. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76521. updateFrom (comp.getBounds(), Rectangle<int>());
  76522. else
  76523. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76524. }
  76525. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76526. {
  76527. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76528. }
  76529. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76530. {
  76531. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76532. | absoluteFromParentBottomRight
  76533. | absoluteFromParentCentre
  76534. | proportionOfParentSize));
  76535. }
  76536. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76537. {
  76538. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76539. }
  76540. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76541. {
  76542. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76543. | absoluteFromParentBottomRight
  76544. | absoluteFromParentCentre
  76545. | proportionOfParentSize));
  76546. }
  76547. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76548. {
  76549. return (SizeMode) wMode;
  76550. }
  76551. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76552. {
  76553. return (SizeMode) hMode;
  76554. }
  76555. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76556. const PositionMode xMode_,
  76557. const AnchorPoint yAnchor,
  76558. const PositionMode yMode_,
  76559. const SizeMode widthMode,
  76560. const SizeMode heightMode,
  76561. const Rectangle<int>& target) throw()
  76562. {
  76563. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76564. {
  76565. double tx, tw;
  76566. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76567. xMode = (uint8) (xAnchor | xMode_);
  76568. wMode = (uint8) widthMode;
  76569. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76570. }
  76571. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76572. {
  76573. double ty, th;
  76574. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76575. yMode = (uint8) (yAnchor | yMode_);
  76576. hMode = (uint8) heightMode;
  76577. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76578. }
  76579. }
  76580. bool PositionedRectangle::isPositionAbsolute() const throw()
  76581. {
  76582. return xMode == absoluteFromParentTopLeft
  76583. && yMode == absoluteFromParentTopLeft
  76584. && wMode == absoluteSize
  76585. && hMode == absoluteSize;
  76586. }
  76587. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76588. {
  76589. if ((mode & proportionOfParentSize) != 0)
  76590. {
  76591. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76592. }
  76593. else
  76594. {
  76595. s << (roundToInt (value * 100.0) / 100.0);
  76596. if ((mode & absoluteFromParentBottomRight) != 0)
  76597. s << 'R';
  76598. else if ((mode & absoluteFromParentCentre) != 0)
  76599. s << 'C';
  76600. }
  76601. if ((mode & anchorAtRightOrBottom) != 0)
  76602. s << 'r';
  76603. else if ((mode & anchorAtCentre) != 0)
  76604. s << 'c';
  76605. }
  76606. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76607. {
  76608. if (mode == proportionalSize)
  76609. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76610. else if (mode == parentSizeMinusAbsolute)
  76611. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76612. else
  76613. s << (roundToInt (value * 100.0) / 100.0);
  76614. }
  76615. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76616. {
  76617. if (s.containsChar ('r'))
  76618. mode = anchorAtRightOrBottom;
  76619. else if (s.containsChar ('c'))
  76620. mode = anchorAtCentre;
  76621. else
  76622. mode = anchorAtLeftOrTop;
  76623. if (s.containsChar ('%'))
  76624. {
  76625. mode |= proportionOfParentSize;
  76626. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76627. }
  76628. else
  76629. {
  76630. if (s.containsChar ('R'))
  76631. mode |= absoluteFromParentBottomRight;
  76632. else if (s.containsChar ('C'))
  76633. mode |= absoluteFromParentCentre;
  76634. else
  76635. mode |= absoluteFromParentTopLeft;
  76636. value = s.removeCharacters ("rcRC").getDoubleValue();
  76637. }
  76638. }
  76639. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76640. {
  76641. if (s.containsChar ('%'))
  76642. {
  76643. mode = proportionalSize;
  76644. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76645. }
  76646. else if (s.containsChar ('M'))
  76647. {
  76648. mode = parentSizeMinusAbsolute;
  76649. value = s.getDoubleValue();
  76650. }
  76651. else
  76652. {
  76653. mode = absoluteSize;
  76654. value = s.getDoubleValue();
  76655. }
  76656. }
  76657. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76658. const double x_, const double w_,
  76659. const uint8 xMode_, const uint8 wMode_,
  76660. const int parentPos,
  76661. const int parentSize) const throw()
  76662. {
  76663. if (wMode_ == proportionalSize)
  76664. wOut = roundToInt (w_ * parentSize);
  76665. else if (wMode_ == parentSizeMinusAbsolute)
  76666. wOut = jmax (0, parentSize - roundToInt (w_));
  76667. else
  76668. wOut = roundToInt (w_);
  76669. if ((xMode_ & proportionOfParentSize) != 0)
  76670. xOut = parentPos + x_ * parentSize;
  76671. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76672. xOut = (parentPos + parentSize) - x_;
  76673. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76674. xOut = x_ + (parentPos + parentSize / 2);
  76675. else
  76676. xOut = x_ + parentPos;
  76677. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76678. xOut -= wOut;
  76679. else if ((xMode_ & anchorAtCentre) != 0)
  76680. xOut -= wOut / 2;
  76681. }
  76682. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76683. double x_, const double w_,
  76684. const uint8 xMode_, const uint8 wMode_,
  76685. const int parentPos,
  76686. const int parentSize) const throw()
  76687. {
  76688. if (wMode_ == proportionalSize)
  76689. {
  76690. if (parentSize > 0)
  76691. wOut = w_ / parentSize;
  76692. }
  76693. else if (wMode_ == parentSizeMinusAbsolute)
  76694. wOut = parentSize - w_;
  76695. else
  76696. wOut = w_;
  76697. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76698. x_ += w_;
  76699. else if ((xMode_ & anchorAtCentre) != 0)
  76700. x_ += w_ / 2;
  76701. if ((xMode_ & proportionOfParentSize) != 0)
  76702. {
  76703. if (parentSize > 0)
  76704. xOut = (x_ - parentPos) / parentSize;
  76705. }
  76706. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76707. xOut = (parentPos + parentSize) - x_;
  76708. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76709. xOut = x_ - (parentPos + parentSize / 2);
  76710. else
  76711. xOut = x_ - parentPos;
  76712. }
  76713. END_JUCE_NAMESPACE
  76714. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76715. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76716. BEGIN_JUCE_NAMESPACE
  76717. RectangleList::RectangleList() throw()
  76718. {
  76719. }
  76720. RectangleList::RectangleList (const Rectangle<int>& rect)
  76721. {
  76722. if (! rect.isEmpty())
  76723. rects.add (rect);
  76724. }
  76725. RectangleList::RectangleList (const RectangleList& other)
  76726. : rects (other.rects)
  76727. {
  76728. }
  76729. RectangleList& RectangleList::operator= (const RectangleList& other)
  76730. {
  76731. rects = other.rects;
  76732. return *this;
  76733. }
  76734. RectangleList::~RectangleList()
  76735. {
  76736. }
  76737. void RectangleList::clear()
  76738. {
  76739. rects.clearQuick();
  76740. }
  76741. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76742. {
  76743. if (((unsigned int) index) < (unsigned int) rects.size())
  76744. return rects.getReference (index);
  76745. return Rectangle<int>();
  76746. }
  76747. bool RectangleList::isEmpty() const throw()
  76748. {
  76749. return rects.size() == 0;
  76750. }
  76751. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76752. : current (0),
  76753. owner (list),
  76754. index (list.rects.size())
  76755. {
  76756. }
  76757. RectangleList::Iterator::~Iterator()
  76758. {
  76759. }
  76760. bool RectangleList::Iterator::next() throw()
  76761. {
  76762. if (--index >= 0)
  76763. {
  76764. current = & (owner.rects.getReference (index));
  76765. return true;
  76766. }
  76767. return false;
  76768. }
  76769. void RectangleList::add (const Rectangle<int>& rect)
  76770. {
  76771. if (! rect.isEmpty())
  76772. {
  76773. if (rects.size() == 0)
  76774. {
  76775. rects.add (rect);
  76776. }
  76777. else
  76778. {
  76779. bool anyOverlaps = false;
  76780. int i;
  76781. for (i = rects.size(); --i >= 0;)
  76782. {
  76783. Rectangle<int>& ourRect = rects.getReference (i);
  76784. if (rect.intersects (ourRect))
  76785. {
  76786. if (rect.contains (ourRect))
  76787. rects.remove (i);
  76788. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76789. anyOverlaps = true;
  76790. }
  76791. }
  76792. if (anyOverlaps && rects.size() > 0)
  76793. {
  76794. RectangleList r (rect);
  76795. for (i = rects.size(); --i >= 0;)
  76796. {
  76797. const Rectangle<int>& ourRect = rects.getReference (i);
  76798. if (rect.intersects (ourRect))
  76799. {
  76800. r.subtract (ourRect);
  76801. if (r.rects.size() == 0)
  76802. return;
  76803. }
  76804. }
  76805. for (i = r.getNumRectangles(); --i >= 0;)
  76806. rects.add (r.rects.getReference (i));
  76807. }
  76808. else
  76809. {
  76810. rects.add (rect);
  76811. }
  76812. }
  76813. }
  76814. }
  76815. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76816. {
  76817. if (! rect.isEmpty())
  76818. rects.add (rect);
  76819. }
  76820. void RectangleList::add (const int x, const int y, const int w, const int h)
  76821. {
  76822. if (rects.size() == 0)
  76823. {
  76824. if (w > 0 && h > 0)
  76825. rects.add (Rectangle<int> (x, y, w, h));
  76826. }
  76827. else
  76828. {
  76829. add (Rectangle<int> (x, y, w, h));
  76830. }
  76831. }
  76832. void RectangleList::add (const RectangleList& other)
  76833. {
  76834. for (int i = 0; i < other.rects.size(); ++i)
  76835. add (other.rects.getReference (i));
  76836. }
  76837. void RectangleList::subtract (const Rectangle<int>& rect)
  76838. {
  76839. const int originalNumRects = rects.size();
  76840. if (originalNumRects > 0)
  76841. {
  76842. const int x1 = rect.x;
  76843. const int y1 = rect.y;
  76844. const int x2 = x1 + rect.w;
  76845. const int y2 = y1 + rect.h;
  76846. for (int i = getNumRectangles(); --i >= 0;)
  76847. {
  76848. Rectangle<int>& r = rects.getReference (i);
  76849. const int rx1 = r.x;
  76850. const int ry1 = r.y;
  76851. const int rx2 = rx1 + r.w;
  76852. const int ry2 = ry1 + r.h;
  76853. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76854. {
  76855. if (x1 > rx1 && x1 < rx2)
  76856. {
  76857. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76858. {
  76859. r.w = x1 - rx1;
  76860. }
  76861. else
  76862. {
  76863. r.x = x1;
  76864. r.w = rx2 - x1;
  76865. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76866. i += 2;
  76867. }
  76868. }
  76869. else if (x2 > rx1 && x2 < rx2)
  76870. {
  76871. r.x = x2;
  76872. r.w = rx2 - x2;
  76873. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76874. {
  76875. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76876. i += 2;
  76877. }
  76878. }
  76879. else if (y1 > ry1 && y1 < ry2)
  76880. {
  76881. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76882. {
  76883. r.h = y1 - ry1;
  76884. }
  76885. else
  76886. {
  76887. r.y = y1;
  76888. r.h = ry2 - y1;
  76889. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76890. i += 2;
  76891. }
  76892. }
  76893. else if (y2 > ry1 && y2 < ry2)
  76894. {
  76895. r.y = y2;
  76896. r.h = ry2 - y2;
  76897. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76898. {
  76899. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76900. i += 2;
  76901. }
  76902. }
  76903. else
  76904. {
  76905. rects.remove (i);
  76906. }
  76907. }
  76908. }
  76909. }
  76910. }
  76911. bool RectangleList::subtract (const RectangleList& otherList)
  76912. {
  76913. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76914. subtract (otherList.rects.getReference (i));
  76915. return rects.size() > 0;
  76916. }
  76917. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76918. {
  76919. bool notEmpty = false;
  76920. if (rect.isEmpty())
  76921. {
  76922. clear();
  76923. }
  76924. else
  76925. {
  76926. for (int i = rects.size(); --i >= 0;)
  76927. {
  76928. Rectangle<int>& r = rects.getReference (i);
  76929. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76930. rects.remove (i);
  76931. else
  76932. notEmpty = true;
  76933. }
  76934. }
  76935. return notEmpty;
  76936. }
  76937. bool RectangleList::clipTo (const RectangleList& other)
  76938. {
  76939. if (rects.size() == 0)
  76940. return false;
  76941. RectangleList result;
  76942. for (int j = 0; j < rects.size(); ++j)
  76943. {
  76944. const Rectangle<int>& rect = rects.getReference (j);
  76945. for (int i = other.rects.size(); --i >= 0;)
  76946. {
  76947. Rectangle<int> r (other.rects.getReference (i));
  76948. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76949. result.rects.add (r);
  76950. }
  76951. }
  76952. swapWith (result);
  76953. return ! isEmpty();
  76954. }
  76955. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76956. {
  76957. destRegion.clear();
  76958. if (! rect.isEmpty())
  76959. {
  76960. for (int i = rects.size(); --i >= 0;)
  76961. {
  76962. Rectangle<int> r (rects.getReference (i));
  76963. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76964. destRegion.rects.add (r);
  76965. }
  76966. }
  76967. return destRegion.rects.size() > 0;
  76968. }
  76969. void RectangleList::swapWith (RectangleList& otherList) throw()
  76970. {
  76971. rects.swapWithArray (otherList.rects);
  76972. }
  76973. void RectangleList::consolidate()
  76974. {
  76975. int i;
  76976. for (i = 0; i < getNumRectangles() - 1; ++i)
  76977. {
  76978. Rectangle<int>& r = rects.getReference (i);
  76979. const int rx1 = r.x;
  76980. const int ry1 = r.y;
  76981. const int rx2 = rx1 + r.w;
  76982. const int ry2 = ry1 + r.h;
  76983. for (int j = rects.size(); --j > i;)
  76984. {
  76985. Rectangle<int>& r2 = rects.getReference (j);
  76986. const int jrx1 = r2.x;
  76987. const int jry1 = r2.y;
  76988. const int jrx2 = jrx1 + r2.w;
  76989. const int jry2 = jry1 + r2.h;
  76990. // if the vertical edges of any blocks are touching and their horizontals don't
  76991. // line up, split them horizontally..
  76992. if (jrx1 == rx2 || jrx2 == rx1)
  76993. {
  76994. if (jry1 > ry1 && jry1 < ry2)
  76995. {
  76996. r.h = jry1 - ry1;
  76997. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76998. i = -1;
  76999. break;
  77000. }
  77001. if (jry2 > ry1 && jry2 < ry2)
  77002. {
  77003. r.h = jry2 - ry1;
  77004. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  77005. i = -1;
  77006. break;
  77007. }
  77008. else if (ry1 > jry1 && ry1 < jry2)
  77009. {
  77010. r2.h = ry1 - jry1;
  77011. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  77012. i = -1;
  77013. break;
  77014. }
  77015. else if (ry2 > jry1 && ry2 < jry2)
  77016. {
  77017. r2.h = ry2 - jry1;
  77018. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  77019. i = -1;
  77020. break;
  77021. }
  77022. }
  77023. }
  77024. }
  77025. for (i = 0; i < rects.size() - 1; ++i)
  77026. {
  77027. Rectangle<int>& r = rects.getReference (i);
  77028. for (int j = rects.size(); --j > i;)
  77029. {
  77030. if (r.enlargeIfAdjacent (rects.getReference (j)))
  77031. {
  77032. rects.remove (j);
  77033. i = -1;
  77034. break;
  77035. }
  77036. }
  77037. }
  77038. }
  77039. bool RectangleList::containsPoint (const int x, const int y) const throw()
  77040. {
  77041. for (int i = getNumRectangles(); --i >= 0;)
  77042. if (rects.getReference (i).contains (x, y))
  77043. return true;
  77044. return false;
  77045. }
  77046. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  77047. {
  77048. if (rects.size() > 1)
  77049. {
  77050. RectangleList r (rectangleToCheck);
  77051. for (int i = rects.size(); --i >= 0;)
  77052. {
  77053. r.subtract (rects.getReference (i));
  77054. if (r.rects.size() == 0)
  77055. return true;
  77056. }
  77057. }
  77058. else if (rects.size() > 0)
  77059. {
  77060. return rects.getReference (0).contains (rectangleToCheck);
  77061. }
  77062. return false;
  77063. }
  77064. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  77065. {
  77066. for (int i = rects.size(); --i >= 0;)
  77067. if (rects.getReference (i).intersects (rectangleToCheck))
  77068. return true;
  77069. return false;
  77070. }
  77071. bool RectangleList::intersects (const RectangleList& other) const throw()
  77072. {
  77073. for (int i = rects.size(); --i >= 0;)
  77074. if (other.intersectsRectangle (rects.getReference (i)))
  77075. return true;
  77076. return false;
  77077. }
  77078. const Rectangle<int> RectangleList::getBounds() const throw()
  77079. {
  77080. if (rects.size() <= 1)
  77081. {
  77082. if (rects.size() == 0)
  77083. return Rectangle<int>();
  77084. else
  77085. return rects.getReference (0);
  77086. }
  77087. else
  77088. {
  77089. const Rectangle<int>& r = rects.getReference (0);
  77090. int minX = r.x;
  77091. int minY = r.y;
  77092. int maxX = minX + r.w;
  77093. int maxY = minY + r.h;
  77094. for (int i = rects.size(); --i > 0;)
  77095. {
  77096. const Rectangle<int>& r2 = rects.getReference (i);
  77097. minX = jmin (minX, r2.x);
  77098. minY = jmin (minY, r2.y);
  77099. maxX = jmax (maxX, r2.getRight());
  77100. maxY = jmax (maxY, r2.getBottom());
  77101. }
  77102. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  77103. }
  77104. }
  77105. void RectangleList::offsetAll (const int dx, const int dy) throw()
  77106. {
  77107. for (int i = rects.size(); --i >= 0;)
  77108. {
  77109. Rectangle<int>& r = rects.getReference (i);
  77110. r.x += dx;
  77111. r.y += dy;
  77112. }
  77113. }
  77114. const Path RectangleList::toPath() const
  77115. {
  77116. Path p;
  77117. for (int i = rects.size(); --i >= 0;)
  77118. {
  77119. const Rectangle<int>& r = rects.getReference (i);
  77120. p.addRectangle ((float) r.x,
  77121. (float) r.y,
  77122. (float) r.w,
  77123. (float) r.h);
  77124. }
  77125. return p;
  77126. }
  77127. END_JUCE_NAMESPACE
  77128. /*** End of inlined file: juce_RectangleList.cpp ***/
  77129. /*** Start of inlined file: juce_Image.cpp ***/
  77130. BEGIN_JUCE_NAMESPACE
  77131. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  77132. : format (format_), width (width_), height (height_)
  77133. {
  77134. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  77135. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  77136. }
  77137. Image::SharedImage::~SharedImage()
  77138. {
  77139. }
  77140. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  77141. {
  77142. return imageData + lineStride * y + pixelStride * x;
  77143. }
  77144. class SoftwareSharedImage : public Image::SharedImage
  77145. {
  77146. public:
  77147. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  77148. : Image::SharedImage (format_, width_, height_)
  77149. {
  77150. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  77151. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  77152. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  77153. imageData = imageDataAllocated;
  77154. }
  77155. ~SoftwareSharedImage()
  77156. {
  77157. }
  77158. Image::ImageType getType() const
  77159. {
  77160. return Image::SoftwareImage;
  77161. }
  77162. LowLevelGraphicsContext* createLowLevelContext()
  77163. {
  77164. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  77165. }
  77166. SharedImage* clone()
  77167. {
  77168. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  77169. memcpy (s->imageData, imageData, lineStride * height);
  77170. return s;
  77171. }
  77172. private:
  77173. HeapBlock<uint8> imageDataAllocated;
  77174. };
  77175. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  77176. {
  77177. return new SoftwareSharedImage (format, width, height, clearImage);
  77178. }
  77179. class SubsectionSharedImage : public Image::SharedImage
  77180. {
  77181. public:
  77182. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77183. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77184. image (image_), area (area_)
  77185. {
  77186. pixelStride = image_->getPixelStride();
  77187. lineStride = image_->getLineStride();
  77188. imageData = image_->getPixelData (area_.getX(), area_.getY());
  77189. }
  77190. ~SubsectionSharedImage() {}
  77191. Image::ImageType getType() const
  77192. {
  77193. return Image::SoftwareImage;
  77194. }
  77195. LowLevelGraphicsContext* createLowLevelContext()
  77196. {
  77197. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77198. g->clipToRectangle (area);
  77199. g->setOrigin (area.getX(), area.getY());
  77200. return g;
  77201. }
  77202. SharedImage* clone()
  77203. {
  77204. return new SubsectionSharedImage (image->clone(), area);
  77205. }
  77206. private:
  77207. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77208. const Rectangle<int> area;
  77209. SubsectionSharedImage (const SubsectionSharedImage&);
  77210. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  77211. };
  77212. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77213. {
  77214. if (area.contains (getBounds()))
  77215. return *this;
  77216. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77217. if (validArea.isEmpty())
  77218. return Image::null;
  77219. return Image (new SubsectionSharedImage (image, validArea));
  77220. }
  77221. Image::Image()
  77222. {
  77223. }
  77224. Image::Image (SharedImage* const instance)
  77225. : image (instance)
  77226. {
  77227. }
  77228. Image::Image (const PixelFormat format,
  77229. const int width, const int height,
  77230. const bool clearImage, const ImageType type)
  77231. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77232. : new SoftwareSharedImage (format, width, height, clearImage))
  77233. {
  77234. }
  77235. Image::Image (const Image& other)
  77236. : image (other.image)
  77237. {
  77238. }
  77239. Image& Image::operator= (const Image& other)
  77240. {
  77241. image = other.image;
  77242. return *this;
  77243. }
  77244. Image::~Image()
  77245. {
  77246. }
  77247. const Image Image::null;
  77248. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77249. {
  77250. return image == 0 ? 0 : image->createLowLevelContext();
  77251. }
  77252. void Image::duplicateIfShared()
  77253. {
  77254. if (image != 0 && image->getReferenceCount() > 1)
  77255. image = image->clone();
  77256. }
  77257. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77258. {
  77259. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77260. return *this;
  77261. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77262. Graphics g (newImage);
  77263. g.setImageResamplingQuality (quality);
  77264. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77265. return newImage;
  77266. }
  77267. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77268. {
  77269. if (image == 0 || newFormat == image->format)
  77270. return *this;
  77271. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77272. if (newFormat == SingleChannel)
  77273. {
  77274. if (! hasAlphaChannel())
  77275. {
  77276. newImage.clear (getBounds(), Colours::black);
  77277. }
  77278. else
  77279. {
  77280. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77281. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77282. for (int y = 0; y < image->height; ++y)
  77283. {
  77284. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77285. uint8* dst = destData.getLinePointer (y);
  77286. for (int x = image->width; --x >= 0;)
  77287. {
  77288. *dst++ = src->getAlpha();
  77289. ++src;
  77290. }
  77291. }
  77292. }
  77293. }
  77294. else
  77295. {
  77296. if (hasAlphaChannel())
  77297. newImage.clear (getBounds());
  77298. Graphics g (newImage);
  77299. g.drawImageAt (*this, 0, 0);
  77300. }
  77301. return newImage;
  77302. }
  77303. const var Image::getTag() const
  77304. {
  77305. return image == 0 ? var::null : image->userTag;
  77306. }
  77307. void Image::setTag (const var& newTag)
  77308. {
  77309. if (image != 0)
  77310. image->userTag = newTag;
  77311. }
  77312. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77313. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77314. pixelFormat (image.getFormat()),
  77315. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77316. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77317. width (w),
  77318. height (h)
  77319. {
  77320. jassert (data != 0);
  77321. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77322. }
  77323. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77324. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77325. pixelFormat (image.getFormat()),
  77326. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77327. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77328. width (w),
  77329. height (h)
  77330. {
  77331. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77332. }
  77333. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77334. : data (image.image == 0 ? 0 : image.image->imageData),
  77335. pixelFormat (image.getFormat()),
  77336. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77337. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77338. width (image.getWidth()),
  77339. height (image.getHeight())
  77340. {
  77341. }
  77342. Image::BitmapData::~BitmapData()
  77343. {
  77344. }
  77345. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77346. {
  77347. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77348. const uint8* const pixel = getPixelPointer (x, y);
  77349. switch (pixelFormat)
  77350. {
  77351. case Image::ARGB:
  77352. {
  77353. PixelARGB p (*(const PixelARGB*) pixel);
  77354. p.unpremultiply();
  77355. return Colour (p.getARGB());
  77356. }
  77357. case Image::RGB:
  77358. return Colour (((const PixelRGB*) pixel)->getARGB());
  77359. case Image::SingleChannel:
  77360. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77361. default:
  77362. jassertfalse;
  77363. break;
  77364. }
  77365. return Colour();
  77366. }
  77367. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77368. {
  77369. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77370. uint8* const pixel = getPixelPointer (x, y);
  77371. const PixelARGB col (colour.getPixelARGB());
  77372. switch (pixelFormat)
  77373. {
  77374. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77375. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77376. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77377. default: jassertfalse; break;
  77378. }
  77379. }
  77380. void Image::setPixelData (int x, int y, int w, int h,
  77381. const uint8* const sourcePixelData, const int sourceLineStride)
  77382. {
  77383. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77384. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77385. {
  77386. const BitmapData dest (*this, x, y, w, h, true);
  77387. for (int i = 0; i < h; ++i)
  77388. {
  77389. memcpy (dest.getLinePointer(i),
  77390. sourcePixelData + sourceLineStride * i,
  77391. w * dest.pixelStride);
  77392. }
  77393. }
  77394. }
  77395. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77396. {
  77397. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77398. if (! clipped.isEmpty())
  77399. {
  77400. const PixelARGB col (colourToClearTo.getPixelARGB());
  77401. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77402. uint8* dest = destData.data;
  77403. int dh = clipped.getHeight();
  77404. while (--dh >= 0)
  77405. {
  77406. uint8* line = dest;
  77407. dest += destData.lineStride;
  77408. if (isARGB())
  77409. {
  77410. for (int x = clipped.getWidth(); --x >= 0;)
  77411. {
  77412. ((PixelARGB*) line)->set (col);
  77413. line += destData.pixelStride;
  77414. }
  77415. }
  77416. else if (isRGB())
  77417. {
  77418. for (int x = clipped.getWidth(); --x >= 0;)
  77419. {
  77420. ((PixelRGB*) line)->set (col);
  77421. line += destData.pixelStride;
  77422. }
  77423. }
  77424. else
  77425. {
  77426. for (int x = clipped.getWidth(); --x >= 0;)
  77427. {
  77428. *line = col.getAlpha();
  77429. line += destData.pixelStride;
  77430. }
  77431. }
  77432. }
  77433. }
  77434. }
  77435. const Colour Image::getPixelAt (const int x, const int y) const
  77436. {
  77437. if (((unsigned int) x) < (unsigned int) getWidth()
  77438. && ((unsigned int) y) < (unsigned int) getHeight())
  77439. {
  77440. const BitmapData srcData (*this, x, y, 1, 1);
  77441. return srcData.getPixelColour (0, 0);
  77442. }
  77443. return Colour();
  77444. }
  77445. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77446. {
  77447. if (((unsigned int) x) < (unsigned int) getWidth()
  77448. && ((unsigned int) y) < (unsigned int) getHeight())
  77449. {
  77450. const BitmapData destData (*this, x, y, 1, 1, true);
  77451. destData.setPixelColour (0, 0, colour);
  77452. }
  77453. }
  77454. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77455. {
  77456. if (((unsigned int) x) < (unsigned int) getWidth()
  77457. && ((unsigned int) y) < (unsigned int) getHeight()
  77458. && hasAlphaChannel())
  77459. {
  77460. const BitmapData destData (*this, x, y, 1, 1, true);
  77461. if (isARGB())
  77462. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77463. else
  77464. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77465. }
  77466. }
  77467. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77468. {
  77469. if (hasAlphaChannel())
  77470. {
  77471. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77472. if (isARGB())
  77473. {
  77474. for (int y = 0; y < destData.height; ++y)
  77475. {
  77476. uint8* p = destData.getLinePointer (y);
  77477. for (int x = 0; x < destData.width; ++x)
  77478. {
  77479. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77480. p += destData.pixelStride;
  77481. }
  77482. }
  77483. }
  77484. else
  77485. {
  77486. for (int y = 0; y < destData.height; ++y)
  77487. {
  77488. uint8* p = destData.getLinePointer (y);
  77489. for (int x = 0; x < destData.width; ++x)
  77490. {
  77491. *p = (uint8) (*p * amountToMultiplyBy);
  77492. p += destData.pixelStride;
  77493. }
  77494. }
  77495. }
  77496. }
  77497. else
  77498. {
  77499. jassertfalse; // can't do this without an alpha-channel!
  77500. }
  77501. }
  77502. void Image::desaturate()
  77503. {
  77504. if (isARGB() || isRGB())
  77505. {
  77506. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77507. if (isARGB())
  77508. {
  77509. for (int y = 0; y < destData.height; ++y)
  77510. {
  77511. uint8* p = destData.getLinePointer (y);
  77512. for (int x = 0; x < destData.width; ++x)
  77513. {
  77514. ((PixelARGB*) p)->desaturate();
  77515. p += destData.pixelStride;
  77516. }
  77517. }
  77518. }
  77519. else
  77520. {
  77521. for (int y = 0; y < destData.height; ++y)
  77522. {
  77523. uint8* p = destData.getLinePointer (y);
  77524. for (int x = 0; x < destData.width; ++x)
  77525. {
  77526. ((PixelRGB*) p)->desaturate();
  77527. p += destData.pixelStride;
  77528. }
  77529. }
  77530. }
  77531. }
  77532. }
  77533. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77534. {
  77535. if (hasAlphaChannel())
  77536. {
  77537. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77538. SparseSet<int> pixelsOnRow;
  77539. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77540. for (int y = 0; y < srcData.height; ++y)
  77541. {
  77542. pixelsOnRow.clear();
  77543. const uint8* lineData = srcData.getLinePointer (y);
  77544. if (isARGB())
  77545. {
  77546. for (int x = 0; x < srcData.width; ++x)
  77547. {
  77548. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77549. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77550. lineData += srcData.pixelStride;
  77551. }
  77552. }
  77553. else
  77554. {
  77555. for (int x = 0; x < srcData.width; ++x)
  77556. {
  77557. if (*lineData >= threshold)
  77558. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77559. lineData += srcData.pixelStride;
  77560. }
  77561. }
  77562. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77563. {
  77564. const Range<int> range (pixelsOnRow.getRange (i));
  77565. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77566. }
  77567. result.consolidate();
  77568. }
  77569. }
  77570. else
  77571. {
  77572. result.add (0, 0, getWidth(), getHeight());
  77573. }
  77574. }
  77575. void Image::moveImageSection (int dx, int dy,
  77576. int sx, int sy,
  77577. int w, int h)
  77578. {
  77579. if (dx < 0)
  77580. {
  77581. w += dx;
  77582. sx -= dx;
  77583. dx = 0;
  77584. }
  77585. if (dy < 0)
  77586. {
  77587. h += dy;
  77588. sy -= dy;
  77589. dy = 0;
  77590. }
  77591. if (sx < 0)
  77592. {
  77593. w += sx;
  77594. dx -= sx;
  77595. sx = 0;
  77596. }
  77597. if (sy < 0)
  77598. {
  77599. h += sy;
  77600. dy -= sy;
  77601. sy = 0;
  77602. }
  77603. const int minX = jmin (dx, sx);
  77604. const int minY = jmin (dy, sy);
  77605. w = jmin (w, getWidth() - jmax (sx, dx));
  77606. h = jmin (h, getHeight() - jmax (sy, dy));
  77607. if (w > 0 && h > 0)
  77608. {
  77609. const int maxX = jmax (dx, sx) + w;
  77610. const int maxY = jmax (dy, sy) + h;
  77611. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77612. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77613. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77614. const int lineSize = destData.pixelStride * w;
  77615. if (dy > sy)
  77616. {
  77617. while (--h >= 0)
  77618. {
  77619. const int offset = h * destData.lineStride;
  77620. memmove (dst + offset, src + offset, lineSize);
  77621. }
  77622. }
  77623. else if (dst != src)
  77624. {
  77625. while (--h >= 0)
  77626. {
  77627. memmove (dst, src, lineSize);
  77628. dst += destData.lineStride;
  77629. src += destData.lineStride;
  77630. }
  77631. }
  77632. }
  77633. }
  77634. END_JUCE_NAMESPACE
  77635. /*** End of inlined file: juce_Image.cpp ***/
  77636. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77637. BEGIN_JUCE_NAMESPACE
  77638. class ImageCache::Pimpl : public Timer,
  77639. public DeletedAtShutdown
  77640. {
  77641. public:
  77642. Pimpl()
  77643. : cacheTimeout (5000)
  77644. {
  77645. }
  77646. ~Pimpl()
  77647. {
  77648. clearSingletonInstance();
  77649. }
  77650. const Image getFromHashCode (const int64 hashCode)
  77651. {
  77652. const ScopedLock sl (lock);
  77653. for (int i = images.size(); --i >= 0;)
  77654. {
  77655. Item* const item = images.getUnchecked(i);
  77656. if (item->hashCode == hashCode)
  77657. return item->image;
  77658. }
  77659. return Image::null;
  77660. }
  77661. void addImageToCache (const Image& image, const int64 hashCode)
  77662. {
  77663. if (image.isValid())
  77664. {
  77665. if (! isTimerRunning())
  77666. startTimer (2000);
  77667. Item* const item = new Item();
  77668. item->hashCode = hashCode;
  77669. item->image = image;
  77670. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77671. const ScopedLock sl (lock);
  77672. images.add (item);
  77673. }
  77674. }
  77675. void timerCallback()
  77676. {
  77677. const uint32 now = Time::getApproximateMillisecondCounter();
  77678. const ScopedLock sl (lock);
  77679. for (int i = images.size(); --i >= 0;)
  77680. {
  77681. Item* const item = images.getUnchecked(i);
  77682. if (item->image.getReferenceCount() <= 1)
  77683. {
  77684. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77685. images.remove (i);
  77686. }
  77687. else
  77688. {
  77689. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77690. }
  77691. }
  77692. if (images.size() == 0)
  77693. stopTimer();
  77694. }
  77695. struct Item
  77696. {
  77697. Image image;
  77698. int64 hashCode;
  77699. uint32 lastUseTime;
  77700. };
  77701. int cacheTimeout;
  77702. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77703. private:
  77704. OwnedArray<Item> images;
  77705. CriticalSection lock;
  77706. Pimpl (const Pimpl&);
  77707. Pimpl& operator= (const Pimpl&);
  77708. };
  77709. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77710. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77711. {
  77712. if (Pimpl::getInstanceWithoutCreating() != 0)
  77713. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77714. return Image::null;
  77715. }
  77716. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77717. {
  77718. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77719. }
  77720. const Image ImageCache::getFromFile (const File& file)
  77721. {
  77722. const int64 hashCode = file.hashCode64();
  77723. Image image (getFromHashCode (hashCode));
  77724. if (image.isNull())
  77725. {
  77726. image = ImageFileFormat::loadFrom (file);
  77727. addImageToCache (image, hashCode);
  77728. }
  77729. return image;
  77730. }
  77731. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77732. {
  77733. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77734. Image image (getFromHashCode (hashCode));
  77735. if (image.isNull())
  77736. {
  77737. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77738. addImageToCache (image, hashCode);
  77739. }
  77740. return image;
  77741. }
  77742. void ImageCache::setCacheTimeout (const int millisecs)
  77743. {
  77744. Pimpl::getInstance()->cacheTimeout = millisecs;
  77745. }
  77746. END_JUCE_NAMESPACE
  77747. /*** End of inlined file: juce_ImageCache.cpp ***/
  77748. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77749. BEGIN_JUCE_NAMESPACE
  77750. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77751. : values (size_ * size_),
  77752. size (size_)
  77753. {
  77754. clear();
  77755. }
  77756. ImageConvolutionKernel::~ImageConvolutionKernel()
  77757. {
  77758. }
  77759. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77760. {
  77761. if (((unsigned int) x) < (unsigned int) size
  77762. && ((unsigned int) y) < (unsigned int) size)
  77763. {
  77764. return values [x + y * size];
  77765. }
  77766. else
  77767. {
  77768. jassertfalse;
  77769. return 0;
  77770. }
  77771. }
  77772. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77773. {
  77774. if (((unsigned int) x) < (unsigned int) size
  77775. && ((unsigned int) y) < (unsigned int) size)
  77776. {
  77777. values [x + y * size] = value;
  77778. }
  77779. else
  77780. {
  77781. jassertfalse;
  77782. }
  77783. }
  77784. void ImageConvolutionKernel::clear()
  77785. {
  77786. for (int i = size * size; --i >= 0;)
  77787. values[i] = 0;
  77788. }
  77789. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77790. {
  77791. double currentTotal = 0.0;
  77792. for (int i = size * size; --i >= 0;)
  77793. currentTotal += values[i];
  77794. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77795. }
  77796. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77797. {
  77798. for (int i = size * size; --i >= 0;)
  77799. values[i] *= multiplier;
  77800. }
  77801. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77802. {
  77803. const double radiusFactor = -1.0 / (radius * radius * 2);
  77804. const int centre = size >> 1;
  77805. for (int y = size; --y >= 0;)
  77806. {
  77807. for (int x = size; --x >= 0;)
  77808. {
  77809. const int cx = x - centre;
  77810. const int cy = y - centre;
  77811. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77812. }
  77813. }
  77814. setOverallSum (1.0f);
  77815. }
  77816. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77817. const Image& sourceImage,
  77818. const Rectangle<int>& destinationArea) const
  77819. {
  77820. if (sourceImage == destImage)
  77821. {
  77822. destImage.duplicateIfShared();
  77823. }
  77824. else
  77825. {
  77826. if (sourceImage.getWidth() != destImage.getWidth()
  77827. || sourceImage.getHeight() != destImage.getHeight()
  77828. || sourceImage.getFormat() != destImage.getFormat())
  77829. {
  77830. jassertfalse;
  77831. return;
  77832. }
  77833. }
  77834. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77835. if (area.isEmpty())
  77836. return;
  77837. const int right = area.getRight();
  77838. const int bottom = area.getBottom();
  77839. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77840. uint8* line = destData.data;
  77841. const Image::BitmapData srcData (sourceImage, false);
  77842. if (destData.pixelStride == 4)
  77843. {
  77844. for (int y = area.getY(); y < bottom; ++y)
  77845. {
  77846. uint8* dest = line;
  77847. line += destData.lineStride;
  77848. for (int x = area.getX(); x < right; ++x)
  77849. {
  77850. float c1 = 0;
  77851. float c2 = 0;
  77852. float c3 = 0;
  77853. float c4 = 0;
  77854. for (int yy = 0; yy < size; ++yy)
  77855. {
  77856. const int sy = y + yy - (size >> 1);
  77857. if (sy >= srcData.height)
  77858. break;
  77859. if (sy >= 0)
  77860. {
  77861. int sx = x - (size >> 1);
  77862. const uint8* src = srcData.getPixelPointer (sx, sy);
  77863. for (int xx = 0; xx < size; ++xx)
  77864. {
  77865. if (sx >= srcData.width)
  77866. break;
  77867. if (sx >= 0)
  77868. {
  77869. const float kernelMult = values [xx + yy * size];
  77870. c1 += kernelMult * *src++;
  77871. c2 += kernelMult * *src++;
  77872. c3 += kernelMult * *src++;
  77873. c4 += kernelMult * *src++;
  77874. }
  77875. else
  77876. {
  77877. src += 4;
  77878. }
  77879. ++sx;
  77880. }
  77881. }
  77882. }
  77883. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77884. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77885. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77886. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77887. }
  77888. }
  77889. }
  77890. else if (destData.pixelStride == 3)
  77891. {
  77892. for (int y = area.getY(); y < bottom; ++y)
  77893. {
  77894. uint8* dest = line;
  77895. line += destData.lineStride;
  77896. for (int x = area.getX(); x < right; ++x)
  77897. {
  77898. float c1 = 0;
  77899. float c2 = 0;
  77900. float c3 = 0;
  77901. for (int yy = 0; yy < size; ++yy)
  77902. {
  77903. const int sy = y + yy - (size >> 1);
  77904. if (sy >= srcData.height)
  77905. break;
  77906. if (sy >= 0)
  77907. {
  77908. int sx = x - (size >> 1);
  77909. const uint8* src = srcData.getPixelPointer (sx, sy);
  77910. for (int xx = 0; xx < size; ++xx)
  77911. {
  77912. if (sx >= srcData.width)
  77913. break;
  77914. if (sx >= 0)
  77915. {
  77916. const float kernelMult = values [xx + yy * size];
  77917. c1 += kernelMult * *src++;
  77918. c2 += kernelMult * *src++;
  77919. c3 += kernelMult * *src++;
  77920. }
  77921. else
  77922. {
  77923. src += 3;
  77924. }
  77925. ++sx;
  77926. }
  77927. }
  77928. }
  77929. *dest++ = (uint8) roundToInt (c1);
  77930. *dest++ = (uint8) roundToInt (c2);
  77931. *dest++ = (uint8) roundToInt (c3);
  77932. }
  77933. }
  77934. }
  77935. }
  77936. END_JUCE_NAMESPACE
  77937. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77938. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77939. BEGIN_JUCE_NAMESPACE
  77940. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77941. {
  77942. static PNGImageFormat png;
  77943. static JPEGImageFormat jpg;
  77944. static GIFImageFormat gif;
  77945. ImageFileFormat* formats[4];
  77946. int numFormats = 0;
  77947. formats [numFormats++] = &png;
  77948. formats [numFormats++] = &jpg;
  77949. formats [numFormats++] = &gif;
  77950. const int64 streamPos = input.getPosition();
  77951. for (int i = 0; i < numFormats; ++i)
  77952. {
  77953. const bool found = formats[i]->canUnderstand (input);
  77954. input.setPosition (streamPos);
  77955. if (found)
  77956. return formats[i];
  77957. }
  77958. return 0;
  77959. }
  77960. const Image ImageFileFormat::loadFrom (InputStream& input)
  77961. {
  77962. ImageFileFormat* const format = findImageFormatForStream (input);
  77963. if (format != 0)
  77964. return format->decodeImage (input);
  77965. return Image::null;
  77966. }
  77967. const Image ImageFileFormat::loadFrom (const File& file)
  77968. {
  77969. InputStream* const in = file.createInputStream();
  77970. if (in != 0)
  77971. {
  77972. BufferedInputStream b (in, 8192, true);
  77973. return loadFrom (b);
  77974. }
  77975. return Image::null;
  77976. }
  77977. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77978. {
  77979. if (rawData != 0 && numBytes > 4)
  77980. {
  77981. MemoryInputStream stream (rawData, numBytes, false);
  77982. return loadFrom (stream);
  77983. }
  77984. return Image::null;
  77985. }
  77986. END_JUCE_NAMESPACE
  77987. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77988. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77989. BEGIN_JUCE_NAMESPACE
  77990. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77991. const Image juce_loadWithCoreImage (InputStream& input);
  77992. #else
  77993. class GIFLoader
  77994. {
  77995. public:
  77996. GIFLoader (InputStream& in)
  77997. : input (in),
  77998. dataBlockIsZero (false),
  77999. fresh (false),
  78000. finished (false)
  78001. {
  78002. currentBit = lastBit = lastByteIndex = 0;
  78003. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  78004. firstcode = oldcode = 0;
  78005. clearCode = end_code = 0;
  78006. int imageWidth, imageHeight;
  78007. int transparent = -1;
  78008. if (! getSizeFromHeader (imageWidth, imageHeight))
  78009. return;
  78010. if ((imageWidth <= 0) || (imageHeight <= 0))
  78011. return;
  78012. unsigned char buf [16];
  78013. if (in.read (buf, 3) != 3)
  78014. return;
  78015. int numColours = 2 << (buf[0] & 7);
  78016. if ((buf[0] & 0x80) != 0)
  78017. readPalette (numColours);
  78018. for (;;)
  78019. {
  78020. if (input.read (buf, 1) != 1 || buf[0] == ';')
  78021. break;
  78022. if (buf[0] == '!')
  78023. {
  78024. if (input.read (buf, 1) != 1)
  78025. break;
  78026. if (processExtension (buf[0], transparent) < 0)
  78027. break;
  78028. continue;
  78029. }
  78030. if (buf[0] != ',')
  78031. continue;
  78032. if (input.read (buf, 9) != 9)
  78033. break;
  78034. imageWidth = makeWord (buf[4], buf[5]);
  78035. imageHeight = makeWord (buf[6], buf[7]);
  78036. numColours = 2 << (buf[8] & 7);
  78037. if ((buf[8] & 0x80) != 0)
  78038. if (! readPalette (numColours))
  78039. break;
  78040. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  78041. imageWidth, imageHeight, (transparent >= 0));
  78042. readImage ((buf[8] & 0x40) != 0, transparent);
  78043. break;
  78044. }
  78045. }
  78046. ~GIFLoader() {}
  78047. Image image;
  78048. private:
  78049. InputStream& input;
  78050. uint8 buffer [300];
  78051. uint8 palette [256][4];
  78052. bool dataBlockIsZero, fresh, finished;
  78053. int currentBit, lastBit, lastByteIndex;
  78054. int codeSize, setCodeSize;
  78055. int maxCode, maxCodeSize;
  78056. int firstcode, oldcode;
  78057. int clearCode, end_code;
  78058. enum { maxGifCode = 1 << 12 };
  78059. int table [2] [maxGifCode];
  78060. int stack [2 * maxGifCode];
  78061. int *sp;
  78062. bool getSizeFromHeader (int& w, int& h)
  78063. {
  78064. char b[8];
  78065. if (input.read (b, 6) == 6)
  78066. {
  78067. if ((strncmp ("GIF87a", b, 6) == 0)
  78068. || (strncmp ("GIF89a", b, 6) == 0))
  78069. {
  78070. if (input.read (b, 4) == 4)
  78071. {
  78072. w = makeWord (b[0], b[1]);
  78073. h = makeWord (b[2], b[3]);
  78074. return true;
  78075. }
  78076. }
  78077. }
  78078. return false;
  78079. }
  78080. bool readPalette (const int numCols)
  78081. {
  78082. unsigned char rgb[4];
  78083. for (int i = 0; i < numCols; ++i)
  78084. {
  78085. input.read (rgb, 3);
  78086. palette [i][0] = rgb[0];
  78087. palette [i][1] = rgb[1];
  78088. palette [i][2] = rgb[2];
  78089. palette [i][3] = 0xff;
  78090. }
  78091. return true;
  78092. }
  78093. int readDataBlock (unsigned char* dest)
  78094. {
  78095. unsigned char n;
  78096. if (input.read (&n, 1) == 1)
  78097. {
  78098. dataBlockIsZero = (n == 0);
  78099. if (dataBlockIsZero || (input.read (dest, n) == n))
  78100. return n;
  78101. }
  78102. return -1;
  78103. }
  78104. int processExtension (const int type, int& transparent)
  78105. {
  78106. unsigned char b [300];
  78107. int n = 0;
  78108. if (type == 0xf9)
  78109. {
  78110. n = readDataBlock (b);
  78111. if (n < 0)
  78112. return 1;
  78113. if ((b[0] & 0x1) != 0)
  78114. transparent = b[3];
  78115. }
  78116. do
  78117. {
  78118. n = readDataBlock (b);
  78119. }
  78120. while (n > 0);
  78121. return n;
  78122. }
  78123. int readLZWByte (const bool initialise, const int inputCodeSize)
  78124. {
  78125. int code, incode, i;
  78126. if (initialise)
  78127. {
  78128. setCodeSize = inputCodeSize;
  78129. codeSize = setCodeSize + 1;
  78130. clearCode = 1 << setCodeSize;
  78131. end_code = clearCode + 1;
  78132. maxCodeSize = 2 * clearCode;
  78133. maxCode = clearCode + 2;
  78134. getCode (0, true);
  78135. fresh = true;
  78136. for (i = 0; i < clearCode; ++i)
  78137. {
  78138. table[0][i] = 0;
  78139. table[1][i] = i;
  78140. }
  78141. for (; i < maxGifCode; ++i)
  78142. {
  78143. table[0][i] = 0;
  78144. table[1][i] = 0;
  78145. }
  78146. sp = stack;
  78147. return 0;
  78148. }
  78149. else if (fresh)
  78150. {
  78151. fresh = false;
  78152. do
  78153. {
  78154. firstcode = oldcode
  78155. = getCode (codeSize, false);
  78156. }
  78157. while (firstcode == clearCode);
  78158. return firstcode;
  78159. }
  78160. if (sp > stack)
  78161. return *--sp;
  78162. while ((code = getCode (codeSize, false)) >= 0)
  78163. {
  78164. if (code == clearCode)
  78165. {
  78166. for (i = 0; i < clearCode; ++i)
  78167. {
  78168. table[0][i] = 0;
  78169. table[1][i] = i;
  78170. }
  78171. for (; i < maxGifCode; ++i)
  78172. {
  78173. table[0][i] = 0;
  78174. table[1][i] = 0;
  78175. }
  78176. codeSize = setCodeSize + 1;
  78177. maxCodeSize = 2 * clearCode;
  78178. maxCode = clearCode + 2;
  78179. sp = stack;
  78180. firstcode = oldcode = getCode (codeSize, false);
  78181. return firstcode;
  78182. }
  78183. else if (code == end_code)
  78184. {
  78185. if (dataBlockIsZero)
  78186. return -2;
  78187. unsigned char buf [260];
  78188. int n;
  78189. while ((n = readDataBlock (buf)) > 0)
  78190. {}
  78191. if (n != 0)
  78192. return -2;
  78193. }
  78194. incode = code;
  78195. if (code >= maxCode)
  78196. {
  78197. *sp++ = firstcode;
  78198. code = oldcode;
  78199. }
  78200. while (code >= clearCode)
  78201. {
  78202. *sp++ = table[1][code];
  78203. if (code == table[0][code])
  78204. return -2;
  78205. code = table[0][code];
  78206. }
  78207. *sp++ = firstcode = table[1][code];
  78208. if ((code = maxCode) < maxGifCode)
  78209. {
  78210. table[0][code] = oldcode;
  78211. table[1][code] = firstcode;
  78212. ++maxCode;
  78213. if ((maxCode >= maxCodeSize)
  78214. && (maxCodeSize < maxGifCode))
  78215. {
  78216. maxCodeSize <<= 1;
  78217. ++codeSize;
  78218. }
  78219. }
  78220. oldcode = incode;
  78221. if (sp > stack)
  78222. return *--sp;
  78223. }
  78224. return code;
  78225. }
  78226. int getCode (const int codeSize_, const bool initialise)
  78227. {
  78228. if (initialise)
  78229. {
  78230. currentBit = 0;
  78231. lastBit = 0;
  78232. finished = false;
  78233. return 0;
  78234. }
  78235. if ((currentBit + codeSize_) >= lastBit)
  78236. {
  78237. if (finished)
  78238. return -1;
  78239. buffer[0] = buffer [lastByteIndex - 2];
  78240. buffer[1] = buffer [lastByteIndex - 1];
  78241. const int n = readDataBlock (&buffer[2]);
  78242. if (n == 0)
  78243. finished = true;
  78244. lastByteIndex = 2 + n;
  78245. currentBit = (currentBit - lastBit) + 16;
  78246. lastBit = (2 + n) * 8 ;
  78247. }
  78248. int result = 0;
  78249. int i = currentBit;
  78250. for (int j = 0; j < codeSize_; ++j)
  78251. {
  78252. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78253. ++i;
  78254. }
  78255. currentBit += codeSize_;
  78256. return result;
  78257. }
  78258. bool readImage (const int interlace, const int transparent)
  78259. {
  78260. unsigned char c;
  78261. if (input.read (&c, 1) != 1
  78262. || readLZWByte (true, c) < 0)
  78263. return false;
  78264. if (transparent >= 0)
  78265. {
  78266. palette [transparent][0] = 0;
  78267. palette [transparent][1] = 0;
  78268. palette [transparent][2] = 0;
  78269. palette [transparent][3] = 0;
  78270. }
  78271. int index;
  78272. int xpos = 0, ypos = 0, pass = 0;
  78273. const Image::BitmapData destData (image, true);
  78274. uint8* p = destData.data;
  78275. const bool hasAlpha = image.hasAlphaChannel();
  78276. while ((index = readLZWByte (false, c)) >= 0)
  78277. {
  78278. const uint8* const paletteEntry = palette [index];
  78279. if (hasAlpha)
  78280. {
  78281. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78282. paletteEntry[0],
  78283. paletteEntry[1],
  78284. paletteEntry[2]);
  78285. ((PixelARGB*) p)->premultiply();
  78286. }
  78287. else
  78288. {
  78289. ((PixelRGB*) p)->setARGB (0,
  78290. paletteEntry[0],
  78291. paletteEntry[1],
  78292. paletteEntry[2]);
  78293. }
  78294. p += destData.pixelStride;
  78295. ++xpos;
  78296. if (xpos == destData.width)
  78297. {
  78298. xpos = 0;
  78299. if (interlace)
  78300. {
  78301. switch (pass)
  78302. {
  78303. case 0:
  78304. case 1: ypos += 8; break;
  78305. case 2: ypos += 4; break;
  78306. case 3: ypos += 2; break;
  78307. }
  78308. while (ypos >= destData.height)
  78309. {
  78310. ++pass;
  78311. switch (pass)
  78312. {
  78313. case 1: ypos = 4; break;
  78314. case 2: ypos = 2; break;
  78315. case 3: ypos = 1; break;
  78316. default: return true;
  78317. }
  78318. }
  78319. }
  78320. else
  78321. {
  78322. ++ypos;
  78323. }
  78324. p = destData.getPixelPointer (xpos, ypos);
  78325. }
  78326. if (ypos >= destData.height)
  78327. break;
  78328. }
  78329. return true;
  78330. }
  78331. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78332. GIFLoader (const GIFLoader&);
  78333. GIFLoader& operator= (const GIFLoader&);
  78334. };
  78335. #endif
  78336. GIFImageFormat::GIFImageFormat() {}
  78337. GIFImageFormat::~GIFImageFormat() {}
  78338. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78339. bool GIFImageFormat::canUnderstand (InputStream& in)
  78340. {
  78341. char header [4];
  78342. return (in.read (header, sizeof (header)) == sizeof (header))
  78343. && header[0] == 'G'
  78344. && header[1] == 'I'
  78345. && header[2] == 'F';
  78346. }
  78347. const Image GIFImageFormat::decodeImage (InputStream& in)
  78348. {
  78349. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78350. return juce_loadWithCoreImage (in);
  78351. #else
  78352. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78353. return loader->image;
  78354. #endif
  78355. }
  78356. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78357. {
  78358. jassertfalse; // writing isn't implemented for GIFs!
  78359. return false;
  78360. }
  78361. END_JUCE_NAMESPACE
  78362. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78363. #endif
  78364. //==============================================================================
  78365. // some files include lots of library code, so leave them to the end to avoid cluttering
  78366. // up the build for the clean files.
  78367. #if JUCE_BUILD_CORE
  78368. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78369. namespace zlibNamespace
  78370. {
  78371. #if JUCE_INCLUDE_ZLIB_CODE
  78372. #undef OS_CODE
  78373. #undef fdopen
  78374. /*** Start of inlined file: zlib.h ***/
  78375. #ifndef ZLIB_H
  78376. #define ZLIB_H
  78377. /*** Start of inlined file: zconf.h ***/
  78378. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78379. #ifndef ZCONF_H
  78380. #define ZCONF_H
  78381. // *** Just a few hacks here to make it compile nicely with Juce..
  78382. #define Z_PREFIX 1
  78383. #undef __MACTYPES__
  78384. #ifdef _MSC_VER
  78385. #pragma warning (disable : 4131 4127 4244 4267)
  78386. #endif
  78387. /*
  78388. * If you *really* need a unique prefix for all types and library functions,
  78389. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78390. */
  78391. #ifdef Z_PREFIX
  78392. # define deflateInit_ z_deflateInit_
  78393. # define deflate z_deflate
  78394. # define deflateEnd z_deflateEnd
  78395. # define inflateInit_ z_inflateInit_
  78396. # define inflate z_inflate
  78397. # define inflateEnd z_inflateEnd
  78398. # define inflatePrime z_inflatePrime
  78399. # define inflateGetHeader z_inflateGetHeader
  78400. # define adler32_combine z_adler32_combine
  78401. # define crc32_combine z_crc32_combine
  78402. # define deflateInit2_ z_deflateInit2_
  78403. # define deflateSetDictionary z_deflateSetDictionary
  78404. # define deflateCopy z_deflateCopy
  78405. # define deflateReset z_deflateReset
  78406. # define deflateParams z_deflateParams
  78407. # define deflateBound z_deflateBound
  78408. # define deflatePrime z_deflatePrime
  78409. # define inflateInit2_ z_inflateInit2_
  78410. # define inflateSetDictionary z_inflateSetDictionary
  78411. # define inflateSync z_inflateSync
  78412. # define inflateSyncPoint z_inflateSyncPoint
  78413. # define inflateCopy z_inflateCopy
  78414. # define inflateReset z_inflateReset
  78415. # define inflateBack z_inflateBack
  78416. # define inflateBackEnd z_inflateBackEnd
  78417. # define compress z_compress
  78418. # define compress2 z_compress2
  78419. # define compressBound z_compressBound
  78420. # define uncompress z_uncompress
  78421. # define adler32 z_adler32
  78422. # define crc32 z_crc32
  78423. # define get_crc_table z_get_crc_table
  78424. # define zError z_zError
  78425. # define alloc_func z_alloc_func
  78426. # define free_func z_free_func
  78427. # define in_func z_in_func
  78428. # define out_func z_out_func
  78429. # define Byte z_Byte
  78430. # define uInt z_uInt
  78431. # define uLong z_uLong
  78432. # define Bytef z_Bytef
  78433. # define charf z_charf
  78434. # define intf z_intf
  78435. # define uIntf z_uIntf
  78436. # define uLongf z_uLongf
  78437. # define voidpf z_voidpf
  78438. # define voidp z_voidp
  78439. #endif
  78440. #if defined(__MSDOS__) && !defined(MSDOS)
  78441. # define MSDOS
  78442. #endif
  78443. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78444. # define OS2
  78445. #endif
  78446. #if defined(_WINDOWS) && !defined(WINDOWS)
  78447. # define WINDOWS
  78448. #endif
  78449. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78450. # ifndef WIN32
  78451. # define WIN32
  78452. # endif
  78453. #endif
  78454. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78455. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78456. # ifndef SYS16BIT
  78457. # define SYS16BIT
  78458. # endif
  78459. # endif
  78460. #endif
  78461. /*
  78462. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78463. * than 64k bytes at a time (needed on systems with 16-bit int).
  78464. */
  78465. #ifdef SYS16BIT
  78466. # define MAXSEG_64K
  78467. #endif
  78468. #ifdef MSDOS
  78469. # define UNALIGNED_OK
  78470. #endif
  78471. #ifdef __STDC_VERSION__
  78472. # ifndef STDC
  78473. # define STDC
  78474. # endif
  78475. # if __STDC_VERSION__ >= 199901L
  78476. # ifndef STDC99
  78477. # define STDC99
  78478. # endif
  78479. # endif
  78480. #endif
  78481. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78482. # define STDC
  78483. #endif
  78484. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78485. # define STDC
  78486. #endif
  78487. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78488. # define STDC
  78489. #endif
  78490. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78491. # define STDC
  78492. #endif
  78493. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78494. # define STDC
  78495. #endif
  78496. #ifndef STDC
  78497. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78498. # define const /* note: need a more gentle solution here */
  78499. # endif
  78500. #endif
  78501. /* Some Mac compilers merge all .h files incorrectly: */
  78502. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78503. # define NO_DUMMY_DECL
  78504. #endif
  78505. /* Maximum value for memLevel in deflateInit2 */
  78506. #ifndef MAX_MEM_LEVEL
  78507. # ifdef MAXSEG_64K
  78508. # define MAX_MEM_LEVEL 8
  78509. # else
  78510. # define MAX_MEM_LEVEL 9
  78511. # endif
  78512. #endif
  78513. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78514. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78515. * created by gzip. (Files created by minigzip can still be extracted by
  78516. * gzip.)
  78517. */
  78518. #ifndef MAX_WBITS
  78519. # define MAX_WBITS 15 /* 32K LZ77 window */
  78520. #endif
  78521. /* The memory requirements for deflate are (in bytes):
  78522. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78523. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78524. plus a few kilobytes for small objects. For example, if you want to reduce
  78525. the default memory requirements from 256K to 128K, compile with
  78526. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78527. Of course this will generally degrade compression (there's no free lunch).
  78528. The memory requirements for inflate are (in bytes) 1 << windowBits
  78529. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78530. for small objects.
  78531. */
  78532. /* Type declarations */
  78533. #ifndef OF /* function prototypes */
  78534. # ifdef STDC
  78535. # define OF(args) args
  78536. # else
  78537. # define OF(args) ()
  78538. # endif
  78539. #endif
  78540. /* The following definitions for FAR are needed only for MSDOS mixed
  78541. * model programming (small or medium model with some far allocations).
  78542. * This was tested only with MSC; for other MSDOS compilers you may have
  78543. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78544. * just define FAR to be empty.
  78545. */
  78546. #ifdef SYS16BIT
  78547. # if defined(M_I86SM) || defined(M_I86MM)
  78548. /* MSC small or medium model */
  78549. # define SMALL_MEDIUM
  78550. # ifdef _MSC_VER
  78551. # define FAR _far
  78552. # else
  78553. # define FAR far
  78554. # endif
  78555. # endif
  78556. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78557. /* Turbo C small or medium model */
  78558. # define SMALL_MEDIUM
  78559. # ifdef __BORLANDC__
  78560. # define FAR _far
  78561. # else
  78562. # define FAR far
  78563. # endif
  78564. # endif
  78565. #endif
  78566. #if defined(WINDOWS) || defined(WIN32)
  78567. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78568. * This is not mandatory, but it offers a little performance increase.
  78569. */
  78570. # ifdef ZLIB_DLL
  78571. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78572. # ifdef ZLIB_INTERNAL
  78573. # define ZEXTERN extern __declspec(dllexport)
  78574. # else
  78575. # define ZEXTERN extern __declspec(dllimport)
  78576. # endif
  78577. # endif
  78578. # endif /* ZLIB_DLL */
  78579. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78580. * define ZLIB_WINAPI.
  78581. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78582. */
  78583. # ifdef ZLIB_WINAPI
  78584. # ifdef FAR
  78585. # undef FAR
  78586. # endif
  78587. # include <windows.h>
  78588. /* No need for _export, use ZLIB.DEF instead. */
  78589. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78590. # define ZEXPORT WINAPI
  78591. # ifdef WIN32
  78592. # define ZEXPORTVA WINAPIV
  78593. # else
  78594. # define ZEXPORTVA FAR CDECL
  78595. # endif
  78596. # endif
  78597. #endif
  78598. #if defined (__BEOS__)
  78599. # ifdef ZLIB_DLL
  78600. # ifdef ZLIB_INTERNAL
  78601. # define ZEXPORT __declspec(dllexport)
  78602. # define ZEXPORTVA __declspec(dllexport)
  78603. # else
  78604. # define ZEXPORT __declspec(dllimport)
  78605. # define ZEXPORTVA __declspec(dllimport)
  78606. # endif
  78607. # endif
  78608. #endif
  78609. #ifndef ZEXTERN
  78610. # define ZEXTERN extern
  78611. #endif
  78612. #ifndef ZEXPORT
  78613. # define ZEXPORT
  78614. #endif
  78615. #ifndef ZEXPORTVA
  78616. # define ZEXPORTVA
  78617. #endif
  78618. #ifndef FAR
  78619. # define FAR
  78620. #endif
  78621. #if !defined(__MACTYPES__)
  78622. typedef unsigned char Byte; /* 8 bits */
  78623. #endif
  78624. typedef unsigned int uInt; /* 16 bits or more */
  78625. typedef unsigned long uLong; /* 32 bits or more */
  78626. #ifdef SMALL_MEDIUM
  78627. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78628. # define Bytef Byte FAR
  78629. #else
  78630. typedef Byte FAR Bytef;
  78631. #endif
  78632. typedef char FAR charf;
  78633. typedef int FAR intf;
  78634. typedef uInt FAR uIntf;
  78635. typedef uLong FAR uLongf;
  78636. #ifdef STDC
  78637. typedef void const *voidpc;
  78638. typedef void FAR *voidpf;
  78639. typedef void *voidp;
  78640. #else
  78641. typedef Byte const *voidpc;
  78642. typedef Byte FAR *voidpf;
  78643. typedef Byte *voidp;
  78644. #endif
  78645. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78646. # include <sys/types.h> /* for off_t */
  78647. # include <unistd.h> /* for SEEK_* and off_t */
  78648. # ifdef VMS
  78649. # include <unixio.h> /* for off_t */
  78650. # endif
  78651. # define z_off_t off_t
  78652. #endif
  78653. #ifndef SEEK_SET
  78654. # define SEEK_SET 0 /* Seek from beginning of file. */
  78655. # define SEEK_CUR 1 /* Seek from current position. */
  78656. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78657. #endif
  78658. #ifndef z_off_t
  78659. # define z_off_t long
  78660. #endif
  78661. #if defined(__OS400__)
  78662. # define NO_vsnprintf
  78663. #endif
  78664. #if defined(__MVS__)
  78665. # define NO_vsnprintf
  78666. # ifdef FAR
  78667. # undef FAR
  78668. # endif
  78669. #endif
  78670. /* MVS linker does not support external names larger than 8 bytes */
  78671. #if defined(__MVS__)
  78672. # pragma map(deflateInit_,"DEIN")
  78673. # pragma map(deflateInit2_,"DEIN2")
  78674. # pragma map(deflateEnd,"DEEND")
  78675. # pragma map(deflateBound,"DEBND")
  78676. # pragma map(inflateInit_,"ININ")
  78677. # pragma map(inflateInit2_,"ININ2")
  78678. # pragma map(inflateEnd,"INEND")
  78679. # pragma map(inflateSync,"INSY")
  78680. # pragma map(inflateSetDictionary,"INSEDI")
  78681. # pragma map(compressBound,"CMBND")
  78682. # pragma map(inflate_table,"INTABL")
  78683. # pragma map(inflate_fast,"INFA")
  78684. # pragma map(inflate_copyright,"INCOPY")
  78685. #endif
  78686. #endif /* ZCONF_H */
  78687. /*** End of inlined file: zconf.h ***/
  78688. #ifdef __cplusplus
  78689. //extern "C" {
  78690. #endif
  78691. #define ZLIB_VERSION "1.2.3"
  78692. #define ZLIB_VERNUM 0x1230
  78693. /*
  78694. The 'zlib' compression library provides in-memory compression and
  78695. decompression functions, including integrity checks of the uncompressed
  78696. data. This version of the library supports only one compression method
  78697. (deflation) but other algorithms will be added later and will have the same
  78698. stream interface.
  78699. Compression can be done in a single step if the buffers are large
  78700. enough (for example if an input file is mmap'ed), or can be done by
  78701. repeated calls of the compression function. In the latter case, the
  78702. application must provide more input and/or consume the output
  78703. (providing more output space) before each call.
  78704. The compressed data format used by default by the in-memory functions is
  78705. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78706. around a deflate stream, which is itself documented in RFC 1951.
  78707. The library also supports reading and writing files in gzip (.gz) format
  78708. with an interface similar to that of stdio using the functions that start
  78709. with "gz". The gzip format is different from the zlib format. gzip is a
  78710. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78711. This library can optionally read and write gzip streams in memory as well.
  78712. The zlib format was designed to be compact and fast for use in memory
  78713. and on communications channels. The gzip format was designed for single-
  78714. file compression on file systems, has a larger header than zlib to maintain
  78715. directory information, and uses a different, slower check method than zlib.
  78716. The library does not install any signal handler. The decoder checks
  78717. the consistency of the compressed data, so the library should never
  78718. crash even in case of corrupted input.
  78719. */
  78720. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78721. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78722. struct internal_state;
  78723. typedef struct z_stream_s {
  78724. Bytef *next_in; /* next input byte */
  78725. uInt avail_in; /* number of bytes available at next_in */
  78726. uLong total_in; /* total nb of input bytes read so far */
  78727. Bytef *next_out; /* next output byte should be put there */
  78728. uInt avail_out; /* remaining free space at next_out */
  78729. uLong total_out; /* total nb of bytes output so far */
  78730. char *msg; /* last error message, NULL if no error */
  78731. struct internal_state FAR *state; /* not visible by applications */
  78732. alloc_func zalloc; /* used to allocate the internal state */
  78733. free_func zfree; /* used to free the internal state */
  78734. voidpf opaque; /* private data object passed to zalloc and zfree */
  78735. int data_type; /* best guess about the data type: binary or text */
  78736. uLong adler; /* adler32 value of the uncompressed data */
  78737. uLong reserved; /* reserved for future use */
  78738. } z_stream;
  78739. typedef z_stream FAR *z_streamp;
  78740. /*
  78741. gzip header information passed to and from zlib routines. See RFC 1952
  78742. for more details on the meanings of these fields.
  78743. */
  78744. typedef struct gz_header_s {
  78745. int text; /* true if compressed data believed to be text */
  78746. uLong time; /* modification time */
  78747. int xflags; /* extra flags (not used when writing a gzip file) */
  78748. int os; /* operating system */
  78749. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78750. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78751. uInt extra_max; /* space at extra (only when reading header) */
  78752. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78753. uInt name_max; /* space at name (only when reading header) */
  78754. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78755. uInt comm_max; /* space at comment (only when reading header) */
  78756. int hcrc; /* true if there was or will be a header crc */
  78757. int done; /* true when done reading gzip header (not used
  78758. when writing a gzip file) */
  78759. } gz_header;
  78760. typedef gz_header FAR *gz_headerp;
  78761. /*
  78762. The application must update next_in and avail_in when avail_in has
  78763. dropped to zero. It must update next_out and avail_out when avail_out
  78764. has dropped to zero. The application must initialize zalloc, zfree and
  78765. opaque before calling the init function. All other fields are set by the
  78766. compression library and must not be updated by the application.
  78767. The opaque value provided by the application will be passed as the first
  78768. parameter for calls of zalloc and zfree. This can be useful for custom
  78769. memory management. The compression library attaches no meaning to the
  78770. opaque value.
  78771. zalloc must return Z_NULL if there is not enough memory for the object.
  78772. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78773. thread safe.
  78774. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78775. exactly 65536 bytes, but will not be required to allocate more than this
  78776. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78777. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78778. have their offset normalized to zero. The default allocation function
  78779. provided by this library ensures this (see zutil.c). To reduce memory
  78780. requirements and avoid any allocation of 64K objects, at the expense of
  78781. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78782. The fields total_in and total_out can be used for statistics or
  78783. progress reports. After compression, total_in holds the total size of
  78784. the uncompressed data and may be saved for use in the decompressor
  78785. (particularly if the decompressor wants to decompress everything in
  78786. a single step).
  78787. */
  78788. /* constants */
  78789. #define Z_NO_FLUSH 0
  78790. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78791. #define Z_SYNC_FLUSH 2
  78792. #define Z_FULL_FLUSH 3
  78793. #define Z_FINISH 4
  78794. #define Z_BLOCK 5
  78795. /* Allowed flush values; see deflate() and inflate() below for details */
  78796. #define Z_OK 0
  78797. #define Z_STREAM_END 1
  78798. #define Z_NEED_DICT 2
  78799. #define Z_ERRNO (-1)
  78800. #define Z_STREAM_ERROR (-2)
  78801. #define Z_DATA_ERROR (-3)
  78802. #define Z_MEM_ERROR (-4)
  78803. #define Z_BUF_ERROR (-5)
  78804. #define Z_VERSION_ERROR (-6)
  78805. /* Return codes for the compression/decompression functions. Negative
  78806. * values are errors, positive values are used for special but normal events.
  78807. */
  78808. #define Z_NO_COMPRESSION 0
  78809. #define Z_BEST_SPEED 1
  78810. #define Z_BEST_COMPRESSION 9
  78811. #define Z_DEFAULT_COMPRESSION (-1)
  78812. /* compression levels */
  78813. #define Z_FILTERED 1
  78814. #define Z_HUFFMAN_ONLY 2
  78815. #define Z_RLE 3
  78816. #define Z_FIXED 4
  78817. #define Z_DEFAULT_STRATEGY 0
  78818. /* compression strategy; see deflateInit2() below for details */
  78819. #define Z_BINARY 0
  78820. #define Z_TEXT 1
  78821. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78822. #define Z_UNKNOWN 2
  78823. /* Possible values of the data_type field (though see inflate()) */
  78824. #define Z_DEFLATED 8
  78825. /* The deflate compression method (the only one supported in this version) */
  78826. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78827. #define zlib_version zlibVersion()
  78828. /* for compatibility with versions < 1.0.2 */
  78829. /* basic functions */
  78830. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78831. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78832. If the first character differs, the library code actually used is
  78833. not compatible with the zlib.h header file used by the application.
  78834. This check is automatically made by deflateInit and inflateInit.
  78835. */
  78836. /*
  78837. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78838. Initializes the internal stream state for compression. The fields
  78839. zalloc, zfree and opaque must be initialized before by the caller.
  78840. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78841. use default allocation functions.
  78842. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78843. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78844. all (the input data is simply copied a block at a time).
  78845. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78846. compression (currently equivalent to level 6).
  78847. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78848. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78849. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78850. with the version assumed by the caller (ZLIB_VERSION).
  78851. msg is set to null if there is no error message. deflateInit does not
  78852. perform any compression: this will be done by deflate().
  78853. */
  78854. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78855. /*
  78856. deflate compresses as much data as possible, and stops when the input
  78857. buffer becomes empty or the output buffer becomes full. It may introduce some
  78858. output latency (reading input without producing any output) except when
  78859. forced to flush.
  78860. The detailed semantics are as follows. deflate performs one or both of the
  78861. following actions:
  78862. - Compress more input starting at next_in and update next_in and avail_in
  78863. accordingly. If not all input can be processed (because there is not
  78864. enough room in the output buffer), next_in and avail_in are updated and
  78865. processing will resume at this point for the next call of deflate().
  78866. - Provide more output starting at next_out and update next_out and avail_out
  78867. accordingly. This action is forced if the parameter flush is non zero.
  78868. Forcing flush frequently degrades the compression ratio, so this parameter
  78869. should be set only when necessary (in interactive applications).
  78870. Some output may be provided even if flush is not set.
  78871. Before the call of deflate(), the application should ensure that at least
  78872. one of the actions is possible, by providing more input and/or consuming
  78873. more output, and updating avail_in or avail_out accordingly; avail_out
  78874. should never be zero before the call. The application can consume the
  78875. compressed output when it wants, for example when the output buffer is full
  78876. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78877. and with zero avail_out, it must be called again after making room in the
  78878. output buffer because there might be more output pending.
  78879. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78880. decide how much data to accumualte before producing output, in order to
  78881. maximize compression.
  78882. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78883. flushed to the output buffer and the output is aligned on a byte boundary, so
  78884. that the decompressor can get all input data available so far. (In particular
  78885. avail_in is zero after the call if enough output space has been provided
  78886. before the call.) Flushing may degrade compression for some compression
  78887. algorithms and so it should be used only when necessary.
  78888. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78889. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78890. restart from this point if previous compressed data has been damaged or if
  78891. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78892. compression.
  78893. If deflate returns with avail_out == 0, this function must be called again
  78894. with the same value of the flush parameter and more output space (updated
  78895. avail_out), until the flush is complete (deflate returns with non-zero
  78896. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78897. avail_out is greater than six to avoid repeated flush markers due to
  78898. avail_out == 0 on return.
  78899. If the parameter flush is set to Z_FINISH, pending input is processed,
  78900. pending output is flushed and deflate returns with Z_STREAM_END if there
  78901. was enough output space; if deflate returns with Z_OK, this function must be
  78902. called again with Z_FINISH and more output space (updated avail_out) but no
  78903. more input data, until it returns with Z_STREAM_END or an error. After
  78904. deflate has returned Z_STREAM_END, the only possible operations on the
  78905. stream are deflateReset or deflateEnd.
  78906. Z_FINISH can be used immediately after deflateInit if all the compression
  78907. is to be done in a single step. In this case, avail_out must be at least
  78908. the value returned by deflateBound (see below). If deflate does not return
  78909. Z_STREAM_END, then it must be called again as described above.
  78910. deflate() sets strm->adler to the adler32 checksum of all input read
  78911. so far (that is, total_in bytes).
  78912. deflate() may update strm->data_type if it can make a good guess about
  78913. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78914. binary. This field is only for information purposes and does not affect
  78915. the compression algorithm in any manner.
  78916. deflate() returns Z_OK if some progress has been made (more input
  78917. processed or more output produced), Z_STREAM_END if all input has been
  78918. consumed and all output has been produced (only when flush is set to
  78919. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78920. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78921. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78922. fatal, and deflate() can be called again with more input and more output
  78923. space to continue compressing.
  78924. */
  78925. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78926. /*
  78927. All dynamically allocated data structures for this stream are freed.
  78928. This function discards any unprocessed input and does not flush any
  78929. pending output.
  78930. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78931. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78932. prematurely (some input or output was discarded). In the error case,
  78933. msg may be set but then points to a static string (which must not be
  78934. deallocated).
  78935. */
  78936. /*
  78937. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78938. Initializes the internal stream state for decompression. The fields
  78939. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78940. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78941. value depends on the compression method), inflateInit determines the
  78942. compression method from the zlib header and allocates all data structures
  78943. accordingly; otherwise the allocation will be deferred to the first call of
  78944. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78945. use default allocation functions.
  78946. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78947. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78948. version assumed by the caller. msg is set to null if there is no error
  78949. message. inflateInit does not perform any decompression apart from reading
  78950. the zlib header if present: this will be done by inflate(). (So next_in and
  78951. avail_in may be modified, but next_out and avail_out are unchanged.)
  78952. */
  78953. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78954. /*
  78955. inflate decompresses as much data as possible, and stops when the input
  78956. buffer becomes empty or the output buffer becomes full. It may introduce
  78957. some output latency (reading input without producing any output) except when
  78958. forced to flush.
  78959. The detailed semantics are as follows. inflate performs one or both of the
  78960. following actions:
  78961. - Decompress more input starting at next_in and update next_in and avail_in
  78962. accordingly. If not all input can be processed (because there is not
  78963. enough room in the output buffer), next_in is updated and processing
  78964. will resume at this point for the next call of inflate().
  78965. - Provide more output starting at next_out and update next_out and avail_out
  78966. accordingly. inflate() provides as much output as possible, until there
  78967. is no more input data or no more space in the output buffer (see below
  78968. about the flush parameter).
  78969. Before the call of inflate(), the application should ensure that at least
  78970. one of the actions is possible, by providing more input and/or consuming
  78971. more output, and updating the next_* and avail_* values accordingly.
  78972. The application can consume the uncompressed output when it wants, for
  78973. example when the output buffer is full (avail_out == 0), or after each
  78974. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78975. must be called again after making room in the output buffer because there
  78976. might be more output pending.
  78977. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78978. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78979. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78980. if and when it gets to the next deflate block boundary. When decoding the
  78981. zlib or gzip format, this will cause inflate() to return immediately after
  78982. the header and before the first block. When doing a raw inflate, inflate()
  78983. will go ahead and process the first block, and will return when it gets to
  78984. the end of that block, or when it runs out of data.
  78985. The Z_BLOCK option assists in appending to or combining deflate streams.
  78986. Also to assist in this, on return inflate() will set strm->data_type to the
  78987. number of unused bits in the last byte taken from strm->next_in, plus 64
  78988. if inflate() is currently decoding the last block in the deflate stream,
  78989. plus 128 if inflate() returned immediately after decoding an end-of-block
  78990. code or decoding the complete header up to just before the first byte of the
  78991. deflate stream. The end-of-block will not be indicated until all of the
  78992. uncompressed data from that block has been written to strm->next_out. The
  78993. number of unused bits may in general be greater than seven, except when
  78994. bit 7 of data_type is set, in which case the number of unused bits will be
  78995. less than eight.
  78996. inflate() should normally be called until it returns Z_STREAM_END or an
  78997. error. However if all decompression is to be performed in a single step
  78998. (a single call of inflate), the parameter flush should be set to
  78999. Z_FINISH. In this case all pending input is processed and all pending
  79000. output is flushed; avail_out must be large enough to hold all the
  79001. uncompressed data. (The size of the uncompressed data may have been saved
  79002. by the compressor for this purpose.) The next operation on this stream must
  79003. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  79004. is never required, but can be used to inform inflate that a faster approach
  79005. may be used for the single inflate() call.
  79006. In this implementation, inflate() always flushes as much output as
  79007. possible to the output buffer, and always uses the faster approach on the
  79008. first call. So the only effect of the flush parameter in this implementation
  79009. is on the return value of inflate(), as noted below, or when it returns early
  79010. because Z_BLOCK is used.
  79011. If a preset dictionary is needed after this call (see inflateSetDictionary
  79012. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  79013. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  79014. strm->adler to the adler32 checksum of all output produced so far (that is,
  79015. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  79016. below. At the end of the stream, inflate() checks that its computed adler32
  79017. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  79018. only if the checksum is correct.
  79019. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  79020. deflate data. The header type is detected automatically. Any information
  79021. contained in the gzip header is not retained, so applications that need that
  79022. information should instead use raw inflate, see inflateInit2() below, or
  79023. inflateBack() and perform their own processing of the gzip header and
  79024. trailer.
  79025. inflate() returns Z_OK if some progress has been made (more input processed
  79026. or more output produced), Z_STREAM_END if the end of the compressed data has
  79027. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  79028. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  79029. corrupted (input stream not conforming to the zlib format or incorrect check
  79030. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  79031. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  79032. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  79033. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  79034. inflate() can be called again with more input and more output space to
  79035. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  79036. call inflateSync() to look for a good compression block if a partial recovery
  79037. of the data is desired.
  79038. */
  79039. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  79040. /*
  79041. All dynamically allocated data structures for this stream are freed.
  79042. This function discards any unprocessed input and does not flush any
  79043. pending output.
  79044. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  79045. was inconsistent. In the error case, msg may be set but then points to a
  79046. static string (which must not be deallocated).
  79047. */
  79048. /* Advanced functions */
  79049. /*
  79050. The following functions are needed only in some special applications.
  79051. */
  79052. /*
  79053. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  79054. int level,
  79055. int method,
  79056. int windowBits,
  79057. int memLevel,
  79058. int strategy));
  79059. This is another version of deflateInit with more compression options. The
  79060. fields next_in, zalloc, zfree and opaque must be initialized before by
  79061. the caller.
  79062. The method parameter is the compression method. It must be Z_DEFLATED in
  79063. this version of the library.
  79064. The windowBits parameter is the base two logarithm of the window size
  79065. (the size of the history buffer). It should be in the range 8..15 for this
  79066. version of the library. Larger values of this parameter result in better
  79067. compression at the expense of memory usage. The default value is 15 if
  79068. deflateInit is used instead.
  79069. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  79070. determines the window size. deflate() will then generate raw deflate data
  79071. with no zlib header or trailer, and will not compute an adler32 check value.
  79072. windowBits can also be greater than 15 for optional gzip encoding. Add
  79073. 16 to windowBits to write a simple gzip header and trailer around the
  79074. compressed data instead of a zlib wrapper. The gzip header will have no
  79075. file name, no extra data, no comment, no modification time (set to zero),
  79076. no header crc, and the operating system will be set to 255 (unknown). If a
  79077. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  79078. The memLevel parameter specifies how much memory should be allocated
  79079. for the internal compression state. memLevel=1 uses minimum memory but
  79080. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  79081. for optimal speed. The default value is 8. See zconf.h for total memory
  79082. usage as a function of windowBits and memLevel.
  79083. The strategy parameter is used to tune the compression algorithm. Use the
  79084. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  79085. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  79086. string match), or Z_RLE to limit match distances to one (run-length
  79087. encoding). Filtered data consists mostly of small values with a somewhat
  79088. random distribution. In this case, the compression algorithm is tuned to
  79089. compress them better. The effect of Z_FILTERED is to force more Huffman
  79090. coding and less string matching; it is somewhat intermediate between
  79091. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  79092. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  79093. parameter only affects the compression ratio but not the correctness of the
  79094. compressed output even if it is not set appropriately. Z_FIXED prevents the
  79095. use of dynamic Huffman codes, allowing for a simpler decoder for special
  79096. applications.
  79097. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79098. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  79099. method). msg is set to null if there is no error message. deflateInit2 does
  79100. not perform any compression: this will be done by deflate().
  79101. */
  79102. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  79103. const Bytef *dictionary,
  79104. uInt dictLength));
  79105. /*
  79106. Initializes the compression dictionary from the given byte sequence
  79107. without producing any compressed output. This function must be called
  79108. immediately after deflateInit, deflateInit2 or deflateReset, before any
  79109. call of deflate. The compressor and decompressor must use exactly the same
  79110. dictionary (see inflateSetDictionary).
  79111. The dictionary should consist of strings (byte sequences) that are likely
  79112. to be encountered later in the data to be compressed, with the most commonly
  79113. used strings preferably put towards the end of the dictionary. Using a
  79114. dictionary is most useful when the data to be compressed is short and can be
  79115. predicted with good accuracy; the data can then be compressed better than
  79116. with the default empty dictionary.
  79117. Depending on the size of the compression data structures selected by
  79118. deflateInit or deflateInit2, a part of the dictionary may in effect be
  79119. discarded, for example if the dictionary is larger than the window size in
  79120. deflate or deflate2. Thus the strings most likely to be useful should be
  79121. put at the end of the dictionary, not at the front. In addition, the
  79122. current implementation of deflate will use at most the window size minus
  79123. 262 bytes of the provided dictionary.
  79124. Upon return of this function, strm->adler is set to the adler32 value
  79125. of the dictionary; the decompressor may later use this value to determine
  79126. which dictionary has been used by the compressor. (The adler32 value
  79127. applies to the whole dictionary even if only a subset of the dictionary is
  79128. actually used by the compressor.) If a raw deflate was requested, then the
  79129. adler32 value is not computed and strm->adler is not set.
  79130. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  79131. parameter is invalid (such as NULL dictionary) or the stream state is
  79132. inconsistent (for example if deflate has already been called for this stream
  79133. or if the compression method is bsort). deflateSetDictionary does not
  79134. perform any compression: this will be done by deflate().
  79135. */
  79136. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  79137. z_streamp source));
  79138. /*
  79139. Sets the destination stream as a complete copy of the source stream.
  79140. This function can be useful when several compression strategies will be
  79141. tried, for example when there are several ways of pre-processing the input
  79142. data with a filter. The streams that will be discarded should then be freed
  79143. by calling deflateEnd. Note that deflateCopy duplicates the internal
  79144. compression state which can be quite large, so this strategy is slow and
  79145. can consume lots of memory.
  79146. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79147. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79148. (such as zalloc being NULL). msg is left unchanged in both source and
  79149. destination.
  79150. */
  79151. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  79152. /*
  79153. This function is equivalent to deflateEnd followed by deflateInit,
  79154. but does not free and reallocate all the internal compression state.
  79155. The stream will keep the same compression level and any other attributes
  79156. that may have been set by deflateInit2.
  79157. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79158. stream state was inconsistent (such as zalloc or state being NULL).
  79159. */
  79160. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  79161. int level,
  79162. int strategy));
  79163. /*
  79164. Dynamically update the compression level and compression strategy. The
  79165. interpretation of level and strategy is as in deflateInit2. This can be
  79166. used to switch between compression and straight copy of the input data, or
  79167. to switch to a different kind of input data requiring a different
  79168. strategy. If the compression level is changed, the input available so far
  79169. is compressed with the old level (and may be flushed); the new level will
  79170. take effect only at the next call of deflate().
  79171. Before the call of deflateParams, the stream state must be set as for
  79172. a call of deflate(), since the currently available input may have to
  79173. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  79174. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  79175. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  79176. if strm->avail_out was zero.
  79177. */
  79178. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  79179. int good_length,
  79180. int max_lazy,
  79181. int nice_length,
  79182. int max_chain));
  79183. /*
  79184. Fine tune deflate's internal compression parameters. This should only be
  79185. used by someone who understands the algorithm used by zlib's deflate for
  79186. searching for the best matching string, and even then only by the most
  79187. fanatic optimizer trying to squeeze out the last compressed bit for their
  79188. specific input data. Read the deflate.c source code for the meaning of the
  79189. max_lazy, good_length, nice_length, and max_chain parameters.
  79190. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79191. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79192. */
  79193. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79194. uLong sourceLen));
  79195. /*
  79196. deflateBound() returns an upper bound on the compressed size after
  79197. deflation of sourceLen bytes. It must be called after deflateInit()
  79198. or deflateInit2(). This would be used to allocate an output buffer
  79199. for deflation in a single pass, and so would be called before deflate().
  79200. */
  79201. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79202. int bits,
  79203. int value));
  79204. /*
  79205. deflatePrime() inserts bits in the deflate output stream. The intent
  79206. is that this function is used to start off the deflate output with the
  79207. bits leftover from a previous deflate stream when appending to it. As such,
  79208. this function can only be used for raw deflate, and must be used before the
  79209. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79210. less than or equal to 16, and that many of the least significant bits of
  79211. value will be inserted in the output.
  79212. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79213. stream state was inconsistent.
  79214. */
  79215. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79216. gz_headerp head));
  79217. /*
  79218. deflateSetHeader() provides gzip header information for when a gzip
  79219. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79220. after deflateInit2() or deflateReset() and before the first call of
  79221. deflate(). The text, time, os, extra field, name, and comment information
  79222. in the provided gz_header structure are written to the gzip header (xflag is
  79223. ignored -- the extra flags are set according to the compression level). The
  79224. caller must assure that, if not Z_NULL, name and comment are terminated with
  79225. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79226. available there. If hcrc is true, a gzip header crc is included. Note that
  79227. the current versions of the command-line version of gzip (up through version
  79228. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79229. gzip file" and give up.
  79230. If deflateSetHeader is not used, the default gzip header has text false,
  79231. the time set to zero, and os set to 255, with no extra, name, or comment
  79232. fields. The gzip header is returned to the default state by deflateReset().
  79233. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79234. stream state was inconsistent.
  79235. */
  79236. /*
  79237. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79238. int windowBits));
  79239. This is another version of inflateInit with an extra parameter. The
  79240. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79241. before by the caller.
  79242. The windowBits parameter is the base two logarithm of the maximum window
  79243. size (the size of the history buffer). It should be in the range 8..15 for
  79244. this version of the library. The default value is 15 if inflateInit is used
  79245. instead. windowBits must be greater than or equal to the windowBits value
  79246. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79247. deflateInit2() was not used. If a compressed stream with a larger window
  79248. size is given as input, inflate() will return with the error code
  79249. Z_DATA_ERROR instead of trying to allocate a larger window.
  79250. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79251. determines the window size. inflate() will then process raw deflate data,
  79252. not looking for a zlib or gzip header, not generating a check value, and not
  79253. looking for any check values for comparison at the end of the stream. This
  79254. is for use with other formats that use the deflate compressed data format
  79255. such as zip. Those formats provide their own check values. If a custom
  79256. format is developed using the raw deflate format for compressed data, it is
  79257. recommended that a check value such as an adler32 or a crc32 be applied to
  79258. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79259. most applications, the zlib format should be used as is. Note that comments
  79260. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79261. windowBits can also be greater than 15 for optional gzip decoding. Add
  79262. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79263. detection, or add 16 to decode only the gzip format (the zlib format will
  79264. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79265. a crc32 instead of an adler32.
  79266. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79267. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79268. is set to null if there is no error message. inflateInit2 does not perform
  79269. any decompression apart from reading the zlib header if present: this will
  79270. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79271. and avail_out are unchanged.)
  79272. */
  79273. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79274. const Bytef *dictionary,
  79275. uInt dictLength));
  79276. /*
  79277. Initializes the decompression dictionary from the given uncompressed byte
  79278. sequence. This function must be called immediately after a call of inflate,
  79279. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79280. can be determined from the adler32 value returned by that call of inflate.
  79281. The compressor and decompressor must use exactly the same dictionary (see
  79282. deflateSetDictionary). For raw inflate, this function can be called
  79283. immediately after inflateInit2() or inflateReset() and before any call of
  79284. inflate() to set the dictionary. The application must insure that the
  79285. dictionary that was used for compression is provided.
  79286. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79287. parameter is invalid (such as NULL dictionary) or the stream state is
  79288. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79289. expected one (incorrect adler32 value). inflateSetDictionary does not
  79290. perform any decompression: this will be done by subsequent calls of
  79291. inflate().
  79292. */
  79293. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79294. /*
  79295. Skips invalid compressed data until a full flush point (see above the
  79296. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79297. available input is skipped. No output is provided.
  79298. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79299. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79300. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79301. case, the application may save the current current value of total_in which
  79302. indicates where valid compressed data was found. In the error case, the
  79303. application may repeatedly call inflateSync, providing more input each time,
  79304. until success or end of the input data.
  79305. */
  79306. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79307. z_streamp source));
  79308. /*
  79309. Sets the destination stream as a complete copy of the source stream.
  79310. This function can be useful when randomly accessing a large stream. The
  79311. first pass through the stream can periodically record the inflate state,
  79312. allowing restarting inflate at those points when randomly accessing the
  79313. stream.
  79314. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79315. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79316. (such as zalloc being NULL). msg is left unchanged in both source and
  79317. destination.
  79318. */
  79319. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79320. /*
  79321. This function is equivalent to inflateEnd followed by inflateInit,
  79322. but does not free and reallocate all the internal decompression state.
  79323. The stream will keep attributes that may have been set by inflateInit2.
  79324. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79325. stream state was inconsistent (such as zalloc or state being NULL).
  79326. */
  79327. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79328. int bits,
  79329. int value));
  79330. /*
  79331. This function inserts bits in the inflate input stream. The intent is
  79332. that this function is used to start inflating at a bit position in the
  79333. middle of a byte. The provided bits will be used before any bytes are used
  79334. from next_in. This function should only be used with raw inflate, and
  79335. should be used before the first inflate() call after inflateInit2() or
  79336. inflateReset(). bits must be less than or equal to 16, and that many of the
  79337. least significant bits of value will be inserted in the input.
  79338. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79339. stream state was inconsistent.
  79340. */
  79341. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79342. gz_headerp head));
  79343. /*
  79344. inflateGetHeader() requests that gzip header information be stored in the
  79345. provided gz_header structure. inflateGetHeader() may be called after
  79346. inflateInit2() or inflateReset(), and before the first call of inflate().
  79347. As inflate() processes the gzip stream, head->done is zero until the header
  79348. is completed, at which time head->done is set to one. If a zlib stream is
  79349. being decoded, then head->done is set to -1 to indicate that there will be
  79350. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79351. force inflate() to return immediately after header processing is complete
  79352. and before any actual data is decompressed.
  79353. The text, time, xflags, and os fields are filled in with the gzip header
  79354. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79355. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79356. contains the maximum number of bytes to write to extra. Once done is true,
  79357. extra_len contains the actual extra field length, and extra contains the
  79358. extra field, or that field truncated if extra_max is less than extra_len.
  79359. If name is not Z_NULL, then up to name_max characters are written there,
  79360. terminated with a zero unless the length is greater than name_max. If
  79361. comment is not Z_NULL, then up to comm_max characters are written there,
  79362. terminated with a zero unless the length is greater than comm_max. When
  79363. any of extra, name, or comment are not Z_NULL and the respective field is
  79364. not present in the header, then that field is set to Z_NULL to signal its
  79365. absence. This allows the use of deflateSetHeader() with the returned
  79366. structure to duplicate the header. However if those fields are set to
  79367. allocated memory, then the application will need to save those pointers
  79368. elsewhere so that they can be eventually freed.
  79369. If inflateGetHeader is not used, then the header information is simply
  79370. discarded. The header is always checked for validity, including the header
  79371. CRC if present. inflateReset() will reset the process to discard the header
  79372. information. The application would need to call inflateGetHeader() again to
  79373. retrieve the header from the next gzip stream.
  79374. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79375. stream state was inconsistent.
  79376. */
  79377. /*
  79378. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79379. unsigned char FAR *window));
  79380. Initialize the internal stream state for decompression using inflateBack()
  79381. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79382. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79383. derived memory allocation routines are used. windowBits is the base two
  79384. logarithm of the window size, in the range 8..15. window is a caller
  79385. supplied buffer of that size. Except for special applications where it is
  79386. assured that deflate was used with small window sizes, windowBits must be 15
  79387. and a 32K byte window must be supplied to be able to decompress general
  79388. deflate streams.
  79389. See inflateBack() for the usage of these routines.
  79390. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79391. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79392. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79393. match the version of the header file.
  79394. */
  79395. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79396. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79397. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79398. in_func in, void FAR *in_desc,
  79399. out_func out, void FAR *out_desc));
  79400. /*
  79401. inflateBack() does a raw inflate with a single call using a call-back
  79402. interface for input and output. This is more efficient than inflate() for
  79403. file i/o applications in that it avoids copying between the output and the
  79404. sliding window by simply making the window itself the output buffer. This
  79405. function trusts the application to not change the output buffer passed by
  79406. the output function, at least until inflateBack() returns.
  79407. inflateBackInit() must be called first to allocate the internal state
  79408. and to initialize the state with the user-provided window buffer.
  79409. inflateBack() may then be used multiple times to inflate a complete, raw
  79410. deflate stream with each call. inflateBackEnd() is then called to free
  79411. the allocated state.
  79412. A raw deflate stream is one with no zlib or gzip header or trailer.
  79413. This routine would normally be used in a utility that reads zip or gzip
  79414. files and writes out uncompressed files. The utility would decode the
  79415. header and process the trailer on its own, hence this routine expects
  79416. only the raw deflate stream to decompress. This is different from the
  79417. normal behavior of inflate(), which expects either a zlib or gzip header and
  79418. trailer around the deflate stream.
  79419. inflateBack() uses two subroutines supplied by the caller that are then
  79420. called by inflateBack() for input and output. inflateBack() calls those
  79421. routines until it reads a complete deflate stream and writes out all of the
  79422. uncompressed data, or until it encounters an error. The function's
  79423. parameters and return types are defined above in the in_func and out_func
  79424. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79425. number of bytes of provided input, and a pointer to that input in buf. If
  79426. there is no input available, in() must return zero--buf is ignored in that
  79427. case--and inflateBack() will return a buffer error. inflateBack() will call
  79428. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79429. should return zero on success, or non-zero on failure. If out() returns
  79430. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79431. are permitted to change the contents of the window provided to
  79432. inflateBackInit(), which is also the buffer that out() uses to write from.
  79433. The length written by out() will be at most the window size. Any non-zero
  79434. amount of input may be provided by in().
  79435. For convenience, inflateBack() can be provided input on the first call by
  79436. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79437. in() will be called. Therefore strm->next_in must be initialized before
  79438. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79439. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79440. must also be initialized, and then if strm->avail_in is not zero, input will
  79441. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79442. The in_desc and out_desc parameters of inflateBack() is passed as the
  79443. first parameter of in() and out() respectively when they are called. These
  79444. descriptors can be optionally used to pass any information that the caller-
  79445. supplied in() and out() functions need to do their job.
  79446. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79447. pass back any unused input that was provided by the last in() call. The
  79448. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79449. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79450. error in the deflate stream (in which case strm->msg is set to indicate the
  79451. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79452. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79453. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79454. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79455. out() returning non-zero. (in() will always be called before out(), so
  79456. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79457. that inflateBack() cannot return Z_OK.
  79458. */
  79459. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79460. /*
  79461. All memory allocated by inflateBackInit() is freed.
  79462. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79463. state was inconsistent.
  79464. */
  79465. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79466. /* Return flags indicating compile-time options.
  79467. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79468. 1.0: size of uInt
  79469. 3.2: size of uLong
  79470. 5.4: size of voidpf (pointer)
  79471. 7.6: size of z_off_t
  79472. Compiler, assembler, and debug options:
  79473. 8: DEBUG
  79474. 9: ASMV or ASMINF -- use ASM code
  79475. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79476. 11: 0 (reserved)
  79477. One-time table building (smaller code, but not thread-safe if true):
  79478. 12: BUILDFIXED -- build static block decoding tables when needed
  79479. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79480. 14,15: 0 (reserved)
  79481. Library content (indicates missing functionality):
  79482. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79483. deflate code when not needed)
  79484. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79485. and decode gzip streams (to avoid linking crc code)
  79486. 18-19: 0 (reserved)
  79487. Operation variations (changes in library functionality):
  79488. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79489. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79490. 22,23: 0 (reserved)
  79491. The sprintf variant used by gzprintf (zero is best):
  79492. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79493. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79494. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79495. Remainder:
  79496. 27-31: 0 (reserved)
  79497. */
  79498. /* utility functions */
  79499. /*
  79500. The following utility functions are implemented on top of the
  79501. basic stream-oriented functions. To simplify the interface, some
  79502. default options are assumed (compression level and memory usage,
  79503. standard memory allocation functions). The source code of these
  79504. utility functions can easily be modified if you need special options.
  79505. */
  79506. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79507. const Bytef *source, uLong sourceLen));
  79508. /*
  79509. Compresses the source buffer into the destination buffer. sourceLen is
  79510. the byte length of the source buffer. Upon entry, destLen is the total
  79511. size of the destination buffer, which must be at least the value returned
  79512. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79513. compressed buffer.
  79514. This function can be used to compress a whole file at once if the
  79515. input file is mmap'ed.
  79516. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79517. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79518. buffer.
  79519. */
  79520. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79521. const Bytef *source, uLong sourceLen,
  79522. int level));
  79523. /*
  79524. Compresses the source buffer into the destination buffer. The level
  79525. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79526. length of the source buffer. Upon entry, destLen is the total size of the
  79527. destination buffer, which must be at least the value returned by
  79528. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79529. compressed buffer.
  79530. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79531. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79532. Z_STREAM_ERROR if the level parameter is invalid.
  79533. */
  79534. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79535. /*
  79536. compressBound() returns an upper bound on the compressed size after
  79537. compress() or compress2() on sourceLen bytes. It would be used before
  79538. a compress() or compress2() call to allocate the destination buffer.
  79539. */
  79540. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79541. const Bytef *source, uLong sourceLen));
  79542. /*
  79543. Decompresses the source buffer into the destination buffer. sourceLen is
  79544. the byte length of the source buffer. Upon entry, destLen is the total
  79545. size of the destination buffer, which must be large enough to hold the
  79546. entire uncompressed data. (The size of the uncompressed data must have
  79547. been saved previously by the compressor and transmitted to the decompressor
  79548. by some mechanism outside the scope of this compression library.)
  79549. Upon exit, destLen is the actual size of the compressed buffer.
  79550. This function can be used to decompress a whole file at once if the
  79551. input file is mmap'ed.
  79552. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79553. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79554. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79555. */
  79556. typedef voidp gzFile;
  79557. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79558. /*
  79559. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79560. is as in fopen ("rb" or "wb") but can also include a compression level
  79561. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79562. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79563. as in "wb1R". (See the description of deflateInit2 for more information
  79564. about the strategy parameter.)
  79565. gzopen can be used to read a file which is not in gzip format; in this
  79566. case gzread will directly read from the file without decompression.
  79567. gzopen returns NULL if the file could not be opened or if there was
  79568. insufficient memory to allocate the (de)compression state; errno
  79569. can be checked to distinguish the two cases (if errno is zero, the
  79570. zlib error is Z_MEM_ERROR). */
  79571. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79572. /*
  79573. gzdopen() associates a gzFile with the file descriptor fd. File
  79574. descriptors are obtained from calls like open, dup, creat, pipe or
  79575. fileno (in the file has been previously opened with fopen).
  79576. The mode parameter is as in gzopen.
  79577. The next call of gzclose on the returned gzFile will also close the
  79578. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79579. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79580. gzdopen returns NULL if there was insufficient memory to allocate
  79581. the (de)compression state.
  79582. */
  79583. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79584. /*
  79585. Dynamically update the compression level or strategy. See the description
  79586. of deflateInit2 for the meaning of these parameters.
  79587. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79588. opened for writing.
  79589. */
  79590. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79591. /*
  79592. Reads the given number of uncompressed bytes from the compressed file.
  79593. If the input file was not in gzip format, gzread copies the given number
  79594. of bytes into the buffer.
  79595. gzread returns the number of uncompressed bytes actually read (0 for
  79596. end of file, -1 for error). */
  79597. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79598. voidpc buf, unsigned len));
  79599. /*
  79600. Writes the given number of uncompressed bytes into the compressed file.
  79601. gzwrite returns the number of uncompressed bytes actually written
  79602. (0 in case of error).
  79603. */
  79604. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79605. /*
  79606. Converts, formats, and writes the args to the compressed file under
  79607. control of the format string, as in fprintf. gzprintf returns the number of
  79608. uncompressed bytes actually written (0 in case of error). The number of
  79609. uncompressed bytes written is limited to 4095. The caller should assure that
  79610. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79611. return an error (0) with nothing written. In this case, there may also be a
  79612. buffer overflow with unpredictable consequences, which is possible only if
  79613. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79614. because the secure snprintf() or vsnprintf() functions were not available.
  79615. */
  79616. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79617. /*
  79618. Writes the given null-terminated string to the compressed file, excluding
  79619. the terminating null character.
  79620. gzputs returns the number of characters written, or -1 in case of error.
  79621. */
  79622. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79623. /*
  79624. Reads bytes from the compressed file until len-1 characters are read, or
  79625. a newline character is read and transferred to buf, or an end-of-file
  79626. condition is encountered. The string is then terminated with a null
  79627. character.
  79628. gzgets returns buf, or Z_NULL in case of error.
  79629. */
  79630. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79631. /*
  79632. Writes c, converted to an unsigned char, into the compressed file.
  79633. gzputc returns the value that was written, or -1 in case of error.
  79634. */
  79635. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79636. /*
  79637. Reads one byte from the compressed file. gzgetc returns this byte
  79638. or -1 in case of end of file or error.
  79639. */
  79640. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79641. /*
  79642. Push one character back onto the stream to be read again later.
  79643. Only one character of push-back is allowed. gzungetc() returns the
  79644. character pushed, or -1 on failure. gzungetc() will fail if a
  79645. character has been pushed but not read yet, or if c is -1. The pushed
  79646. character will be discarded if the stream is repositioned with gzseek()
  79647. or gzrewind().
  79648. */
  79649. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79650. /*
  79651. Flushes all pending output into the compressed file. The parameter
  79652. flush is as in the deflate() function. The return value is the zlib
  79653. error number (see function gzerror below). gzflush returns Z_OK if
  79654. the flush parameter is Z_FINISH and all output could be flushed.
  79655. gzflush should be called only when strictly necessary because it can
  79656. degrade compression.
  79657. */
  79658. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79659. z_off_t offset, int whence));
  79660. /*
  79661. Sets the starting position for the next gzread or gzwrite on the
  79662. given compressed file. The offset represents a number of bytes in the
  79663. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79664. the value SEEK_END is not supported.
  79665. If the file is opened for reading, this function is emulated but can be
  79666. extremely slow. If the file is opened for writing, only forward seeks are
  79667. supported; gzseek then compresses a sequence of zeroes up to the new
  79668. starting position.
  79669. gzseek returns the resulting offset location as measured in bytes from
  79670. the beginning of the uncompressed stream, or -1 in case of error, in
  79671. particular if the file is opened for writing and the new starting position
  79672. would be before the current position.
  79673. */
  79674. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79675. /*
  79676. Rewinds the given file. This function is supported only for reading.
  79677. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79678. */
  79679. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79680. /*
  79681. Returns the starting position for the next gzread or gzwrite on the
  79682. given compressed file. This position represents a number of bytes in the
  79683. uncompressed data stream.
  79684. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79685. */
  79686. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79687. /*
  79688. Returns 1 when EOF has previously been detected reading the given
  79689. input stream, otherwise zero.
  79690. */
  79691. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79692. /*
  79693. Returns 1 if file is being read directly without decompression, otherwise
  79694. zero.
  79695. */
  79696. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79697. /*
  79698. Flushes all pending output if necessary, closes the compressed file
  79699. and deallocates all the (de)compression state. The return value is the zlib
  79700. error number (see function gzerror below).
  79701. */
  79702. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79703. /*
  79704. Returns the error message for the last error which occurred on the
  79705. given compressed file. errnum is set to zlib error number. If an
  79706. error occurred in the file system and not in the compression library,
  79707. errnum is set to Z_ERRNO and the application may consult errno
  79708. to get the exact error code.
  79709. */
  79710. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79711. /*
  79712. Clears the error and end-of-file flags for file. This is analogous to the
  79713. clearerr() function in stdio. This is useful for continuing to read a gzip
  79714. file that is being written concurrently.
  79715. */
  79716. /* checksum functions */
  79717. /*
  79718. These functions are not related to compression but are exported
  79719. anyway because they might be useful in applications using the
  79720. compression library.
  79721. */
  79722. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79723. /*
  79724. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79725. return the updated checksum. If buf is NULL, this function returns
  79726. the required initial value for the checksum.
  79727. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79728. much faster. Usage example:
  79729. uLong adler = adler32(0L, Z_NULL, 0);
  79730. while (read_buffer(buffer, length) != EOF) {
  79731. adler = adler32(adler, buffer, length);
  79732. }
  79733. if (adler != original_adler) error();
  79734. */
  79735. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79736. z_off_t len2));
  79737. /*
  79738. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79739. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79740. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79741. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79742. */
  79743. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79744. /*
  79745. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79746. updated CRC-32. If buf is NULL, this function returns the required initial
  79747. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79748. performed within this function so it shouldn't be done by the application.
  79749. Usage example:
  79750. uLong crc = crc32(0L, Z_NULL, 0);
  79751. while (read_buffer(buffer, length) != EOF) {
  79752. crc = crc32(crc, buffer, length);
  79753. }
  79754. if (crc != original_crc) error();
  79755. */
  79756. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79757. /*
  79758. Combine two CRC-32 check values into one. For two sequences of bytes,
  79759. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79760. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79761. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79762. len2.
  79763. */
  79764. /* various hacks, don't look :) */
  79765. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79766. * and the compiler's view of z_stream:
  79767. */
  79768. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79769. const char *version, int stream_size));
  79770. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79771. const char *version, int stream_size));
  79772. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79773. int windowBits, int memLevel,
  79774. int strategy, const char *version,
  79775. int stream_size));
  79776. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79777. const char *version, int stream_size));
  79778. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79779. unsigned char FAR *window,
  79780. const char *version,
  79781. int stream_size));
  79782. #define deflateInit(strm, level) \
  79783. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79784. #define inflateInit(strm) \
  79785. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79786. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79787. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79788. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79789. #define inflateInit2(strm, windowBits) \
  79790. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79791. #define inflateBackInit(strm, windowBits, window) \
  79792. inflateBackInit_((strm), (windowBits), (window), \
  79793. ZLIB_VERSION, sizeof(z_stream))
  79794. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79795. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79796. #endif
  79797. ZEXTERN const char * ZEXPORT zError OF((int));
  79798. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79799. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79800. #ifdef __cplusplus
  79801. //}
  79802. #endif
  79803. #endif /* ZLIB_H */
  79804. /*** End of inlined file: zlib.h ***/
  79805. #undef OS_CODE
  79806. #else
  79807. #include <zlib.h>
  79808. #endif
  79809. }
  79810. BEGIN_JUCE_NAMESPACE
  79811. // internal helper object that holds the zlib structures so they don't have to be
  79812. // included publicly.
  79813. class GZIPCompressorHelper
  79814. {
  79815. public:
  79816. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79817. : data (0),
  79818. dataSize (0),
  79819. compLevel (compressionLevel),
  79820. strategy (0),
  79821. setParams (true),
  79822. streamIsValid (false),
  79823. finished (false),
  79824. shouldFinish (false)
  79825. {
  79826. using namespace zlibNamespace;
  79827. zerostruct (stream);
  79828. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79829. nowrap ? -MAX_WBITS : MAX_WBITS,
  79830. 8, strategy) == Z_OK);
  79831. }
  79832. ~GZIPCompressorHelper()
  79833. {
  79834. using namespace zlibNamespace;
  79835. if (streamIsValid)
  79836. deflateEnd (&stream);
  79837. }
  79838. bool needsInput() const throw()
  79839. {
  79840. return dataSize <= 0;
  79841. }
  79842. void setInput (const uint8* const newData, const int size) throw()
  79843. {
  79844. data = newData;
  79845. dataSize = size;
  79846. }
  79847. int doNextBlock (uint8* const dest, const int destSize) throw()
  79848. {
  79849. using namespace zlibNamespace;
  79850. if (streamIsValid)
  79851. {
  79852. stream.next_in = const_cast <uint8*> (data);
  79853. stream.next_out = dest;
  79854. stream.avail_in = dataSize;
  79855. stream.avail_out = destSize;
  79856. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79857. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79858. setParams = false;
  79859. switch (result)
  79860. {
  79861. case Z_STREAM_END:
  79862. finished = true;
  79863. // Deliberate fall-through..
  79864. case Z_OK:
  79865. data += dataSize - stream.avail_in;
  79866. dataSize = stream.avail_in;
  79867. return destSize - stream.avail_out;
  79868. default:
  79869. break;
  79870. }
  79871. }
  79872. return 0;
  79873. }
  79874. private:
  79875. zlibNamespace::z_stream stream;
  79876. const uint8* data;
  79877. int dataSize, compLevel, strategy;
  79878. bool setParams, streamIsValid;
  79879. public:
  79880. bool finished, shouldFinish;
  79881. };
  79882. const int gzipCompBufferSize = 32768;
  79883. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79884. int compressionLevel,
  79885. const bool deleteDestStream,
  79886. const bool noWrap)
  79887. : destStream (destStream_),
  79888. streamToDelete (deleteDestStream ? destStream_ : 0),
  79889. buffer (gzipCompBufferSize)
  79890. {
  79891. if (compressionLevel < 1 || compressionLevel > 9)
  79892. compressionLevel = -1;
  79893. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79894. }
  79895. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79896. {
  79897. flush();
  79898. }
  79899. void GZIPCompressorOutputStream::flush()
  79900. {
  79901. if (! helper->finished)
  79902. {
  79903. helper->shouldFinish = true;
  79904. while (! helper->finished)
  79905. doNextBlock();
  79906. }
  79907. destStream->flush();
  79908. }
  79909. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79910. {
  79911. if (! helper->finished)
  79912. {
  79913. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79914. while (! helper->needsInput())
  79915. {
  79916. if (! doNextBlock())
  79917. return false;
  79918. }
  79919. }
  79920. return true;
  79921. }
  79922. bool GZIPCompressorOutputStream::doNextBlock()
  79923. {
  79924. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79925. if (len > 0)
  79926. return destStream->write (buffer, len);
  79927. else
  79928. return true;
  79929. }
  79930. int64 GZIPCompressorOutputStream::getPosition()
  79931. {
  79932. return destStream->getPosition();
  79933. }
  79934. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79935. {
  79936. jassertfalse; // can't do it!
  79937. return false;
  79938. }
  79939. END_JUCE_NAMESPACE
  79940. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79941. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79942. #if JUCE_MSVC
  79943. #pragma warning (push)
  79944. #pragma warning (disable: 4309 4305)
  79945. #endif
  79946. namespace zlibNamespace
  79947. {
  79948. #if JUCE_INCLUDE_ZLIB_CODE
  79949. #undef OS_CODE
  79950. #undef fdopen
  79951. #define ZLIB_INTERNAL
  79952. #define NO_DUMMY_DECL
  79953. /*** Start of inlined file: adler32.c ***/
  79954. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79955. #define ZLIB_INTERNAL
  79956. #define BASE 65521UL /* largest prime smaller than 65536 */
  79957. #define NMAX 5552
  79958. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79959. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79960. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79961. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79962. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79963. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79964. /* use NO_DIVIDE if your processor does not do division in hardware */
  79965. #ifdef NO_DIVIDE
  79966. # define MOD(a) \
  79967. do { \
  79968. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79969. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79970. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79971. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79972. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79973. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79974. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79975. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79976. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79977. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79978. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79979. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79980. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79981. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79982. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79983. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79984. if (a >= BASE) a -= BASE; \
  79985. } while (0)
  79986. # define MOD4(a) \
  79987. do { \
  79988. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79989. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79990. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79991. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79992. if (a >= BASE) a -= BASE; \
  79993. } while (0)
  79994. #else
  79995. # define MOD(a) a %= BASE
  79996. # define MOD4(a) a %= BASE
  79997. #endif
  79998. /* ========================================================================= */
  79999. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  80000. {
  80001. unsigned long sum2;
  80002. unsigned n;
  80003. /* split Adler-32 into component sums */
  80004. sum2 = (adler >> 16) & 0xffff;
  80005. adler &= 0xffff;
  80006. /* in case user likes doing a byte at a time, keep it fast */
  80007. if (len == 1) {
  80008. adler += buf[0];
  80009. if (adler >= BASE)
  80010. adler -= BASE;
  80011. sum2 += adler;
  80012. if (sum2 >= BASE)
  80013. sum2 -= BASE;
  80014. return adler | (sum2 << 16);
  80015. }
  80016. /* initial Adler-32 value (deferred check for len == 1 speed) */
  80017. if (buf == Z_NULL)
  80018. return 1L;
  80019. /* in case short lengths are provided, keep it somewhat fast */
  80020. if (len < 16) {
  80021. while (len--) {
  80022. adler += *buf++;
  80023. sum2 += adler;
  80024. }
  80025. if (adler >= BASE)
  80026. adler -= BASE;
  80027. MOD4(sum2); /* only added so many BASE's */
  80028. return adler | (sum2 << 16);
  80029. }
  80030. /* do length NMAX blocks -- requires just one modulo operation */
  80031. while (len >= NMAX) {
  80032. len -= NMAX;
  80033. n = NMAX / 16; /* NMAX is divisible by 16 */
  80034. do {
  80035. DO16(buf); /* 16 sums unrolled */
  80036. buf += 16;
  80037. } while (--n);
  80038. MOD(adler);
  80039. MOD(sum2);
  80040. }
  80041. /* do remaining bytes (less than NMAX, still just one modulo) */
  80042. if (len) { /* avoid modulos if none remaining */
  80043. while (len >= 16) {
  80044. len -= 16;
  80045. DO16(buf);
  80046. buf += 16;
  80047. }
  80048. while (len--) {
  80049. adler += *buf++;
  80050. sum2 += adler;
  80051. }
  80052. MOD(adler);
  80053. MOD(sum2);
  80054. }
  80055. /* return recombined sums */
  80056. return adler | (sum2 << 16);
  80057. }
  80058. /* ========================================================================= */
  80059. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  80060. {
  80061. unsigned long sum1;
  80062. unsigned long sum2;
  80063. unsigned rem;
  80064. /* the derivation of this formula is left as an exercise for the reader */
  80065. rem = (unsigned)(len2 % BASE);
  80066. sum1 = adler1 & 0xffff;
  80067. sum2 = rem * sum1;
  80068. MOD(sum2);
  80069. sum1 += (adler2 & 0xffff) + BASE - 1;
  80070. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  80071. if (sum1 > BASE) sum1 -= BASE;
  80072. if (sum1 > BASE) sum1 -= BASE;
  80073. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  80074. if (sum2 > BASE) sum2 -= BASE;
  80075. return sum1 | (sum2 << 16);
  80076. }
  80077. /*** End of inlined file: adler32.c ***/
  80078. /*** Start of inlined file: compress.c ***/
  80079. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80080. #define ZLIB_INTERNAL
  80081. /* ===========================================================================
  80082. Compresses the source buffer into the destination buffer. The level
  80083. parameter has the same meaning as in deflateInit. sourceLen is the byte
  80084. length of the source buffer. Upon entry, destLen is the total size of the
  80085. destination buffer, which must be at least 0.1% larger than sourceLen plus
  80086. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  80087. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  80088. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  80089. Z_STREAM_ERROR if the level parameter is invalid.
  80090. */
  80091. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  80092. uLong sourceLen, int level)
  80093. {
  80094. z_stream stream;
  80095. int err;
  80096. stream.next_in = (Bytef*)source;
  80097. stream.avail_in = (uInt)sourceLen;
  80098. #ifdef MAXSEG_64K
  80099. /* Check for source > 64K on 16-bit machine: */
  80100. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  80101. #endif
  80102. stream.next_out = dest;
  80103. stream.avail_out = (uInt)*destLen;
  80104. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80105. stream.zalloc = (alloc_func)0;
  80106. stream.zfree = (free_func)0;
  80107. stream.opaque = (voidpf)0;
  80108. err = deflateInit(&stream, level);
  80109. if (err != Z_OK) return err;
  80110. err = deflate(&stream, Z_FINISH);
  80111. if (err != Z_STREAM_END) {
  80112. deflateEnd(&stream);
  80113. return err == Z_OK ? Z_BUF_ERROR : err;
  80114. }
  80115. *destLen = stream.total_out;
  80116. err = deflateEnd(&stream);
  80117. return err;
  80118. }
  80119. /* ===========================================================================
  80120. */
  80121. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  80122. {
  80123. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  80124. }
  80125. /* ===========================================================================
  80126. If the default memLevel or windowBits for deflateInit() is changed, then
  80127. this function needs to be updated.
  80128. */
  80129. uLong ZEXPORT compressBound (uLong sourceLen)
  80130. {
  80131. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  80132. }
  80133. /*** End of inlined file: compress.c ***/
  80134. #undef DO1
  80135. #undef DO8
  80136. /*** Start of inlined file: crc32.c ***/
  80137. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80138. /*
  80139. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  80140. protection on the static variables used to control the first-use generation
  80141. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  80142. first call get_crc_table() to initialize the tables before allowing more than
  80143. one thread to use crc32().
  80144. */
  80145. #ifdef MAKECRCH
  80146. # include <stdio.h>
  80147. # ifndef DYNAMIC_CRC_TABLE
  80148. # define DYNAMIC_CRC_TABLE
  80149. # endif /* !DYNAMIC_CRC_TABLE */
  80150. #endif /* MAKECRCH */
  80151. /*** Start of inlined file: zutil.h ***/
  80152. /* WARNING: this file should *not* be used by applications. It is
  80153. part of the implementation of the compression library and is
  80154. subject to change. Applications should only use zlib.h.
  80155. */
  80156. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80157. #ifndef ZUTIL_H
  80158. #define ZUTIL_H
  80159. #define ZLIB_INTERNAL
  80160. #ifdef STDC
  80161. # ifndef _WIN32_WCE
  80162. # include <stddef.h>
  80163. # endif
  80164. # include <string.h>
  80165. # include <stdlib.h>
  80166. #endif
  80167. #ifdef NO_ERRNO_H
  80168. # ifdef _WIN32_WCE
  80169. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80170. * errno. We define it as a global variable to simplify porting.
  80171. * Its value is always 0 and should not be used. We rename it to
  80172. * avoid conflict with other libraries that use the same workaround.
  80173. */
  80174. # define errno z_errno
  80175. # endif
  80176. extern int errno;
  80177. #else
  80178. # ifndef _WIN32_WCE
  80179. # include <errno.h>
  80180. # endif
  80181. #endif
  80182. #ifndef local
  80183. # define local static
  80184. #endif
  80185. /* compile with -Dlocal if your debugger can't find static symbols */
  80186. typedef unsigned char uch;
  80187. typedef uch FAR uchf;
  80188. typedef unsigned short ush;
  80189. typedef ush FAR ushf;
  80190. typedef unsigned long ulg;
  80191. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80192. /* (size given to avoid silly warnings with Visual C++) */
  80193. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80194. #define ERR_RETURN(strm,err) \
  80195. return (strm->msg = (char*)ERR_MSG(err), (err))
  80196. /* To be used only when the state is known to be valid */
  80197. /* common constants */
  80198. #ifndef DEF_WBITS
  80199. # define DEF_WBITS MAX_WBITS
  80200. #endif
  80201. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80202. #if MAX_MEM_LEVEL >= 8
  80203. # define DEF_MEM_LEVEL 8
  80204. #else
  80205. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80206. #endif
  80207. /* default memLevel */
  80208. #define STORED_BLOCK 0
  80209. #define STATIC_TREES 1
  80210. #define DYN_TREES 2
  80211. /* The three kinds of block type */
  80212. #define MIN_MATCH 3
  80213. #define MAX_MATCH 258
  80214. /* The minimum and maximum match lengths */
  80215. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80216. /* target dependencies */
  80217. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80218. # define OS_CODE 0x00
  80219. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80220. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80221. /* Allow compilation with ANSI keywords only enabled */
  80222. void _Cdecl farfree( void *block );
  80223. void *_Cdecl farmalloc( unsigned long nbytes );
  80224. # else
  80225. # include <alloc.h>
  80226. # endif
  80227. # else /* MSC or DJGPP */
  80228. # include <malloc.h>
  80229. # endif
  80230. #endif
  80231. #ifdef AMIGA
  80232. # define OS_CODE 0x01
  80233. #endif
  80234. #if defined(VAXC) || defined(VMS)
  80235. # define OS_CODE 0x02
  80236. # define F_OPEN(name, mode) \
  80237. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80238. #endif
  80239. #if defined(ATARI) || defined(atarist)
  80240. # define OS_CODE 0x05
  80241. #endif
  80242. #ifdef OS2
  80243. # define OS_CODE 0x06
  80244. # ifdef M_I86
  80245. #include <malloc.h>
  80246. # endif
  80247. #endif
  80248. #if defined(MACOS) || TARGET_OS_MAC
  80249. # define OS_CODE 0x07
  80250. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80251. # include <unix.h> /* for fdopen */
  80252. # else
  80253. # ifndef fdopen
  80254. # define fdopen(fd,mode) NULL /* No fdopen() */
  80255. # endif
  80256. # endif
  80257. #endif
  80258. #ifdef TOPS20
  80259. # define OS_CODE 0x0a
  80260. #endif
  80261. #ifdef WIN32
  80262. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80263. # define OS_CODE 0x0b
  80264. # endif
  80265. #endif
  80266. #ifdef __50SERIES /* Prime/PRIMOS */
  80267. # define OS_CODE 0x0f
  80268. #endif
  80269. #if defined(_BEOS_) || defined(RISCOS)
  80270. # define fdopen(fd,mode) NULL /* No fdopen() */
  80271. #endif
  80272. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80273. # if defined(_WIN32_WCE)
  80274. # define fdopen(fd,mode) NULL /* No fdopen() */
  80275. # ifndef _PTRDIFF_T_DEFINED
  80276. typedef int ptrdiff_t;
  80277. # define _PTRDIFF_T_DEFINED
  80278. # endif
  80279. # else
  80280. # define fdopen(fd,type) _fdopen(fd,type)
  80281. # endif
  80282. #endif
  80283. /* common defaults */
  80284. #ifndef OS_CODE
  80285. # define OS_CODE 0x03 /* assume Unix */
  80286. #endif
  80287. #ifndef F_OPEN
  80288. # define F_OPEN(name, mode) fopen((name), (mode))
  80289. #endif
  80290. /* functions */
  80291. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80292. # ifndef HAVE_VSNPRINTF
  80293. # define HAVE_VSNPRINTF
  80294. # endif
  80295. #endif
  80296. #if defined(__CYGWIN__)
  80297. # ifndef HAVE_VSNPRINTF
  80298. # define HAVE_VSNPRINTF
  80299. # endif
  80300. #endif
  80301. #ifndef HAVE_VSNPRINTF
  80302. # ifdef MSDOS
  80303. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80304. but for now we just assume it doesn't. */
  80305. # define NO_vsnprintf
  80306. # endif
  80307. # ifdef __TURBOC__
  80308. # define NO_vsnprintf
  80309. # endif
  80310. # ifdef WIN32
  80311. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80312. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80313. # define vsnprintf _vsnprintf
  80314. # endif
  80315. # endif
  80316. # ifdef __SASC
  80317. # define NO_vsnprintf
  80318. # endif
  80319. #endif
  80320. #ifdef VMS
  80321. # define NO_vsnprintf
  80322. #endif
  80323. #if defined(pyr)
  80324. # define NO_MEMCPY
  80325. #endif
  80326. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80327. /* Use our own functions for small and medium model with MSC <= 5.0.
  80328. * You may have to use the same strategy for Borland C (untested).
  80329. * The __SC__ check is for Symantec.
  80330. */
  80331. # define NO_MEMCPY
  80332. #endif
  80333. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80334. # define HAVE_MEMCPY
  80335. #endif
  80336. #ifdef HAVE_MEMCPY
  80337. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80338. # define zmemcpy _fmemcpy
  80339. # define zmemcmp _fmemcmp
  80340. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80341. # else
  80342. # define zmemcpy memcpy
  80343. # define zmemcmp memcmp
  80344. # define zmemzero(dest, len) memset(dest, 0, len)
  80345. # endif
  80346. #else
  80347. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80348. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80349. extern void zmemzero OF((Bytef* dest, uInt len));
  80350. #endif
  80351. /* Diagnostic functions */
  80352. #ifdef DEBUG
  80353. # include <stdio.h>
  80354. extern int z_verbose;
  80355. extern void z_error OF((const char *m));
  80356. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80357. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80358. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80359. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80360. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80361. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80362. #else
  80363. # define Assert(cond,msg)
  80364. # define Trace(x)
  80365. # define Tracev(x)
  80366. # define Tracevv(x)
  80367. # define Tracec(c,x)
  80368. # define Tracecv(c,x)
  80369. #endif
  80370. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80371. void zcfree OF((voidpf opaque, voidpf ptr));
  80372. #define ZALLOC(strm, items, size) \
  80373. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80374. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80375. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80376. #endif /* ZUTIL_H */
  80377. /*** End of inlined file: zutil.h ***/
  80378. /* for STDC and FAR definitions */
  80379. #define local static
  80380. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80381. #ifndef NOBYFOUR
  80382. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80383. # include <limits.h>
  80384. # define BYFOUR
  80385. # if (UINT_MAX == 0xffffffffUL)
  80386. typedef unsigned int u4;
  80387. # else
  80388. # if (ULONG_MAX == 0xffffffffUL)
  80389. typedef unsigned long u4;
  80390. # else
  80391. # if (USHRT_MAX == 0xffffffffUL)
  80392. typedef unsigned short u4;
  80393. # else
  80394. # undef BYFOUR /* can't find a four-byte integer type! */
  80395. # endif
  80396. # endif
  80397. # endif
  80398. # endif /* STDC */
  80399. #endif /* !NOBYFOUR */
  80400. /* Definitions for doing the crc four data bytes at a time. */
  80401. #ifdef BYFOUR
  80402. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80403. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80404. local unsigned long crc32_little OF((unsigned long,
  80405. const unsigned char FAR *, unsigned));
  80406. local unsigned long crc32_big OF((unsigned long,
  80407. const unsigned char FAR *, unsigned));
  80408. # define TBLS 8
  80409. #else
  80410. # define TBLS 1
  80411. #endif /* BYFOUR */
  80412. /* Local functions for crc concatenation */
  80413. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80414. unsigned long vec));
  80415. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80416. #ifdef DYNAMIC_CRC_TABLE
  80417. local volatile int crc_table_empty = 1;
  80418. local unsigned long FAR crc_table[TBLS][256];
  80419. local void make_crc_table OF((void));
  80420. #ifdef MAKECRCH
  80421. local void write_table OF((FILE *, const unsigned long FAR *));
  80422. #endif /* MAKECRCH */
  80423. /*
  80424. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80425. 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.
  80426. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80427. with the lowest powers in the most significant bit. Then adding polynomials
  80428. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80429. one. If we call the above polynomial p, and represent a byte as the
  80430. polynomial q, also with the lowest power in the most significant bit (so the
  80431. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80432. where a mod b means the remainder after dividing a by b.
  80433. This calculation is done using the shift-register method of multiplying and
  80434. taking the remainder. The register is initialized to zero, and for each
  80435. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80436. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80437. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80438. out is a one). We start with the highest power (least significant bit) of
  80439. q and repeat for all eight bits of q.
  80440. The first table is simply the CRC of all possible eight bit values. This is
  80441. all the information needed to generate CRCs on data a byte at a time for all
  80442. combinations of CRC register values and incoming bytes. The remaining tables
  80443. allow for word-at-a-time CRC calculation for both big-endian and little-
  80444. endian machines, where a word is four bytes.
  80445. */
  80446. local void make_crc_table()
  80447. {
  80448. unsigned long c;
  80449. int n, k;
  80450. unsigned long poly; /* polynomial exclusive-or pattern */
  80451. /* terms of polynomial defining this crc (except x^32): */
  80452. static volatile int first = 1; /* flag to limit concurrent making */
  80453. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80454. /* See if another task is already doing this (not thread-safe, but better
  80455. than nothing -- significantly reduces duration of vulnerability in
  80456. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80457. if (first) {
  80458. first = 0;
  80459. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80460. poly = 0UL;
  80461. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80462. poly |= 1UL << (31 - p[n]);
  80463. /* generate a crc for every 8-bit value */
  80464. for (n = 0; n < 256; n++) {
  80465. c = (unsigned long)n;
  80466. for (k = 0; k < 8; k++)
  80467. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80468. crc_table[0][n] = c;
  80469. }
  80470. #ifdef BYFOUR
  80471. /* generate crc for each value followed by one, two, and three zeros,
  80472. and then the byte reversal of those as well as the first table */
  80473. for (n = 0; n < 256; n++) {
  80474. c = crc_table[0][n];
  80475. crc_table[4][n] = REV(c);
  80476. for (k = 1; k < 4; k++) {
  80477. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80478. crc_table[k][n] = c;
  80479. crc_table[k + 4][n] = REV(c);
  80480. }
  80481. }
  80482. #endif /* BYFOUR */
  80483. crc_table_empty = 0;
  80484. }
  80485. else { /* not first */
  80486. /* wait for the other guy to finish (not efficient, but rare) */
  80487. while (crc_table_empty)
  80488. ;
  80489. }
  80490. #ifdef MAKECRCH
  80491. /* write out CRC tables to crc32.h */
  80492. {
  80493. FILE *out;
  80494. out = fopen("crc32.h", "w");
  80495. if (out == NULL) return;
  80496. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80497. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80498. fprintf(out, "local const unsigned long FAR ");
  80499. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80500. write_table(out, crc_table[0]);
  80501. # ifdef BYFOUR
  80502. fprintf(out, "#ifdef BYFOUR\n");
  80503. for (k = 1; k < 8; k++) {
  80504. fprintf(out, " },\n {\n");
  80505. write_table(out, crc_table[k]);
  80506. }
  80507. fprintf(out, "#endif\n");
  80508. # endif /* BYFOUR */
  80509. fprintf(out, " }\n};\n");
  80510. fclose(out);
  80511. }
  80512. #endif /* MAKECRCH */
  80513. }
  80514. #ifdef MAKECRCH
  80515. local void write_table(out, table)
  80516. FILE *out;
  80517. const unsigned long FAR *table;
  80518. {
  80519. int n;
  80520. for (n = 0; n < 256; n++)
  80521. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80522. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80523. }
  80524. #endif /* MAKECRCH */
  80525. #else /* !DYNAMIC_CRC_TABLE */
  80526. /* ========================================================================
  80527. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80528. */
  80529. /*** Start of inlined file: crc32.h ***/
  80530. local const unsigned long FAR crc_table[TBLS][256] =
  80531. {
  80532. {
  80533. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80534. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80535. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80536. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80537. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80538. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80539. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80540. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80541. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80542. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80543. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80544. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80545. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80546. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80547. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80548. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80549. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80550. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80551. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80552. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80553. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80554. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80555. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80556. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80557. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80558. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80559. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80560. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80561. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80562. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80563. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80564. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80565. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80566. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80567. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80568. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80569. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80570. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80571. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80572. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80573. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80574. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80575. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80576. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80577. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80578. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80579. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80580. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80581. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80582. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80583. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80584. 0x2d02ef8dUL
  80585. #ifdef BYFOUR
  80586. },
  80587. {
  80588. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80589. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80590. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80591. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80592. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80593. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80594. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80595. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80596. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80597. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80598. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80599. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80600. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80601. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80602. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80603. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80604. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80605. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80606. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80607. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80608. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80609. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80610. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80611. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80612. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80613. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80614. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80615. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80616. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80617. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80618. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80619. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80620. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80621. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80622. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80623. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80624. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80625. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80626. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80627. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80628. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80629. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80630. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80631. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80632. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80633. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80634. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80635. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80636. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80637. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80638. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80639. 0x9324fd72UL
  80640. },
  80641. {
  80642. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80643. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80644. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80645. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80646. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80647. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80648. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80649. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80650. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80651. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80652. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80653. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80654. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80655. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80656. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80657. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80658. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80659. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80660. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80661. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80662. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80663. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80664. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80665. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80666. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80667. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80668. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80669. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80670. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80671. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80672. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80673. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80674. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80675. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80676. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80677. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80678. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80679. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80680. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80681. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80682. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80683. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80684. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80685. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80686. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80687. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80688. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80689. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80690. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80691. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80692. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80693. 0xbe9834edUL
  80694. },
  80695. {
  80696. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80697. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80698. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80699. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80700. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80701. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80702. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80703. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80704. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80705. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80706. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80707. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80708. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80709. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80710. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80711. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80712. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80713. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80714. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80715. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80716. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80717. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80718. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80719. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80720. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80721. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80722. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80723. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80724. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80725. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80726. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80727. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80728. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80729. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80730. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80731. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80732. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80733. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80734. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80735. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80736. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80737. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80738. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80739. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80740. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80741. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80742. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80743. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80744. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80745. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80746. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80747. 0xde0506f1UL
  80748. },
  80749. {
  80750. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80751. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80752. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80753. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80754. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80755. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80756. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80757. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80758. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80759. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80760. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80761. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80762. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80763. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80764. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80765. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80766. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80767. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80768. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80769. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80770. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80771. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80772. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80773. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80774. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80775. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80776. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80777. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80778. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80779. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80780. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80781. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80782. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80783. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80784. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80785. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80786. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80787. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80788. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80789. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80790. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80791. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80792. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80793. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80794. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80795. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80796. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80797. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80798. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80799. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80800. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80801. 0x8def022dUL
  80802. },
  80803. {
  80804. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80805. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80806. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80807. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80808. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80809. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80810. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80811. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80812. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80813. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80814. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80815. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80816. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80817. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80818. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80819. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80820. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80821. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80822. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80823. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80824. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80825. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80826. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80827. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80828. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80829. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80830. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80831. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80832. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80833. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80834. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80835. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80836. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80837. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80838. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80839. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80840. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80841. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80842. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80843. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80844. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80845. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80846. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80847. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80848. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80849. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80850. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80851. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80852. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80853. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80854. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80855. 0x72fd2493UL
  80856. },
  80857. {
  80858. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80859. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80860. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80861. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80862. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80863. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80864. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80865. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80866. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80867. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80868. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80869. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80870. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80871. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80872. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80873. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80874. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80875. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80876. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80877. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80878. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80879. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80880. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80881. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80882. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80883. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80884. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80885. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80886. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80887. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80888. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80889. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80890. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80891. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80892. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80893. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80894. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80895. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80896. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80897. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80898. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80899. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80900. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80901. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80902. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80903. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80904. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80905. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80906. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80907. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80908. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80909. 0xed3498beUL
  80910. },
  80911. {
  80912. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80913. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80914. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80915. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80916. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80917. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80918. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80919. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80920. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80921. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80922. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80923. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80924. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80925. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80926. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80927. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80928. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80929. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80930. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80931. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80932. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80933. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80934. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80935. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80936. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80937. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80938. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80939. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80940. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80941. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80942. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80943. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80944. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80945. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80946. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80947. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80948. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80949. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80950. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80951. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80952. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80953. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80954. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80955. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80956. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80957. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80958. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80959. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80960. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80961. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80962. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80963. 0xf10605deUL
  80964. #endif
  80965. }
  80966. };
  80967. /*** End of inlined file: crc32.h ***/
  80968. #endif /* DYNAMIC_CRC_TABLE */
  80969. /* =========================================================================
  80970. * This function can be used by asm versions of crc32()
  80971. */
  80972. const unsigned long FAR * ZEXPORT get_crc_table()
  80973. {
  80974. #ifdef DYNAMIC_CRC_TABLE
  80975. if (crc_table_empty)
  80976. make_crc_table();
  80977. #endif /* DYNAMIC_CRC_TABLE */
  80978. return (const unsigned long FAR *)crc_table;
  80979. }
  80980. /* ========================================================================= */
  80981. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80982. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80983. /* ========================================================================= */
  80984. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80985. {
  80986. if (buf == Z_NULL) return 0UL;
  80987. #ifdef DYNAMIC_CRC_TABLE
  80988. if (crc_table_empty)
  80989. make_crc_table();
  80990. #endif /* DYNAMIC_CRC_TABLE */
  80991. #ifdef BYFOUR
  80992. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80993. u4 endian;
  80994. endian = 1;
  80995. if (*((unsigned char *)(&endian)))
  80996. return crc32_little(crc, buf, len);
  80997. else
  80998. return crc32_big(crc, buf, len);
  80999. }
  81000. #endif /* BYFOUR */
  81001. crc = crc ^ 0xffffffffUL;
  81002. while (len >= 8) {
  81003. DO8;
  81004. len -= 8;
  81005. }
  81006. if (len) do {
  81007. DO1;
  81008. } while (--len);
  81009. return crc ^ 0xffffffffUL;
  81010. }
  81011. #ifdef BYFOUR
  81012. /* ========================================================================= */
  81013. #define DOLIT4 c ^= *buf4++; \
  81014. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  81015. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  81016. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  81017. /* ========================================================================= */
  81018. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  81019. {
  81020. register u4 c;
  81021. register const u4 FAR *buf4;
  81022. c = (u4)crc;
  81023. c = ~c;
  81024. while (len && ((ptrdiff_t)buf & 3)) {
  81025. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  81026. len--;
  81027. }
  81028. buf4 = (const u4 FAR *)(const void FAR *)buf;
  81029. while (len >= 32) {
  81030. DOLIT32;
  81031. len -= 32;
  81032. }
  81033. while (len >= 4) {
  81034. DOLIT4;
  81035. len -= 4;
  81036. }
  81037. buf = (const unsigned char FAR *)buf4;
  81038. if (len) do {
  81039. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  81040. } while (--len);
  81041. c = ~c;
  81042. return (unsigned long)c;
  81043. }
  81044. /* ========================================================================= */
  81045. #define DOBIG4 c ^= *++buf4; \
  81046. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  81047. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  81048. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  81049. /* ========================================================================= */
  81050. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  81051. {
  81052. register u4 c;
  81053. register const u4 FAR *buf4;
  81054. c = REV((u4)crc);
  81055. c = ~c;
  81056. while (len && ((ptrdiff_t)buf & 3)) {
  81057. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81058. len--;
  81059. }
  81060. buf4 = (const u4 FAR *)(const void FAR *)buf;
  81061. buf4--;
  81062. while (len >= 32) {
  81063. DOBIG32;
  81064. len -= 32;
  81065. }
  81066. while (len >= 4) {
  81067. DOBIG4;
  81068. len -= 4;
  81069. }
  81070. buf4++;
  81071. buf = (const unsigned char FAR *)buf4;
  81072. if (len) do {
  81073. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81074. } while (--len);
  81075. c = ~c;
  81076. return (unsigned long)(REV(c));
  81077. }
  81078. #endif /* BYFOUR */
  81079. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  81080. /* ========================================================================= */
  81081. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  81082. {
  81083. unsigned long sum;
  81084. sum = 0;
  81085. while (vec) {
  81086. if (vec & 1)
  81087. sum ^= *mat;
  81088. vec >>= 1;
  81089. mat++;
  81090. }
  81091. return sum;
  81092. }
  81093. /* ========================================================================= */
  81094. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  81095. {
  81096. int n;
  81097. for (n = 0; n < GF2_DIM; n++)
  81098. square[n] = gf2_matrix_times(mat, mat[n]);
  81099. }
  81100. /* ========================================================================= */
  81101. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  81102. {
  81103. int n;
  81104. unsigned long row;
  81105. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  81106. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  81107. /* degenerate case */
  81108. if (len2 == 0)
  81109. return crc1;
  81110. /* put operator for one zero bit in odd */
  81111. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  81112. row = 1;
  81113. for (n = 1; n < GF2_DIM; n++) {
  81114. odd[n] = row;
  81115. row <<= 1;
  81116. }
  81117. /* put operator for two zero bits in even */
  81118. gf2_matrix_square(even, odd);
  81119. /* put operator for four zero bits in odd */
  81120. gf2_matrix_square(odd, even);
  81121. /* apply len2 zeros to crc1 (first square will put the operator for one
  81122. zero byte, eight zero bits, in even) */
  81123. do {
  81124. /* apply zeros operator for this bit of len2 */
  81125. gf2_matrix_square(even, odd);
  81126. if (len2 & 1)
  81127. crc1 = gf2_matrix_times(even, crc1);
  81128. len2 >>= 1;
  81129. /* if no more bits set, then done */
  81130. if (len2 == 0)
  81131. break;
  81132. /* another iteration of the loop with odd and even swapped */
  81133. gf2_matrix_square(odd, even);
  81134. if (len2 & 1)
  81135. crc1 = gf2_matrix_times(odd, crc1);
  81136. len2 >>= 1;
  81137. /* if no more bits set, then done */
  81138. } while (len2 != 0);
  81139. /* return combined crc */
  81140. crc1 ^= crc2;
  81141. return crc1;
  81142. }
  81143. /*** End of inlined file: crc32.c ***/
  81144. /*** Start of inlined file: deflate.c ***/
  81145. /*
  81146. * ALGORITHM
  81147. *
  81148. * The "deflation" process depends on being able to identify portions
  81149. * of the input text which are identical to earlier input (within a
  81150. * sliding window trailing behind the input currently being processed).
  81151. *
  81152. * The most straightforward technique turns out to be the fastest for
  81153. * most input files: try all possible matches and select the longest.
  81154. * The key feature of this algorithm is that insertions into the string
  81155. * dictionary are very simple and thus fast, and deletions are avoided
  81156. * completely. Insertions are performed at each input character, whereas
  81157. * string matches are performed only when the previous match ends. So it
  81158. * is preferable to spend more time in matches to allow very fast string
  81159. * insertions and avoid deletions. The matching algorithm for small
  81160. * strings is inspired from that of Rabin & Karp. A brute force approach
  81161. * is used to find longer strings when a small match has been found.
  81162. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  81163. * (by Leonid Broukhis).
  81164. * A previous version of this file used a more sophisticated algorithm
  81165. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  81166. * time, but has a larger average cost, uses more memory and is patented.
  81167. * However the F&G algorithm may be faster for some highly redundant
  81168. * files if the parameter max_chain_length (described below) is too large.
  81169. *
  81170. * ACKNOWLEDGEMENTS
  81171. *
  81172. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  81173. * I found it in 'freeze' written by Leonid Broukhis.
  81174. * Thanks to many people for bug reports and testing.
  81175. *
  81176. * REFERENCES
  81177. *
  81178. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  81179. * Available in http://www.ietf.org/rfc/rfc1951.txt
  81180. *
  81181. * A description of the Rabin and Karp algorithm is given in the book
  81182. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  81183. *
  81184. * Fiala,E.R., and Greene,D.H.
  81185. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81186. *
  81187. */
  81188. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81189. /*** Start of inlined file: deflate.h ***/
  81190. /* WARNING: this file should *not* be used by applications. It is
  81191. part of the implementation of the compression library and is
  81192. subject to change. Applications should only use zlib.h.
  81193. */
  81194. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81195. #ifndef DEFLATE_H
  81196. #define DEFLATE_H
  81197. /* define NO_GZIP when compiling if you want to disable gzip header and
  81198. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81199. the crc code when it is not needed. For shared libraries, gzip encoding
  81200. should be left enabled. */
  81201. #ifndef NO_GZIP
  81202. # define GZIP
  81203. #endif
  81204. #define NO_DUMMY_DECL
  81205. /* ===========================================================================
  81206. * Internal compression state.
  81207. */
  81208. #define LENGTH_CODES 29
  81209. /* number of length codes, not counting the special END_BLOCK code */
  81210. #define LITERALS 256
  81211. /* number of literal bytes 0..255 */
  81212. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81213. /* number of Literal or Length codes, including the END_BLOCK code */
  81214. #define D_CODES 30
  81215. /* number of distance codes */
  81216. #define BL_CODES 19
  81217. /* number of codes used to transfer the bit lengths */
  81218. #define HEAP_SIZE (2*L_CODES+1)
  81219. /* maximum heap size */
  81220. #define MAX_BITS 15
  81221. /* All codes must not exceed MAX_BITS bits */
  81222. #define INIT_STATE 42
  81223. #define EXTRA_STATE 69
  81224. #define NAME_STATE 73
  81225. #define COMMENT_STATE 91
  81226. #define HCRC_STATE 103
  81227. #define BUSY_STATE 113
  81228. #define FINISH_STATE 666
  81229. /* Stream status */
  81230. /* Data structure describing a single value and its code string. */
  81231. typedef struct ct_data_s {
  81232. union {
  81233. ush freq; /* frequency count */
  81234. ush code; /* bit string */
  81235. } fc;
  81236. union {
  81237. ush dad; /* father node in Huffman tree */
  81238. ush len; /* length of bit string */
  81239. } dl;
  81240. } FAR ct_data;
  81241. #define Freq fc.freq
  81242. #define Code fc.code
  81243. #define Dad dl.dad
  81244. #define Len dl.len
  81245. typedef struct static_tree_desc_s static_tree_desc;
  81246. typedef struct tree_desc_s {
  81247. ct_data *dyn_tree; /* the dynamic tree */
  81248. int max_code; /* largest code with non zero frequency */
  81249. static_tree_desc *stat_desc; /* the corresponding static tree */
  81250. } FAR tree_desc;
  81251. typedef ush Pos;
  81252. typedef Pos FAR Posf;
  81253. typedef unsigned IPos;
  81254. /* A Pos is an index in the character window. We use short instead of int to
  81255. * save space in the various tables. IPos is used only for parameter passing.
  81256. */
  81257. typedef struct internal_state {
  81258. z_streamp strm; /* pointer back to this zlib stream */
  81259. int status; /* as the name implies */
  81260. Bytef *pending_buf; /* output still pending */
  81261. ulg pending_buf_size; /* size of pending_buf */
  81262. Bytef *pending_out; /* next pending byte to output to the stream */
  81263. uInt pending; /* nb of bytes in the pending buffer */
  81264. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81265. gz_headerp gzhead; /* gzip header information to write */
  81266. uInt gzindex; /* where in extra, name, or comment */
  81267. Byte method; /* STORED (for zip only) or DEFLATED */
  81268. int last_flush; /* value of flush param for previous deflate call */
  81269. /* used by deflate.c: */
  81270. uInt w_size; /* LZ77 window size (32K by default) */
  81271. uInt w_bits; /* log2(w_size) (8..16) */
  81272. uInt w_mask; /* w_size - 1 */
  81273. Bytef *window;
  81274. /* Sliding window. Input bytes are read into the second half of the window,
  81275. * and move to the first half later to keep a dictionary of at least wSize
  81276. * bytes. With this organization, matches are limited to a distance of
  81277. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81278. * performed with a length multiple of the block size. Also, it limits
  81279. * the window size to 64K, which is quite useful on MSDOS.
  81280. * To do: use the user input buffer as sliding window.
  81281. */
  81282. ulg window_size;
  81283. /* Actual size of window: 2*wSize, except when the user input buffer
  81284. * is directly used as sliding window.
  81285. */
  81286. Posf *prev;
  81287. /* Link to older string with same hash index. To limit the size of this
  81288. * array to 64K, this link is maintained only for the last 32K strings.
  81289. * An index in this array is thus a window index modulo 32K.
  81290. */
  81291. Posf *head; /* Heads of the hash chains or NIL. */
  81292. uInt ins_h; /* hash index of string to be inserted */
  81293. uInt hash_size; /* number of elements in hash table */
  81294. uInt hash_bits; /* log2(hash_size) */
  81295. uInt hash_mask; /* hash_size-1 */
  81296. uInt hash_shift;
  81297. /* Number of bits by which ins_h must be shifted at each input
  81298. * step. It must be such that after MIN_MATCH steps, the oldest
  81299. * byte no longer takes part in the hash key, that is:
  81300. * hash_shift * MIN_MATCH >= hash_bits
  81301. */
  81302. long block_start;
  81303. /* Window position at the beginning of the current output block. Gets
  81304. * negative when the window is moved backwards.
  81305. */
  81306. uInt match_length; /* length of best match */
  81307. IPos prev_match; /* previous match */
  81308. int match_available; /* set if previous match exists */
  81309. uInt strstart; /* start of string to insert */
  81310. uInt match_start; /* start of matching string */
  81311. uInt lookahead; /* number of valid bytes ahead in window */
  81312. uInt prev_length;
  81313. /* Length of the best match at previous step. Matches not greater than this
  81314. * are discarded. This is used in the lazy match evaluation.
  81315. */
  81316. uInt max_chain_length;
  81317. /* To speed up deflation, hash chains are never searched beyond this
  81318. * length. A higher limit improves compression ratio but degrades the
  81319. * speed.
  81320. */
  81321. uInt max_lazy_match;
  81322. /* Attempt to find a better match only when the current match is strictly
  81323. * smaller than this value. This mechanism is used only for compression
  81324. * levels >= 4.
  81325. */
  81326. # define max_insert_length max_lazy_match
  81327. /* Insert new strings in the hash table only if the match length is not
  81328. * greater than this length. This saves time but degrades compression.
  81329. * max_insert_length is used only for compression levels <= 3.
  81330. */
  81331. int level; /* compression level (1..9) */
  81332. int strategy; /* favor or force Huffman coding*/
  81333. uInt good_match;
  81334. /* Use a faster search when the previous match is longer than this */
  81335. int nice_match; /* Stop searching when current match exceeds this */
  81336. /* used by trees.c: */
  81337. /* Didn't use ct_data typedef below to supress compiler warning */
  81338. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81339. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81340. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81341. struct tree_desc_s l_desc; /* desc. for literal tree */
  81342. struct tree_desc_s d_desc; /* desc. for distance tree */
  81343. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81344. ush bl_count[MAX_BITS+1];
  81345. /* number of codes at each bit length for an optimal tree */
  81346. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81347. int heap_len; /* number of elements in the heap */
  81348. int heap_max; /* element of largest frequency */
  81349. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81350. * The same heap array is used to build all trees.
  81351. */
  81352. uch depth[2*L_CODES+1];
  81353. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81354. */
  81355. uchf *l_buf; /* buffer for literals or lengths */
  81356. uInt lit_bufsize;
  81357. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81358. * limiting lit_bufsize to 64K:
  81359. * - frequencies can be kept in 16 bit counters
  81360. * - if compression is not successful for the first block, all input
  81361. * data is still in the window so we can still emit a stored block even
  81362. * when input comes from standard input. (This can also be done for
  81363. * all blocks if lit_bufsize is not greater than 32K.)
  81364. * - if compression is not successful for a file smaller than 64K, we can
  81365. * even emit a stored file instead of a stored block (saving 5 bytes).
  81366. * This is applicable only for zip (not gzip or zlib).
  81367. * - creating new Huffman trees less frequently may not provide fast
  81368. * adaptation to changes in the input data statistics. (Take for
  81369. * example a binary file with poorly compressible code followed by
  81370. * a highly compressible string table.) Smaller buffer sizes give
  81371. * fast adaptation but have of course the overhead of transmitting
  81372. * trees more frequently.
  81373. * - I can't count above 4
  81374. */
  81375. uInt last_lit; /* running index in l_buf */
  81376. ushf *d_buf;
  81377. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81378. * the same number of elements. To use different lengths, an extra flag
  81379. * array would be necessary.
  81380. */
  81381. ulg opt_len; /* bit length of current block with optimal trees */
  81382. ulg static_len; /* bit length of current block with static trees */
  81383. uInt matches; /* number of string matches in current block */
  81384. int last_eob_len; /* bit length of EOB code for last block */
  81385. #ifdef DEBUG
  81386. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81387. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81388. #endif
  81389. ush bi_buf;
  81390. /* Output buffer. bits are inserted starting at the bottom (least
  81391. * significant bits).
  81392. */
  81393. int bi_valid;
  81394. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81395. * are always zero.
  81396. */
  81397. } FAR deflate_state;
  81398. /* Output a byte on the stream.
  81399. * IN assertion: there is enough room in pending_buf.
  81400. */
  81401. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81402. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81403. /* Minimum amount of lookahead, except at the end of the input file.
  81404. * See deflate.c for comments about the MIN_MATCH+1.
  81405. */
  81406. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81407. /* In order to simplify the code, particularly on 16 bit machines, match
  81408. * distances are limited to MAX_DIST instead of WSIZE.
  81409. */
  81410. /* in trees.c */
  81411. void _tr_init OF((deflate_state *s));
  81412. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81413. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81414. int eof));
  81415. void _tr_align OF((deflate_state *s));
  81416. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81417. int eof));
  81418. #define d_code(dist) \
  81419. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81420. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81421. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81422. * used.
  81423. */
  81424. #ifndef DEBUG
  81425. /* Inline versions of _tr_tally for speed: */
  81426. #if defined(GEN_TREES_H) || !defined(STDC)
  81427. extern uch _length_code[];
  81428. extern uch _dist_code[];
  81429. #else
  81430. extern const uch _length_code[];
  81431. extern const uch _dist_code[];
  81432. #endif
  81433. # define _tr_tally_lit(s, c, flush) \
  81434. { uch cc = (c); \
  81435. s->d_buf[s->last_lit] = 0; \
  81436. s->l_buf[s->last_lit++] = cc; \
  81437. s->dyn_ltree[cc].Freq++; \
  81438. flush = (s->last_lit == s->lit_bufsize-1); \
  81439. }
  81440. # define _tr_tally_dist(s, distance, length, flush) \
  81441. { uch len = (length); \
  81442. ush dist = (distance); \
  81443. s->d_buf[s->last_lit] = dist; \
  81444. s->l_buf[s->last_lit++] = len; \
  81445. dist--; \
  81446. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81447. s->dyn_dtree[d_code(dist)].Freq++; \
  81448. flush = (s->last_lit == s->lit_bufsize-1); \
  81449. }
  81450. #else
  81451. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81452. # define _tr_tally_dist(s, distance, length, flush) \
  81453. flush = _tr_tally(s, distance, length)
  81454. #endif
  81455. #endif /* DEFLATE_H */
  81456. /*** End of inlined file: deflate.h ***/
  81457. const char deflate_copyright[] =
  81458. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81459. /*
  81460. If you use the zlib library in a product, an acknowledgment is welcome
  81461. in the documentation of your product. If for some reason you cannot
  81462. include such an acknowledgment, I would appreciate that you keep this
  81463. copyright string in the executable of your product.
  81464. */
  81465. /* ===========================================================================
  81466. * Function prototypes.
  81467. */
  81468. typedef enum {
  81469. need_more, /* block not completed, need more input or more output */
  81470. block_done, /* block flush performed */
  81471. finish_started, /* finish started, need only more output at next deflate */
  81472. finish_done /* finish done, accept no more input or output */
  81473. } block_state;
  81474. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81475. /* Compression function. Returns the block state after the call. */
  81476. local void fill_window OF((deflate_state *s));
  81477. local block_state deflate_stored OF((deflate_state *s, int flush));
  81478. local block_state deflate_fast OF((deflate_state *s, int flush));
  81479. #ifndef FASTEST
  81480. local block_state deflate_slow OF((deflate_state *s, int flush));
  81481. #endif
  81482. local void lm_init OF((deflate_state *s));
  81483. local void putShortMSB OF((deflate_state *s, uInt b));
  81484. local void flush_pending OF((z_streamp strm));
  81485. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81486. #ifndef FASTEST
  81487. #ifdef ASMV
  81488. void match_init OF((void)); /* asm code initialization */
  81489. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81490. #else
  81491. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81492. #endif
  81493. #endif
  81494. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81495. #ifdef DEBUG
  81496. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81497. int length));
  81498. #endif
  81499. /* ===========================================================================
  81500. * Local data
  81501. */
  81502. #define NIL 0
  81503. /* Tail of hash chains */
  81504. #ifndef TOO_FAR
  81505. # define TOO_FAR 4096
  81506. #endif
  81507. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81508. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81509. /* Minimum amount of lookahead, except at the end of the input file.
  81510. * See deflate.c for comments about the MIN_MATCH+1.
  81511. */
  81512. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81513. * the desired pack level (0..9). The values given below have been tuned to
  81514. * exclude worst case performance for pathological files. Better values may be
  81515. * found for specific files.
  81516. */
  81517. typedef struct config_s {
  81518. ush good_length; /* reduce lazy search above this match length */
  81519. ush max_lazy; /* do not perform lazy search above this match length */
  81520. ush nice_length; /* quit search above this match length */
  81521. ush max_chain;
  81522. compress_func func;
  81523. } config;
  81524. #ifdef FASTEST
  81525. local const config configuration_table[2] = {
  81526. /* good lazy nice chain */
  81527. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81528. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81529. #else
  81530. local const config configuration_table[10] = {
  81531. /* good lazy nice chain */
  81532. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81533. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81534. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81535. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81536. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81537. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81538. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81539. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81540. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81541. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81542. #endif
  81543. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81544. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81545. * meaning.
  81546. */
  81547. #define EQUAL 0
  81548. /* result of memcmp for equal strings */
  81549. #ifndef NO_DUMMY_DECL
  81550. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81551. #endif
  81552. /* ===========================================================================
  81553. * Update a hash value with the given input byte
  81554. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81555. * input characters, so that a running hash key can be computed from the
  81556. * previous key instead of complete recalculation each time.
  81557. */
  81558. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81559. /* ===========================================================================
  81560. * Insert string str in the dictionary and set match_head to the previous head
  81561. * of the hash chain (the most recent string with same hash key). Return
  81562. * the previous length of the hash chain.
  81563. * If this file is compiled with -DFASTEST, the compression level is forced
  81564. * to 1, and no hash chains are maintained.
  81565. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81566. * input characters and the first MIN_MATCH bytes of str are valid
  81567. * (except for the last MIN_MATCH-1 bytes of the input file).
  81568. */
  81569. #ifdef FASTEST
  81570. #define INSERT_STRING(s, str, match_head) \
  81571. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81572. match_head = s->head[s->ins_h], \
  81573. s->head[s->ins_h] = (Pos)(str))
  81574. #else
  81575. #define INSERT_STRING(s, str, match_head) \
  81576. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81577. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81578. s->head[s->ins_h] = (Pos)(str))
  81579. #endif
  81580. /* ===========================================================================
  81581. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81582. * prev[] will be initialized on the fly.
  81583. */
  81584. #define CLEAR_HASH(s) \
  81585. s->head[s->hash_size-1] = NIL; \
  81586. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81587. /* ========================================================================= */
  81588. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81589. {
  81590. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81591. Z_DEFAULT_STRATEGY, version, stream_size);
  81592. /* To do: ignore strm->next_in if we use it as window */
  81593. }
  81594. /* ========================================================================= */
  81595. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81596. {
  81597. deflate_state *s;
  81598. int wrap = 1;
  81599. static const char my_version[] = ZLIB_VERSION;
  81600. ushf *overlay;
  81601. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81602. * output size for (length,distance) codes is <= 24 bits.
  81603. */
  81604. if (version == Z_NULL || version[0] != my_version[0] ||
  81605. stream_size != sizeof(z_stream)) {
  81606. return Z_VERSION_ERROR;
  81607. }
  81608. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81609. strm->msg = Z_NULL;
  81610. if (strm->zalloc == (alloc_func)0) {
  81611. strm->zalloc = zcalloc;
  81612. strm->opaque = (voidpf)0;
  81613. }
  81614. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81615. #ifdef FASTEST
  81616. if (level != 0) level = 1;
  81617. #else
  81618. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81619. #endif
  81620. if (windowBits < 0) { /* suppress zlib wrapper */
  81621. wrap = 0;
  81622. windowBits = -windowBits;
  81623. }
  81624. #ifdef GZIP
  81625. else if (windowBits > 15) {
  81626. wrap = 2; /* write gzip wrapper instead */
  81627. windowBits -= 16;
  81628. }
  81629. #endif
  81630. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81631. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81632. strategy < 0 || strategy > Z_FIXED) {
  81633. return Z_STREAM_ERROR;
  81634. }
  81635. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81636. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81637. if (s == Z_NULL) return Z_MEM_ERROR;
  81638. strm->state = (struct internal_state FAR *)s;
  81639. s->strm = strm;
  81640. s->wrap = wrap;
  81641. s->gzhead = Z_NULL;
  81642. s->w_bits = windowBits;
  81643. s->w_size = 1 << s->w_bits;
  81644. s->w_mask = s->w_size - 1;
  81645. s->hash_bits = memLevel + 7;
  81646. s->hash_size = 1 << s->hash_bits;
  81647. s->hash_mask = s->hash_size - 1;
  81648. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81649. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81650. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81651. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81652. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81653. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81654. s->pending_buf = (uchf *) overlay;
  81655. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81656. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81657. s->pending_buf == Z_NULL) {
  81658. s->status = FINISH_STATE;
  81659. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81660. deflateEnd (strm);
  81661. return Z_MEM_ERROR;
  81662. }
  81663. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81664. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81665. s->level = level;
  81666. s->strategy = strategy;
  81667. s->method = (Byte)method;
  81668. return deflateReset(strm);
  81669. }
  81670. /* ========================================================================= */
  81671. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81672. {
  81673. deflate_state *s;
  81674. uInt length = dictLength;
  81675. uInt n;
  81676. IPos hash_head = 0;
  81677. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81678. strm->state->wrap == 2 ||
  81679. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81680. return Z_STREAM_ERROR;
  81681. s = strm->state;
  81682. if (s->wrap)
  81683. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81684. if (length < MIN_MATCH) return Z_OK;
  81685. if (length > MAX_DIST(s)) {
  81686. length = MAX_DIST(s);
  81687. dictionary += dictLength - length; /* use the tail of the dictionary */
  81688. }
  81689. zmemcpy(s->window, dictionary, length);
  81690. s->strstart = length;
  81691. s->block_start = (long)length;
  81692. /* Insert all strings in the hash table (except for the last two bytes).
  81693. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81694. * call of fill_window.
  81695. */
  81696. s->ins_h = s->window[0];
  81697. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81698. for (n = 0; n <= length - MIN_MATCH; n++) {
  81699. INSERT_STRING(s, n, hash_head);
  81700. }
  81701. if (hash_head) hash_head = 0; /* to make compiler happy */
  81702. return Z_OK;
  81703. }
  81704. /* ========================================================================= */
  81705. int ZEXPORT deflateReset (z_streamp strm)
  81706. {
  81707. deflate_state *s;
  81708. if (strm == Z_NULL || strm->state == Z_NULL ||
  81709. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81710. return Z_STREAM_ERROR;
  81711. }
  81712. strm->total_in = strm->total_out = 0;
  81713. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81714. strm->data_type = Z_UNKNOWN;
  81715. s = (deflate_state *)strm->state;
  81716. s->pending = 0;
  81717. s->pending_out = s->pending_buf;
  81718. if (s->wrap < 0) {
  81719. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81720. }
  81721. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81722. strm->adler =
  81723. #ifdef GZIP
  81724. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81725. #endif
  81726. adler32(0L, Z_NULL, 0);
  81727. s->last_flush = Z_NO_FLUSH;
  81728. _tr_init(s);
  81729. lm_init(s);
  81730. return Z_OK;
  81731. }
  81732. /* ========================================================================= */
  81733. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81734. {
  81735. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81736. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81737. strm->state->gzhead = head;
  81738. return Z_OK;
  81739. }
  81740. /* ========================================================================= */
  81741. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81742. {
  81743. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81744. strm->state->bi_valid = bits;
  81745. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81746. return Z_OK;
  81747. }
  81748. /* ========================================================================= */
  81749. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81750. {
  81751. deflate_state *s;
  81752. compress_func func;
  81753. int err = Z_OK;
  81754. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81755. s = strm->state;
  81756. #ifdef FASTEST
  81757. if (level != 0) level = 1;
  81758. #else
  81759. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81760. #endif
  81761. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81762. return Z_STREAM_ERROR;
  81763. }
  81764. func = configuration_table[s->level].func;
  81765. if (func != configuration_table[level].func && strm->total_in != 0) {
  81766. /* Flush the last buffer: */
  81767. err = deflate(strm, Z_PARTIAL_FLUSH);
  81768. }
  81769. if (s->level != level) {
  81770. s->level = level;
  81771. s->max_lazy_match = configuration_table[level].max_lazy;
  81772. s->good_match = configuration_table[level].good_length;
  81773. s->nice_match = configuration_table[level].nice_length;
  81774. s->max_chain_length = configuration_table[level].max_chain;
  81775. }
  81776. s->strategy = strategy;
  81777. return err;
  81778. }
  81779. /* ========================================================================= */
  81780. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81781. {
  81782. deflate_state *s;
  81783. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81784. s = strm->state;
  81785. s->good_match = good_length;
  81786. s->max_lazy_match = max_lazy;
  81787. s->nice_match = nice_length;
  81788. s->max_chain_length = max_chain;
  81789. return Z_OK;
  81790. }
  81791. /* =========================================================================
  81792. * For the default windowBits of 15 and memLevel of 8, this function returns
  81793. * a close to exact, as well as small, upper bound on the compressed size.
  81794. * They are coded as constants here for a reason--if the #define's are
  81795. * changed, then this function needs to be changed as well. The return
  81796. * value for 15 and 8 only works for those exact settings.
  81797. *
  81798. * For any setting other than those defaults for windowBits and memLevel,
  81799. * the value returned is a conservative worst case for the maximum expansion
  81800. * resulting from using fixed blocks instead of stored blocks, which deflate
  81801. * can emit on compressed data for some combinations of the parameters.
  81802. *
  81803. * This function could be more sophisticated to provide closer upper bounds
  81804. * for every combination of windowBits and memLevel, as well as wrap.
  81805. * But even the conservative upper bound of about 14% expansion does not
  81806. * seem onerous for output buffer allocation.
  81807. */
  81808. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81809. {
  81810. deflate_state *s;
  81811. uLong destLen;
  81812. /* conservative upper bound */
  81813. destLen = sourceLen +
  81814. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81815. /* if can't get parameters, return conservative bound */
  81816. if (strm == Z_NULL || strm->state == Z_NULL)
  81817. return destLen;
  81818. /* if not default parameters, return conservative bound */
  81819. s = strm->state;
  81820. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81821. return destLen;
  81822. /* default settings: return tight bound for that case */
  81823. return compressBound(sourceLen);
  81824. }
  81825. /* =========================================================================
  81826. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81827. * IN assertion: the stream state is correct and there is enough room in
  81828. * pending_buf.
  81829. */
  81830. local void putShortMSB (deflate_state *s, uInt b)
  81831. {
  81832. put_byte(s, (Byte)(b >> 8));
  81833. put_byte(s, (Byte)(b & 0xff));
  81834. }
  81835. /* =========================================================================
  81836. * Flush as much pending output as possible. All deflate() output goes
  81837. * through this function so some applications may wish to modify it
  81838. * to avoid allocating a large strm->next_out buffer and copying into it.
  81839. * (See also read_buf()).
  81840. */
  81841. local void flush_pending (z_streamp strm)
  81842. {
  81843. unsigned len = strm->state->pending;
  81844. if (len > strm->avail_out) len = strm->avail_out;
  81845. if (len == 0) return;
  81846. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81847. strm->next_out += len;
  81848. strm->state->pending_out += len;
  81849. strm->total_out += len;
  81850. strm->avail_out -= len;
  81851. strm->state->pending -= len;
  81852. if (strm->state->pending == 0) {
  81853. strm->state->pending_out = strm->state->pending_buf;
  81854. }
  81855. }
  81856. /* ========================================================================= */
  81857. int ZEXPORT deflate (z_streamp strm, int flush)
  81858. {
  81859. int old_flush; /* value of flush param for previous deflate call */
  81860. deflate_state *s;
  81861. if (strm == Z_NULL || strm->state == Z_NULL ||
  81862. flush > Z_FINISH || flush < 0) {
  81863. return Z_STREAM_ERROR;
  81864. }
  81865. s = strm->state;
  81866. if (strm->next_out == Z_NULL ||
  81867. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81868. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81869. ERR_RETURN(strm, Z_STREAM_ERROR);
  81870. }
  81871. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81872. s->strm = strm; /* just in case */
  81873. old_flush = s->last_flush;
  81874. s->last_flush = flush;
  81875. /* Write the header */
  81876. if (s->status == INIT_STATE) {
  81877. #ifdef GZIP
  81878. if (s->wrap == 2) {
  81879. strm->adler = crc32(0L, Z_NULL, 0);
  81880. put_byte(s, 31);
  81881. put_byte(s, 139);
  81882. put_byte(s, 8);
  81883. if (s->gzhead == NULL) {
  81884. put_byte(s, 0);
  81885. put_byte(s, 0);
  81886. put_byte(s, 0);
  81887. put_byte(s, 0);
  81888. put_byte(s, 0);
  81889. put_byte(s, s->level == 9 ? 2 :
  81890. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81891. 4 : 0));
  81892. put_byte(s, OS_CODE);
  81893. s->status = BUSY_STATE;
  81894. }
  81895. else {
  81896. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81897. (s->gzhead->hcrc ? 2 : 0) +
  81898. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81899. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81900. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81901. );
  81902. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81903. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81904. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81905. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81906. put_byte(s, s->level == 9 ? 2 :
  81907. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81908. 4 : 0));
  81909. put_byte(s, s->gzhead->os & 0xff);
  81910. if (s->gzhead->extra != NULL) {
  81911. put_byte(s, s->gzhead->extra_len & 0xff);
  81912. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81913. }
  81914. if (s->gzhead->hcrc)
  81915. strm->adler = crc32(strm->adler, s->pending_buf,
  81916. s->pending);
  81917. s->gzindex = 0;
  81918. s->status = EXTRA_STATE;
  81919. }
  81920. }
  81921. else
  81922. #endif
  81923. {
  81924. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81925. uInt level_flags;
  81926. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81927. level_flags = 0;
  81928. else if (s->level < 6)
  81929. level_flags = 1;
  81930. else if (s->level == 6)
  81931. level_flags = 2;
  81932. else
  81933. level_flags = 3;
  81934. header |= (level_flags << 6);
  81935. if (s->strstart != 0) header |= PRESET_DICT;
  81936. header += 31 - (header % 31);
  81937. s->status = BUSY_STATE;
  81938. putShortMSB(s, header);
  81939. /* Save the adler32 of the preset dictionary: */
  81940. if (s->strstart != 0) {
  81941. putShortMSB(s, (uInt)(strm->adler >> 16));
  81942. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81943. }
  81944. strm->adler = adler32(0L, Z_NULL, 0);
  81945. }
  81946. }
  81947. #ifdef GZIP
  81948. if (s->status == EXTRA_STATE) {
  81949. if (s->gzhead->extra != NULL) {
  81950. uInt beg = s->pending; /* start of bytes to update crc */
  81951. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81952. if (s->pending == s->pending_buf_size) {
  81953. if (s->gzhead->hcrc && s->pending > beg)
  81954. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81955. s->pending - beg);
  81956. flush_pending(strm);
  81957. beg = s->pending;
  81958. if (s->pending == s->pending_buf_size)
  81959. break;
  81960. }
  81961. put_byte(s, s->gzhead->extra[s->gzindex]);
  81962. s->gzindex++;
  81963. }
  81964. if (s->gzhead->hcrc && s->pending > beg)
  81965. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81966. s->pending - beg);
  81967. if (s->gzindex == s->gzhead->extra_len) {
  81968. s->gzindex = 0;
  81969. s->status = NAME_STATE;
  81970. }
  81971. }
  81972. else
  81973. s->status = NAME_STATE;
  81974. }
  81975. if (s->status == NAME_STATE) {
  81976. if (s->gzhead->name != NULL) {
  81977. uInt beg = s->pending; /* start of bytes to update crc */
  81978. int val;
  81979. do {
  81980. if (s->pending == s->pending_buf_size) {
  81981. if (s->gzhead->hcrc && s->pending > beg)
  81982. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81983. s->pending - beg);
  81984. flush_pending(strm);
  81985. beg = s->pending;
  81986. if (s->pending == s->pending_buf_size) {
  81987. val = 1;
  81988. break;
  81989. }
  81990. }
  81991. val = s->gzhead->name[s->gzindex++];
  81992. put_byte(s, val);
  81993. } while (val != 0);
  81994. if (s->gzhead->hcrc && s->pending > beg)
  81995. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81996. s->pending - beg);
  81997. if (val == 0) {
  81998. s->gzindex = 0;
  81999. s->status = COMMENT_STATE;
  82000. }
  82001. }
  82002. else
  82003. s->status = COMMENT_STATE;
  82004. }
  82005. if (s->status == COMMENT_STATE) {
  82006. if (s->gzhead->comment != NULL) {
  82007. uInt beg = s->pending; /* start of bytes to update crc */
  82008. int val;
  82009. do {
  82010. if (s->pending == s->pending_buf_size) {
  82011. if (s->gzhead->hcrc && s->pending > beg)
  82012. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  82013. s->pending - beg);
  82014. flush_pending(strm);
  82015. beg = s->pending;
  82016. if (s->pending == s->pending_buf_size) {
  82017. val = 1;
  82018. break;
  82019. }
  82020. }
  82021. val = s->gzhead->comment[s->gzindex++];
  82022. put_byte(s, val);
  82023. } while (val != 0);
  82024. if (s->gzhead->hcrc && s->pending > beg)
  82025. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  82026. s->pending - beg);
  82027. if (val == 0)
  82028. s->status = HCRC_STATE;
  82029. }
  82030. else
  82031. s->status = HCRC_STATE;
  82032. }
  82033. if (s->status == HCRC_STATE) {
  82034. if (s->gzhead->hcrc) {
  82035. if (s->pending + 2 > s->pending_buf_size)
  82036. flush_pending(strm);
  82037. if (s->pending + 2 <= s->pending_buf_size) {
  82038. put_byte(s, (Byte)(strm->adler & 0xff));
  82039. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82040. strm->adler = crc32(0L, Z_NULL, 0);
  82041. s->status = BUSY_STATE;
  82042. }
  82043. }
  82044. else
  82045. s->status = BUSY_STATE;
  82046. }
  82047. #endif
  82048. /* Flush as much pending output as possible */
  82049. if (s->pending != 0) {
  82050. flush_pending(strm);
  82051. if (strm->avail_out == 0) {
  82052. /* Since avail_out is 0, deflate will be called again with
  82053. * more output space, but possibly with both pending and
  82054. * avail_in equal to zero. There won't be anything to do,
  82055. * but this is not an error situation so make sure we
  82056. * return OK instead of BUF_ERROR at next call of deflate:
  82057. */
  82058. s->last_flush = -1;
  82059. return Z_OK;
  82060. }
  82061. /* Make sure there is something to do and avoid duplicate consecutive
  82062. * flushes. For repeated and useless calls with Z_FINISH, we keep
  82063. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  82064. */
  82065. } else if (strm->avail_in == 0 && flush <= old_flush &&
  82066. flush != Z_FINISH) {
  82067. ERR_RETURN(strm, Z_BUF_ERROR);
  82068. }
  82069. /* User must not provide more input after the first FINISH: */
  82070. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  82071. ERR_RETURN(strm, Z_BUF_ERROR);
  82072. }
  82073. /* Start a new block or continue the current one.
  82074. */
  82075. if (strm->avail_in != 0 || s->lookahead != 0 ||
  82076. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  82077. block_state bstate;
  82078. bstate = (*(configuration_table[s->level].func))(s, flush);
  82079. if (bstate == finish_started || bstate == finish_done) {
  82080. s->status = FINISH_STATE;
  82081. }
  82082. if (bstate == need_more || bstate == finish_started) {
  82083. if (strm->avail_out == 0) {
  82084. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  82085. }
  82086. return Z_OK;
  82087. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  82088. * of deflate should use the same flush parameter to make sure
  82089. * that the flush is complete. So we don't have to output an
  82090. * empty block here, this will be done at next call. This also
  82091. * ensures that for a very small output buffer, we emit at most
  82092. * one empty block.
  82093. */
  82094. }
  82095. if (bstate == block_done) {
  82096. if (flush == Z_PARTIAL_FLUSH) {
  82097. _tr_align(s);
  82098. } else { /* FULL_FLUSH or SYNC_FLUSH */
  82099. _tr_stored_block(s, (char*)0, 0L, 0);
  82100. /* For a full flush, this empty block will be recognized
  82101. * as a special marker by inflate_sync().
  82102. */
  82103. if (flush == Z_FULL_FLUSH) {
  82104. CLEAR_HASH(s); /* forget history */
  82105. }
  82106. }
  82107. flush_pending(strm);
  82108. if (strm->avail_out == 0) {
  82109. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  82110. return Z_OK;
  82111. }
  82112. }
  82113. }
  82114. Assert(strm->avail_out > 0, "bug2");
  82115. if (flush != Z_FINISH) return Z_OK;
  82116. if (s->wrap <= 0) return Z_STREAM_END;
  82117. /* Write the trailer */
  82118. #ifdef GZIP
  82119. if (s->wrap == 2) {
  82120. put_byte(s, (Byte)(strm->adler & 0xff));
  82121. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82122. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  82123. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  82124. put_byte(s, (Byte)(strm->total_in & 0xff));
  82125. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  82126. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  82127. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  82128. }
  82129. else
  82130. #endif
  82131. {
  82132. putShortMSB(s, (uInt)(strm->adler >> 16));
  82133. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  82134. }
  82135. flush_pending(strm);
  82136. /* If avail_out is zero, the application will call deflate again
  82137. * to flush the rest.
  82138. */
  82139. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  82140. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  82141. }
  82142. /* ========================================================================= */
  82143. int ZEXPORT deflateEnd (z_streamp strm)
  82144. {
  82145. int status;
  82146. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82147. status = strm->state->status;
  82148. if (status != INIT_STATE &&
  82149. status != EXTRA_STATE &&
  82150. status != NAME_STATE &&
  82151. status != COMMENT_STATE &&
  82152. status != HCRC_STATE &&
  82153. status != BUSY_STATE &&
  82154. status != FINISH_STATE) {
  82155. return Z_STREAM_ERROR;
  82156. }
  82157. /* Deallocate in reverse order of allocations: */
  82158. TRY_FREE(strm, strm->state->pending_buf);
  82159. TRY_FREE(strm, strm->state->head);
  82160. TRY_FREE(strm, strm->state->prev);
  82161. TRY_FREE(strm, strm->state->window);
  82162. ZFREE(strm, strm->state);
  82163. strm->state = Z_NULL;
  82164. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  82165. }
  82166. /* =========================================================================
  82167. * Copy the source state to the destination state.
  82168. * To simplify the source, this is not supported for 16-bit MSDOS (which
  82169. * doesn't have enough memory anyway to duplicate compression states).
  82170. */
  82171. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  82172. {
  82173. #ifdef MAXSEG_64K
  82174. return Z_STREAM_ERROR;
  82175. #else
  82176. deflate_state *ds;
  82177. deflate_state *ss;
  82178. ushf *overlay;
  82179. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  82180. return Z_STREAM_ERROR;
  82181. }
  82182. ss = source->state;
  82183. zmemcpy(dest, source, sizeof(z_stream));
  82184. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  82185. if (ds == Z_NULL) return Z_MEM_ERROR;
  82186. dest->state = (struct internal_state FAR *) ds;
  82187. zmemcpy(ds, ss, sizeof(deflate_state));
  82188. ds->strm = dest;
  82189. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82190. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82191. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82192. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82193. ds->pending_buf = (uchf *) overlay;
  82194. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82195. ds->pending_buf == Z_NULL) {
  82196. deflateEnd (dest);
  82197. return Z_MEM_ERROR;
  82198. }
  82199. /* following zmemcpy do not work for 16-bit MSDOS */
  82200. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82201. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82202. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82203. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82204. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82205. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82206. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82207. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82208. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82209. ds->bl_desc.dyn_tree = ds->bl_tree;
  82210. return Z_OK;
  82211. #endif /* MAXSEG_64K */
  82212. }
  82213. /* ===========================================================================
  82214. * Read a new buffer from the current input stream, update the adler32
  82215. * and total number of bytes read. All deflate() input goes through
  82216. * this function so some applications may wish to modify it to avoid
  82217. * allocating a large strm->next_in buffer and copying from it.
  82218. * (See also flush_pending()).
  82219. */
  82220. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82221. {
  82222. unsigned len = strm->avail_in;
  82223. if (len > size) len = size;
  82224. if (len == 0) return 0;
  82225. strm->avail_in -= len;
  82226. if (strm->state->wrap == 1) {
  82227. strm->adler = adler32(strm->adler, strm->next_in, len);
  82228. }
  82229. #ifdef GZIP
  82230. else if (strm->state->wrap == 2) {
  82231. strm->adler = crc32(strm->adler, strm->next_in, len);
  82232. }
  82233. #endif
  82234. zmemcpy(buf, strm->next_in, len);
  82235. strm->next_in += len;
  82236. strm->total_in += len;
  82237. return (int)len;
  82238. }
  82239. /* ===========================================================================
  82240. * Initialize the "longest match" routines for a new zlib stream
  82241. */
  82242. local void lm_init (deflate_state *s)
  82243. {
  82244. s->window_size = (ulg)2L*s->w_size;
  82245. CLEAR_HASH(s);
  82246. /* Set the default configuration parameters:
  82247. */
  82248. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82249. s->good_match = configuration_table[s->level].good_length;
  82250. s->nice_match = configuration_table[s->level].nice_length;
  82251. s->max_chain_length = configuration_table[s->level].max_chain;
  82252. s->strstart = 0;
  82253. s->block_start = 0L;
  82254. s->lookahead = 0;
  82255. s->match_length = s->prev_length = MIN_MATCH-1;
  82256. s->match_available = 0;
  82257. s->ins_h = 0;
  82258. #ifndef FASTEST
  82259. #ifdef ASMV
  82260. match_init(); /* initialize the asm code */
  82261. #endif
  82262. #endif
  82263. }
  82264. #ifndef FASTEST
  82265. /* ===========================================================================
  82266. * Set match_start to the longest match starting at the given string and
  82267. * return its length. Matches shorter or equal to prev_length are discarded,
  82268. * in which case the result is equal to prev_length and match_start is
  82269. * garbage.
  82270. * IN assertions: cur_match is the head of the hash chain for the current
  82271. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82272. * OUT assertion: the match length is not greater than s->lookahead.
  82273. */
  82274. #ifndef ASMV
  82275. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82276. * match.S. The code will be functionally equivalent.
  82277. */
  82278. local uInt longest_match(deflate_state *s, IPos cur_match)
  82279. {
  82280. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82281. register Bytef *scan = s->window + s->strstart; /* current string */
  82282. register Bytef *match; /* matched string */
  82283. register int len; /* length of current match */
  82284. int best_len = s->prev_length; /* best match length so far */
  82285. int nice_match = s->nice_match; /* stop if match long enough */
  82286. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82287. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82288. /* Stop when cur_match becomes <= limit. To simplify the code,
  82289. * we prevent matches with the string of window index 0.
  82290. */
  82291. Posf *prev = s->prev;
  82292. uInt wmask = s->w_mask;
  82293. #ifdef UNALIGNED_OK
  82294. /* Compare two bytes at a time. Note: this is not always beneficial.
  82295. * Try with and without -DUNALIGNED_OK to check.
  82296. */
  82297. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82298. register ush scan_start = *(ushf*)scan;
  82299. register ush scan_end = *(ushf*)(scan+best_len-1);
  82300. #else
  82301. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82302. register Byte scan_end1 = scan[best_len-1];
  82303. register Byte scan_end = scan[best_len];
  82304. #endif
  82305. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82306. * It is easy to get rid of this optimization if necessary.
  82307. */
  82308. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82309. /* Do not waste too much time if we already have a good match: */
  82310. if (s->prev_length >= s->good_match) {
  82311. chain_length >>= 2;
  82312. }
  82313. /* Do not look for matches beyond the end of the input. This is necessary
  82314. * to make deflate deterministic.
  82315. */
  82316. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82317. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82318. do {
  82319. Assert(cur_match < s->strstart, "no future");
  82320. match = s->window + cur_match;
  82321. /* Skip to next match if the match length cannot increase
  82322. * or if the match length is less than 2. Note that the checks below
  82323. * for insufficient lookahead only occur occasionally for performance
  82324. * reasons. Therefore uninitialized memory will be accessed, and
  82325. * conditional jumps will be made that depend on those values.
  82326. * However the length of the match is limited to the lookahead, so
  82327. * the output of deflate is not affected by the uninitialized values.
  82328. */
  82329. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82330. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82331. * UNALIGNED_OK if your compiler uses a different size.
  82332. */
  82333. if (*(ushf*)(match+best_len-1) != scan_end ||
  82334. *(ushf*)match != scan_start) continue;
  82335. /* It is not necessary to compare scan[2] and match[2] since they are
  82336. * always equal when the other bytes match, given that the hash keys
  82337. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82338. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82339. * lookahead only every 4th comparison; the 128th check will be made
  82340. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82341. * necessary to put more guard bytes at the end of the window, or
  82342. * to check more often for insufficient lookahead.
  82343. */
  82344. Assert(scan[2] == match[2], "scan[2]?");
  82345. scan++, match++;
  82346. do {
  82347. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82348. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82349. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82350. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82351. scan < strend);
  82352. /* The funny "do {}" generates better code on most compilers */
  82353. /* Here, scan <= window+strstart+257 */
  82354. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82355. if (*scan == *match) scan++;
  82356. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82357. scan = strend - (MAX_MATCH-1);
  82358. #else /* UNALIGNED_OK */
  82359. if (match[best_len] != scan_end ||
  82360. match[best_len-1] != scan_end1 ||
  82361. *match != *scan ||
  82362. *++match != scan[1]) continue;
  82363. /* The check at best_len-1 can be removed because it will be made
  82364. * again later. (This heuristic is not always a win.)
  82365. * It is not necessary to compare scan[2] and match[2] since they
  82366. * are always equal when the other bytes match, given that
  82367. * the hash keys are equal and that HASH_BITS >= 8.
  82368. */
  82369. scan += 2, match++;
  82370. Assert(*scan == *match, "match[2]?");
  82371. /* We check for insufficient lookahead only every 8th comparison;
  82372. * the 256th check will be made at strstart+258.
  82373. */
  82374. do {
  82375. } while (*++scan == *++match && *++scan == *++match &&
  82376. *++scan == *++match && *++scan == *++match &&
  82377. *++scan == *++match && *++scan == *++match &&
  82378. *++scan == *++match && *++scan == *++match &&
  82379. scan < strend);
  82380. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82381. len = MAX_MATCH - (int)(strend - scan);
  82382. scan = strend - MAX_MATCH;
  82383. #endif /* UNALIGNED_OK */
  82384. if (len > best_len) {
  82385. s->match_start = cur_match;
  82386. best_len = len;
  82387. if (len >= nice_match) break;
  82388. #ifdef UNALIGNED_OK
  82389. scan_end = *(ushf*)(scan+best_len-1);
  82390. #else
  82391. scan_end1 = scan[best_len-1];
  82392. scan_end = scan[best_len];
  82393. #endif
  82394. }
  82395. } while ((cur_match = prev[cur_match & wmask]) > limit
  82396. && --chain_length != 0);
  82397. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82398. return s->lookahead;
  82399. }
  82400. #endif /* ASMV */
  82401. #endif /* FASTEST */
  82402. /* ---------------------------------------------------------------------------
  82403. * Optimized version for level == 1 or strategy == Z_RLE only
  82404. */
  82405. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82406. {
  82407. register Bytef *scan = s->window + s->strstart; /* current string */
  82408. register Bytef *match; /* matched string */
  82409. register int len; /* length of current match */
  82410. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82411. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82412. * It is easy to get rid of this optimization if necessary.
  82413. */
  82414. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82415. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82416. Assert(cur_match < s->strstart, "no future");
  82417. match = s->window + cur_match;
  82418. /* Return failure if the match length is less than 2:
  82419. */
  82420. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82421. /* The check at best_len-1 can be removed because it will be made
  82422. * again later. (This heuristic is not always a win.)
  82423. * It is not necessary to compare scan[2] and match[2] since they
  82424. * are always equal when the other bytes match, given that
  82425. * the hash keys are equal and that HASH_BITS >= 8.
  82426. */
  82427. scan += 2, match += 2;
  82428. Assert(*scan == *match, "match[2]?");
  82429. /* We check for insufficient lookahead only every 8th comparison;
  82430. * the 256th check will be made at strstart+258.
  82431. */
  82432. do {
  82433. } while (*++scan == *++match && *++scan == *++match &&
  82434. *++scan == *++match && *++scan == *++match &&
  82435. *++scan == *++match && *++scan == *++match &&
  82436. *++scan == *++match && *++scan == *++match &&
  82437. scan < strend);
  82438. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82439. len = MAX_MATCH - (int)(strend - scan);
  82440. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82441. s->match_start = cur_match;
  82442. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82443. }
  82444. #ifdef DEBUG
  82445. /* ===========================================================================
  82446. * Check that the match at match_start is indeed a match.
  82447. */
  82448. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82449. {
  82450. /* check that the match is indeed a match */
  82451. if (zmemcmp(s->window + match,
  82452. s->window + start, length) != EQUAL) {
  82453. fprintf(stderr, " start %u, match %u, length %d\n",
  82454. start, match, length);
  82455. do {
  82456. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82457. } while (--length != 0);
  82458. z_error("invalid match");
  82459. }
  82460. if (z_verbose > 1) {
  82461. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82462. do { putc(s->window[start++], stderr); } while (--length != 0);
  82463. }
  82464. }
  82465. #else
  82466. # define check_match(s, start, match, length)
  82467. #endif /* DEBUG */
  82468. /* ===========================================================================
  82469. * Fill the window when the lookahead becomes insufficient.
  82470. * Updates strstart and lookahead.
  82471. *
  82472. * IN assertion: lookahead < MIN_LOOKAHEAD
  82473. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82474. * At least one byte has been read, or avail_in == 0; reads are
  82475. * performed for at least two bytes (required for the zip translate_eol
  82476. * option -- not supported here).
  82477. */
  82478. local void fill_window (deflate_state *s)
  82479. {
  82480. register unsigned n, m;
  82481. register Posf *p;
  82482. unsigned more; /* Amount of free space at the end of the window. */
  82483. uInt wsize = s->w_size;
  82484. do {
  82485. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82486. /* Deal with !@#$% 64K limit: */
  82487. if (sizeof(int) <= 2) {
  82488. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82489. more = wsize;
  82490. } else if (more == (unsigned)(-1)) {
  82491. /* Very unlikely, but possible on 16 bit machine if
  82492. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82493. */
  82494. more--;
  82495. }
  82496. }
  82497. /* If the window is almost full and there is insufficient lookahead,
  82498. * move the upper half to the lower one to make room in the upper half.
  82499. */
  82500. if (s->strstart >= wsize+MAX_DIST(s)) {
  82501. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82502. s->match_start -= wsize;
  82503. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82504. s->block_start -= (long) wsize;
  82505. /* Slide the hash table (could be avoided with 32 bit values
  82506. at the expense of memory usage). We slide even when level == 0
  82507. to keep the hash table consistent if we switch back to level > 0
  82508. later. (Using level 0 permanently is not an optimal usage of
  82509. zlib, so we don't care about this pathological case.)
  82510. */
  82511. /* %%% avoid this when Z_RLE */
  82512. n = s->hash_size;
  82513. p = &s->head[n];
  82514. do {
  82515. m = *--p;
  82516. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82517. } while (--n);
  82518. n = wsize;
  82519. #ifndef FASTEST
  82520. p = &s->prev[n];
  82521. do {
  82522. m = *--p;
  82523. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82524. /* If n is not on any hash chain, prev[n] is garbage but
  82525. * its value will never be used.
  82526. */
  82527. } while (--n);
  82528. #endif
  82529. more += wsize;
  82530. }
  82531. if (s->strm->avail_in == 0) return;
  82532. /* If there was no sliding:
  82533. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82534. * more == window_size - lookahead - strstart
  82535. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82536. * => more >= window_size - 2*WSIZE + 2
  82537. * In the BIG_MEM or MMAP case (not yet supported),
  82538. * window_size == input_size + MIN_LOOKAHEAD &&
  82539. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82540. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82541. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82542. */
  82543. Assert(more >= 2, "more < 2");
  82544. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82545. s->lookahead += n;
  82546. /* Initialize the hash value now that we have some input: */
  82547. if (s->lookahead >= MIN_MATCH) {
  82548. s->ins_h = s->window[s->strstart];
  82549. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82550. #if MIN_MATCH != 3
  82551. Call UPDATE_HASH() MIN_MATCH-3 more times
  82552. #endif
  82553. }
  82554. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82555. * but this is not important since only literal bytes will be emitted.
  82556. */
  82557. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82558. }
  82559. /* ===========================================================================
  82560. * Flush the current block, with given end-of-file flag.
  82561. * IN assertion: strstart is set to the end of the current match.
  82562. */
  82563. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82564. _tr_flush_block(s, (s->block_start >= 0L ? \
  82565. (charf *)&s->window[(unsigned)s->block_start] : \
  82566. (charf *)Z_NULL), \
  82567. (ulg)((long)s->strstart - s->block_start), \
  82568. (eof)); \
  82569. s->block_start = s->strstart; \
  82570. flush_pending(s->strm); \
  82571. Tracev((stderr,"[FLUSH]")); \
  82572. }
  82573. /* Same but force premature exit if necessary. */
  82574. #define FLUSH_BLOCK(s, eof) { \
  82575. FLUSH_BLOCK_ONLY(s, eof); \
  82576. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82577. }
  82578. /* ===========================================================================
  82579. * Copy without compression as much as possible from the input stream, return
  82580. * the current block state.
  82581. * This function does not insert new strings in the dictionary since
  82582. * uncompressible data is probably not useful. This function is used
  82583. * only for the level=0 compression option.
  82584. * NOTE: this function should be optimized to avoid extra copying from
  82585. * window to pending_buf.
  82586. */
  82587. local block_state deflate_stored(deflate_state *s, int flush)
  82588. {
  82589. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82590. * to pending_buf_size, and each stored block has a 5 byte header:
  82591. */
  82592. ulg max_block_size = 0xffff;
  82593. ulg max_start;
  82594. if (max_block_size > s->pending_buf_size - 5) {
  82595. max_block_size = s->pending_buf_size - 5;
  82596. }
  82597. /* Copy as much as possible from input to output: */
  82598. for (;;) {
  82599. /* Fill the window as much as possible: */
  82600. if (s->lookahead <= 1) {
  82601. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82602. s->block_start >= (long)s->w_size, "slide too late");
  82603. fill_window(s);
  82604. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82605. if (s->lookahead == 0) break; /* flush the current block */
  82606. }
  82607. Assert(s->block_start >= 0L, "block gone");
  82608. s->strstart += s->lookahead;
  82609. s->lookahead = 0;
  82610. /* Emit a stored block if pending_buf will be full: */
  82611. max_start = s->block_start + max_block_size;
  82612. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82613. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82614. s->lookahead = (uInt)(s->strstart - max_start);
  82615. s->strstart = (uInt)max_start;
  82616. FLUSH_BLOCK(s, 0);
  82617. }
  82618. /* Flush if we may have to slide, otherwise block_start may become
  82619. * negative and the data will be gone:
  82620. */
  82621. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82622. FLUSH_BLOCK(s, 0);
  82623. }
  82624. }
  82625. FLUSH_BLOCK(s, flush == Z_FINISH);
  82626. return flush == Z_FINISH ? finish_done : block_done;
  82627. }
  82628. /* ===========================================================================
  82629. * Compress as much as possible from the input stream, return the current
  82630. * block state.
  82631. * This function does not perform lazy evaluation of matches and inserts
  82632. * new strings in the dictionary only for unmatched strings or for short
  82633. * matches. It is used only for the fast compression options.
  82634. */
  82635. local block_state deflate_fast(deflate_state *s, int flush)
  82636. {
  82637. IPos hash_head = NIL; /* head of the hash chain */
  82638. int bflush; /* set if current block must be flushed */
  82639. for (;;) {
  82640. /* Make sure that we always have enough lookahead, except
  82641. * at the end of the input file. We need MAX_MATCH bytes
  82642. * for the next match, plus MIN_MATCH bytes to insert the
  82643. * string following the next match.
  82644. */
  82645. if (s->lookahead < MIN_LOOKAHEAD) {
  82646. fill_window(s);
  82647. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82648. return need_more;
  82649. }
  82650. if (s->lookahead == 0) break; /* flush the current block */
  82651. }
  82652. /* Insert the string window[strstart .. strstart+2] in the
  82653. * dictionary, and set hash_head to the head of the hash chain:
  82654. */
  82655. if (s->lookahead >= MIN_MATCH) {
  82656. INSERT_STRING(s, s->strstart, hash_head);
  82657. }
  82658. /* Find the longest match, discarding those <= prev_length.
  82659. * At this point we have always match_length < MIN_MATCH
  82660. */
  82661. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82662. /* To simplify the code, we prevent matches with the string
  82663. * of window index 0 (in particular we have to avoid a match
  82664. * of the string with itself at the start of the input file).
  82665. */
  82666. #ifdef FASTEST
  82667. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82668. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82669. s->match_length = longest_match_fast (s, hash_head);
  82670. }
  82671. #else
  82672. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82673. s->match_length = longest_match (s, hash_head);
  82674. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82675. s->match_length = longest_match_fast (s, hash_head);
  82676. }
  82677. #endif
  82678. /* longest_match() or longest_match_fast() sets match_start */
  82679. }
  82680. if (s->match_length >= MIN_MATCH) {
  82681. check_match(s, s->strstart, s->match_start, s->match_length);
  82682. _tr_tally_dist(s, s->strstart - s->match_start,
  82683. s->match_length - MIN_MATCH, bflush);
  82684. s->lookahead -= s->match_length;
  82685. /* Insert new strings in the hash table only if the match length
  82686. * is not too large. This saves time but degrades compression.
  82687. */
  82688. #ifndef FASTEST
  82689. if (s->match_length <= s->max_insert_length &&
  82690. s->lookahead >= MIN_MATCH) {
  82691. s->match_length--; /* string at strstart already in table */
  82692. do {
  82693. s->strstart++;
  82694. INSERT_STRING(s, s->strstart, hash_head);
  82695. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82696. * always MIN_MATCH bytes ahead.
  82697. */
  82698. } while (--s->match_length != 0);
  82699. s->strstart++;
  82700. } else
  82701. #endif
  82702. {
  82703. s->strstart += s->match_length;
  82704. s->match_length = 0;
  82705. s->ins_h = s->window[s->strstart];
  82706. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82707. #if MIN_MATCH != 3
  82708. Call UPDATE_HASH() MIN_MATCH-3 more times
  82709. #endif
  82710. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82711. * matter since it will be recomputed at next deflate call.
  82712. */
  82713. }
  82714. } else {
  82715. /* No match, output a literal byte */
  82716. Tracevv((stderr,"%c", s->window[s->strstart]));
  82717. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82718. s->lookahead--;
  82719. s->strstart++;
  82720. }
  82721. if (bflush) FLUSH_BLOCK(s, 0);
  82722. }
  82723. FLUSH_BLOCK(s, flush == Z_FINISH);
  82724. return flush == Z_FINISH ? finish_done : block_done;
  82725. }
  82726. #ifndef FASTEST
  82727. /* ===========================================================================
  82728. * Same as above, but achieves better compression. We use a lazy
  82729. * evaluation for matches: a match is finally adopted only if there is
  82730. * no better match at the next window position.
  82731. */
  82732. local block_state deflate_slow(deflate_state *s, int flush)
  82733. {
  82734. IPos hash_head = NIL; /* head of hash chain */
  82735. int bflush; /* set if current block must be flushed */
  82736. /* Process the input block. */
  82737. for (;;) {
  82738. /* Make sure that we always have enough lookahead, except
  82739. * at the end of the input file. We need MAX_MATCH bytes
  82740. * for the next match, plus MIN_MATCH bytes to insert the
  82741. * string following the next match.
  82742. */
  82743. if (s->lookahead < MIN_LOOKAHEAD) {
  82744. fill_window(s);
  82745. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82746. return need_more;
  82747. }
  82748. if (s->lookahead == 0) break; /* flush the current block */
  82749. }
  82750. /* Insert the string window[strstart .. strstart+2] in the
  82751. * dictionary, and set hash_head to the head of the hash chain:
  82752. */
  82753. if (s->lookahead >= MIN_MATCH) {
  82754. INSERT_STRING(s, s->strstart, hash_head);
  82755. }
  82756. /* Find the longest match, discarding those <= prev_length.
  82757. */
  82758. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82759. s->match_length = MIN_MATCH-1;
  82760. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82761. s->strstart - hash_head <= MAX_DIST(s)) {
  82762. /* To simplify the code, we prevent matches with the string
  82763. * of window index 0 (in particular we have to avoid a match
  82764. * of the string with itself at the start of the input file).
  82765. */
  82766. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82767. s->match_length = longest_match (s, hash_head);
  82768. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82769. s->match_length = longest_match_fast (s, hash_head);
  82770. }
  82771. /* longest_match() or longest_match_fast() sets match_start */
  82772. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82773. #if TOO_FAR <= 32767
  82774. || (s->match_length == MIN_MATCH &&
  82775. s->strstart - s->match_start > TOO_FAR)
  82776. #endif
  82777. )) {
  82778. /* If prev_match is also MIN_MATCH, match_start is garbage
  82779. * but we will ignore the current match anyway.
  82780. */
  82781. s->match_length = MIN_MATCH-1;
  82782. }
  82783. }
  82784. /* If there was a match at the previous step and the current
  82785. * match is not better, output the previous match:
  82786. */
  82787. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82788. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82789. /* Do not insert strings in hash table beyond this. */
  82790. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82791. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82792. s->prev_length - MIN_MATCH, bflush);
  82793. /* Insert in hash table all strings up to the end of the match.
  82794. * strstart-1 and strstart are already inserted. If there is not
  82795. * enough lookahead, the last two strings are not inserted in
  82796. * the hash table.
  82797. */
  82798. s->lookahead -= s->prev_length-1;
  82799. s->prev_length -= 2;
  82800. do {
  82801. if (++s->strstart <= max_insert) {
  82802. INSERT_STRING(s, s->strstart, hash_head);
  82803. }
  82804. } while (--s->prev_length != 0);
  82805. s->match_available = 0;
  82806. s->match_length = MIN_MATCH-1;
  82807. s->strstart++;
  82808. if (bflush) FLUSH_BLOCK(s, 0);
  82809. } else if (s->match_available) {
  82810. /* If there was no match at the previous position, output a
  82811. * single literal. If there was a match but the current match
  82812. * is longer, truncate the previous match to a single literal.
  82813. */
  82814. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82815. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82816. if (bflush) {
  82817. FLUSH_BLOCK_ONLY(s, 0);
  82818. }
  82819. s->strstart++;
  82820. s->lookahead--;
  82821. if (s->strm->avail_out == 0) return need_more;
  82822. } else {
  82823. /* There is no previous match to compare with, wait for
  82824. * the next step to decide.
  82825. */
  82826. s->match_available = 1;
  82827. s->strstart++;
  82828. s->lookahead--;
  82829. }
  82830. }
  82831. Assert (flush != Z_NO_FLUSH, "no flush?");
  82832. if (s->match_available) {
  82833. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82834. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82835. s->match_available = 0;
  82836. }
  82837. FLUSH_BLOCK(s, flush == Z_FINISH);
  82838. return flush == Z_FINISH ? finish_done : block_done;
  82839. }
  82840. #endif /* FASTEST */
  82841. #if 0
  82842. /* ===========================================================================
  82843. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82844. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82845. * deflate switches away from Z_RLE.)
  82846. */
  82847. local block_state deflate_rle(s, flush)
  82848. deflate_state *s;
  82849. int flush;
  82850. {
  82851. int bflush; /* set if current block must be flushed */
  82852. uInt run; /* length of run */
  82853. uInt max; /* maximum length of run */
  82854. uInt prev; /* byte at distance one to match */
  82855. Bytef *scan; /* scan for end of run */
  82856. for (;;) {
  82857. /* Make sure that we always have enough lookahead, except
  82858. * at the end of the input file. We need MAX_MATCH bytes
  82859. * for the longest encodable run.
  82860. */
  82861. if (s->lookahead < MAX_MATCH) {
  82862. fill_window(s);
  82863. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82864. return need_more;
  82865. }
  82866. if (s->lookahead == 0) break; /* flush the current block */
  82867. }
  82868. /* See how many times the previous byte repeats */
  82869. run = 0;
  82870. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82871. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82872. scan = s->window + s->strstart - 1;
  82873. prev = *scan++;
  82874. do {
  82875. if (*scan++ != prev)
  82876. break;
  82877. } while (++run < max);
  82878. }
  82879. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82880. if (run >= MIN_MATCH) {
  82881. check_match(s, s->strstart, s->strstart - 1, run);
  82882. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82883. s->lookahead -= run;
  82884. s->strstart += run;
  82885. } else {
  82886. /* No match, output a literal byte */
  82887. Tracevv((stderr,"%c", s->window[s->strstart]));
  82888. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82889. s->lookahead--;
  82890. s->strstart++;
  82891. }
  82892. if (bflush) FLUSH_BLOCK(s, 0);
  82893. }
  82894. FLUSH_BLOCK(s, flush == Z_FINISH);
  82895. return flush == Z_FINISH ? finish_done : block_done;
  82896. }
  82897. #endif
  82898. /*** End of inlined file: deflate.c ***/
  82899. /*** Start of inlined file: inffast.c ***/
  82900. /*** Start of inlined file: inftrees.h ***/
  82901. /* WARNING: this file should *not* be used by applications. It is
  82902. part of the implementation of the compression library and is
  82903. subject to change. Applications should only use zlib.h.
  82904. */
  82905. #ifndef _INFTREES_H_
  82906. #define _INFTREES_H_
  82907. /* Structure for decoding tables. Each entry provides either the
  82908. information needed to do the operation requested by the code that
  82909. indexed that table entry, or it provides a pointer to another
  82910. table that indexes more bits of the code. op indicates whether
  82911. the entry is a pointer to another table, a literal, a length or
  82912. distance, an end-of-block, or an invalid code. For a table
  82913. pointer, the low four bits of op is the number of index bits of
  82914. that table. For a length or distance, the low four bits of op
  82915. is the number of extra bits to get after the code. bits is
  82916. the number of bits in this code or part of the code to drop off
  82917. of the bit buffer. val is the actual byte to output in the case
  82918. of a literal, the base length or distance, or the offset from
  82919. the current table to the next table. Each entry is four bytes. */
  82920. typedef struct {
  82921. unsigned char op; /* operation, extra bits, table bits */
  82922. unsigned char bits; /* bits in this part of the code */
  82923. unsigned short val; /* offset in table or code value */
  82924. } code;
  82925. /* op values as set by inflate_table():
  82926. 00000000 - literal
  82927. 0000tttt - table link, tttt != 0 is the number of table index bits
  82928. 0001eeee - length or distance, eeee is the number of extra bits
  82929. 01100000 - end of block
  82930. 01000000 - invalid code
  82931. */
  82932. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82933. exhaustive search was 1444 code structures (852 for length/literals
  82934. and 592 for distances, the latter actually the result of an
  82935. exhaustive search). The true maximum is not known, but the value
  82936. below is more than safe. */
  82937. #define ENOUGH 2048
  82938. #define MAXD 592
  82939. /* Type of code to build for inftable() */
  82940. typedef enum {
  82941. CODES,
  82942. LENS,
  82943. DISTS
  82944. } codetype;
  82945. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82946. unsigned codes, code FAR * FAR *table,
  82947. unsigned FAR *bits, unsigned short FAR *work));
  82948. #endif
  82949. /*** End of inlined file: inftrees.h ***/
  82950. /*** Start of inlined file: inflate.h ***/
  82951. /* WARNING: this file should *not* be used by applications. It is
  82952. part of the implementation of the compression library and is
  82953. subject to change. Applications should only use zlib.h.
  82954. */
  82955. #ifndef _INFLATE_H_
  82956. #define _INFLATE_H_
  82957. /* define NO_GZIP when compiling if you want to disable gzip header and
  82958. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82959. the crc code when it is not needed. For shared libraries, gzip decoding
  82960. should be left enabled. */
  82961. #ifndef NO_GZIP
  82962. # define GUNZIP
  82963. #endif
  82964. /* Possible inflate modes between inflate() calls */
  82965. typedef enum {
  82966. HEAD, /* i: waiting for magic header */
  82967. FLAGS, /* i: waiting for method and flags (gzip) */
  82968. TIME, /* i: waiting for modification time (gzip) */
  82969. OS, /* i: waiting for extra flags and operating system (gzip) */
  82970. EXLEN, /* i: waiting for extra length (gzip) */
  82971. EXTRA, /* i: waiting for extra bytes (gzip) */
  82972. NAME, /* i: waiting for end of file name (gzip) */
  82973. COMMENT, /* i: waiting for end of comment (gzip) */
  82974. HCRC, /* i: waiting for header crc (gzip) */
  82975. DICTID, /* i: waiting for dictionary check value */
  82976. DICT, /* waiting for inflateSetDictionary() call */
  82977. TYPE, /* i: waiting for type bits, including last-flag bit */
  82978. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82979. STORED, /* i: waiting for stored size (length and complement) */
  82980. COPY, /* i/o: waiting for input or output to copy stored block */
  82981. TABLE, /* i: waiting for dynamic block table lengths */
  82982. LENLENS, /* i: waiting for code length code lengths */
  82983. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82984. LEN, /* i: waiting for length/lit code */
  82985. LENEXT, /* i: waiting for length extra bits */
  82986. DIST, /* i: waiting for distance code */
  82987. DISTEXT, /* i: waiting for distance extra bits */
  82988. MATCH, /* o: waiting for output space to copy string */
  82989. LIT, /* o: waiting for output space to write literal */
  82990. CHECK, /* i: waiting for 32-bit check value */
  82991. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82992. DONE, /* finished check, done -- remain here until reset */
  82993. BAD, /* got a data error -- remain here until reset */
  82994. MEM, /* got an inflate() memory error -- remain here until reset */
  82995. SYNC /* looking for synchronization bytes to restart inflate() */
  82996. } inflate_mode;
  82997. /*
  82998. State transitions between above modes -
  82999. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  83000. Process header:
  83001. HEAD -> (gzip) or (zlib)
  83002. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  83003. NAME -> COMMENT -> HCRC -> TYPE
  83004. (zlib) -> DICTID or TYPE
  83005. DICTID -> DICT -> TYPE
  83006. Read deflate blocks:
  83007. TYPE -> STORED or TABLE or LEN or CHECK
  83008. STORED -> COPY -> TYPE
  83009. TABLE -> LENLENS -> CODELENS -> LEN
  83010. Read deflate codes:
  83011. LEN -> LENEXT or LIT or TYPE
  83012. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  83013. LIT -> LEN
  83014. Process trailer:
  83015. CHECK -> LENGTH -> DONE
  83016. */
  83017. /* state maintained between inflate() calls. Approximately 7K bytes. */
  83018. struct inflate_state {
  83019. inflate_mode mode; /* current inflate mode */
  83020. int last; /* true if processing last block */
  83021. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  83022. int havedict; /* true if dictionary provided */
  83023. int flags; /* gzip header method and flags (0 if zlib) */
  83024. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  83025. unsigned long check; /* protected copy of check value */
  83026. unsigned long total; /* protected copy of output count */
  83027. gz_headerp head; /* where to save gzip header information */
  83028. /* sliding window */
  83029. unsigned wbits; /* log base 2 of requested window size */
  83030. unsigned wsize; /* window size or zero if not using window */
  83031. unsigned whave; /* valid bytes in the window */
  83032. unsigned write; /* window write index */
  83033. unsigned char FAR *window; /* allocated sliding window, if needed */
  83034. /* bit accumulator */
  83035. unsigned long hold; /* input bit accumulator */
  83036. unsigned bits; /* number of bits in "in" */
  83037. /* for string and stored block copying */
  83038. unsigned length; /* literal or length of data to copy */
  83039. unsigned offset; /* distance back to copy string from */
  83040. /* for table and code decoding */
  83041. unsigned extra; /* extra bits needed */
  83042. /* fixed and dynamic code tables */
  83043. code const FAR *lencode; /* starting table for length/literal codes */
  83044. code const FAR *distcode; /* starting table for distance codes */
  83045. unsigned lenbits; /* index bits for lencode */
  83046. unsigned distbits; /* index bits for distcode */
  83047. /* dynamic table building */
  83048. unsigned ncode; /* number of code length code lengths */
  83049. unsigned nlen; /* number of length code lengths */
  83050. unsigned ndist; /* number of distance code lengths */
  83051. unsigned have; /* number of code lengths in lens[] */
  83052. code FAR *next; /* next available space in codes[] */
  83053. unsigned short lens[320]; /* temporary storage for code lengths */
  83054. unsigned short work[288]; /* work area for code table building */
  83055. code codes[ENOUGH]; /* space for code tables */
  83056. };
  83057. #endif
  83058. /*** End of inlined file: inflate.h ***/
  83059. /*** Start of inlined file: inffast.h ***/
  83060. /* WARNING: this file should *not* be used by applications. It is
  83061. part of the implementation of the compression library and is
  83062. subject to change. Applications should only use zlib.h.
  83063. */
  83064. void inflate_fast OF((z_streamp strm, unsigned start));
  83065. /*** End of inlined file: inffast.h ***/
  83066. #ifndef ASMINF
  83067. /* Allow machine dependent optimization for post-increment or pre-increment.
  83068. Based on testing to date,
  83069. Pre-increment preferred for:
  83070. - PowerPC G3 (Adler)
  83071. - MIPS R5000 (Randers-Pehrson)
  83072. Post-increment preferred for:
  83073. - none
  83074. No measurable difference:
  83075. - Pentium III (Anderson)
  83076. - M68060 (Nikl)
  83077. */
  83078. #ifdef POSTINC
  83079. # define OFF 0
  83080. # define PUP(a) *(a)++
  83081. #else
  83082. # define OFF 1
  83083. # define PUP(a) *++(a)
  83084. #endif
  83085. /*
  83086. Decode literal, length, and distance codes and write out the resulting
  83087. literal and match bytes until either not enough input or output is
  83088. available, an end-of-block is encountered, or a data error is encountered.
  83089. When large enough input and output buffers are supplied to inflate(), for
  83090. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  83091. inflate execution time is spent in this routine.
  83092. Entry assumptions:
  83093. state->mode == LEN
  83094. strm->avail_in >= 6
  83095. strm->avail_out >= 258
  83096. start >= strm->avail_out
  83097. state->bits < 8
  83098. On return, state->mode is one of:
  83099. LEN -- ran out of enough output space or enough available input
  83100. TYPE -- reached end of block code, inflate() to interpret next block
  83101. BAD -- error in block data
  83102. Notes:
  83103. - The maximum input bits used by a length/distance pair is 15 bits for the
  83104. length code, 5 bits for the length extra, 15 bits for the distance code,
  83105. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83106. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  83107. checking for available input while decoding.
  83108. - The maximum bytes that a single length/distance pair can output is 258
  83109. bytes, which is the maximum length that can be coded. inflate_fast()
  83110. requires strm->avail_out >= 258 for each loop to avoid checking for
  83111. output space.
  83112. */
  83113. void inflate_fast (z_streamp strm, unsigned start)
  83114. {
  83115. struct inflate_state FAR *state;
  83116. unsigned char FAR *in; /* local strm->next_in */
  83117. unsigned char FAR *last; /* while in < last, enough input available */
  83118. unsigned char FAR *out; /* local strm->next_out */
  83119. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  83120. unsigned char FAR *end; /* while out < end, enough space available */
  83121. #ifdef INFLATE_STRICT
  83122. unsigned dmax; /* maximum distance from zlib header */
  83123. #endif
  83124. unsigned wsize; /* window size or zero if not using window */
  83125. unsigned whave; /* valid bytes in the window */
  83126. unsigned write; /* window write index */
  83127. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  83128. unsigned long hold; /* local strm->hold */
  83129. unsigned bits; /* local strm->bits */
  83130. code const FAR *lcode; /* local strm->lencode */
  83131. code const FAR *dcode; /* local strm->distcode */
  83132. unsigned lmask; /* mask for first level of length codes */
  83133. unsigned dmask; /* mask for first level of distance codes */
  83134. code thisx; /* retrieved table entry */
  83135. unsigned op; /* code bits, operation, extra bits, or */
  83136. /* window position, window bytes to copy */
  83137. unsigned len; /* match length, unused bytes */
  83138. unsigned dist; /* match distance */
  83139. unsigned char FAR *from; /* where to copy match from */
  83140. /* copy state to local variables */
  83141. state = (struct inflate_state FAR *)strm->state;
  83142. in = strm->next_in - OFF;
  83143. last = in + (strm->avail_in - 5);
  83144. out = strm->next_out - OFF;
  83145. beg = out - (start - strm->avail_out);
  83146. end = out + (strm->avail_out - 257);
  83147. #ifdef INFLATE_STRICT
  83148. dmax = state->dmax;
  83149. #endif
  83150. wsize = state->wsize;
  83151. whave = state->whave;
  83152. write = state->write;
  83153. window = state->window;
  83154. hold = state->hold;
  83155. bits = state->bits;
  83156. lcode = state->lencode;
  83157. dcode = state->distcode;
  83158. lmask = (1U << state->lenbits) - 1;
  83159. dmask = (1U << state->distbits) - 1;
  83160. /* decode literals and length/distances until end-of-block or not enough
  83161. input data or output space */
  83162. do {
  83163. if (bits < 15) {
  83164. hold += (unsigned long)(PUP(in)) << bits;
  83165. bits += 8;
  83166. hold += (unsigned long)(PUP(in)) << bits;
  83167. bits += 8;
  83168. }
  83169. thisx = lcode[hold & lmask];
  83170. dolen:
  83171. op = (unsigned)(thisx.bits);
  83172. hold >>= op;
  83173. bits -= op;
  83174. op = (unsigned)(thisx.op);
  83175. if (op == 0) { /* literal */
  83176. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83177. "inflate: literal '%c'\n" :
  83178. "inflate: literal 0x%02x\n", thisx.val));
  83179. PUP(out) = (unsigned char)(thisx.val);
  83180. }
  83181. else if (op & 16) { /* length base */
  83182. len = (unsigned)(thisx.val);
  83183. op &= 15; /* number of extra bits */
  83184. if (op) {
  83185. if (bits < op) {
  83186. hold += (unsigned long)(PUP(in)) << bits;
  83187. bits += 8;
  83188. }
  83189. len += (unsigned)hold & ((1U << op) - 1);
  83190. hold >>= op;
  83191. bits -= op;
  83192. }
  83193. Tracevv((stderr, "inflate: length %u\n", len));
  83194. if (bits < 15) {
  83195. hold += (unsigned long)(PUP(in)) << bits;
  83196. bits += 8;
  83197. hold += (unsigned long)(PUP(in)) << bits;
  83198. bits += 8;
  83199. }
  83200. thisx = dcode[hold & dmask];
  83201. dodist:
  83202. op = (unsigned)(thisx.bits);
  83203. hold >>= op;
  83204. bits -= op;
  83205. op = (unsigned)(thisx.op);
  83206. if (op & 16) { /* distance base */
  83207. dist = (unsigned)(thisx.val);
  83208. op &= 15; /* number of extra bits */
  83209. if (bits < op) {
  83210. hold += (unsigned long)(PUP(in)) << bits;
  83211. bits += 8;
  83212. if (bits < op) {
  83213. hold += (unsigned long)(PUP(in)) << bits;
  83214. bits += 8;
  83215. }
  83216. }
  83217. dist += (unsigned)hold & ((1U << op) - 1);
  83218. #ifdef INFLATE_STRICT
  83219. if (dist > dmax) {
  83220. strm->msg = (char *)"invalid distance too far back";
  83221. state->mode = BAD;
  83222. break;
  83223. }
  83224. #endif
  83225. hold >>= op;
  83226. bits -= op;
  83227. Tracevv((stderr, "inflate: distance %u\n", dist));
  83228. op = (unsigned)(out - beg); /* max distance in output */
  83229. if (dist > op) { /* see if copy from window */
  83230. op = dist - op; /* distance back in window */
  83231. if (op > whave) {
  83232. strm->msg = (char *)"invalid distance too far back";
  83233. state->mode = BAD;
  83234. break;
  83235. }
  83236. from = window - OFF;
  83237. if (write == 0) { /* very common case */
  83238. from += wsize - op;
  83239. if (op < len) { /* some from window */
  83240. len -= op;
  83241. do {
  83242. PUP(out) = PUP(from);
  83243. } while (--op);
  83244. from = out - dist; /* rest from output */
  83245. }
  83246. }
  83247. else if (write < op) { /* wrap around window */
  83248. from += wsize + write - op;
  83249. op -= write;
  83250. if (op < len) { /* some from end of window */
  83251. len -= op;
  83252. do {
  83253. PUP(out) = PUP(from);
  83254. } while (--op);
  83255. from = window - OFF;
  83256. if (write < len) { /* some from start of window */
  83257. op = write;
  83258. len -= op;
  83259. do {
  83260. PUP(out) = PUP(from);
  83261. } while (--op);
  83262. from = out - dist; /* rest from output */
  83263. }
  83264. }
  83265. }
  83266. else { /* contiguous in window */
  83267. from += write - op;
  83268. if (op < len) { /* some from window */
  83269. len -= op;
  83270. do {
  83271. PUP(out) = PUP(from);
  83272. } while (--op);
  83273. from = out - dist; /* rest from output */
  83274. }
  83275. }
  83276. while (len > 2) {
  83277. PUP(out) = PUP(from);
  83278. PUP(out) = PUP(from);
  83279. PUP(out) = PUP(from);
  83280. len -= 3;
  83281. }
  83282. if (len) {
  83283. PUP(out) = PUP(from);
  83284. if (len > 1)
  83285. PUP(out) = PUP(from);
  83286. }
  83287. }
  83288. else {
  83289. from = out - dist; /* copy direct from output */
  83290. do { /* minimum length is three */
  83291. PUP(out) = PUP(from);
  83292. PUP(out) = PUP(from);
  83293. PUP(out) = PUP(from);
  83294. len -= 3;
  83295. } while (len > 2);
  83296. if (len) {
  83297. PUP(out) = PUP(from);
  83298. if (len > 1)
  83299. PUP(out) = PUP(from);
  83300. }
  83301. }
  83302. }
  83303. else if ((op & 64) == 0) { /* 2nd level distance code */
  83304. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83305. goto dodist;
  83306. }
  83307. else {
  83308. strm->msg = (char *)"invalid distance code";
  83309. state->mode = BAD;
  83310. break;
  83311. }
  83312. }
  83313. else if ((op & 64) == 0) { /* 2nd level length code */
  83314. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83315. goto dolen;
  83316. }
  83317. else if (op & 32) { /* end-of-block */
  83318. Tracevv((stderr, "inflate: end of block\n"));
  83319. state->mode = TYPE;
  83320. break;
  83321. }
  83322. else {
  83323. strm->msg = (char *)"invalid literal/length code";
  83324. state->mode = BAD;
  83325. break;
  83326. }
  83327. } while (in < last && out < end);
  83328. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83329. len = bits >> 3;
  83330. in -= len;
  83331. bits -= len << 3;
  83332. hold &= (1U << bits) - 1;
  83333. /* update state and return */
  83334. strm->next_in = in + OFF;
  83335. strm->next_out = out + OFF;
  83336. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83337. strm->avail_out = (unsigned)(out < end ?
  83338. 257 + (end - out) : 257 - (out - end));
  83339. state->hold = hold;
  83340. state->bits = bits;
  83341. return;
  83342. }
  83343. /*
  83344. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83345. - Using bit fields for code structure
  83346. - Different op definition to avoid & for extra bits (do & for table bits)
  83347. - Three separate decoding do-loops for direct, window, and write == 0
  83348. - Special case for distance > 1 copies to do overlapped load and store copy
  83349. - Explicit branch predictions (based on measured branch probabilities)
  83350. - Deferring match copy and interspersed it with decoding subsequent codes
  83351. - Swapping literal/length else
  83352. - Swapping window/direct else
  83353. - Larger unrolled copy loops (three is about right)
  83354. - Moving len -= 3 statement into middle of loop
  83355. */
  83356. #endif /* !ASMINF */
  83357. /*** End of inlined file: inffast.c ***/
  83358. #undef PULLBYTE
  83359. #undef LOAD
  83360. #undef RESTORE
  83361. #undef INITBITS
  83362. #undef NEEDBITS
  83363. #undef DROPBITS
  83364. #undef BYTEBITS
  83365. /*** Start of inlined file: inflate.c ***/
  83366. /*
  83367. * Change history:
  83368. *
  83369. * 1.2.beta0 24 Nov 2002
  83370. * - First version -- complete rewrite of inflate to simplify code, avoid
  83371. * creation of window when not needed, minimize use of window when it is
  83372. * needed, make inffast.c even faster, implement gzip decoding, and to
  83373. * improve code readability and style over the previous zlib inflate code
  83374. *
  83375. * 1.2.beta1 25 Nov 2002
  83376. * - Use pointers for available input and output checking in inffast.c
  83377. * - Remove input and output counters in inffast.c
  83378. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83379. * - Remove unnecessary second byte pull from length extra in inffast.c
  83380. * - Unroll direct copy to three copies per loop in inffast.c
  83381. *
  83382. * 1.2.beta2 4 Dec 2002
  83383. * - Change external routine names to reduce potential conflicts
  83384. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83385. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83386. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83387. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83388. *
  83389. * 1.2.beta3 22 Dec 2002
  83390. * - Add comments on state->bits assertion in inffast.c
  83391. * - Add comments on op field in inftrees.h
  83392. * - Fix bug in reuse of allocated window after inflateReset()
  83393. * - Remove bit fields--back to byte structure for speed
  83394. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83395. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83396. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83397. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83398. * - Use local copies of stream next and avail values, as well as local bit
  83399. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83400. *
  83401. * 1.2.beta4 1 Jan 2003
  83402. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83403. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83404. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83405. * - Rearrange window copies in inflate_fast() for speed and simplification
  83406. * - Unroll last copy for window match in inflate_fast()
  83407. * - Use local copies of window variables in inflate_fast() for speed
  83408. * - Pull out common write == 0 case for speed in inflate_fast()
  83409. * - Make op and len in inflate_fast() unsigned for consistency
  83410. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83411. * - Simplified bad distance check in inflate_fast()
  83412. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83413. * source file infback.c to provide a call-back interface to inflate for
  83414. * programs like gzip and unzip -- uses window as output buffer to avoid
  83415. * window copying
  83416. *
  83417. * 1.2.beta5 1 Jan 2003
  83418. * - Improved inflateBack() interface to allow the caller to provide initial
  83419. * input in strm.
  83420. * - Fixed stored blocks bug in inflateBack()
  83421. *
  83422. * 1.2.beta6 4 Jan 2003
  83423. * - Added comments in inffast.c on effectiveness of POSTINC
  83424. * - Typecasting all around to reduce compiler warnings
  83425. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83426. * make compilers happy
  83427. * - Changed type of window in inflateBackInit() to unsigned char *
  83428. *
  83429. * 1.2.beta7 27 Jan 2003
  83430. * - Changed many types to unsigned or unsigned short to avoid warnings
  83431. * - Added inflateCopy() function
  83432. *
  83433. * 1.2.0 9 Mar 2003
  83434. * - Changed inflateBack() interface to provide separate opaque descriptors
  83435. * for the in() and out() functions
  83436. * - Changed inflateBack() argument and in_func typedef to swap the length
  83437. * and buffer address return values for the input function
  83438. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83439. *
  83440. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83441. */
  83442. /*** Start of inlined file: inffast.h ***/
  83443. /* WARNING: this file should *not* be used by applications. It is
  83444. part of the implementation of the compression library and is
  83445. subject to change. Applications should only use zlib.h.
  83446. */
  83447. void inflate_fast OF((z_streamp strm, unsigned start));
  83448. /*** End of inlined file: inffast.h ***/
  83449. #ifdef MAKEFIXED
  83450. # ifndef BUILDFIXED
  83451. # define BUILDFIXED
  83452. # endif
  83453. #endif
  83454. /* function prototypes */
  83455. local void fixedtables OF((struct inflate_state FAR *state));
  83456. local int updatewindow OF((z_streamp strm, unsigned out));
  83457. #ifdef BUILDFIXED
  83458. void makefixed OF((void));
  83459. #endif
  83460. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83461. unsigned len));
  83462. int ZEXPORT inflateReset (z_streamp strm)
  83463. {
  83464. struct inflate_state FAR *state;
  83465. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83466. state = (struct inflate_state FAR *)strm->state;
  83467. strm->total_in = strm->total_out = state->total = 0;
  83468. strm->msg = Z_NULL;
  83469. strm->adler = 1; /* to support ill-conceived Java test suite */
  83470. state->mode = HEAD;
  83471. state->last = 0;
  83472. state->havedict = 0;
  83473. state->dmax = 32768U;
  83474. state->head = Z_NULL;
  83475. state->wsize = 0;
  83476. state->whave = 0;
  83477. state->write = 0;
  83478. state->hold = 0;
  83479. state->bits = 0;
  83480. state->lencode = state->distcode = state->next = state->codes;
  83481. Tracev((stderr, "inflate: reset\n"));
  83482. return Z_OK;
  83483. }
  83484. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83485. {
  83486. struct inflate_state FAR *state;
  83487. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83488. state = (struct inflate_state FAR *)strm->state;
  83489. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83490. value &= (1L << bits) - 1;
  83491. state->hold += value << state->bits;
  83492. state->bits += bits;
  83493. return Z_OK;
  83494. }
  83495. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83496. {
  83497. struct inflate_state FAR *state;
  83498. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83499. stream_size != (int)(sizeof(z_stream)))
  83500. return Z_VERSION_ERROR;
  83501. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83502. strm->msg = Z_NULL; /* in case we return an error */
  83503. if (strm->zalloc == (alloc_func)0) {
  83504. strm->zalloc = zcalloc;
  83505. strm->opaque = (voidpf)0;
  83506. }
  83507. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83508. state = (struct inflate_state FAR *)
  83509. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83510. if (state == Z_NULL) return Z_MEM_ERROR;
  83511. Tracev((stderr, "inflate: allocated\n"));
  83512. strm->state = (struct internal_state FAR *)state;
  83513. if (windowBits < 0) {
  83514. state->wrap = 0;
  83515. windowBits = -windowBits;
  83516. }
  83517. else {
  83518. state->wrap = (windowBits >> 4) + 1;
  83519. #ifdef GUNZIP
  83520. if (windowBits < 48) windowBits &= 15;
  83521. #endif
  83522. }
  83523. if (windowBits < 8 || windowBits > 15) {
  83524. ZFREE(strm, state);
  83525. strm->state = Z_NULL;
  83526. return Z_STREAM_ERROR;
  83527. }
  83528. state->wbits = (unsigned)windowBits;
  83529. state->window = Z_NULL;
  83530. return inflateReset(strm);
  83531. }
  83532. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83533. {
  83534. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83535. }
  83536. /*
  83537. Return state with length and distance decoding tables and index sizes set to
  83538. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83539. If BUILDFIXED is defined, then instead this routine builds the tables the
  83540. first time it's called, and returns those tables the first time and
  83541. thereafter. This reduces the size of the code by about 2K bytes, in
  83542. exchange for a little execution time. However, BUILDFIXED should not be
  83543. used for threaded applications, since the rewriting of the tables and virgin
  83544. may not be thread-safe.
  83545. */
  83546. local void fixedtables (struct inflate_state FAR *state)
  83547. {
  83548. #ifdef BUILDFIXED
  83549. static int virgin = 1;
  83550. static code *lenfix, *distfix;
  83551. static code fixed[544];
  83552. /* build fixed huffman tables if first call (may not be thread safe) */
  83553. if (virgin) {
  83554. unsigned sym, bits;
  83555. static code *next;
  83556. /* literal/length table */
  83557. sym = 0;
  83558. while (sym < 144) state->lens[sym++] = 8;
  83559. while (sym < 256) state->lens[sym++] = 9;
  83560. while (sym < 280) state->lens[sym++] = 7;
  83561. while (sym < 288) state->lens[sym++] = 8;
  83562. next = fixed;
  83563. lenfix = next;
  83564. bits = 9;
  83565. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83566. /* distance table */
  83567. sym = 0;
  83568. while (sym < 32) state->lens[sym++] = 5;
  83569. distfix = next;
  83570. bits = 5;
  83571. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83572. /* do this just once */
  83573. virgin = 0;
  83574. }
  83575. #else /* !BUILDFIXED */
  83576. /*** Start of inlined file: inffixed.h ***/
  83577. /* WARNING: this file should *not* be used by applications. It
  83578. is part of the implementation of the compression library and
  83579. is subject to change. Applications should only use zlib.h.
  83580. */
  83581. static const code lenfix[512] = {
  83582. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83583. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83584. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83585. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83586. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83587. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83588. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83589. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83590. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83591. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83592. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83593. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83594. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83595. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83596. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83597. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83598. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83599. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83600. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83601. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83602. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83603. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83604. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83605. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83606. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83607. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83608. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83609. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83610. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83611. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83612. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83613. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83614. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83615. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83616. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83617. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83618. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83619. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83620. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83621. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83622. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83623. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83624. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83625. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83626. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83627. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83628. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83629. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83630. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83631. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83632. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83633. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83634. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83635. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83636. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83637. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83638. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83639. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83640. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83641. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83642. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83643. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83644. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83645. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83646. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83647. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83648. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83649. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83650. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83651. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83652. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83653. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83654. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83655. {0,9,255}
  83656. };
  83657. static const code distfix[32] = {
  83658. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83659. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83660. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83661. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83662. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83663. {22,5,193},{64,5,0}
  83664. };
  83665. /*** End of inlined file: inffixed.h ***/
  83666. #endif /* BUILDFIXED */
  83667. state->lencode = lenfix;
  83668. state->lenbits = 9;
  83669. state->distcode = distfix;
  83670. state->distbits = 5;
  83671. }
  83672. #ifdef MAKEFIXED
  83673. #include <stdio.h>
  83674. /*
  83675. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83676. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83677. those tables to stdout, which would be piped to inffixed.h. A small program
  83678. can simply call makefixed to do this:
  83679. void makefixed(void);
  83680. int main(void)
  83681. {
  83682. makefixed();
  83683. return 0;
  83684. }
  83685. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83686. a.out > inffixed.h
  83687. */
  83688. void makefixed()
  83689. {
  83690. unsigned low, size;
  83691. struct inflate_state state;
  83692. fixedtables(&state);
  83693. puts(" /* inffixed.h -- table for decoding fixed codes");
  83694. puts(" * Generated automatically by makefixed().");
  83695. puts(" */");
  83696. puts("");
  83697. puts(" /* WARNING: this file should *not* be used by applications.");
  83698. puts(" It is part of the implementation of this library and is");
  83699. puts(" subject to change. Applications should only use zlib.h.");
  83700. puts(" */");
  83701. puts("");
  83702. size = 1U << 9;
  83703. printf(" static const code lenfix[%u] = {", size);
  83704. low = 0;
  83705. for (;;) {
  83706. if ((low % 7) == 0) printf("\n ");
  83707. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83708. state.lencode[low].val);
  83709. if (++low == size) break;
  83710. putchar(',');
  83711. }
  83712. puts("\n };");
  83713. size = 1U << 5;
  83714. printf("\n static const code distfix[%u] = {", size);
  83715. low = 0;
  83716. for (;;) {
  83717. if ((low % 6) == 0) printf("\n ");
  83718. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83719. state.distcode[low].val);
  83720. if (++low == size) break;
  83721. putchar(',');
  83722. }
  83723. puts("\n };");
  83724. }
  83725. #endif /* MAKEFIXED */
  83726. /*
  83727. Update the window with the last wsize (normally 32K) bytes written before
  83728. returning. If window does not exist yet, create it. This is only called
  83729. when a window is already in use, or when output has been written during this
  83730. inflate call, but the end of the deflate stream has not been reached yet.
  83731. It is also called to create a window for dictionary data when a dictionary
  83732. is loaded.
  83733. Providing output buffers larger than 32K to inflate() should provide a speed
  83734. advantage, since only the last 32K of output is copied to the sliding window
  83735. upon return from inflate(), and since all distances after the first 32K of
  83736. output will fall in the output data, making match copies simpler and faster.
  83737. The advantage may be dependent on the size of the processor's data caches.
  83738. */
  83739. local int updatewindow (z_streamp strm, unsigned out)
  83740. {
  83741. struct inflate_state FAR *state;
  83742. unsigned copy, dist;
  83743. state = (struct inflate_state FAR *)strm->state;
  83744. /* if it hasn't been done already, allocate space for the window */
  83745. if (state->window == Z_NULL) {
  83746. state->window = (unsigned char FAR *)
  83747. ZALLOC(strm, 1U << state->wbits,
  83748. sizeof(unsigned char));
  83749. if (state->window == Z_NULL) return 1;
  83750. }
  83751. /* if window not in use yet, initialize */
  83752. if (state->wsize == 0) {
  83753. state->wsize = 1U << state->wbits;
  83754. state->write = 0;
  83755. state->whave = 0;
  83756. }
  83757. /* copy state->wsize or less output bytes into the circular window */
  83758. copy = out - strm->avail_out;
  83759. if (copy >= state->wsize) {
  83760. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83761. state->write = 0;
  83762. state->whave = state->wsize;
  83763. }
  83764. else {
  83765. dist = state->wsize - state->write;
  83766. if (dist > copy) dist = copy;
  83767. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83768. copy -= dist;
  83769. if (copy) {
  83770. zmemcpy(state->window, strm->next_out - copy, copy);
  83771. state->write = copy;
  83772. state->whave = state->wsize;
  83773. }
  83774. else {
  83775. state->write += dist;
  83776. if (state->write == state->wsize) state->write = 0;
  83777. if (state->whave < state->wsize) state->whave += dist;
  83778. }
  83779. }
  83780. return 0;
  83781. }
  83782. /* Macros for inflate(): */
  83783. /* check function to use adler32() for zlib or crc32() for gzip */
  83784. #ifdef GUNZIP
  83785. # define UPDATE(check, buf, len) \
  83786. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83787. #else
  83788. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83789. #endif
  83790. /* check macros for header crc */
  83791. #ifdef GUNZIP
  83792. # define CRC2(check, word) \
  83793. do { \
  83794. hbuf[0] = (unsigned char)(word); \
  83795. hbuf[1] = (unsigned char)((word) >> 8); \
  83796. check = crc32(check, hbuf, 2); \
  83797. } while (0)
  83798. # define CRC4(check, word) \
  83799. do { \
  83800. hbuf[0] = (unsigned char)(word); \
  83801. hbuf[1] = (unsigned char)((word) >> 8); \
  83802. hbuf[2] = (unsigned char)((word) >> 16); \
  83803. hbuf[3] = (unsigned char)((word) >> 24); \
  83804. check = crc32(check, hbuf, 4); \
  83805. } while (0)
  83806. #endif
  83807. /* Load registers with state in inflate() for speed */
  83808. #define LOAD() \
  83809. do { \
  83810. put = strm->next_out; \
  83811. left = strm->avail_out; \
  83812. next = strm->next_in; \
  83813. have = strm->avail_in; \
  83814. hold = state->hold; \
  83815. bits = state->bits; \
  83816. } while (0)
  83817. /* Restore state from registers in inflate() */
  83818. #define RESTORE() \
  83819. do { \
  83820. strm->next_out = put; \
  83821. strm->avail_out = left; \
  83822. strm->next_in = next; \
  83823. strm->avail_in = have; \
  83824. state->hold = hold; \
  83825. state->bits = bits; \
  83826. } while (0)
  83827. /* Clear the input bit accumulator */
  83828. #define INITBITS() \
  83829. do { \
  83830. hold = 0; \
  83831. bits = 0; \
  83832. } while (0)
  83833. /* Get a byte of input into the bit accumulator, or return from inflate()
  83834. if there is no input available. */
  83835. #define PULLBYTE() \
  83836. do { \
  83837. if (have == 0) goto inf_leave; \
  83838. have--; \
  83839. hold += (unsigned long)(*next++) << bits; \
  83840. bits += 8; \
  83841. } while (0)
  83842. /* Assure that there are at least n bits in the bit accumulator. If there is
  83843. not enough available input to do that, then return from inflate(). */
  83844. #define NEEDBITS(n) \
  83845. do { \
  83846. while (bits < (unsigned)(n)) \
  83847. PULLBYTE(); \
  83848. } while (0)
  83849. /* Return the low n bits of the bit accumulator (n < 16) */
  83850. #define BITS(n) \
  83851. ((unsigned)hold & ((1U << (n)) - 1))
  83852. /* Remove n bits from the bit accumulator */
  83853. #define DROPBITS(n) \
  83854. do { \
  83855. hold >>= (n); \
  83856. bits -= (unsigned)(n); \
  83857. } while (0)
  83858. /* Remove zero to seven bits as needed to go to a byte boundary */
  83859. #define BYTEBITS() \
  83860. do { \
  83861. hold >>= bits & 7; \
  83862. bits -= bits & 7; \
  83863. } while (0)
  83864. /* Reverse the bytes in a 32-bit value */
  83865. #define REVERSE(q) \
  83866. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83867. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83868. /*
  83869. inflate() uses a state machine to process as much input data and generate as
  83870. much output data as possible before returning. The state machine is
  83871. structured roughly as follows:
  83872. for (;;) switch (state) {
  83873. ...
  83874. case STATEn:
  83875. if (not enough input data or output space to make progress)
  83876. return;
  83877. ... make progress ...
  83878. state = STATEm;
  83879. break;
  83880. ...
  83881. }
  83882. so when inflate() is called again, the same case is attempted again, and
  83883. if the appropriate resources are provided, the machine proceeds to the
  83884. next state. The NEEDBITS() macro is usually the way the state evaluates
  83885. whether it can proceed or should return. NEEDBITS() does the return if
  83886. the requested bits are not available. The typical use of the BITS macros
  83887. is:
  83888. NEEDBITS(n);
  83889. ... do something with BITS(n) ...
  83890. DROPBITS(n);
  83891. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83892. input left to load n bits into the accumulator, or it continues. BITS(n)
  83893. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83894. the low n bits off the accumulator. INITBITS() clears the accumulator
  83895. and sets the number of available bits to zero. BYTEBITS() discards just
  83896. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83897. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83898. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83899. if there is no input available. The decoding of variable length codes uses
  83900. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83901. code, and no more.
  83902. Some states loop until they get enough input, making sure that enough
  83903. state information is maintained to continue the loop where it left off
  83904. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83905. would all have to actually be part of the saved state in case NEEDBITS()
  83906. returns:
  83907. case STATEw:
  83908. while (want < need) {
  83909. NEEDBITS(n);
  83910. keep[want++] = BITS(n);
  83911. DROPBITS(n);
  83912. }
  83913. state = STATEx;
  83914. case STATEx:
  83915. As shown above, if the next state is also the next case, then the break
  83916. is omitted.
  83917. A state may also return if there is not enough output space available to
  83918. complete that state. Those states are copying stored data, writing a
  83919. literal byte, and copying a matching string.
  83920. When returning, a "goto inf_leave" is used to update the total counters,
  83921. update the check value, and determine whether any progress has been made
  83922. during that inflate() call in order to return the proper return code.
  83923. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83924. When there is a window, goto inf_leave will update the window with the last
  83925. output written. If a goto inf_leave occurs in the middle of decompression
  83926. and there is no window currently, goto inf_leave will create one and copy
  83927. output to the window for the next call of inflate().
  83928. In this implementation, the flush parameter of inflate() only affects the
  83929. return code (per zlib.h). inflate() always writes as much as possible to
  83930. strm->next_out, given the space available and the provided input--the effect
  83931. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83932. the allocation of and copying into a sliding window until necessary, which
  83933. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83934. stream available. So the only thing the flush parameter actually does is:
  83935. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83936. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83937. */
  83938. int ZEXPORT inflate (z_streamp strm, int flush)
  83939. {
  83940. struct inflate_state FAR *state;
  83941. unsigned char FAR *next; /* next input */
  83942. unsigned char FAR *put; /* next output */
  83943. unsigned have, left; /* available input and output */
  83944. unsigned long hold; /* bit buffer */
  83945. unsigned bits; /* bits in bit buffer */
  83946. unsigned in, out; /* save starting available input and output */
  83947. unsigned copy; /* number of stored or match bytes to copy */
  83948. unsigned char FAR *from; /* where to copy match bytes from */
  83949. code thisx; /* current decoding table entry */
  83950. code last; /* parent table entry */
  83951. unsigned len; /* length to copy for repeats, bits to drop */
  83952. int ret; /* return code */
  83953. #ifdef GUNZIP
  83954. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83955. #endif
  83956. static const unsigned short order[19] = /* permutation of code lengths */
  83957. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83958. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83959. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83960. return Z_STREAM_ERROR;
  83961. state = (struct inflate_state FAR *)strm->state;
  83962. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83963. LOAD();
  83964. in = have;
  83965. out = left;
  83966. ret = Z_OK;
  83967. for (;;)
  83968. switch (state->mode) {
  83969. case HEAD:
  83970. if (state->wrap == 0) {
  83971. state->mode = TYPEDO;
  83972. break;
  83973. }
  83974. NEEDBITS(16);
  83975. #ifdef GUNZIP
  83976. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83977. state->check = crc32(0L, Z_NULL, 0);
  83978. CRC2(state->check, hold);
  83979. INITBITS();
  83980. state->mode = FLAGS;
  83981. break;
  83982. }
  83983. state->flags = 0; /* expect zlib header */
  83984. if (state->head != Z_NULL)
  83985. state->head->done = -1;
  83986. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83987. #else
  83988. if (
  83989. #endif
  83990. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83991. strm->msg = (char *)"incorrect header check";
  83992. state->mode = BAD;
  83993. break;
  83994. }
  83995. if (BITS(4) != Z_DEFLATED) {
  83996. strm->msg = (char *)"unknown compression method";
  83997. state->mode = BAD;
  83998. break;
  83999. }
  84000. DROPBITS(4);
  84001. len = BITS(4) + 8;
  84002. if (len > state->wbits) {
  84003. strm->msg = (char *)"invalid window size";
  84004. state->mode = BAD;
  84005. break;
  84006. }
  84007. state->dmax = 1U << len;
  84008. Tracev((stderr, "inflate: zlib header ok\n"));
  84009. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84010. state->mode = hold & 0x200 ? DICTID : TYPE;
  84011. INITBITS();
  84012. break;
  84013. #ifdef GUNZIP
  84014. case FLAGS:
  84015. NEEDBITS(16);
  84016. state->flags = (int)(hold);
  84017. if ((state->flags & 0xff) != Z_DEFLATED) {
  84018. strm->msg = (char *)"unknown compression method";
  84019. state->mode = BAD;
  84020. break;
  84021. }
  84022. if (state->flags & 0xe000) {
  84023. strm->msg = (char *)"unknown header flags set";
  84024. state->mode = BAD;
  84025. break;
  84026. }
  84027. if (state->head != Z_NULL)
  84028. state->head->text = (int)((hold >> 8) & 1);
  84029. if (state->flags & 0x0200) CRC2(state->check, hold);
  84030. INITBITS();
  84031. state->mode = TIME;
  84032. case TIME:
  84033. NEEDBITS(32);
  84034. if (state->head != Z_NULL)
  84035. state->head->time = hold;
  84036. if (state->flags & 0x0200) CRC4(state->check, hold);
  84037. INITBITS();
  84038. state->mode = OS;
  84039. case OS:
  84040. NEEDBITS(16);
  84041. if (state->head != Z_NULL) {
  84042. state->head->xflags = (int)(hold & 0xff);
  84043. state->head->os = (int)(hold >> 8);
  84044. }
  84045. if (state->flags & 0x0200) CRC2(state->check, hold);
  84046. INITBITS();
  84047. state->mode = EXLEN;
  84048. case EXLEN:
  84049. if (state->flags & 0x0400) {
  84050. NEEDBITS(16);
  84051. state->length = (unsigned)(hold);
  84052. if (state->head != Z_NULL)
  84053. state->head->extra_len = (unsigned)hold;
  84054. if (state->flags & 0x0200) CRC2(state->check, hold);
  84055. INITBITS();
  84056. }
  84057. else if (state->head != Z_NULL)
  84058. state->head->extra = Z_NULL;
  84059. state->mode = EXTRA;
  84060. case EXTRA:
  84061. if (state->flags & 0x0400) {
  84062. copy = state->length;
  84063. if (copy > have) copy = have;
  84064. if (copy) {
  84065. if (state->head != Z_NULL &&
  84066. state->head->extra != Z_NULL) {
  84067. len = state->head->extra_len - state->length;
  84068. zmemcpy(state->head->extra + len, next,
  84069. len + copy > state->head->extra_max ?
  84070. state->head->extra_max - len : copy);
  84071. }
  84072. if (state->flags & 0x0200)
  84073. state->check = crc32(state->check, next, copy);
  84074. have -= copy;
  84075. next += copy;
  84076. state->length -= copy;
  84077. }
  84078. if (state->length) goto inf_leave;
  84079. }
  84080. state->length = 0;
  84081. state->mode = NAME;
  84082. case NAME:
  84083. if (state->flags & 0x0800) {
  84084. if (have == 0) goto inf_leave;
  84085. copy = 0;
  84086. do {
  84087. len = (unsigned)(next[copy++]);
  84088. if (state->head != Z_NULL &&
  84089. state->head->name != Z_NULL &&
  84090. state->length < state->head->name_max)
  84091. state->head->name[state->length++] = len;
  84092. } while (len && copy < have);
  84093. if (state->flags & 0x0200)
  84094. state->check = crc32(state->check, next, copy);
  84095. have -= copy;
  84096. next += copy;
  84097. if (len) goto inf_leave;
  84098. }
  84099. else if (state->head != Z_NULL)
  84100. state->head->name = Z_NULL;
  84101. state->length = 0;
  84102. state->mode = COMMENT;
  84103. case COMMENT:
  84104. if (state->flags & 0x1000) {
  84105. if (have == 0) goto inf_leave;
  84106. copy = 0;
  84107. do {
  84108. len = (unsigned)(next[copy++]);
  84109. if (state->head != Z_NULL &&
  84110. state->head->comment != Z_NULL &&
  84111. state->length < state->head->comm_max)
  84112. state->head->comment[state->length++] = len;
  84113. } while (len && copy < have);
  84114. if (state->flags & 0x0200)
  84115. state->check = crc32(state->check, next, copy);
  84116. have -= copy;
  84117. next += copy;
  84118. if (len) goto inf_leave;
  84119. }
  84120. else if (state->head != Z_NULL)
  84121. state->head->comment = Z_NULL;
  84122. state->mode = HCRC;
  84123. case HCRC:
  84124. if (state->flags & 0x0200) {
  84125. NEEDBITS(16);
  84126. if (hold != (state->check & 0xffff)) {
  84127. strm->msg = (char *)"header crc mismatch";
  84128. state->mode = BAD;
  84129. break;
  84130. }
  84131. INITBITS();
  84132. }
  84133. if (state->head != Z_NULL) {
  84134. state->head->hcrc = (int)((state->flags >> 9) & 1);
  84135. state->head->done = 1;
  84136. }
  84137. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  84138. state->mode = TYPE;
  84139. break;
  84140. #endif
  84141. case DICTID:
  84142. NEEDBITS(32);
  84143. strm->adler = state->check = REVERSE(hold);
  84144. INITBITS();
  84145. state->mode = DICT;
  84146. case DICT:
  84147. if (state->havedict == 0) {
  84148. RESTORE();
  84149. return Z_NEED_DICT;
  84150. }
  84151. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84152. state->mode = TYPE;
  84153. case TYPE:
  84154. if (flush == Z_BLOCK) goto inf_leave;
  84155. case TYPEDO:
  84156. if (state->last) {
  84157. BYTEBITS();
  84158. state->mode = CHECK;
  84159. break;
  84160. }
  84161. NEEDBITS(3);
  84162. state->last = BITS(1);
  84163. DROPBITS(1);
  84164. switch (BITS(2)) {
  84165. case 0: /* stored block */
  84166. Tracev((stderr, "inflate: stored block%s\n",
  84167. state->last ? " (last)" : ""));
  84168. state->mode = STORED;
  84169. break;
  84170. case 1: /* fixed block */
  84171. fixedtables(state);
  84172. Tracev((stderr, "inflate: fixed codes block%s\n",
  84173. state->last ? " (last)" : ""));
  84174. state->mode = LEN; /* decode codes */
  84175. break;
  84176. case 2: /* dynamic block */
  84177. Tracev((stderr, "inflate: dynamic codes block%s\n",
  84178. state->last ? " (last)" : ""));
  84179. state->mode = TABLE;
  84180. break;
  84181. case 3:
  84182. strm->msg = (char *)"invalid block type";
  84183. state->mode = BAD;
  84184. }
  84185. DROPBITS(2);
  84186. break;
  84187. case STORED:
  84188. BYTEBITS(); /* go to byte boundary */
  84189. NEEDBITS(32);
  84190. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84191. strm->msg = (char *)"invalid stored block lengths";
  84192. state->mode = BAD;
  84193. break;
  84194. }
  84195. state->length = (unsigned)hold & 0xffff;
  84196. Tracev((stderr, "inflate: stored length %u\n",
  84197. state->length));
  84198. INITBITS();
  84199. state->mode = COPY;
  84200. case COPY:
  84201. copy = state->length;
  84202. if (copy) {
  84203. if (copy > have) copy = have;
  84204. if (copy > left) copy = left;
  84205. if (copy == 0) goto inf_leave;
  84206. zmemcpy(put, next, copy);
  84207. have -= copy;
  84208. next += copy;
  84209. left -= copy;
  84210. put += copy;
  84211. state->length -= copy;
  84212. break;
  84213. }
  84214. Tracev((stderr, "inflate: stored end\n"));
  84215. state->mode = TYPE;
  84216. break;
  84217. case TABLE:
  84218. NEEDBITS(14);
  84219. state->nlen = BITS(5) + 257;
  84220. DROPBITS(5);
  84221. state->ndist = BITS(5) + 1;
  84222. DROPBITS(5);
  84223. state->ncode = BITS(4) + 4;
  84224. DROPBITS(4);
  84225. #ifndef PKZIP_BUG_WORKAROUND
  84226. if (state->nlen > 286 || state->ndist > 30) {
  84227. strm->msg = (char *)"too many length or distance symbols";
  84228. state->mode = BAD;
  84229. break;
  84230. }
  84231. #endif
  84232. Tracev((stderr, "inflate: table sizes ok\n"));
  84233. state->have = 0;
  84234. state->mode = LENLENS;
  84235. case LENLENS:
  84236. while (state->have < state->ncode) {
  84237. NEEDBITS(3);
  84238. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84239. DROPBITS(3);
  84240. }
  84241. while (state->have < 19)
  84242. state->lens[order[state->have++]] = 0;
  84243. state->next = state->codes;
  84244. state->lencode = (code const FAR *)(state->next);
  84245. state->lenbits = 7;
  84246. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84247. &(state->lenbits), state->work);
  84248. if (ret) {
  84249. strm->msg = (char *)"invalid code lengths set";
  84250. state->mode = BAD;
  84251. break;
  84252. }
  84253. Tracev((stderr, "inflate: code lengths ok\n"));
  84254. state->have = 0;
  84255. state->mode = CODELENS;
  84256. case CODELENS:
  84257. while (state->have < state->nlen + state->ndist) {
  84258. for (;;) {
  84259. thisx = state->lencode[BITS(state->lenbits)];
  84260. if ((unsigned)(thisx.bits) <= bits) break;
  84261. PULLBYTE();
  84262. }
  84263. if (thisx.val < 16) {
  84264. NEEDBITS(thisx.bits);
  84265. DROPBITS(thisx.bits);
  84266. state->lens[state->have++] = thisx.val;
  84267. }
  84268. else {
  84269. if (thisx.val == 16) {
  84270. NEEDBITS(thisx.bits + 2);
  84271. DROPBITS(thisx.bits);
  84272. if (state->have == 0) {
  84273. strm->msg = (char *)"invalid bit length repeat";
  84274. state->mode = BAD;
  84275. break;
  84276. }
  84277. len = state->lens[state->have - 1];
  84278. copy = 3 + BITS(2);
  84279. DROPBITS(2);
  84280. }
  84281. else if (thisx.val == 17) {
  84282. NEEDBITS(thisx.bits + 3);
  84283. DROPBITS(thisx.bits);
  84284. len = 0;
  84285. copy = 3 + BITS(3);
  84286. DROPBITS(3);
  84287. }
  84288. else {
  84289. NEEDBITS(thisx.bits + 7);
  84290. DROPBITS(thisx.bits);
  84291. len = 0;
  84292. copy = 11 + BITS(7);
  84293. DROPBITS(7);
  84294. }
  84295. if (state->have + copy > state->nlen + state->ndist) {
  84296. strm->msg = (char *)"invalid bit length repeat";
  84297. state->mode = BAD;
  84298. break;
  84299. }
  84300. while (copy--)
  84301. state->lens[state->have++] = (unsigned short)len;
  84302. }
  84303. }
  84304. /* handle error breaks in while */
  84305. if (state->mode == BAD) break;
  84306. /* build code tables */
  84307. state->next = state->codes;
  84308. state->lencode = (code const FAR *)(state->next);
  84309. state->lenbits = 9;
  84310. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84311. &(state->lenbits), state->work);
  84312. if (ret) {
  84313. strm->msg = (char *)"invalid literal/lengths set";
  84314. state->mode = BAD;
  84315. break;
  84316. }
  84317. state->distcode = (code const FAR *)(state->next);
  84318. state->distbits = 6;
  84319. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84320. &(state->next), &(state->distbits), state->work);
  84321. if (ret) {
  84322. strm->msg = (char *)"invalid distances set";
  84323. state->mode = BAD;
  84324. break;
  84325. }
  84326. Tracev((stderr, "inflate: codes ok\n"));
  84327. state->mode = LEN;
  84328. case LEN:
  84329. if (have >= 6 && left >= 258) {
  84330. RESTORE();
  84331. inflate_fast(strm, out);
  84332. LOAD();
  84333. break;
  84334. }
  84335. for (;;) {
  84336. thisx = state->lencode[BITS(state->lenbits)];
  84337. if ((unsigned)(thisx.bits) <= bits) break;
  84338. PULLBYTE();
  84339. }
  84340. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84341. last = thisx;
  84342. for (;;) {
  84343. thisx = state->lencode[last.val +
  84344. (BITS(last.bits + last.op) >> last.bits)];
  84345. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84346. PULLBYTE();
  84347. }
  84348. DROPBITS(last.bits);
  84349. }
  84350. DROPBITS(thisx.bits);
  84351. state->length = (unsigned)thisx.val;
  84352. if ((int)(thisx.op) == 0) {
  84353. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84354. "inflate: literal '%c'\n" :
  84355. "inflate: literal 0x%02x\n", thisx.val));
  84356. state->mode = LIT;
  84357. break;
  84358. }
  84359. if (thisx.op & 32) {
  84360. Tracevv((stderr, "inflate: end of block\n"));
  84361. state->mode = TYPE;
  84362. break;
  84363. }
  84364. if (thisx.op & 64) {
  84365. strm->msg = (char *)"invalid literal/length code";
  84366. state->mode = BAD;
  84367. break;
  84368. }
  84369. state->extra = (unsigned)(thisx.op) & 15;
  84370. state->mode = LENEXT;
  84371. case LENEXT:
  84372. if (state->extra) {
  84373. NEEDBITS(state->extra);
  84374. state->length += BITS(state->extra);
  84375. DROPBITS(state->extra);
  84376. }
  84377. Tracevv((stderr, "inflate: length %u\n", state->length));
  84378. state->mode = DIST;
  84379. case DIST:
  84380. for (;;) {
  84381. thisx = state->distcode[BITS(state->distbits)];
  84382. if ((unsigned)(thisx.bits) <= bits) break;
  84383. PULLBYTE();
  84384. }
  84385. if ((thisx.op & 0xf0) == 0) {
  84386. last = thisx;
  84387. for (;;) {
  84388. thisx = state->distcode[last.val +
  84389. (BITS(last.bits + last.op) >> last.bits)];
  84390. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84391. PULLBYTE();
  84392. }
  84393. DROPBITS(last.bits);
  84394. }
  84395. DROPBITS(thisx.bits);
  84396. if (thisx.op & 64) {
  84397. strm->msg = (char *)"invalid distance code";
  84398. state->mode = BAD;
  84399. break;
  84400. }
  84401. state->offset = (unsigned)thisx.val;
  84402. state->extra = (unsigned)(thisx.op) & 15;
  84403. state->mode = DISTEXT;
  84404. case DISTEXT:
  84405. if (state->extra) {
  84406. NEEDBITS(state->extra);
  84407. state->offset += BITS(state->extra);
  84408. DROPBITS(state->extra);
  84409. }
  84410. #ifdef INFLATE_STRICT
  84411. if (state->offset > state->dmax) {
  84412. strm->msg = (char *)"invalid distance too far back";
  84413. state->mode = BAD;
  84414. break;
  84415. }
  84416. #endif
  84417. if (state->offset > state->whave + out - left) {
  84418. strm->msg = (char *)"invalid distance too far back";
  84419. state->mode = BAD;
  84420. break;
  84421. }
  84422. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84423. state->mode = MATCH;
  84424. case MATCH:
  84425. if (left == 0) goto inf_leave;
  84426. copy = out - left;
  84427. if (state->offset > copy) { /* copy from window */
  84428. copy = state->offset - copy;
  84429. if (copy > state->write) {
  84430. copy -= state->write;
  84431. from = state->window + (state->wsize - copy);
  84432. }
  84433. else
  84434. from = state->window + (state->write - copy);
  84435. if (copy > state->length) copy = state->length;
  84436. }
  84437. else { /* copy from output */
  84438. from = put - state->offset;
  84439. copy = state->length;
  84440. }
  84441. if (copy > left) copy = left;
  84442. left -= copy;
  84443. state->length -= copy;
  84444. do {
  84445. *put++ = *from++;
  84446. } while (--copy);
  84447. if (state->length == 0) state->mode = LEN;
  84448. break;
  84449. case LIT:
  84450. if (left == 0) goto inf_leave;
  84451. *put++ = (unsigned char)(state->length);
  84452. left--;
  84453. state->mode = LEN;
  84454. break;
  84455. case CHECK:
  84456. if (state->wrap) {
  84457. NEEDBITS(32);
  84458. out -= left;
  84459. strm->total_out += out;
  84460. state->total += out;
  84461. if (out)
  84462. strm->adler = state->check =
  84463. UPDATE(state->check, put - out, out);
  84464. out = left;
  84465. if ((
  84466. #ifdef GUNZIP
  84467. state->flags ? hold :
  84468. #endif
  84469. REVERSE(hold)) != state->check) {
  84470. strm->msg = (char *)"incorrect data check";
  84471. state->mode = BAD;
  84472. break;
  84473. }
  84474. INITBITS();
  84475. Tracev((stderr, "inflate: check matches trailer\n"));
  84476. }
  84477. #ifdef GUNZIP
  84478. state->mode = LENGTH;
  84479. case LENGTH:
  84480. if (state->wrap && state->flags) {
  84481. NEEDBITS(32);
  84482. if (hold != (state->total & 0xffffffffUL)) {
  84483. strm->msg = (char *)"incorrect length check";
  84484. state->mode = BAD;
  84485. break;
  84486. }
  84487. INITBITS();
  84488. Tracev((stderr, "inflate: length matches trailer\n"));
  84489. }
  84490. #endif
  84491. state->mode = DONE;
  84492. case DONE:
  84493. ret = Z_STREAM_END;
  84494. goto inf_leave;
  84495. case BAD:
  84496. ret = Z_DATA_ERROR;
  84497. goto inf_leave;
  84498. case MEM:
  84499. return Z_MEM_ERROR;
  84500. case SYNC:
  84501. default:
  84502. return Z_STREAM_ERROR;
  84503. }
  84504. /*
  84505. Return from inflate(), updating the total counts and the check value.
  84506. If there was no progress during the inflate() call, return a buffer
  84507. error. Call updatewindow() to create and/or update the window state.
  84508. Note: a memory error from inflate() is non-recoverable.
  84509. */
  84510. inf_leave:
  84511. RESTORE();
  84512. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84513. if (updatewindow(strm, out)) {
  84514. state->mode = MEM;
  84515. return Z_MEM_ERROR;
  84516. }
  84517. in -= strm->avail_in;
  84518. out -= strm->avail_out;
  84519. strm->total_in += in;
  84520. strm->total_out += out;
  84521. state->total += out;
  84522. if (state->wrap && out)
  84523. strm->adler = state->check =
  84524. UPDATE(state->check, strm->next_out - out, out);
  84525. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84526. (state->mode == TYPE ? 128 : 0);
  84527. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84528. ret = Z_BUF_ERROR;
  84529. return ret;
  84530. }
  84531. int ZEXPORT inflateEnd (z_streamp strm)
  84532. {
  84533. struct inflate_state FAR *state;
  84534. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84535. return Z_STREAM_ERROR;
  84536. state = (struct inflate_state FAR *)strm->state;
  84537. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84538. ZFREE(strm, strm->state);
  84539. strm->state = Z_NULL;
  84540. Tracev((stderr, "inflate: end\n"));
  84541. return Z_OK;
  84542. }
  84543. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84544. {
  84545. struct inflate_state FAR *state;
  84546. unsigned long id_;
  84547. /* check state */
  84548. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84549. state = (struct inflate_state FAR *)strm->state;
  84550. if (state->wrap != 0 && state->mode != DICT)
  84551. return Z_STREAM_ERROR;
  84552. /* check for correct dictionary id */
  84553. if (state->mode == DICT) {
  84554. id_ = adler32(0L, Z_NULL, 0);
  84555. id_ = adler32(id_, dictionary, dictLength);
  84556. if (id_ != state->check)
  84557. return Z_DATA_ERROR;
  84558. }
  84559. /* copy dictionary to window */
  84560. if (updatewindow(strm, strm->avail_out)) {
  84561. state->mode = MEM;
  84562. return Z_MEM_ERROR;
  84563. }
  84564. if (dictLength > state->wsize) {
  84565. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84566. state->wsize);
  84567. state->whave = state->wsize;
  84568. }
  84569. else {
  84570. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84571. dictLength);
  84572. state->whave = dictLength;
  84573. }
  84574. state->havedict = 1;
  84575. Tracev((stderr, "inflate: dictionary set\n"));
  84576. return Z_OK;
  84577. }
  84578. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84579. {
  84580. struct inflate_state FAR *state;
  84581. /* check state */
  84582. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84583. state = (struct inflate_state FAR *)strm->state;
  84584. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84585. /* save header structure */
  84586. state->head = head;
  84587. head->done = 0;
  84588. return Z_OK;
  84589. }
  84590. /*
  84591. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84592. or when out of input. When called, *have is the number of pattern bytes
  84593. found in order so far, in 0..3. On return *have is updated to the new
  84594. state. If on return *have equals four, then the pattern was found and the
  84595. return value is how many bytes were read including the last byte of the
  84596. pattern. If *have is less than four, then the pattern has not been found
  84597. yet and the return value is len. In the latter case, syncsearch() can be
  84598. called again with more data and the *have state. *have is initialized to
  84599. zero for the first call.
  84600. */
  84601. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84602. {
  84603. unsigned got;
  84604. unsigned next;
  84605. got = *have;
  84606. next = 0;
  84607. while (next < len && got < 4) {
  84608. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84609. got++;
  84610. else if (buf[next])
  84611. got = 0;
  84612. else
  84613. got = 4 - got;
  84614. next++;
  84615. }
  84616. *have = got;
  84617. return next;
  84618. }
  84619. int ZEXPORT inflateSync (z_streamp strm)
  84620. {
  84621. unsigned len; /* number of bytes to look at or looked at */
  84622. unsigned long in, out; /* temporary to save total_in and total_out */
  84623. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84624. struct inflate_state FAR *state;
  84625. /* check parameters */
  84626. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84627. state = (struct inflate_state FAR *)strm->state;
  84628. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84629. /* if first time, start search in bit buffer */
  84630. if (state->mode != SYNC) {
  84631. state->mode = SYNC;
  84632. state->hold <<= state->bits & 7;
  84633. state->bits -= state->bits & 7;
  84634. len = 0;
  84635. while (state->bits >= 8) {
  84636. buf[len++] = (unsigned char)(state->hold);
  84637. state->hold >>= 8;
  84638. state->bits -= 8;
  84639. }
  84640. state->have = 0;
  84641. syncsearch(&(state->have), buf, len);
  84642. }
  84643. /* search available input */
  84644. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84645. strm->avail_in -= len;
  84646. strm->next_in += len;
  84647. strm->total_in += len;
  84648. /* return no joy or set up to restart inflate() on a new block */
  84649. if (state->have != 4) return Z_DATA_ERROR;
  84650. in = strm->total_in; out = strm->total_out;
  84651. inflateReset(strm);
  84652. strm->total_in = in; strm->total_out = out;
  84653. state->mode = TYPE;
  84654. return Z_OK;
  84655. }
  84656. /*
  84657. Returns true if inflate is currently at the end of a block generated by
  84658. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84659. implementation to provide an additional safety check. PPP uses
  84660. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84661. block. When decompressing, PPP checks that at the end of input packet,
  84662. inflate is waiting for these length bytes.
  84663. */
  84664. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84665. {
  84666. struct inflate_state FAR *state;
  84667. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84668. state = (struct inflate_state FAR *)strm->state;
  84669. return state->mode == STORED && state->bits == 0;
  84670. }
  84671. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84672. {
  84673. struct inflate_state FAR *state;
  84674. struct inflate_state FAR *copy;
  84675. unsigned char FAR *window;
  84676. unsigned wsize;
  84677. /* check input */
  84678. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84679. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84680. return Z_STREAM_ERROR;
  84681. state = (struct inflate_state FAR *)source->state;
  84682. /* allocate space */
  84683. copy = (struct inflate_state FAR *)
  84684. ZALLOC(source, 1, sizeof(struct inflate_state));
  84685. if (copy == Z_NULL) return Z_MEM_ERROR;
  84686. window = Z_NULL;
  84687. if (state->window != Z_NULL) {
  84688. window = (unsigned char FAR *)
  84689. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84690. if (window == Z_NULL) {
  84691. ZFREE(source, copy);
  84692. return Z_MEM_ERROR;
  84693. }
  84694. }
  84695. /* copy state */
  84696. zmemcpy(dest, source, sizeof(z_stream));
  84697. zmemcpy(copy, state, sizeof(struct inflate_state));
  84698. if (state->lencode >= state->codes &&
  84699. state->lencode <= state->codes + ENOUGH - 1) {
  84700. copy->lencode = copy->codes + (state->lencode - state->codes);
  84701. copy->distcode = copy->codes + (state->distcode - state->codes);
  84702. }
  84703. copy->next = copy->codes + (state->next - state->codes);
  84704. if (window != Z_NULL) {
  84705. wsize = 1U << state->wbits;
  84706. zmemcpy(window, state->window, wsize);
  84707. }
  84708. copy->window = window;
  84709. dest->state = (struct internal_state FAR *)copy;
  84710. return Z_OK;
  84711. }
  84712. /*** End of inlined file: inflate.c ***/
  84713. /*** Start of inlined file: inftrees.c ***/
  84714. #define MAXBITS 15
  84715. const char inflate_copyright[] =
  84716. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84717. /*
  84718. If you use the zlib library in a product, an acknowledgment is welcome
  84719. in the documentation of your product. If for some reason you cannot
  84720. include such an acknowledgment, I would appreciate that you keep this
  84721. copyright string in the executable of your product.
  84722. */
  84723. /*
  84724. Build a set of tables to decode the provided canonical Huffman code.
  84725. The code lengths are lens[0..codes-1]. The result starts at *table,
  84726. whose indices are 0..2^bits-1. work is a writable array of at least
  84727. lens shorts, which is used as a work area. type is the type of code
  84728. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84729. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84730. on return points to the next available entry's address. bits is the
  84731. requested root table index bits, and on return it is the actual root
  84732. table index bits. It will differ if the request is greater than the
  84733. longest code or if it is less than the shortest code.
  84734. */
  84735. int inflate_table (codetype type,
  84736. unsigned short FAR *lens,
  84737. unsigned codes,
  84738. code FAR * FAR *table,
  84739. unsigned FAR *bits,
  84740. unsigned short FAR *work)
  84741. {
  84742. unsigned len; /* a code's length in bits */
  84743. unsigned sym; /* index of code symbols */
  84744. unsigned min, max; /* minimum and maximum code lengths */
  84745. unsigned root; /* number of index bits for root table */
  84746. unsigned curr; /* number of index bits for current table */
  84747. unsigned drop; /* code bits to drop for sub-table */
  84748. int left; /* number of prefix codes available */
  84749. unsigned used; /* code entries in table used */
  84750. unsigned huff; /* Huffman code */
  84751. unsigned incr; /* for incrementing code, index */
  84752. unsigned fill; /* index for replicating entries */
  84753. unsigned low; /* low bits for current root entry */
  84754. unsigned mask; /* mask for low root bits */
  84755. code thisx; /* table entry for duplication */
  84756. code FAR *next; /* next available space in table */
  84757. const unsigned short FAR *base; /* base value table to use */
  84758. const unsigned short FAR *extra; /* extra bits table to use */
  84759. int end; /* use base and extra for symbol > end */
  84760. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84761. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84762. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84763. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84764. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84765. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84766. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84767. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84768. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84769. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84770. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84771. 8193, 12289, 16385, 24577, 0, 0};
  84772. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84773. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84774. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84775. 28, 28, 29, 29, 64, 64};
  84776. /*
  84777. Process a set of code lengths to create a canonical Huffman code. The
  84778. code lengths are lens[0..codes-1]. Each length corresponds to the
  84779. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84780. symbols by length from short to long, and retaining the symbol order
  84781. for codes with equal lengths. Then the code starts with all zero bits
  84782. for the first code of the shortest length, and the codes are integer
  84783. increments for the same length, and zeros are appended as the length
  84784. increases. For the deflate format, these bits are stored backwards
  84785. from their more natural integer increment ordering, and so when the
  84786. decoding tables are built in the large loop below, the integer codes
  84787. are incremented backwards.
  84788. This routine assumes, but does not check, that all of the entries in
  84789. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84790. 1..MAXBITS is interpreted as that code length. zero means that that
  84791. symbol does not occur in this code.
  84792. The codes are sorted by computing a count of codes for each length,
  84793. creating from that a table of starting indices for each length in the
  84794. sorted table, and then entering the symbols in order in the sorted
  84795. table. The sorted table is work[], with that space being provided by
  84796. the caller.
  84797. The length counts are used for other purposes as well, i.e. finding
  84798. the minimum and maximum length codes, determining if there are any
  84799. codes at all, checking for a valid set of lengths, and looking ahead
  84800. at length counts to determine sub-table sizes when building the
  84801. decoding tables.
  84802. */
  84803. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84804. for (len = 0; len <= MAXBITS; len++)
  84805. count[len] = 0;
  84806. for (sym = 0; sym < codes; sym++)
  84807. count[lens[sym]]++;
  84808. /* bound code lengths, force root to be within code lengths */
  84809. root = *bits;
  84810. for (max = MAXBITS; max >= 1; max--)
  84811. if (count[max] != 0) break;
  84812. if (root > max) root = max;
  84813. if (max == 0) { /* no symbols to code at all */
  84814. thisx.op = (unsigned char)64; /* invalid code marker */
  84815. thisx.bits = (unsigned char)1;
  84816. thisx.val = (unsigned short)0;
  84817. *(*table)++ = thisx; /* make a table to force an error */
  84818. *(*table)++ = thisx;
  84819. *bits = 1;
  84820. return 0; /* no symbols, but wait for decoding to report error */
  84821. }
  84822. for (min = 1; min <= MAXBITS; min++)
  84823. if (count[min] != 0) break;
  84824. if (root < min) root = min;
  84825. /* check for an over-subscribed or incomplete set of lengths */
  84826. left = 1;
  84827. for (len = 1; len <= MAXBITS; len++) {
  84828. left <<= 1;
  84829. left -= count[len];
  84830. if (left < 0) return -1; /* over-subscribed */
  84831. }
  84832. if (left > 0 && (type == CODES || max != 1))
  84833. return -1; /* incomplete set */
  84834. /* generate offsets into symbol table for each length for sorting */
  84835. offs[1] = 0;
  84836. for (len = 1; len < MAXBITS; len++)
  84837. offs[len + 1] = offs[len] + count[len];
  84838. /* sort symbols by length, by symbol order within each length */
  84839. for (sym = 0; sym < codes; sym++)
  84840. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84841. /*
  84842. Create and fill in decoding tables. In this loop, the table being
  84843. filled is at next and has curr index bits. The code being used is huff
  84844. with length len. That code is converted to an index by dropping drop
  84845. bits off of the bottom. For codes where len is less than drop + curr,
  84846. those top drop + curr - len bits are incremented through all values to
  84847. fill the table with replicated entries.
  84848. root is the number of index bits for the root table. When len exceeds
  84849. root, sub-tables are created pointed to by the root entry with an index
  84850. of the low root bits of huff. This is saved in low to check for when a
  84851. new sub-table should be started. drop is zero when the root table is
  84852. being filled, and drop is root when sub-tables are being filled.
  84853. When a new sub-table is needed, it is necessary to look ahead in the
  84854. code lengths to determine what size sub-table is needed. The length
  84855. counts are used for this, and so count[] is decremented as codes are
  84856. entered in the tables.
  84857. used keeps track of how many table entries have been allocated from the
  84858. provided *table space. It is checked when a LENS table is being made
  84859. against the space in *table, ENOUGH, minus the maximum space needed by
  84860. the worst case distance code, MAXD. This should never happen, but the
  84861. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84862. This assumes that when type == LENS, bits == 9.
  84863. sym increments through all symbols, and the loop terminates when
  84864. all codes of length max, i.e. all codes, have been processed. This
  84865. routine permits incomplete codes, so another loop after this one fills
  84866. in the rest of the decoding tables with invalid code markers.
  84867. */
  84868. /* set up for code type */
  84869. switch (type) {
  84870. case CODES:
  84871. base = extra = work; /* dummy value--not used */
  84872. end = 19;
  84873. break;
  84874. case LENS:
  84875. base = lbase;
  84876. base -= 257;
  84877. extra = lext;
  84878. extra -= 257;
  84879. end = 256;
  84880. break;
  84881. default: /* DISTS */
  84882. base = dbase;
  84883. extra = dext;
  84884. end = -1;
  84885. }
  84886. /* initialize state for loop */
  84887. huff = 0; /* starting code */
  84888. sym = 0; /* starting code symbol */
  84889. len = min; /* starting code length */
  84890. next = *table; /* current table to fill in */
  84891. curr = root; /* current table index bits */
  84892. drop = 0; /* current bits to drop from code for index */
  84893. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84894. used = 1U << root; /* use root table entries */
  84895. mask = used - 1; /* mask for comparing low */
  84896. /* check available table space */
  84897. if (type == LENS && used >= ENOUGH - MAXD)
  84898. return 1;
  84899. /* process all codes and make table entries */
  84900. for (;;) {
  84901. /* create table entry */
  84902. thisx.bits = (unsigned char)(len - drop);
  84903. if ((int)(work[sym]) < end) {
  84904. thisx.op = (unsigned char)0;
  84905. thisx.val = work[sym];
  84906. }
  84907. else if ((int)(work[sym]) > end) {
  84908. thisx.op = (unsigned char)(extra[work[sym]]);
  84909. thisx.val = base[work[sym]];
  84910. }
  84911. else {
  84912. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84913. thisx.val = 0;
  84914. }
  84915. /* replicate for those indices with low len bits equal to huff */
  84916. incr = 1U << (len - drop);
  84917. fill = 1U << curr;
  84918. min = fill; /* save offset to next table */
  84919. do {
  84920. fill -= incr;
  84921. next[(huff >> drop) + fill] = thisx;
  84922. } while (fill != 0);
  84923. /* backwards increment the len-bit code huff */
  84924. incr = 1U << (len - 1);
  84925. while (huff & incr)
  84926. incr >>= 1;
  84927. if (incr != 0) {
  84928. huff &= incr - 1;
  84929. huff += incr;
  84930. }
  84931. else
  84932. huff = 0;
  84933. /* go to next symbol, update count, len */
  84934. sym++;
  84935. if (--(count[len]) == 0) {
  84936. if (len == max) break;
  84937. len = lens[work[sym]];
  84938. }
  84939. /* create new sub-table if needed */
  84940. if (len > root && (huff & mask) != low) {
  84941. /* if first time, transition to sub-tables */
  84942. if (drop == 0)
  84943. drop = root;
  84944. /* increment past last table */
  84945. next += min; /* here min is 1 << curr */
  84946. /* determine length of next table */
  84947. curr = len - drop;
  84948. left = (int)(1 << curr);
  84949. while (curr + drop < max) {
  84950. left -= count[curr + drop];
  84951. if (left <= 0) break;
  84952. curr++;
  84953. left <<= 1;
  84954. }
  84955. /* check for enough space */
  84956. used += 1U << curr;
  84957. if (type == LENS && used >= ENOUGH - MAXD)
  84958. return 1;
  84959. /* point entry in root table to sub-table */
  84960. low = huff & mask;
  84961. (*table)[low].op = (unsigned char)curr;
  84962. (*table)[low].bits = (unsigned char)root;
  84963. (*table)[low].val = (unsigned short)(next - *table);
  84964. }
  84965. }
  84966. /*
  84967. Fill in rest of table for incomplete codes. This loop is similar to the
  84968. loop above in incrementing huff for table indices. It is assumed that
  84969. len is equal to curr + drop, so there is no loop needed to increment
  84970. through high index bits. When the current sub-table is filled, the loop
  84971. drops back to the root table to fill in any remaining entries there.
  84972. */
  84973. thisx.op = (unsigned char)64; /* invalid code marker */
  84974. thisx.bits = (unsigned char)(len - drop);
  84975. thisx.val = (unsigned short)0;
  84976. while (huff != 0) {
  84977. /* when done with sub-table, drop back to root table */
  84978. if (drop != 0 && (huff & mask) != low) {
  84979. drop = 0;
  84980. len = root;
  84981. next = *table;
  84982. thisx.bits = (unsigned char)len;
  84983. }
  84984. /* put invalid code marker in table */
  84985. next[huff >> drop] = thisx;
  84986. /* backwards increment the len-bit code huff */
  84987. incr = 1U << (len - 1);
  84988. while (huff & incr)
  84989. incr >>= 1;
  84990. if (incr != 0) {
  84991. huff &= incr - 1;
  84992. huff += incr;
  84993. }
  84994. else
  84995. huff = 0;
  84996. }
  84997. /* set return parameters */
  84998. *table += used;
  84999. *bits = root;
  85000. return 0;
  85001. }
  85002. /*** End of inlined file: inftrees.c ***/
  85003. /*** Start of inlined file: trees.c ***/
  85004. /*
  85005. * ALGORITHM
  85006. *
  85007. * The "deflation" process uses several Huffman trees. The more
  85008. * common source values are represented by shorter bit sequences.
  85009. *
  85010. * Each code tree is stored in a compressed form which is itself
  85011. * a Huffman encoding of the lengths of all the code strings (in
  85012. * ascending order by source values). The actual code strings are
  85013. * reconstructed from the lengths in the inflate process, as described
  85014. * in the deflate specification.
  85015. *
  85016. * REFERENCES
  85017. *
  85018. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  85019. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  85020. *
  85021. * Storer, James A.
  85022. * Data Compression: Methods and Theory, pp. 49-50.
  85023. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  85024. *
  85025. * Sedgewick, R.
  85026. * Algorithms, p290.
  85027. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  85028. */
  85029. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85030. /* #define GEN_TREES_H */
  85031. #ifdef DEBUG
  85032. # include <ctype.h>
  85033. #endif
  85034. /* ===========================================================================
  85035. * Constants
  85036. */
  85037. #define MAX_BL_BITS 7
  85038. /* Bit length codes must not exceed MAX_BL_BITS bits */
  85039. #define END_BLOCK 256
  85040. /* end of block literal code */
  85041. #define REP_3_6 16
  85042. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  85043. #define REPZ_3_10 17
  85044. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  85045. #define REPZ_11_138 18
  85046. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  85047. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  85048. = {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};
  85049. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  85050. = {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};
  85051. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  85052. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  85053. local const uch bl_order[BL_CODES]
  85054. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  85055. /* The lengths of the bit length codes are sent in order of decreasing
  85056. * probability, to avoid transmitting the lengths for unused bit length codes.
  85057. */
  85058. #define Buf_size (8 * 2*sizeof(char))
  85059. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  85060. * more than 16 bits on some systems.)
  85061. */
  85062. /* ===========================================================================
  85063. * Local data. These are initialized only once.
  85064. */
  85065. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  85066. #if defined(GEN_TREES_H) || !defined(STDC)
  85067. /* non ANSI compilers may not accept trees.h */
  85068. local ct_data static_ltree[L_CODES+2];
  85069. /* The static literal tree. Since the bit lengths are imposed, there is no
  85070. * need for the L_CODES extra codes used during heap construction. However
  85071. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  85072. * below).
  85073. */
  85074. local ct_data static_dtree[D_CODES];
  85075. /* The static distance tree. (Actually a trivial tree since all codes use
  85076. * 5 bits.)
  85077. */
  85078. uch _dist_code[DIST_CODE_LEN];
  85079. /* Distance codes. The first 256 values correspond to the distances
  85080. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  85081. * the 15 bit distances.
  85082. */
  85083. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  85084. /* length code for each normalized match length (0 == MIN_MATCH) */
  85085. local int base_length[LENGTH_CODES];
  85086. /* First normalized length for each code (0 = MIN_MATCH) */
  85087. local int base_dist[D_CODES];
  85088. /* First normalized distance for each code (0 = distance of 1) */
  85089. #else
  85090. /*** Start of inlined file: trees.h ***/
  85091. local const ct_data static_ltree[L_CODES+2] = {
  85092. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  85093. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  85094. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  85095. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  85096. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  85097. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  85098. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  85099. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  85100. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  85101. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  85102. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  85103. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  85104. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  85105. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  85106. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  85107. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  85108. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  85109. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  85110. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  85111. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  85112. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  85113. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  85114. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  85115. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  85116. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  85117. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  85118. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  85119. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  85120. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  85121. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  85122. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  85123. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  85124. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  85125. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  85126. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  85127. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  85128. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  85129. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  85130. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  85131. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  85132. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  85133. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  85134. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  85135. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  85136. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  85137. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  85138. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  85139. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  85140. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  85141. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  85142. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  85143. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  85144. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  85145. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  85146. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  85147. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  85148. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  85149. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  85150. };
  85151. local const ct_data static_dtree[D_CODES] = {
  85152. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  85153. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  85154. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  85155. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  85156. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  85157. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  85158. };
  85159. const uch _dist_code[DIST_CODE_LEN] = {
  85160. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  85161. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  85162. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  85163. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  85164. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  85165. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  85166. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85167. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85168. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85169. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  85170. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85171. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85172. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  85173. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  85174. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85175. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85176. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85177. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  85178. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85179. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85180. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85181. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85182. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85183. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85184. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85185. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85186. };
  85187. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85188. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85189. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85190. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85191. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85192. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85193. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85194. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85195. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85196. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85197. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85198. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85199. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85200. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85201. };
  85202. local const int base_length[LENGTH_CODES] = {
  85203. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85204. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85205. };
  85206. local const int base_dist[D_CODES] = {
  85207. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85208. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85209. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85210. };
  85211. /*** End of inlined file: trees.h ***/
  85212. #endif /* GEN_TREES_H */
  85213. struct static_tree_desc_s {
  85214. const ct_data *static_tree; /* static tree or NULL */
  85215. const intf *extra_bits; /* extra bits for each code or NULL */
  85216. int extra_base; /* base index for extra_bits */
  85217. int elems; /* max number of elements in the tree */
  85218. int max_length; /* max bit length for the codes */
  85219. };
  85220. local static_tree_desc static_l_desc =
  85221. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85222. local static_tree_desc static_d_desc =
  85223. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85224. local static_tree_desc static_bl_desc =
  85225. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85226. /* ===========================================================================
  85227. * Local (static) routines in this file.
  85228. */
  85229. local void tr_static_init OF((void));
  85230. local void init_block OF((deflate_state *s));
  85231. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85232. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85233. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85234. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85235. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85236. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85237. local int build_bl_tree OF((deflate_state *s));
  85238. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85239. int blcodes));
  85240. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85241. ct_data *dtree));
  85242. local void set_data_type OF((deflate_state *s));
  85243. local unsigned bi_reverse OF((unsigned value, int length));
  85244. local void bi_windup OF((deflate_state *s));
  85245. local void bi_flush OF((deflate_state *s));
  85246. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85247. int header));
  85248. #ifdef GEN_TREES_H
  85249. local void gen_trees_header OF((void));
  85250. #endif
  85251. #ifndef DEBUG
  85252. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85253. /* Send a code of the given tree. c and tree must not have side effects */
  85254. #else /* DEBUG */
  85255. # define send_code(s, c, tree) \
  85256. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85257. send_bits(s, tree[c].Code, tree[c].Len); }
  85258. #endif
  85259. /* ===========================================================================
  85260. * Output a short LSB first on the stream.
  85261. * IN assertion: there is enough room in pendingBuf.
  85262. */
  85263. #define put_short(s, w) { \
  85264. put_byte(s, (uch)((w) & 0xff)); \
  85265. put_byte(s, (uch)((ush)(w) >> 8)); \
  85266. }
  85267. /* ===========================================================================
  85268. * Send a value on a given number of bits.
  85269. * IN assertion: length <= 16 and value fits in length bits.
  85270. */
  85271. #ifdef DEBUG
  85272. local void send_bits OF((deflate_state *s, int value, int length));
  85273. local void send_bits (deflate_state *s, int value, int length)
  85274. {
  85275. Tracevv((stderr," l %2d v %4x ", length, value));
  85276. Assert(length > 0 && length <= 15, "invalid length");
  85277. s->bits_sent += (ulg)length;
  85278. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85279. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85280. * unused bits in value.
  85281. */
  85282. if (s->bi_valid > (int)Buf_size - length) {
  85283. s->bi_buf |= (value << s->bi_valid);
  85284. put_short(s, s->bi_buf);
  85285. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85286. s->bi_valid += length - Buf_size;
  85287. } else {
  85288. s->bi_buf |= value << s->bi_valid;
  85289. s->bi_valid += length;
  85290. }
  85291. }
  85292. #else /* !DEBUG */
  85293. #define send_bits(s, value, length) \
  85294. { int len = length;\
  85295. if (s->bi_valid > (int)Buf_size - len) {\
  85296. int val = value;\
  85297. s->bi_buf |= (val << s->bi_valid);\
  85298. put_short(s, s->bi_buf);\
  85299. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85300. s->bi_valid += len - Buf_size;\
  85301. } else {\
  85302. s->bi_buf |= (value) << s->bi_valid;\
  85303. s->bi_valid += len;\
  85304. }\
  85305. }
  85306. #endif /* DEBUG */
  85307. /* the arguments must not have side effects */
  85308. /* ===========================================================================
  85309. * Initialize the various 'constant' tables.
  85310. */
  85311. local void tr_static_init()
  85312. {
  85313. #if defined(GEN_TREES_H) || !defined(STDC)
  85314. static int static_init_done = 0;
  85315. int n; /* iterates over tree elements */
  85316. int bits; /* bit counter */
  85317. int length; /* length value */
  85318. int code; /* code value */
  85319. int dist; /* distance index */
  85320. ush bl_count[MAX_BITS+1];
  85321. /* number of codes at each bit length for an optimal tree */
  85322. if (static_init_done) return;
  85323. /* For some embedded targets, global variables are not initialized: */
  85324. static_l_desc.static_tree = static_ltree;
  85325. static_l_desc.extra_bits = extra_lbits;
  85326. static_d_desc.static_tree = static_dtree;
  85327. static_d_desc.extra_bits = extra_dbits;
  85328. static_bl_desc.extra_bits = extra_blbits;
  85329. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85330. length = 0;
  85331. for (code = 0; code < LENGTH_CODES-1; code++) {
  85332. base_length[code] = length;
  85333. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85334. _length_code[length++] = (uch)code;
  85335. }
  85336. }
  85337. Assert (length == 256, "tr_static_init: length != 256");
  85338. /* Note that the length 255 (match length 258) can be represented
  85339. * in two different ways: code 284 + 5 bits or code 285, so we
  85340. * overwrite length_code[255] to use the best encoding:
  85341. */
  85342. _length_code[length-1] = (uch)code;
  85343. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85344. dist = 0;
  85345. for (code = 0 ; code < 16; code++) {
  85346. base_dist[code] = dist;
  85347. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85348. _dist_code[dist++] = (uch)code;
  85349. }
  85350. }
  85351. Assert (dist == 256, "tr_static_init: dist != 256");
  85352. dist >>= 7; /* from now on, all distances are divided by 128 */
  85353. for ( ; code < D_CODES; code++) {
  85354. base_dist[code] = dist << 7;
  85355. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85356. _dist_code[256 + dist++] = (uch)code;
  85357. }
  85358. }
  85359. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85360. /* Construct the codes of the static literal tree */
  85361. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85362. n = 0;
  85363. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85364. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85365. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85366. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85367. /* Codes 286 and 287 do not exist, but we must include them in the
  85368. * tree construction to get a canonical Huffman tree (longest code
  85369. * all ones)
  85370. */
  85371. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85372. /* The static distance tree is trivial: */
  85373. for (n = 0; n < D_CODES; n++) {
  85374. static_dtree[n].Len = 5;
  85375. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85376. }
  85377. static_init_done = 1;
  85378. # ifdef GEN_TREES_H
  85379. gen_trees_header();
  85380. # endif
  85381. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85382. }
  85383. /* ===========================================================================
  85384. * Genererate the file trees.h describing the static trees.
  85385. */
  85386. #ifdef GEN_TREES_H
  85387. # ifndef DEBUG
  85388. # include <stdio.h>
  85389. # endif
  85390. # define SEPARATOR(i, last, width) \
  85391. ((i) == (last)? "\n};\n\n" : \
  85392. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85393. void gen_trees_header()
  85394. {
  85395. FILE *header = fopen("trees.h", "w");
  85396. int i;
  85397. Assert (header != NULL, "Can't open trees.h");
  85398. fprintf(header,
  85399. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85400. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85401. for (i = 0; i < L_CODES+2; i++) {
  85402. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85403. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85404. }
  85405. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85406. for (i = 0; i < D_CODES; i++) {
  85407. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85408. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85409. }
  85410. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85411. for (i = 0; i < DIST_CODE_LEN; i++) {
  85412. fprintf(header, "%2u%s", _dist_code[i],
  85413. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85414. }
  85415. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85416. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85417. fprintf(header, "%2u%s", _length_code[i],
  85418. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85419. }
  85420. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85421. for (i = 0; i < LENGTH_CODES; i++) {
  85422. fprintf(header, "%1u%s", base_length[i],
  85423. SEPARATOR(i, LENGTH_CODES-1, 20));
  85424. }
  85425. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85426. for (i = 0; i < D_CODES; i++) {
  85427. fprintf(header, "%5u%s", base_dist[i],
  85428. SEPARATOR(i, D_CODES-1, 10));
  85429. }
  85430. fclose(header);
  85431. }
  85432. #endif /* GEN_TREES_H */
  85433. /* ===========================================================================
  85434. * Initialize the tree data structures for a new zlib stream.
  85435. */
  85436. void _tr_init(deflate_state *s)
  85437. {
  85438. tr_static_init();
  85439. s->l_desc.dyn_tree = s->dyn_ltree;
  85440. s->l_desc.stat_desc = &static_l_desc;
  85441. s->d_desc.dyn_tree = s->dyn_dtree;
  85442. s->d_desc.stat_desc = &static_d_desc;
  85443. s->bl_desc.dyn_tree = s->bl_tree;
  85444. s->bl_desc.stat_desc = &static_bl_desc;
  85445. s->bi_buf = 0;
  85446. s->bi_valid = 0;
  85447. s->last_eob_len = 8; /* enough lookahead for inflate */
  85448. #ifdef DEBUG
  85449. s->compressed_len = 0L;
  85450. s->bits_sent = 0L;
  85451. #endif
  85452. /* Initialize the first block of the first file: */
  85453. init_block(s);
  85454. }
  85455. /* ===========================================================================
  85456. * Initialize a new block.
  85457. */
  85458. local void init_block (deflate_state *s)
  85459. {
  85460. int n; /* iterates over tree elements */
  85461. /* Initialize the trees. */
  85462. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85463. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85464. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85465. s->dyn_ltree[END_BLOCK].Freq = 1;
  85466. s->opt_len = s->static_len = 0L;
  85467. s->last_lit = s->matches = 0;
  85468. }
  85469. #define SMALLEST 1
  85470. /* Index within the heap array of least frequent node in the Huffman tree */
  85471. /* ===========================================================================
  85472. * Remove the smallest element from the heap and recreate the heap with
  85473. * one less element. Updates heap and heap_len.
  85474. */
  85475. #define pqremove(s, tree, top) \
  85476. {\
  85477. top = s->heap[SMALLEST]; \
  85478. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85479. pqdownheap(s, tree, SMALLEST); \
  85480. }
  85481. /* ===========================================================================
  85482. * Compares to subtrees, using the tree depth as tie breaker when
  85483. * the subtrees have equal frequency. This minimizes the worst case length.
  85484. */
  85485. #define smaller(tree, n, m, depth) \
  85486. (tree[n].Freq < tree[m].Freq || \
  85487. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85488. /* ===========================================================================
  85489. * Restore the heap property by moving down the tree starting at node k,
  85490. * exchanging a node with the smallest of its two sons if necessary, stopping
  85491. * when the heap property is re-established (each father smaller than its
  85492. * two sons).
  85493. */
  85494. local void pqdownheap (deflate_state *s,
  85495. ct_data *tree, /* the tree to restore */
  85496. int k) /* node to move down */
  85497. {
  85498. int v = s->heap[k];
  85499. int j = k << 1; /* left son of k */
  85500. while (j <= s->heap_len) {
  85501. /* Set j to the smallest of the two sons: */
  85502. if (j < s->heap_len &&
  85503. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85504. j++;
  85505. }
  85506. /* Exit if v is smaller than both sons */
  85507. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85508. /* Exchange v with the smallest son */
  85509. s->heap[k] = s->heap[j]; k = j;
  85510. /* And continue down the tree, setting j to the left son of k */
  85511. j <<= 1;
  85512. }
  85513. s->heap[k] = v;
  85514. }
  85515. /* ===========================================================================
  85516. * Compute the optimal bit lengths for a tree and update the total bit length
  85517. * for the current block.
  85518. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85519. * above are the tree nodes sorted by increasing frequency.
  85520. * OUT assertions: the field len is set to the optimal bit length, the
  85521. * array bl_count contains the frequencies for each bit length.
  85522. * The length opt_len is updated; static_len is also updated if stree is
  85523. * not null.
  85524. */
  85525. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85526. {
  85527. ct_data *tree = desc->dyn_tree;
  85528. int max_code = desc->max_code;
  85529. const ct_data *stree = desc->stat_desc->static_tree;
  85530. const intf *extra = desc->stat_desc->extra_bits;
  85531. int base = desc->stat_desc->extra_base;
  85532. int max_length = desc->stat_desc->max_length;
  85533. int h; /* heap index */
  85534. int n, m; /* iterate over the tree elements */
  85535. int bits; /* bit length */
  85536. int xbits; /* extra bits */
  85537. ush f; /* frequency */
  85538. int overflow = 0; /* number of elements with bit length too large */
  85539. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85540. /* In a first pass, compute the optimal bit lengths (which may
  85541. * overflow in the case of the bit length tree).
  85542. */
  85543. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85544. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85545. n = s->heap[h];
  85546. bits = tree[tree[n].Dad].Len + 1;
  85547. if (bits > max_length) bits = max_length, overflow++;
  85548. tree[n].Len = (ush)bits;
  85549. /* We overwrite tree[n].Dad which is no longer needed */
  85550. if (n > max_code) continue; /* not a leaf node */
  85551. s->bl_count[bits]++;
  85552. xbits = 0;
  85553. if (n >= base) xbits = extra[n-base];
  85554. f = tree[n].Freq;
  85555. s->opt_len += (ulg)f * (bits + xbits);
  85556. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85557. }
  85558. if (overflow == 0) return;
  85559. Trace((stderr,"\nbit length overflow\n"));
  85560. /* This happens for example on obj2 and pic of the Calgary corpus */
  85561. /* Find the first bit length which could increase: */
  85562. do {
  85563. bits = max_length-1;
  85564. while (s->bl_count[bits] == 0) bits--;
  85565. s->bl_count[bits]--; /* move one leaf down the tree */
  85566. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85567. s->bl_count[max_length]--;
  85568. /* The brother of the overflow item also moves one step up,
  85569. * but this does not affect bl_count[max_length]
  85570. */
  85571. overflow -= 2;
  85572. } while (overflow > 0);
  85573. /* Now recompute all bit lengths, scanning in increasing frequency.
  85574. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85575. * lengths instead of fixing only the wrong ones. This idea is taken
  85576. * from 'ar' written by Haruhiko Okumura.)
  85577. */
  85578. for (bits = max_length; bits != 0; bits--) {
  85579. n = s->bl_count[bits];
  85580. while (n != 0) {
  85581. m = s->heap[--h];
  85582. if (m > max_code) continue;
  85583. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85584. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85585. s->opt_len += ((long)bits - (long)tree[m].Len)
  85586. *(long)tree[m].Freq;
  85587. tree[m].Len = (ush)bits;
  85588. }
  85589. n--;
  85590. }
  85591. }
  85592. }
  85593. /* ===========================================================================
  85594. * Generate the codes for a given tree and bit counts (which need not be
  85595. * optimal).
  85596. * IN assertion: the array bl_count contains the bit length statistics for
  85597. * the given tree and the field len is set for all tree elements.
  85598. * OUT assertion: the field code is set for all tree elements of non
  85599. * zero code length.
  85600. */
  85601. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85602. int max_code, /* largest code with non zero frequency */
  85603. ushf *bl_count) /* number of codes at each bit length */
  85604. {
  85605. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85606. ush code = 0; /* running code value */
  85607. int bits; /* bit index */
  85608. int n; /* code index */
  85609. /* The distribution counts are first used to generate the code values
  85610. * without bit reversal.
  85611. */
  85612. for (bits = 1; bits <= MAX_BITS; bits++) {
  85613. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85614. }
  85615. /* Check that the bit counts in bl_count are consistent. The last code
  85616. * must be all ones.
  85617. */
  85618. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85619. "inconsistent bit counts");
  85620. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85621. for (n = 0; n <= max_code; n++) {
  85622. int len = tree[n].Len;
  85623. if (len == 0) continue;
  85624. /* Now reverse the bits */
  85625. tree[n].Code = bi_reverse(next_code[len]++, len);
  85626. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85627. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85628. }
  85629. }
  85630. /* ===========================================================================
  85631. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85632. * Update the total bit length for the current block.
  85633. * IN assertion: the field freq is set for all tree elements.
  85634. * OUT assertions: the fields len and code are set to the optimal bit length
  85635. * and corresponding code. The length opt_len is updated; static_len is
  85636. * also updated if stree is not null. The field max_code is set.
  85637. */
  85638. local void build_tree (deflate_state *s,
  85639. tree_desc *desc) /* the tree descriptor */
  85640. {
  85641. ct_data *tree = desc->dyn_tree;
  85642. const ct_data *stree = desc->stat_desc->static_tree;
  85643. int elems = desc->stat_desc->elems;
  85644. int n, m; /* iterate over heap elements */
  85645. int max_code = -1; /* largest code with non zero frequency */
  85646. int node; /* new node being created */
  85647. /* Construct the initial heap, with least frequent element in
  85648. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85649. * heap[0] is not used.
  85650. */
  85651. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85652. for (n = 0; n < elems; n++) {
  85653. if (tree[n].Freq != 0) {
  85654. s->heap[++(s->heap_len)] = max_code = n;
  85655. s->depth[n] = 0;
  85656. } else {
  85657. tree[n].Len = 0;
  85658. }
  85659. }
  85660. /* The pkzip format requires that at least one distance code exists,
  85661. * and that at least one bit should be sent even if there is only one
  85662. * possible code. So to avoid special checks later on we force at least
  85663. * two codes of non zero frequency.
  85664. */
  85665. while (s->heap_len < 2) {
  85666. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85667. tree[node].Freq = 1;
  85668. s->depth[node] = 0;
  85669. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85670. /* node is 0 or 1 so it does not have extra bits */
  85671. }
  85672. desc->max_code = max_code;
  85673. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85674. * establish sub-heaps of increasing lengths:
  85675. */
  85676. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85677. /* Construct the Huffman tree by repeatedly combining the least two
  85678. * frequent nodes.
  85679. */
  85680. node = elems; /* next internal node of the tree */
  85681. do {
  85682. pqremove(s, tree, n); /* n = node of least frequency */
  85683. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85684. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85685. s->heap[--(s->heap_max)] = m;
  85686. /* Create a new node father of n and m */
  85687. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85688. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85689. s->depth[n] : s->depth[m]) + 1);
  85690. tree[n].Dad = tree[m].Dad = (ush)node;
  85691. #ifdef DUMP_BL_TREE
  85692. if (tree == s->bl_tree) {
  85693. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85694. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85695. }
  85696. #endif
  85697. /* and insert the new node in the heap */
  85698. s->heap[SMALLEST] = node++;
  85699. pqdownheap(s, tree, SMALLEST);
  85700. } while (s->heap_len >= 2);
  85701. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85702. /* At this point, the fields freq and dad are set. We can now
  85703. * generate the bit lengths.
  85704. */
  85705. gen_bitlen(s, (tree_desc *)desc);
  85706. /* The field len is now set, we can generate the bit codes */
  85707. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85708. }
  85709. /* ===========================================================================
  85710. * Scan a literal or distance tree to determine the frequencies of the codes
  85711. * in the bit length tree.
  85712. */
  85713. local void scan_tree (deflate_state *s,
  85714. ct_data *tree, /* the tree to be scanned */
  85715. int max_code) /* and its largest code of non zero frequency */
  85716. {
  85717. int n; /* iterates over all tree elements */
  85718. int prevlen = -1; /* last emitted length */
  85719. int curlen; /* length of current code */
  85720. int nextlen = tree[0].Len; /* length of next code */
  85721. int count = 0; /* repeat count of the current code */
  85722. int max_count = 7; /* max repeat count */
  85723. int min_count = 4; /* min repeat count */
  85724. if (nextlen == 0) max_count = 138, min_count = 3;
  85725. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85726. for (n = 0; n <= max_code; n++) {
  85727. curlen = nextlen; nextlen = tree[n+1].Len;
  85728. if (++count < max_count && curlen == nextlen) {
  85729. continue;
  85730. } else if (count < min_count) {
  85731. s->bl_tree[curlen].Freq += count;
  85732. } else if (curlen != 0) {
  85733. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85734. s->bl_tree[REP_3_6].Freq++;
  85735. } else if (count <= 10) {
  85736. s->bl_tree[REPZ_3_10].Freq++;
  85737. } else {
  85738. s->bl_tree[REPZ_11_138].Freq++;
  85739. }
  85740. count = 0; prevlen = curlen;
  85741. if (nextlen == 0) {
  85742. max_count = 138, min_count = 3;
  85743. } else if (curlen == nextlen) {
  85744. max_count = 6, min_count = 3;
  85745. } else {
  85746. max_count = 7, min_count = 4;
  85747. }
  85748. }
  85749. }
  85750. /* ===========================================================================
  85751. * Send a literal or distance tree in compressed form, using the codes in
  85752. * bl_tree.
  85753. */
  85754. local void send_tree (deflate_state *s,
  85755. ct_data *tree, /* the tree to be scanned */
  85756. int max_code) /* and its largest code of non zero frequency */
  85757. {
  85758. int n; /* iterates over all tree elements */
  85759. int prevlen = -1; /* last emitted length */
  85760. int curlen; /* length of current code */
  85761. int nextlen = tree[0].Len; /* length of next code */
  85762. int count = 0; /* repeat count of the current code */
  85763. int max_count = 7; /* max repeat count */
  85764. int min_count = 4; /* min repeat count */
  85765. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85766. if (nextlen == 0) max_count = 138, min_count = 3;
  85767. for (n = 0; n <= max_code; n++) {
  85768. curlen = nextlen; nextlen = tree[n+1].Len;
  85769. if (++count < max_count && curlen == nextlen) {
  85770. continue;
  85771. } else if (count < min_count) {
  85772. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85773. } else if (curlen != 0) {
  85774. if (curlen != prevlen) {
  85775. send_code(s, curlen, s->bl_tree); count--;
  85776. }
  85777. Assert(count >= 3 && count <= 6, " 3_6?");
  85778. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85779. } else if (count <= 10) {
  85780. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85781. } else {
  85782. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85783. }
  85784. count = 0; prevlen = curlen;
  85785. if (nextlen == 0) {
  85786. max_count = 138, min_count = 3;
  85787. } else if (curlen == nextlen) {
  85788. max_count = 6, min_count = 3;
  85789. } else {
  85790. max_count = 7, min_count = 4;
  85791. }
  85792. }
  85793. }
  85794. /* ===========================================================================
  85795. * Construct the Huffman tree for the bit lengths and return the index in
  85796. * bl_order of the last bit length code to send.
  85797. */
  85798. local int build_bl_tree (deflate_state *s)
  85799. {
  85800. int max_blindex; /* index of last bit length code of non zero freq */
  85801. /* Determine the bit length frequencies for literal and distance trees */
  85802. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85803. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85804. /* Build the bit length tree: */
  85805. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85806. /* opt_len now includes the length of the tree representations, except
  85807. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85808. */
  85809. /* Determine the number of bit length codes to send. The pkzip format
  85810. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85811. * 3 but the actual value used is 4.)
  85812. */
  85813. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85814. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85815. }
  85816. /* Update opt_len to include the bit length tree and counts */
  85817. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85818. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85819. s->opt_len, s->static_len));
  85820. return max_blindex;
  85821. }
  85822. /* ===========================================================================
  85823. * Send the header for a block using dynamic Huffman trees: the counts, the
  85824. * lengths of the bit length codes, the literal tree and the distance tree.
  85825. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85826. */
  85827. local void send_all_trees (deflate_state *s,
  85828. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85829. {
  85830. int rank; /* index in bl_order */
  85831. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85832. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85833. "too many codes");
  85834. Tracev((stderr, "\nbl counts: "));
  85835. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85836. send_bits(s, dcodes-1, 5);
  85837. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85838. for (rank = 0; rank < blcodes; rank++) {
  85839. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85840. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85841. }
  85842. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85843. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85844. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85845. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85846. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85847. }
  85848. /* ===========================================================================
  85849. * Send a stored block
  85850. */
  85851. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85852. {
  85853. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85854. #ifdef DEBUG
  85855. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85856. s->compressed_len += (stored_len + 4) << 3;
  85857. #endif
  85858. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85859. }
  85860. /* ===========================================================================
  85861. * Send one empty static block to give enough lookahead for inflate.
  85862. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85863. * The current inflate code requires 9 bits of lookahead. If the
  85864. * last two codes for the previous block (real code plus EOB) were coded
  85865. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85866. * the last real code. In this case we send two empty static blocks instead
  85867. * of one. (There are no problems if the previous block is stored or fixed.)
  85868. * To simplify the code, we assume the worst case of last real code encoded
  85869. * on one bit only.
  85870. */
  85871. void _tr_align (deflate_state *s)
  85872. {
  85873. send_bits(s, STATIC_TREES<<1, 3);
  85874. send_code(s, END_BLOCK, static_ltree);
  85875. #ifdef DEBUG
  85876. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85877. #endif
  85878. bi_flush(s);
  85879. /* Of the 10 bits for the empty block, we have already sent
  85880. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85881. * the EOB of the previous block) was thus at least one plus the length
  85882. * of the EOB plus what we have just sent of the empty static block.
  85883. */
  85884. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85885. send_bits(s, STATIC_TREES<<1, 3);
  85886. send_code(s, END_BLOCK, static_ltree);
  85887. #ifdef DEBUG
  85888. s->compressed_len += 10L;
  85889. #endif
  85890. bi_flush(s);
  85891. }
  85892. s->last_eob_len = 7;
  85893. }
  85894. /* ===========================================================================
  85895. * Determine the best encoding for the current block: dynamic trees, static
  85896. * trees or store, and output the encoded block to the zip file.
  85897. */
  85898. void _tr_flush_block (deflate_state *s,
  85899. charf *buf, /* input block, or NULL if too old */
  85900. ulg stored_len, /* length of input block */
  85901. int eof) /* true if this is the last block for a file */
  85902. {
  85903. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85904. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85905. /* Build the Huffman trees unless a stored block is forced */
  85906. if (s->level > 0) {
  85907. /* Check if the file is binary or text */
  85908. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85909. set_data_type(s);
  85910. /* Construct the literal and distance trees */
  85911. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85912. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85913. s->static_len));
  85914. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85915. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85916. s->static_len));
  85917. /* At this point, opt_len and static_len are the total bit lengths of
  85918. * the compressed block data, excluding the tree representations.
  85919. */
  85920. /* Build the bit length tree for the above two trees, and get the index
  85921. * in bl_order of the last bit length code to send.
  85922. */
  85923. max_blindex = build_bl_tree(s);
  85924. /* Determine the best encoding. Compute the block lengths in bytes. */
  85925. opt_lenb = (s->opt_len+3+7)>>3;
  85926. static_lenb = (s->static_len+3+7)>>3;
  85927. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85928. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85929. s->last_lit));
  85930. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85931. } else {
  85932. Assert(buf != (char*)0, "lost buf");
  85933. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85934. }
  85935. #ifdef FORCE_STORED
  85936. if (buf != (char*)0) { /* force stored block */
  85937. #else
  85938. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85939. /* 4: two words for the lengths */
  85940. #endif
  85941. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85942. * Otherwise we can't have processed more than WSIZE input bytes since
  85943. * the last block flush, because compression would have been
  85944. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85945. * transform a block into a stored block.
  85946. */
  85947. _tr_stored_block(s, buf, stored_len, eof);
  85948. #ifdef FORCE_STATIC
  85949. } else if (static_lenb >= 0) { /* force static trees */
  85950. #else
  85951. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85952. #endif
  85953. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85954. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85955. #ifdef DEBUG
  85956. s->compressed_len += 3 + s->static_len;
  85957. #endif
  85958. } else {
  85959. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85960. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85961. max_blindex+1);
  85962. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85963. #ifdef DEBUG
  85964. s->compressed_len += 3 + s->opt_len;
  85965. #endif
  85966. }
  85967. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85968. /* The above check is made mod 2^32, for files larger than 512 MB
  85969. * and uLong implemented on 32 bits.
  85970. */
  85971. init_block(s);
  85972. if (eof) {
  85973. bi_windup(s);
  85974. #ifdef DEBUG
  85975. s->compressed_len += 7; /* align on byte boundary */
  85976. #endif
  85977. }
  85978. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85979. s->compressed_len-7*eof));
  85980. }
  85981. /* ===========================================================================
  85982. * Save the match info and tally the frequency counts. Return true if
  85983. * the current block must be flushed.
  85984. */
  85985. int _tr_tally (deflate_state *s,
  85986. unsigned dist, /* distance of matched string */
  85987. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85988. {
  85989. s->d_buf[s->last_lit] = (ush)dist;
  85990. s->l_buf[s->last_lit++] = (uch)lc;
  85991. if (dist == 0) {
  85992. /* lc is the unmatched char */
  85993. s->dyn_ltree[lc].Freq++;
  85994. } else {
  85995. s->matches++;
  85996. /* Here, lc is the match length - MIN_MATCH */
  85997. dist--; /* dist = match distance - 1 */
  85998. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85999. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  86000. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  86001. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  86002. s->dyn_dtree[d_code(dist)].Freq++;
  86003. }
  86004. #ifdef TRUNCATE_BLOCK
  86005. /* Try to guess if it is profitable to stop the current block here */
  86006. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  86007. /* Compute an upper bound for the compressed length */
  86008. ulg out_length = (ulg)s->last_lit*8L;
  86009. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  86010. int dcode;
  86011. for (dcode = 0; dcode < D_CODES; dcode++) {
  86012. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  86013. (5L+extra_dbits[dcode]);
  86014. }
  86015. out_length >>= 3;
  86016. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  86017. s->last_lit, in_length, out_length,
  86018. 100L - out_length*100L/in_length));
  86019. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  86020. }
  86021. #endif
  86022. return (s->last_lit == s->lit_bufsize-1);
  86023. /* We avoid equality with lit_bufsize because of wraparound at 64K
  86024. * on 16 bit machines and because stored blocks are restricted to
  86025. * 64K-1 bytes.
  86026. */
  86027. }
  86028. /* ===========================================================================
  86029. * Send the block data compressed using the given Huffman trees
  86030. */
  86031. local void compress_block (deflate_state *s,
  86032. ct_data *ltree, /* literal tree */
  86033. ct_data *dtree) /* distance tree */
  86034. {
  86035. unsigned dist; /* distance of matched string */
  86036. int lc; /* match length or unmatched char (if dist == 0) */
  86037. unsigned lx = 0; /* running index in l_buf */
  86038. unsigned code; /* the code to send */
  86039. int extra; /* number of extra bits to send */
  86040. if (s->last_lit != 0) do {
  86041. dist = s->d_buf[lx];
  86042. lc = s->l_buf[lx++];
  86043. if (dist == 0) {
  86044. send_code(s, lc, ltree); /* send a literal byte */
  86045. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  86046. } else {
  86047. /* Here, lc is the match length - MIN_MATCH */
  86048. code = _length_code[lc];
  86049. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  86050. extra = extra_lbits[code];
  86051. if (extra != 0) {
  86052. lc -= base_length[code];
  86053. send_bits(s, lc, extra); /* send the extra length bits */
  86054. }
  86055. dist--; /* dist is now the match distance - 1 */
  86056. code = d_code(dist);
  86057. Assert (code < D_CODES, "bad d_code");
  86058. send_code(s, code, dtree); /* send the distance code */
  86059. extra = extra_dbits[code];
  86060. if (extra != 0) {
  86061. dist -= base_dist[code];
  86062. send_bits(s, dist, extra); /* send the extra distance bits */
  86063. }
  86064. } /* literal or match pair ? */
  86065. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  86066. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  86067. "pendingBuf overflow");
  86068. } while (lx < s->last_lit);
  86069. send_code(s, END_BLOCK, ltree);
  86070. s->last_eob_len = ltree[END_BLOCK].Len;
  86071. }
  86072. /* ===========================================================================
  86073. * Set the data type to BINARY or TEXT, using a crude approximation:
  86074. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  86075. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  86076. * IN assertion: the fields Freq of dyn_ltree are set.
  86077. */
  86078. local void set_data_type (deflate_state *s)
  86079. {
  86080. int n;
  86081. for (n = 0; n < 9; n++)
  86082. if (s->dyn_ltree[n].Freq != 0)
  86083. break;
  86084. if (n == 9)
  86085. for (n = 14; n < 32; n++)
  86086. if (s->dyn_ltree[n].Freq != 0)
  86087. break;
  86088. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  86089. }
  86090. /* ===========================================================================
  86091. * Reverse the first len bits of a code, using straightforward code (a faster
  86092. * method would use a table)
  86093. * IN assertion: 1 <= len <= 15
  86094. */
  86095. local unsigned bi_reverse (unsigned code, int len)
  86096. {
  86097. register unsigned res = 0;
  86098. do {
  86099. res |= code & 1;
  86100. code >>= 1, res <<= 1;
  86101. } while (--len > 0);
  86102. return res >> 1;
  86103. }
  86104. /* ===========================================================================
  86105. * Flush the bit buffer, keeping at most 7 bits in it.
  86106. */
  86107. local void bi_flush (deflate_state *s)
  86108. {
  86109. if (s->bi_valid == 16) {
  86110. put_short(s, s->bi_buf);
  86111. s->bi_buf = 0;
  86112. s->bi_valid = 0;
  86113. } else if (s->bi_valid >= 8) {
  86114. put_byte(s, (Byte)s->bi_buf);
  86115. s->bi_buf >>= 8;
  86116. s->bi_valid -= 8;
  86117. }
  86118. }
  86119. /* ===========================================================================
  86120. * Flush the bit buffer and align the output on a byte boundary
  86121. */
  86122. local void bi_windup (deflate_state *s)
  86123. {
  86124. if (s->bi_valid > 8) {
  86125. put_short(s, s->bi_buf);
  86126. } else if (s->bi_valid > 0) {
  86127. put_byte(s, (Byte)s->bi_buf);
  86128. }
  86129. s->bi_buf = 0;
  86130. s->bi_valid = 0;
  86131. #ifdef DEBUG
  86132. s->bits_sent = (s->bits_sent+7) & ~7;
  86133. #endif
  86134. }
  86135. /* ===========================================================================
  86136. * Copy a stored block, storing first the length and its
  86137. * one's complement if requested.
  86138. */
  86139. local void copy_block(deflate_state *s,
  86140. charf *buf, /* the input data */
  86141. unsigned len, /* its length */
  86142. int header) /* true if block header must be written */
  86143. {
  86144. bi_windup(s); /* align on byte boundary */
  86145. s->last_eob_len = 8; /* enough lookahead for inflate */
  86146. if (header) {
  86147. put_short(s, (ush)len);
  86148. put_short(s, (ush)~len);
  86149. #ifdef DEBUG
  86150. s->bits_sent += 2*16;
  86151. #endif
  86152. }
  86153. #ifdef DEBUG
  86154. s->bits_sent += (ulg)len<<3;
  86155. #endif
  86156. while (len--) {
  86157. put_byte(s, *buf++);
  86158. }
  86159. }
  86160. /*** End of inlined file: trees.c ***/
  86161. /*** Start of inlined file: zutil.c ***/
  86162. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  86163. #ifndef NO_DUMMY_DECL
  86164. struct internal_state {int dummy;}; /* for buggy compilers */
  86165. #endif
  86166. const char * const z_errmsg[10] = {
  86167. "need dictionary", /* Z_NEED_DICT 2 */
  86168. "stream end", /* Z_STREAM_END 1 */
  86169. "", /* Z_OK 0 */
  86170. "file error", /* Z_ERRNO (-1) */
  86171. "stream error", /* Z_STREAM_ERROR (-2) */
  86172. "data error", /* Z_DATA_ERROR (-3) */
  86173. "insufficient memory", /* Z_MEM_ERROR (-4) */
  86174. "buffer error", /* Z_BUF_ERROR (-5) */
  86175. "incompatible version",/* Z_VERSION_ERROR (-6) */
  86176. ""};
  86177. /*const char * ZEXPORT zlibVersion()
  86178. {
  86179. return ZLIB_VERSION;
  86180. }
  86181. uLong ZEXPORT zlibCompileFlags()
  86182. {
  86183. uLong flags;
  86184. flags = 0;
  86185. switch (sizeof(uInt)) {
  86186. case 2: break;
  86187. case 4: flags += 1; break;
  86188. case 8: flags += 2; break;
  86189. default: flags += 3;
  86190. }
  86191. switch (sizeof(uLong)) {
  86192. case 2: break;
  86193. case 4: flags += 1 << 2; break;
  86194. case 8: flags += 2 << 2; break;
  86195. default: flags += 3 << 2;
  86196. }
  86197. switch (sizeof(voidpf)) {
  86198. case 2: break;
  86199. case 4: flags += 1 << 4; break;
  86200. case 8: flags += 2 << 4; break;
  86201. default: flags += 3 << 4;
  86202. }
  86203. switch (sizeof(z_off_t)) {
  86204. case 2: break;
  86205. case 4: flags += 1 << 6; break;
  86206. case 8: flags += 2 << 6; break;
  86207. default: flags += 3 << 6;
  86208. }
  86209. #ifdef DEBUG
  86210. flags += 1 << 8;
  86211. #endif
  86212. #if defined(ASMV) || defined(ASMINF)
  86213. flags += 1 << 9;
  86214. #endif
  86215. #ifdef ZLIB_WINAPI
  86216. flags += 1 << 10;
  86217. #endif
  86218. #ifdef BUILDFIXED
  86219. flags += 1 << 12;
  86220. #endif
  86221. #ifdef DYNAMIC_CRC_TABLE
  86222. flags += 1 << 13;
  86223. #endif
  86224. #ifdef NO_GZCOMPRESS
  86225. flags += 1L << 16;
  86226. #endif
  86227. #ifdef NO_GZIP
  86228. flags += 1L << 17;
  86229. #endif
  86230. #ifdef PKZIP_BUG_WORKAROUND
  86231. flags += 1L << 20;
  86232. #endif
  86233. #ifdef FASTEST
  86234. flags += 1L << 21;
  86235. #endif
  86236. #ifdef STDC
  86237. # ifdef NO_vsnprintf
  86238. flags += 1L << 25;
  86239. # ifdef HAS_vsprintf_void
  86240. flags += 1L << 26;
  86241. # endif
  86242. # else
  86243. # ifdef HAS_vsnprintf_void
  86244. flags += 1L << 26;
  86245. # endif
  86246. # endif
  86247. #else
  86248. flags += 1L << 24;
  86249. # ifdef NO_snprintf
  86250. flags += 1L << 25;
  86251. # ifdef HAS_sprintf_void
  86252. flags += 1L << 26;
  86253. # endif
  86254. # else
  86255. # ifdef HAS_snprintf_void
  86256. flags += 1L << 26;
  86257. # endif
  86258. # endif
  86259. #endif
  86260. return flags;
  86261. }*/
  86262. #ifdef DEBUG
  86263. # ifndef verbose
  86264. # define verbose 0
  86265. # endif
  86266. int z_verbose = verbose;
  86267. void z_error (const char *m)
  86268. {
  86269. fprintf(stderr, "%s\n", m);
  86270. exit(1);
  86271. }
  86272. #endif
  86273. /* exported to allow conversion of error code to string for compress() and
  86274. * uncompress()
  86275. */
  86276. const char * ZEXPORT zError(int err)
  86277. {
  86278. return ERR_MSG(err);
  86279. }
  86280. #if defined(_WIN32_WCE)
  86281. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86282. * errno. We define it as a global variable to simplify porting.
  86283. * Its value is always 0 and should not be used.
  86284. */
  86285. int errno = 0;
  86286. #endif
  86287. #ifndef HAVE_MEMCPY
  86288. void zmemcpy(dest, source, len)
  86289. Bytef* dest;
  86290. const Bytef* source;
  86291. uInt len;
  86292. {
  86293. if (len == 0) return;
  86294. do {
  86295. *dest++ = *source++; /* ??? to be unrolled */
  86296. } while (--len != 0);
  86297. }
  86298. int zmemcmp(s1, s2, len)
  86299. const Bytef* s1;
  86300. const Bytef* s2;
  86301. uInt len;
  86302. {
  86303. uInt j;
  86304. for (j = 0; j < len; j++) {
  86305. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86306. }
  86307. return 0;
  86308. }
  86309. void zmemzero(dest, len)
  86310. Bytef* dest;
  86311. uInt len;
  86312. {
  86313. if (len == 0) return;
  86314. do {
  86315. *dest++ = 0; /* ??? to be unrolled */
  86316. } while (--len != 0);
  86317. }
  86318. #endif
  86319. #ifdef SYS16BIT
  86320. #ifdef __TURBOC__
  86321. /* Turbo C in 16-bit mode */
  86322. # define MY_ZCALLOC
  86323. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86324. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86325. * must fix the pointer. Warning: the pointer must be put back to its
  86326. * original form in order to free it, use zcfree().
  86327. */
  86328. #define MAX_PTR 10
  86329. /* 10*64K = 640K */
  86330. local int next_ptr = 0;
  86331. typedef struct ptr_table_s {
  86332. voidpf org_ptr;
  86333. voidpf new_ptr;
  86334. } ptr_table;
  86335. local ptr_table table[MAX_PTR];
  86336. /* This table is used to remember the original form of pointers
  86337. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86338. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86339. * protected from concurrent access. This hack doesn't work anyway on
  86340. * a protected system like OS/2. Use Microsoft C instead.
  86341. */
  86342. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86343. {
  86344. voidpf buf = opaque; /* just to make some compilers happy */
  86345. ulg bsize = (ulg)items*size;
  86346. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86347. * will return a usable pointer which doesn't have to be normalized.
  86348. */
  86349. if (bsize < 65520L) {
  86350. buf = farmalloc(bsize);
  86351. if (*(ush*)&buf != 0) return buf;
  86352. } else {
  86353. buf = farmalloc(bsize + 16L);
  86354. }
  86355. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86356. table[next_ptr].org_ptr = buf;
  86357. /* Normalize the pointer to seg:0 */
  86358. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86359. *(ush*)&buf = 0;
  86360. table[next_ptr++].new_ptr = buf;
  86361. return buf;
  86362. }
  86363. void zcfree (voidpf opaque, voidpf ptr)
  86364. {
  86365. int n;
  86366. if (*(ush*)&ptr != 0) { /* object < 64K */
  86367. farfree(ptr);
  86368. return;
  86369. }
  86370. /* Find the original pointer */
  86371. for (n = 0; n < next_ptr; n++) {
  86372. if (ptr != table[n].new_ptr) continue;
  86373. farfree(table[n].org_ptr);
  86374. while (++n < next_ptr) {
  86375. table[n-1] = table[n];
  86376. }
  86377. next_ptr--;
  86378. return;
  86379. }
  86380. ptr = opaque; /* just to make some compilers happy */
  86381. Assert(0, "zcfree: ptr not found");
  86382. }
  86383. #endif /* __TURBOC__ */
  86384. #ifdef M_I86
  86385. /* Microsoft C in 16-bit mode */
  86386. # define MY_ZCALLOC
  86387. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86388. # define _halloc halloc
  86389. # define _hfree hfree
  86390. #endif
  86391. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86392. {
  86393. if (opaque) opaque = 0; /* to make compiler happy */
  86394. return _halloc((long)items, size);
  86395. }
  86396. void zcfree (voidpf opaque, voidpf ptr)
  86397. {
  86398. if (opaque) opaque = 0; /* to make compiler happy */
  86399. _hfree(ptr);
  86400. }
  86401. #endif /* M_I86 */
  86402. #endif /* SYS16BIT */
  86403. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86404. #ifndef STDC
  86405. extern voidp malloc OF((uInt size));
  86406. extern voidp calloc OF((uInt items, uInt size));
  86407. extern void free OF((voidpf ptr));
  86408. #endif
  86409. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86410. {
  86411. if (opaque) items += size - size; /* make compiler happy */
  86412. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86413. (voidpf)calloc(items, size);
  86414. }
  86415. void zcfree (voidpf opaque, voidpf ptr)
  86416. {
  86417. free(ptr);
  86418. if (opaque) return; /* make compiler happy */
  86419. }
  86420. #endif /* MY_ZCALLOC */
  86421. /*** End of inlined file: zutil.c ***/
  86422. #undef Byte
  86423. #else
  86424. #include <zlib.h>
  86425. #endif
  86426. }
  86427. #if JUCE_MSVC
  86428. #pragma warning (pop)
  86429. #endif
  86430. BEGIN_JUCE_NAMESPACE
  86431. // internal helper object that holds the zlib structures so they don't have to be
  86432. // included publicly.
  86433. class GZIPDecompressHelper
  86434. {
  86435. public:
  86436. GZIPDecompressHelper (const bool noWrap)
  86437. : finished (true),
  86438. needsDictionary (false),
  86439. error (true),
  86440. streamIsValid (false),
  86441. data (0),
  86442. dataSize (0)
  86443. {
  86444. using namespace zlibNamespace;
  86445. zerostruct (stream);
  86446. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86447. finished = error = ! streamIsValid;
  86448. }
  86449. ~GZIPDecompressHelper()
  86450. {
  86451. using namespace zlibNamespace;
  86452. if (streamIsValid)
  86453. inflateEnd (&stream);
  86454. }
  86455. bool needsInput() const throw() { return dataSize <= 0; }
  86456. void setInput (uint8* const data_, const int size) throw()
  86457. {
  86458. data = data_;
  86459. dataSize = size;
  86460. }
  86461. int doNextBlock (uint8* const dest, const int destSize)
  86462. {
  86463. using namespace zlibNamespace;
  86464. if (streamIsValid && data != 0 && ! finished)
  86465. {
  86466. stream.next_in = data;
  86467. stream.next_out = dest;
  86468. stream.avail_in = dataSize;
  86469. stream.avail_out = destSize;
  86470. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86471. {
  86472. case Z_STREAM_END:
  86473. finished = true;
  86474. // deliberate fall-through
  86475. case Z_OK:
  86476. data += dataSize - stream.avail_in;
  86477. dataSize = stream.avail_in;
  86478. return destSize - stream.avail_out;
  86479. case Z_NEED_DICT:
  86480. needsDictionary = true;
  86481. data += dataSize - stream.avail_in;
  86482. dataSize = stream.avail_in;
  86483. break;
  86484. case Z_DATA_ERROR:
  86485. case Z_MEM_ERROR:
  86486. error = true;
  86487. default:
  86488. break;
  86489. }
  86490. }
  86491. return 0;
  86492. }
  86493. bool finished, needsDictionary, error, streamIsValid;
  86494. private:
  86495. zlibNamespace::z_stream stream;
  86496. uint8* data;
  86497. int dataSize;
  86498. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86499. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86500. };
  86501. const int gzipDecompBufferSize = 32768;
  86502. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86503. const bool deleteSourceWhenDestroyed,
  86504. const bool noWrap_,
  86505. const int64 uncompressedStreamLength_)
  86506. : sourceStream (sourceStream_),
  86507. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86508. uncompressedStreamLength (uncompressedStreamLength_),
  86509. noWrap (noWrap_),
  86510. isEof (false),
  86511. activeBufferSize (0),
  86512. originalSourcePos (sourceStream_->getPosition()),
  86513. currentPos (0),
  86514. buffer (gzipDecompBufferSize),
  86515. helper (new GZIPDecompressHelper (noWrap_))
  86516. {
  86517. }
  86518. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86519. {
  86520. }
  86521. int64 GZIPDecompressorInputStream::getTotalLength()
  86522. {
  86523. return uncompressedStreamLength;
  86524. }
  86525. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86526. {
  86527. if ((howMany > 0) && ! isEof)
  86528. {
  86529. jassert (destBuffer != 0);
  86530. if (destBuffer != 0)
  86531. {
  86532. int numRead = 0;
  86533. uint8* d = static_cast <uint8*> (destBuffer);
  86534. while (! helper->error)
  86535. {
  86536. const int n = helper->doNextBlock (d, howMany);
  86537. currentPos += n;
  86538. if (n == 0)
  86539. {
  86540. if (helper->finished || helper->needsDictionary)
  86541. {
  86542. isEof = true;
  86543. return numRead;
  86544. }
  86545. if (helper->needsInput())
  86546. {
  86547. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86548. if (activeBufferSize > 0)
  86549. {
  86550. helper->setInput (buffer, activeBufferSize);
  86551. }
  86552. else
  86553. {
  86554. isEof = true;
  86555. return numRead;
  86556. }
  86557. }
  86558. }
  86559. else
  86560. {
  86561. numRead += n;
  86562. howMany -= n;
  86563. d += n;
  86564. if (howMany <= 0)
  86565. return numRead;
  86566. }
  86567. }
  86568. }
  86569. }
  86570. return 0;
  86571. }
  86572. bool GZIPDecompressorInputStream::isExhausted()
  86573. {
  86574. return helper->error || isEof;
  86575. }
  86576. int64 GZIPDecompressorInputStream::getPosition()
  86577. {
  86578. return currentPos;
  86579. }
  86580. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86581. {
  86582. if (newPos < currentPos)
  86583. {
  86584. // to go backwards, reset the stream and start again..
  86585. isEof = false;
  86586. activeBufferSize = 0;
  86587. currentPos = 0;
  86588. helper = new GZIPDecompressHelper (noWrap);
  86589. sourceStream->setPosition (originalSourcePos);
  86590. }
  86591. skipNextBytes (newPos - currentPos);
  86592. return true;
  86593. }
  86594. END_JUCE_NAMESPACE
  86595. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86596. #endif
  86597. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86598. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86599. #if JUCE_USE_FLAC
  86600. #if JUCE_WINDOWS
  86601. #include <windows.h>
  86602. #endif
  86603. namespace FlacNamespace
  86604. {
  86605. #if JUCE_INCLUDE_FLAC_CODE
  86606. #if JUCE_MSVC
  86607. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86608. #endif
  86609. #define FLAC__NO_DLL 1
  86610. #if ! defined (SIZE_MAX)
  86611. #define SIZE_MAX 0xffffffff
  86612. #endif
  86613. #define __STDC_LIMIT_MACROS 1
  86614. /*** Start of inlined file: all.h ***/
  86615. #ifndef FLAC__ALL_H
  86616. #define FLAC__ALL_H
  86617. /*** Start of inlined file: export.h ***/
  86618. #ifndef FLAC__EXPORT_H
  86619. #define FLAC__EXPORT_H
  86620. /** \file include/FLAC/export.h
  86621. *
  86622. * \brief
  86623. * This module contains #defines and symbols for exporting function
  86624. * calls, and providing version information and compiled-in features.
  86625. *
  86626. * See the \link flac_export export \endlink module.
  86627. */
  86628. /** \defgroup flac_export FLAC/export.h: export symbols
  86629. * \ingroup flac
  86630. *
  86631. * \brief
  86632. * This module contains #defines and symbols for exporting function
  86633. * calls, and providing version information and compiled-in features.
  86634. *
  86635. * If you are compiling with MSVC and will link to the static library
  86636. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86637. * make sure the symbols are exported properly.
  86638. *
  86639. * \{
  86640. */
  86641. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86642. #define FLAC_API
  86643. #else
  86644. #ifdef FLAC_API_EXPORTS
  86645. #define FLAC_API _declspec(dllexport)
  86646. #else
  86647. #define FLAC_API _declspec(dllimport)
  86648. #endif
  86649. #endif
  86650. /** These #defines will mirror the libtool-based library version number, see
  86651. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86652. */
  86653. #define FLAC_API_VERSION_CURRENT 10
  86654. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86655. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86656. #ifdef __cplusplus
  86657. extern "C" {
  86658. #endif
  86659. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86660. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86661. #ifdef __cplusplus
  86662. }
  86663. #endif
  86664. /* \} */
  86665. #endif
  86666. /*** End of inlined file: export.h ***/
  86667. /*** Start of inlined file: assert.h ***/
  86668. #ifndef FLAC__ASSERT_H
  86669. #define FLAC__ASSERT_H
  86670. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86671. #ifdef DEBUG
  86672. #include <assert.h>
  86673. #define FLAC__ASSERT(x) assert(x)
  86674. #define FLAC__ASSERT_DECLARATION(x) x
  86675. #else
  86676. #define FLAC__ASSERT(x)
  86677. #define FLAC__ASSERT_DECLARATION(x)
  86678. #endif
  86679. #endif
  86680. /*** End of inlined file: assert.h ***/
  86681. /*** Start of inlined file: callback.h ***/
  86682. #ifndef FLAC__CALLBACK_H
  86683. #define FLAC__CALLBACK_H
  86684. /*** Start of inlined file: ordinals.h ***/
  86685. #ifndef FLAC__ORDINALS_H
  86686. #define FLAC__ORDINALS_H
  86687. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86688. #include <inttypes.h>
  86689. #endif
  86690. typedef signed char FLAC__int8;
  86691. typedef unsigned char FLAC__uint8;
  86692. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86693. typedef __int16 FLAC__int16;
  86694. typedef __int32 FLAC__int32;
  86695. typedef __int64 FLAC__int64;
  86696. typedef unsigned __int16 FLAC__uint16;
  86697. typedef unsigned __int32 FLAC__uint32;
  86698. typedef unsigned __int64 FLAC__uint64;
  86699. #elif defined(__EMX__)
  86700. typedef short FLAC__int16;
  86701. typedef long FLAC__int32;
  86702. typedef long long FLAC__int64;
  86703. typedef unsigned short FLAC__uint16;
  86704. typedef unsigned long FLAC__uint32;
  86705. typedef unsigned long long FLAC__uint64;
  86706. #else
  86707. typedef int16_t FLAC__int16;
  86708. typedef int32_t FLAC__int32;
  86709. typedef int64_t FLAC__int64;
  86710. typedef uint16_t FLAC__uint16;
  86711. typedef uint32_t FLAC__uint32;
  86712. typedef uint64_t FLAC__uint64;
  86713. #endif
  86714. typedef int FLAC__bool;
  86715. typedef FLAC__uint8 FLAC__byte;
  86716. #ifdef true
  86717. #undef true
  86718. #endif
  86719. #ifdef false
  86720. #undef false
  86721. #endif
  86722. #ifndef __cplusplus
  86723. #define true 1
  86724. #define false 0
  86725. #endif
  86726. #endif
  86727. /*** End of inlined file: ordinals.h ***/
  86728. #include <stdlib.h> /* for size_t */
  86729. /** \file include/FLAC/callback.h
  86730. *
  86731. * \brief
  86732. * This module defines the structures for describing I/O callbacks
  86733. * to the other FLAC interfaces.
  86734. *
  86735. * See the detailed documentation for callbacks in the
  86736. * \link flac_callbacks callbacks \endlink module.
  86737. */
  86738. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86739. * \ingroup flac
  86740. *
  86741. * \brief
  86742. * This module defines the structures for describing I/O callbacks
  86743. * to the other FLAC interfaces.
  86744. *
  86745. * The purpose of the I/O callback functions is to create a common way
  86746. * for the metadata interfaces to handle I/O.
  86747. *
  86748. * Originally the metadata interfaces required filenames as the way of
  86749. * specifying FLAC files to operate on. This is problematic in some
  86750. * environments so there is an additional option to specify a set of
  86751. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86752. *
  86753. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86754. * opaque structure for a data source.
  86755. *
  86756. * The callback function prototypes are similar (but not identical) to the
  86757. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86758. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86759. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86760. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86761. * is required. \warning You generally CANNOT directly use fseek or ftell
  86762. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86763. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86764. * large files. You will have to find an equivalent function (e.g. ftello),
  86765. * or write a wrapper. The same is true for feof() since this is usually
  86766. * implemented as a macro, not as a function whose address can be taken.
  86767. *
  86768. * \{
  86769. */
  86770. #ifdef __cplusplus
  86771. extern "C" {
  86772. #endif
  86773. /** This is the opaque handle type used by the callbacks. Typically
  86774. * this is a \c FILE* or address of a file descriptor.
  86775. */
  86776. typedef void* FLAC__IOHandle;
  86777. /** Signature for the read callback.
  86778. * The signature and semantics match POSIX fread() implementations
  86779. * and can generally be used interchangeably.
  86780. *
  86781. * \param ptr The address of the read buffer.
  86782. * \param size The size of the records to be read.
  86783. * \param nmemb The number of records to be read.
  86784. * \param handle The handle to the data source.
  86785. * \retval size_t
  86786. * The number of records read.
  86787. */
  86788. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86789. /** Signature for the write callback.
  86790. * The signature and semantics match POSIX fwrite() implementations
  86791. * and can generally be used interchangeably.
  86792. *
  86793. * \param ptr The address of the write buffer.
  86794. * \param size The size of the records to be written.
  86795. * \param nmemb The number of records to be written.
  86796. * \param handle The handle to the data source.
  86797. * \retval size_t
  86798. * The number of records written.
  86799. */
  86800. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86801. /** Signature for the seek callback.
  86802. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86803. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86804. * and 32-bits wide.
  86805. *
  86806. * \param handle The handle to the data source.
  86807. * \param offset The new position, relative to \a whence
  86808. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86809. * \retval int
  86810. * \c 0 on success, \c -1 on error.
  86811. */
  86812. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86813. /** Signature for the tell callback.
  86814. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86815. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86816. * and 32-bits wide.
  86817. *
  86818. * \param handle The handle to the data source.
  86819. * \retval FLAC__int64
  86820. * The current position on success, \c -1 on error.
  86821. */
  86822. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86823. /** Signature for the EOF callback.
  86824. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86825. * on many systems, feof() is a macro, so in this case a wrapper function
  86826. * must be provided instead.
  86827. *
  86828. * \param handle The handle to the data source.
  86829. * \retval int
  86830. * \c 0 if not at end of file, nonzero if at end of file.
  86831. */
  86832. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86833. /** Signature for the close callback.
  86834. * The signature and semantics match POSIX fclose() implementations
  86835. * and can generally be used interchangeably.
  86836. *
  86837. * \param handle The handle to the data source.
  86838. * \retval int
  86839. * \c 0 on success, \c EOF on error.
  86840. */
  86841. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86842. /** A structure for holding a set of callbacks.
  86843. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86844. * describe which of the callbacks are required. The ones that are not
  86845. * required may be set to NULL.
  86846. *
  86847. * If the seek requirement for an interface is optional, you can signify that
  86848. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86849. */
  86850. typedef struct {
  86851. FLAC__IOCallback_Read read;
  86852. FLAC__IOCallback_Write write;
  86853. FLAC__IOCallback_Seek seek;
  86854. FLAC__IOCallback_Tell tell;
  86855. FLAC__IOCallback_Eof eof;
  86856. FLAC__IOCallback_Close close;
  86857. } FLAC__IOCallbacks;
  86858. /* \} */
  86859. #ifdef __cplusplus
  86860. }
  86861. #endif
  86862. #endif
  86863. /*** End of inlined file: callback.h ***/
  86864. /*** Start of inlined file: format.h ***/
  86865. #ifndef FLAC__FORMAT_H
  86866. #define FLAC__FORMAT_H
  86867. #ifdef __cplusplus
  86868. extern "C" {
  86869. #endif
  86870. /** \file include/FLAC/format.h
  86871. *
  86872. * \brief
  86873. * This module contains structure definitions for the representation
  86874. * of FLAC format components in memory. These are the basic
  86875. * structures used by the rest of the interfaces.
  86876. *
  86877. * See the detailed documentation in the
  86878. * \link flac_format format \endlink module.
  86879. */
  86880. /** \defgroup flac_format FLAC/format.h: format components
  86881. * \ingroup flac
  86882. *
  86883. * \brief
  86884. * This module contains structure definitions for the representation
  86885. * of FLAC format components in memory. These are the basic
  86886. * structures used by the rest of the interfaces.
  86887. *
  86888. * First, you should be familiar with the
  86889. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86890. * follow directly from the specification. As a user of libFLAC, the
  86891. * interesting parts really are the structures that describe the frame
  86892. * header and metadata blocks.
  86893. *
  86894. * The format structures here are very primitive, designed to store
  86895. * information in an efficient way. Reading information from the
  86896. * structures is easy but creating or modifying them directly is
  86897. * more complex. For the most part, as a user of a library, editing
  86898. * is not necessary; however, for metadata blocks it is, so there are
  86899. * convenience functions provided in the \link flac_metadata metadata
  86900. * module \endlink to simplify the manipulation of metadata blocks.
  86901. *
  86902. * \note
  86903. * It's not the best convention, but symbols ending in _LEN are in bits
  86904. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86905. * global variables because they are usually used when declaring byte
  86906. * arrays and some compilers require compile-time knowledge of array
  86907. * sizes when declared on the stack.
  86908. *
  86909. * \{
  86910. */
  86911. /*
  86912. Most of the values described in this file are defined by the FLAC
  86913. format specification. There is nothing to tune here.
  86914. */
  86915. /** The largest legal metadata type code. */
  86916. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86917. /** The minimum block size, in samples, permitted by the format. */
  86918. #define FLAC__MIN_BLOCK_SIZE (16u)
  86919. /** The maximum block size, in samples, permitted by the format. */
  86920. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86921. /** The maximum block size, in samples, permitted by the FLAC subset for
  86922. * sample rates up to 48kHz. */
  86923. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86924. /** The maximum number of channels permitted by the format. */
  86925. #define FLAC__MAX_CHANNELS (8u)
  86926. /** The minimum sample resolution permitted by the format. */
  86927. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86928. /** The maximum sample resolution permitted by the format. */
  86929. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86930. /** The maximum sample resolution permitted by libFLAC.
  86931. *
  86932. * \warning
  86933. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86934. * the reference encoder/decoder is currently limited to 24 bits because
  86935. * of prevalent 32-bit math, so make sure and use this value when
  86936. * appropriate.
  86937. */
  86938. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86939. /** The maximum sample rate permitted by the format. The value is
  86940. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86941. * as to why.
  86942. */
  86943. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86944. /** The maximum LPC order permitted by the format. */
  86945. #define FLAC__MAX_LPC_ORDER (32u)
  86946. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86947. * up to 48kHz. */
  86948. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86949. /** The minimum quantized linear predictor coefficient precision
  86950. * permitted by the format.
  86951. */
  86952. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86953. /** The maximum quantized linear predictor coefficient precision
  86954. * permitted by the format.
  86955. */
  86956. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86957. /** The maximum order of the fixed predictors permitted by the format. */
  86958. #define FLAC__MAX_FIXED_ORDER (4u)
  86959. /** The maximum Rice partition order permitted by the format. */
  86960. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86961. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86962. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86963. /** The version string of the release, stamped onto the libraries and binaries.
  86964. *
  86965. * \note
  86966. * This does not correspond to the shared library version number, which
  86967. * is used to determine binary compatibility.
  86968. */
  86969. extern FLAC_API const char *FLAC__VERSION_STRING;
  86970. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86971. * This is a NUL-terminated ASCII string; when inserted into the
  86972. * VORBIS_COMMENT the trailing null is stripped.
  86973. */
  86974. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86975. /** The byte string representation of the beginning of a FLAC stream. */
  86976. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86977. /** The 32-bit integer big-endian representation of the beginning of
  86978. * a FLAC stream.
  86979. */
  86980. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86981. /** The length of the FLAC signature in bits. */
  86982. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86983. /** The length of the FLAC signature in bytes. */
  86984. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86985. /*****************************************************************************
  86986. *
  86987. * Subframe structures
  86988. *
  86989. *****************************************************************************/
  86990. /*****************************************************************************/
  86991. /** An enumeration of the available entropy coding methods. */
  86992. typedef enum {
  86993. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86994. /**< Residual is coded by partitioning into contexts, each with it's own
  86995. * 4-bit Rice parameter. */
  86996. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86997. /**< Residual is coded by partitioning into contexts, each with it's own
  86998. * 5-bit Rice parameter. */
  86999. } FLAC__EntropyCodingMethodType;
  87000. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  87001. *
  87002. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  87003. * give the string equivalent. The contents should not be modified.
  87004. */
  87005. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  87006. /** Contents of a Rice partitioned residual
  87007. */
  87008. typedef struct {
  87009. unsigned *parameters;
  87010. /**< The Rice parameters for each context. */
  87011. unsigned *raw_bits;
  87012. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  87013. * partitions and zero for unescaped partitions.
  87014. */
  87015. unsigned capacity_by_order;
  87016. /**< The capacity of the \a parameters and \a raw_bits arrays
  87017. * specified as an order, i.e. the number of array elements
  87018. * allocated is 2 ^ \a capacity_by_order.
  87019. */
  87020. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  87021. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  87022. */
  87023. typedef struct {
  87024. unsigned order;
  87025. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  87026. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  87027. /**< The context's Rice parameters and/or raw bits. */
  87028. } FLAC__EntropyCodingMethod_PartitionedRice;
  87029. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  87030. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  87031. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  87032. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  87033. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  87034. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  87035. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  87036. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  87037. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  87038. */
  87039. typedef struct {
  87040. FLAC__EntropyCodingMethodType type;
  87041. union {
  87042. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  87043. } data;
  87044. } FLAC__EntropyCodingMethod;
  87045. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  87046. /*****************************************************************************/
  87047. /** An enumeration of the available subframe types. */
  87048. typedef enum {
  87049. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  87050. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  87051. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  87052. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  87053. } FLAC__SubframeType;
  87054. /** Maps a FLAC__SubframeType to a C string.
  87055. *
  87056. * Using a FLAC__SubframeType as the index to this array will
  87057. * give the string equivalent. The contents should not be modified.
  87058. */
  87059. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  87060. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  87061. */
  87062. typedef struct {
  87063. FLAC__int32 value; /**< The constant signal value. */
  87064. } FLAC__Subframe_Constant;
  87065. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  87066. */
  87067. typedef struct {
  87068. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  87069. } FLAC__Subframe_Verbatim;
  87070. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  87071. */
  87072. typedef struct {
  87073. FLAC__EntropyCodingMethod entropy_coding_method;
  87074. /**< The residual coding method. */
  87075. unsigned order;
  87076. /**< The polynomial order. */
  87077. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  87078. /**< Warmup samples to prime the predictor, length == order. */
  87079. const FLAC__int32 *residual;
  87080. /**< The residual signal, length == (blocksize minus order) samples. */
  87081. } FLAC__Subframe_Fixed;
  87082. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  87083. */
  87084. typedef struct {
  87085. FLAC__EntropyCodingMethod entropy_coding_method;
  87086. /**< The residual coding method. */
  87087. unsigned order;
  87088. /**< The FIR order. */
  87089. unsigned qlp_coeff_precision;
  87090. /**< Quantized FIR filter coefficient precision in bits. */
  87091. int quantization_level;
  87092. /**< The qlp coeff shift needed. */
  87093. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  87094. /**< FIR filter coefficients. */
  87095. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  87096. /**< Warmup samples to prime the predictor, length == order. */
  87097. const FLAC__int32 *residual;
  87098. /**< The residual signal, length == (blocksize minus order) samples. */
  87099. } FLAC__Subframe_LPC;
  87100. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  87101. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  87102. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  87103. */
  87104. typedef struct {
  87105. FLAC__SubframeType type;
  87106. union {
  87107. FLAC__Subframe_Constant constant;
  87108. FLAC__Subframe_Fixed fixed;
  87109. FLAC__Subframe_LPC lpc;
  87110. FLAC__Subframe_Verbatim verbatim;
  87111. } data;
  87112. unsigned wasted_bits;
  87113. } FLAC__Subframe;
  87114. /** == 1 (bit)
  87115. *
  87116. * This used to be a zero-padding bit (hence the name
  87117. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  87118. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  87119. * to mean something else.
  87120. */
  87121. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  87122. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  87123. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  87124. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  87125. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  87126. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  87127. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  87128. /*****************************************************************************/
  87129. /*****************************************************************************
  87130. *
  87131. * Frame structures
  87132. *
  87133. *****************************************************************************/
  87134. /** An enumeration of the available channel assignments. */
  87135. typedef enum {
  87136. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  87137. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  87138. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  87139. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  87140. } FLAC__ChannelAssignment;
  87141. /** Maps a FLAC__ChannelAssignment to a C string.
  87142. *
  87143. * Using a FLAC__ChannelAssignment as the index to this array will
  87144. * give the string equivalent. The contents should not be modified.
  87145. */
  87146. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  87147. /** An enumeration of the possible frame numbering methods. */
  87148. typedef enum {
  87149. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  87150. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  87151. } FLAC__FrameNumberType;
  87152. /** Maps a FLAC__FrameNumberType to a C string.
  87153. *
  87154. * Using a FLAC__FrameNumberType as the index to this array will
  87155. * give the string equivalent. The contents should not be modified.
  87156. */
  87157. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  87158. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  87159. */
  87160. typedef struct {
  87161. unsigned blocksize;
  87162. /**< The number of samples per subframe. */
  87163. unsigned sample_rate;
  87164. /**< The sample rate in Hz. */
  87165. unsigned channels;
  87166. /**< The number of channels (== number of subframes). */
  87167. FLAC__ChannelAssignment channel_assignment;
  87168. /**< The channel assignment for the frame. */
  87169. unsigned bits_per_sample;
  87170. /**< The sample resolution. */
  87171. FLAC__FrameNumberType number_type;
  87172. /**< The numbering scheme used for the frame. As a convenience, the
  87173. * decoder will always convert a frame number to a sample number because
  87174. * the rules are complex. */
  87175. union {
  87176. FLAC__uint32 frame_number;
  87177. FLAC__uint64 sample_number;
  87178. } number;
  87179. /**< The frame number or sample number of first sample in frame;
  87180. * use the \a number_type value to determine which to use. */
  87181. FLAC__uint8 crc;
  87182. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87183. * of the raw frame header bytes, meaning everything before the CRC byte
  87184. * including the sync code.
  87185. */
  87186. } FLAC__FrameHeader;
  87187. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87188. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87189. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87190. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87191. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87192. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87193. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87194. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87195. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87196. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87197. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87198. */
  87199. typedef struct {
  87200. FLAC__uint16 crc;
  87201. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87202. * 0) of the bytes before the crc, back to and including the frame header
  87203. * sync code.
  87204. */
  87205. } FLAC__FrameFooter;
  87206. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87207. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87208. */
  87209. typedef struct {
  87210. FLAC__FrameHeader header;
  87211. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87212. FLAC__FrameFooter footer;
  87213. } FLAC__Frame;
  87214. /*****************************************************************************/
  87215. /*****************************************************************************
  87216. *
  87217. * Meta-data structures
  87218. *
  87219. *****************************************************************************/
  87220. /** An enumeration of the available metadata block types. */
  87221. typedef enum {
  87222. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87223. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87224. FLAC__METADATA_TYPE_PADDING = 1,
  87225. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87226. FLAC__METADATA_TYPE_APPLICATION = 2,
  87227. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87228. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87229. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87230. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87231. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87232. FLAC__METADATA_TYPE_CUESHEET = 5,
  87233. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87234. FLAC__METADATA_TYPE_PICTURE = 6,
  87235. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87236. FLAC__METADATA_TYPE_UNDEFINED = 7
  87237. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87238. } FLAC__MetadataType;
  87239. /** Maps a FLAC__MetadataType to a C string.
  87240. *
  87241. * Using a FLAC__MetadataType as the index to this array will
  87242. * give the string equivalent. The contents should not be modified.
  87243. */
  87244. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87245. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87246. */
  87247. typedef struct {
  87248. unsigned min_blocksize, max_blocksize;
  87249. unsigned min_framesize, max_framesize;
  87250. unsigned sample_rate;
  87251. unsigned channels;
  87252. unsigned bits_per_sample;
  87253. FLAC__uint64 total_samples;
  87254. FLAC__byte md5sum[16];
  87255. } FLAC__StreamMetadata_StreamInfo;
  87256. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87257. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87258. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87259. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87260. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87261. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87262. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87263. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87264. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87265. /** The total stream length of the STREAMINFO block in bytes. */
  87266. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87267. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87268. */
  87269. typedef struct {
  87270. int dummy;
  87271. /**< Conceptually this is an empty struct since we don't store the
  87272. * padding bytes. Empty structs are not allowed by some C compilers,
  87273. * hence the dummy.
  87274. */
  87275. } FLAC__StreamMetadata_Padding;
  87276. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87277. */
  87278. typedef struct {
  87279. FLAC__byte id[4];
  87280. FLAC__byte *data;
  87281. } FLAC__StreamMetadata_Application;
  87282. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87283. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87284. */
  87285. typedef struct {
  87286. FLAC__uint64 sample_number;
  87287. /**< The sample number of the target frame. */
  87288. FLAC__uint64 stream_offset;
  87289. /**< The offset, in bytes, of the target frame with respect to
  87290. * beginning of the first frame. */
  87291. unsigned frame_samples;
  87292. /**< The number of samples in the target frame. */
  87293. } FLAC__StreamMetadata_SeekPoint;
  87294. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87295. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87296. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87297. /** The total stream length of a seek point in bytes. */
  87298. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87299. /** The value used in the \a sample_number field of
  87300. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87301. * point (== 0xffffffffffffffff).
  87302. */
  87303. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87304. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87305. *
  87306. * \note From the format specification:
  87307. * - The seek points must be sorted by ascending sample number.
  87308. * - Each seek point's sample number must be the first sample of the
  87309. * target frame.
  87310. * - Each seek point's sample number must be unique within the table.
  87311. * - Existence of a SEEKTABLE block implies a correct setting of
  87312. * total_samples in the stream_info block.
  87313. * - Behavior is undefined when more than one SEEKTABLE block is
  87314. * present in a stream.
  87315. */
  87316. typedef struct {
  87317. unsigned num_points;
  87318. FLAC__StreamMetadata_SeekPoint *points;
  87319. } FLAC__StreamMetadata_SeekTable;
  87320. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87321. *
  87322. * For convenience, the APIs maintain a trailing NUL character at the end of
  87323. * \a entry which is not counted toward \a length, i.e.
  87324. * \code strlen(entry) == length \endcode
  87325. */
  87326. typedef struct {
  87327. FLAC__uint32 length;
  87328. FLAC__byte *entry;
  87329. } FLAC__StreamMetadata_VorbisComment_Entry;
  87330. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87331. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87332. */
  87333. typedef struct {
  87334. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87335. FLAC__uint32 num_comments;
  87336. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87337. } FLAC__StreamMetadata_VorbisComment;
  87338. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87339. /** FLAC CUESHEET track index structure. (See the
  87340. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87341. * the full description of each field.)
  87342. */
  87343. typedef struct {
  87344. FLAC__uint64 offset;
  87345. /**< Offset in samples, relative to the track offset, of the index
  87346. * point.
  87347. */
  87348. FLAC__byte number;
  87349. /**< The index point number. */
  87350. } FLAC__StreamMetadata_CueSheet_Index;
  87351. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87352. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87353. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87354. /** FLAC CUESHEET track structure. (See the
  87355. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87356. * the full description of each field.)
  87357. */
  87358. typedef struct {
  87359. FLAC__uint64 offset;
  87360. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87361. FLAC__byte number;
  87362. /**< The track number. */
  87363. char isrc[13];
  87364. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87365. unsigned type:1;
  87366. /**< The track type: 0 for audio, 1 for non-audio. */
  87367. unsigned pre_emphasis:1;
  87368. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87369. FLAC__byte num_indices;
  87370. /**< The number of track index points. */
  87371. FLAC__StreamMetadata_CueSheet_Index *indices;
  87372. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87373. } FLAC__StreamMetadata_CueSheet_Track;
  87374. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87375. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87376. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87377. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87378. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87379. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87380. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87381. /** FLAC CUESHEET structure. (See the
  87382. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87383. * for the full description of each field.)
  87384. */
  87385. typedef struct {
  87386. char media_catalog_number[129];
  87387. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87388. * general, the media catalog number may be 0 to 128 bytes long; any
  87389. * unused characters should be right-padded with NUL characters.
  87390. */
  87391. FLAC__uint64 lead_in;
  87392. /**< The number of lead-in samples. */
  87393. FLAC__bool is_cd;
  87394. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87395. unsigned num_tracks;
  87396. /**< The number of tracks. */
  87397. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87398. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87399. } FLAC__StreamMetadata_CueSheet;
  87400. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87401. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87402. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87403. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87404. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87405. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87406. typedef enum {
  87407. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87408. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87409. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87410. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87411. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87412. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87413. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87414. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87415. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87416. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87417. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87418. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87419. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87420. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87421. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87422. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87423. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87424. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87425. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87426. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87427. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87428. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87429. } FLAC__StreamMetadata_Picture_Type;
  87430. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87431. *
  87432. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87433. * will give the string equivalent. The contents should not be
  87434. * modified.
  87435. */
  87436. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87437. /** FLAC PICTURE structure. (See the
  87438. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87439. * for the full description of each field.)
  87440. */
  87441. typedef struct {
  87442. FLAC__StreamMetadata_Picture_Type type;
  87443. /**< The kind of picture stored. */
  87444. char *mime_type;
  87445. /**< Picture data's MIME type, in ASCII printable characters
  87446. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87447. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87448. * MIME type of '-->' is also allowed, in which case the picture
  87449. * data should be a complete URL. In file storage, the MIME type is
  87450. * stored as a 32-bit length followed by the ASCII string with no NUL
  87451. * terminator, but is converted to a plain C string in this structure
  87452. * for convenience.
  87453. */
  87454. FLAC__byte *description;
  87455. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87456. * the description is stored as a 32-bit length followed by the UTF-8
  87457. * string with no NUL terminator, but is converted to a plain C string
  87458. * in this structure for convenience.
  87459. */
  87460. FLAC__uint32 width;
  87461. /**< Picture's width in pixels. */
  87462. FLAC__uint32 height;
  87463. /**< Picture's height in pixels. */
  87464. FLAC__uint32 depth;
  87465. /**< Picture's color depth in bits-per-pixel. */
  87466. FLAC__uint32 colors;
  87467. /**< For indexed palettes (like GIF), picture's number of colors (the
  87468. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87469. */
  87470. FLAC__uint32 data_length;
  87471. /**< Length of binary picture data in bytes. */
  87472. FLAC__byte *data;
  87473. /**< Binary picture data. */
  87474. } FLAC__StreamMetadata_Picture;
  87475. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87476. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87477. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87478. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87479. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87480. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87481. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87482. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87483. /** Structure that is used when a metadata block of unknown type is loaded.
  87484. * The contents are opaque. The structure is used only internally to
  87485. * correctly handle unknown metadata.
  87486. */
  87487. typedef struct {
  87488. FLAC__byte *data;
  87489. } FLAC__StreamMetadata_Unknown;
  87490. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87491. */
  87492. typedef struct {
  87493. FLAC__MetadataType type;
  87494. /**< The type of the metadata block; used determine which member of the
  87495. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87496. * then \a data.unknown must be used. */
  87497. FLAC__bool is_last;
  87498. /**< \c true if this metadata block is the last, else \a false */
  87499. unsigned length;
  87500. /**< Length, in bytes, of the block data as it appears in the stream. */
  87501. union {
  87502. FLAC__StreamMetadata_StreamInfo stream_info;
  87503. FLAC__StreamMetadata_Padding padding;
  87504. FLAC__StreamMetadata_Application application;
  87505. FLAC__StreamMetadata_SeekTable seek_table;
  87506. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87507. FLAC__StreamMetadata_CueSheet cue_sheet;
  87508. FLAC__StreamMetadata_Picture picture;
  87509. FLAC__StreamMetadata_Unknown unknown;
  87510. } data;
  87511. /**< Polymorphic block data; use the \a type value to determine which
  87512. * to use. */
  87513. } FLAC__StreamMetadata;
  87514. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87515. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87516. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87517. /** The total stream length of a metadata block header in bytes. */
  87518. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87519. /*****************************************************************************/
  87520. /*****************************************************************************
  87521. *
  87522. * Utility functions
  87523. *
  87524. *****************************************************************************/
  87525. /** Tests that a sample rate is valid for FLAC.
  87526. *
  87527. * \param sample_rate The sample rate to test for compliance.
  87528. * \retval FLAC__bool
  87529. * \c true if the given sample rate conforms to the specification, else
  87530. * \c false.
  87531. */
  87532. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87533. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87534. * for valid sample rates are slightly more complex since the rate has to
  87535. * be expressible completely in the frame header.
  87536. *
  87537. * \param sample_rate The sample rate to test for compliance.
  87538. * \retval FLAC__bool
  87539. * \c true if the given sample rate conforms to the specification for the
  87540. * subset, else \c false.
  87541. */
  87542. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87543. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87544. * comment specification.
  87545. *
  87546. * Vorbis comment names must be composed only of characters from
  87547. * [0x20-0x3C,0x3E-0x7D].
  87548. *
  87549. * \param name A NUL-terminated string to be checked.
  87550. * \assert
  87551. * \code name != NULL \endcode
  87552. * \retval FLAC__bool
  87553. * \c false if entry name is illegal, else \c true.
  87554. */
  87555. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87556. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87557. * comment specification.
  87558. *
  87559. * Vorbis comment values must be valid UTF-8 sequences.
  87560. *
  87561. * \param value A string to be checked.
  87562. * \param length A the length of \a value in bytes. May be
  87563. * \c (unsigned)(-1) to indicate that \a value is a plain
  87564. * UTF-8 NUL-terminated string.
  87565. * \assert
  87566. * \code value != NULL \endcode
  87567. * \retval FLAC__bool
  87568. * \c false if entry name is illegal, else \c true.
  87569. */
  87570. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87571. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87572. * comment specification.
  87573. *
  87574. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87575. * 'value' must be legal according to
  87576. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87577. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87578. *
  87579. * \param entry An entry to be checked.
  87580. * \param length The length of \a entry in bytes.
  87581. * \assert
  87582. * \code value != NULL \endcode
  87583. * \retval FLAC__bool
  87584. * \c false if entry name is illegal, else \c true.
  87585. */
  87586. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87587. /** Check a seek table to see if it conforms to the FLAC specification.
  87588. * See the format specification for limits on the contents of the
  87589. * seek table.
  87590. *
  87591. * \param seek_table A pointer to a seek table to be checked.
  87592. * \assert
  87593. * \code seek_table != NULL \endcode
  87594. * \retval FLAC__bool
  87595. * \c false if seek table is illegal, else \c true.
  87596. */
  87597. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87598. /** Sort a seek table's seek points according to the format specification.
  87599. * This includes a "unique-ification" step to remove duplicates, i.e.
  87600. * seek points with identical \a sample_number values. Duplicate seek
  87601. * points are converted into placeholder points and sorted to the end of
  87602. * the table.
  87603. *
  87604. * \param seek_table A pointer to a seek table to be sorted.
  87605. * \assert
  87606. * \code seek_table != NULL \endcode
  87607. * \retval unsigned
  87608. * The number of duplicate seek points converted into placeholders.
  87609. */
  87610. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87611. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87612. * See the format specification for limits on the contents of the
  87613. * cue sheet.
  87614. *
  87615. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87616. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87617. * stringent requirements for a CD-DA (audio) disc.
  87618. * \param violation Address of a pointer to a string. If there is a
  87619. * violation, a pointer to a string explanation of the
  87620. * violation will be returned here. \a violation may be
  87621. * \c NULL if you don't need the returned string. Do not
  87622. * free the returned string; it will always point to static
  87623. * data.
  87624. * \assert
  87625. * \code cue_sheet != NULL \endcode
  87626. * \retval FLAC__bool
  87627. * \c false if cue sheet is illegal, else \c true.
  87628. */
  87629. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87630. /** Check picture data to see if it conforms to the FLAC specification.
  87631. * See the format specification for limits on the contents of the
  87632. * PICTURE block.
  87633. *
  87634. * \param picture A pointer to existing picture data to be checked.
  87635. * \param violation Address of a pointer to a string. If there is a
  87636. * violation, a pointer to a string explanation of the
  87637. * violation will be returned here. \a violation may be
  87638. * \c NULL if you don't need the returned string. Do not
  87639. * free the returned string; it will always point to static
  87640. * data.
  87641. * \assert
  87642. * \code picture != NULL \endcode
  87643. * \retval FLAC__bool
  87644. * \c false if picture data is illegal, else \c true.
  87645. */
  87646. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87647. /* \} */
  87648. #ifdef __cplusplus
  87649. }
  87650. #endif
  87651. #endif
  87652. /*** End of inlined file: format.h ***/
  87653. /*** Start of inlined file: metadata.h ***/
  87654. #ifndef FLAC__METADATA_H
  87655. #define FLAC__METADATA_H
  87656. #include <sys/types.h> /* for off_t */
  87657. /* --------------------------------------------------------------------
  87658. (For an example of how all these routines are used, see the source
  87659. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87660. metaflac in src/metaflac/)
  87661. ------------------------------------------------------------------*/
  87662. /** \file include/FLAC/metadata.h
  87663. *
  87664. * \brief
  87665. * This module provides functions for creating and manipulating FLAC
  87666. * metadata blocks in memory, and three progressively more powerful
  87667. * interfaces for traversing and editing metadata in FLAC files.
  87668. *
  87669. * See the detailed documentation for each interface in the
  87670. * \link flac_metadata metadata \endlink module.
  87671. */
  87672. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87673. * \ingroup flac
  87674. *
  87675. * \brief
  87676. * This module provides functions for creating and manipulating FLAC
  87677. * metadata blocks in memory, and three progressively more powerful
  87678. * interfaces for traversing and editing metadata in native FLAC files.
  87679. * Note that currently only the Chain interface (level 2) supports Ogg
  87680. * FLAC files, and it is read-only i.e. no writing back changed
  87681. * metadata to file.
  87682. *
  87683. * There are three metadata interfaces of increasing complexity:
  87684. *
  87685. * Level 0:
  87686. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87687. * PICTURE blocks.
  87688. *
  87689. * Level 1:
  87690. * Read-write access to all metadata blocks. This level is write-
  87691. * efficient in most cases (more on this below), and uses less memory
  87692. * than level 2.
  87693. *
  87694. * Level 2:
  87695. * Read-write access to all metadata blocks. This level is write-
  87696. * efficient in all cases, but uses more memory since all metadata for
  87697. * the whole file is read into memory and manipulated before writing
  87698. * out again.
  87699. *
  87700. * What do we mean by efficient? Since FLAC metadata appears at the
  87701. * beginning of the file, when writing metadata back to a FLAC file
  87702. * it is possible to grow or shrink the metadata such that the entire
  87703. * file must be rewritten. However, if the size remains the same during
  87704. * changes or PADDING blocks are utilized, only the metadata needs to be
  87705. * overwritten, which is much faster.
  87706. *
  87707. * Efficient means the whole file is rewritten at most one time, and only
  87708. * when necessary. Level 1 is not efficient only in the case that you
  87709. * cause more than one metadata block to grow or shrink beyond what can
  87710. * be accomodated by padding. In this case you should probably use level
  87711. * 2, which allows you to edit all the metadata for a file in memory and
  87712. * write it out all at once.
  87713. *
  87714. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87715. * front of the file.
  87716. *
  87717. * All levels access files via their filenames. In addition, level 2
  87718. * has additional alternative read and write functions that take an I/O
  87719. * handle and callbacks, for situations where access by filename is not
  87720. * possible.
  87721. *
  87722. * In addition to the three interfaces, this module defines functions for
  87723. * creating and manipulating various metadata objects in memory. As we see
  87724. * from the Format module, FLAC metadata blocks in memory are very primitive
  87725. * structures for storing information in an efficient way. Reading
  87726. * information from the structures is easy but creating or modifying them
  87727. * directly is more complex. The metadata object routines here facilitate
  87728. * this by taking care of the consistency and memory management drudgery.
  87729. *
  87730. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87731. * metadata however, you will not probably not need these.
  87732. *
  87733. * From a dependency standpoint, none of the encoders or decoders require
  87734. * the metadata module. This is so that embedded users can strip out the
  87735. * metadata module from libFLAC to reduce the size and complexity.
  87736. */
  87737. #ifdef __cplusplus
  87738. extern "C" {
  87739. #endif
  87740. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87741. * \ingroup flac_metadata
  87742. *
  87743. * \brief
  87744. * The level 0 interface consists of individual routines to read the
  87745. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87746. * only a filename.
  87747. *
  87748. * They try to skip any ID3v2 tag at the head of the file.
  87749. *
  87750. * \{
  87751. */
  87752. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87753. * will try to skip any ID3v2 tag at the head of the file.
  87754. *
  87755. * \param filename The path to the FLAC file to read.
  87756. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87757. * FLAC__StreamMetadata is a simple structure with no
  87758. * memory allocation involved, you pass the address of
  87759. * an existing structure. It need not be initialized.
  87760. * \assert
  87761. * \code filename != NULL \endcode
  87762. * \code streaminfo != NULL \endcode
  87763. * \retval FLAC__bool
  87764. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87765. * \c false if there was a memory allocation error, a file decoder error,
  87766. * or the file contained no STREAMINFO block. (A memory allocation error
  87767. * is possible because this function must set up a file decoder.)
  87768. */
  87769. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87770. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87771. * function will try to skip any ID3v2 tag at the head of the file.
  87772. *
  87773. * \param filename The path to the FLAC file to read.
  87774. * \param tags The address where the returned pointer will be
  87775. * stored. The \a tags object must be deleted by
  87776. * the caller using FLAC__metadata_object_delete().
  87777. * \assert
  87778. * \code filename != NULL \endcode
  87779. * \code tags != NULL \endcode
  87780. * \retval FLAC__bool
  87781. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87782. * and \a *tags will be set to the address of the metadata structure.
  87783. * Returns \c false if there was a memory allocation error, a file
  87784. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87785. * \a *tags will be set to \c NULL.
  87786. */
  87787. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87788. /** Read the CUESHEET metadata block of the given FLAC file. This
  87789. * function will try to skip any ID3v2 tag at the head of the file.
  87790. *
  87791. * \param filename The path to the FLAC file to read.
  87792. * \param cuesheet The address where the returned pointer will be
  87793. * stored. The \a cuesheet object must be deleted by
  87794. * the caller using FLAC__metadata_object_delete().
  87795. * \assert
  87796. * \code filename != NULL \endcode
  87797. * \code cuesheet != NULL \endcode
  87798. * \retval FLAC__bool
  87799. * \c true if a valid CUESHEET block was read from \a filename,
  87800. * and \a *cuesheet will be set to the address of the metadata
  87801. * structure. Returns \c false if there was a memory allocation
  87802. * error, a file decoder error, or the file contained no CUESHEET
  87803. * block, and \a *cuesheet will be set to \c NULL.
  87804. */
  87805. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87806. /** Read a PICTURE metadata block of the given FLAC file. This
  87807. * function will try to skip any ID3v2 tag at the head of the file.
  87808. * Since there can be more than one PICTURE block in a file, this
  87809. * function takes a number of parameters that act as constraints to
  87810. * the search. The PICTURE block with the largest area matching all
  87811. * the constraints will be returned, or \a *picture will be set to
  87812. * \c NULL if there was no such block.
  87813. *
  87814. * \param filename The path to the FLAC file to read.
  87815. * \param picture The address where the returned pointer will be
  87816. * stored. The \a picture object must be deleted by
  87817. * the caller using FLAC__metadata_object_delete().
  87818. * \param type The desired picture type. Use \c -1 to mean
  87819. * "any type".
  87820. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87821. * string will be matched exactly. Use \c NULL to
  87822. * mean "any MIME type".
  87823. * \param description The desired description. The string will be
  87824. * matched exactly. Use \c NULL to mean "any
  87825. * description".
  87826. * \param max_width The maximum width in pixels desired. Use
  87827. * \c (unsigned)(-1) to mean "any width".
  87828. * \param max_height The maximum height in pixels desired. Use
  87829. * \c (unsigned)(-1) to mean "any height".
  87830. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87831. * Use \c (unsigned)(-1) to mean "any depth".
  87832. * \param max_colors The maximum number of colors desired. Use
  87833. * \c (unsigned)(-1) to mean "any number of colors".
  87834. * \assert
  87835. * \code filename != NULL \endcode
  87836. * \code picture != NULL \endcode
  87837. * \retval FLAC__bool
  87838. * \c true if a valid PICTURE block was read from \a filename,
  87839. * and \a *picture will be set to the address of the metadata
  87840. * structure. Returns \c false if there was a memory allocation
  87841. * error, a file decoder error, or the file contained no PICTURE
  87842. * block, and \a *picture will be set to \c NULL.
  87843. */
  87844. 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);
  87845. /* \} */
  87846. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87847. * \ingroup flac_metadata
  87848. *
  87849. * \brief
  87850. * The level 1 interface provides read-write access to FLAC file metadata and
  87851. * operates directly on the FLAC file.
  87852. *
  87853. * The general usage of this interface is:
  87854. *
  87855. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87856. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87857. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87858. * see if the file is writable, or only read access is allowed.
  87859. * - Use FLAC__metadata_simple_iterator_next() and
  87860. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87861. * This is does not read the actual blocks themselves.
  87862. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87863. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87864. * forward from the front of the file.
  87865. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87866. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87867. * the current iterator position. The returned object is yours to modify
  87868. * and free.
  87869. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87870. * back. You must have write permission to the original file. Make sure to
  87871. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87872. * below.
  87873. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87874. * Use the object creation functions from
  87875. * \link flac_metadata_object here \endlink to generate new objects.
  87876. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87877. * currently referred to by the iterator, or replace it with padding.
  87878. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87879. * finished.
  87880. *
  87881. * \note
  87882. * The FLAC file remains open the whole time between
  87883. * FLAC__metadata_simple_iterator_init() and
  87884. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87885. * the file during this time.
  87886. *
  87887. * \note
  87888. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87889. * FLAC__StreamMetadata objects. These are managed automatically.
  87890. *
  87891. * \note
  87892. * If any of the modification functions
  87893. * (FLAC__metadata_simple_iterator_set_block(),
  87894. * FLAC__metadata_simple_iterator_delete_block(),
  87895. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87896. * you should delete the iterator as it may no longer be valid.
  87897. *
  87898. * \{
  87899. */
  87900. struct FLAC__Metadata_SimpleIterator;
  87901. /** The opaque structure definition for the level 1 iterator type.
  87902. * See the
  87903. * \link flac_metadata_level1 metadata level 1 module \endlink
  87904. * for a detailed description.
  87905. */
  87906. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87907. /** Status type for FLAC__Metadata_SimpleIterator.
  87908. *
  87909. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87910. */
  87911. typedef enum {
  87912. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87913. /**< The iterator is in the normal OK state */
  87914. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87915. /**< The data passed into a function violated the function's usage criteria */
  87916. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87917. /**< The iterator could not open the target file */
  87918. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87919. /**< The iterator could not find the FLAC signature at the start of the file */
  87920. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87921. /**< The iterator tried to write to a file that was not writable */
  87922. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87923. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87924. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87925. /**< The iterator encountered an error while reading the FLAC file */
  87926. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87927. /**< The iterator encountered an error while seeking in the FLAC file */
  87928. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87929. /**< The iterator encountered an error while writing the FLAC file */
  87930. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87931. /**< The iterator encountered an error renaming the FLAC file */
  87932. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87933. /**< The iterator encountered an error removing the temporary file */
  87934. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87935. /**< Memory allocation failed */
  87936. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87937. /**< The caller violated an assertion or an unexpected error occurred */
  87938. } FLAC__Metadata_SimpleIteratorStatus;
  87939. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87940. *
  87941. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87942. * will give the string equivalent. The contents should not be modified.
  87943. */
  87944. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87945. /** Create a new iterator instance.
  87946. *
  87947. * \retval FLAC__Metadata_SimpleIterator*
  87948. * \c NULL if there was an error allocating memory, else the new instance.
  87949. */
  87950. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87951. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87952. *
  87953. * \param iterator A pointer to an existing iterator.
  87954. * \assert
  87955. * \code iterator != NULL \endcode
  87956. */
  87957. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87958. /** Get the current status of the iterator. Call this after a function
  87959. * returns \c false to get the reason for the error. Also resets the status
  87960. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87961. *
  87962. * \param iterator A pointer to an existing iterator.
  87963. * \assert
  87964. * \code iterator != NULL \endcode
  87965. * \retval FLAC__Metadata_SimpleIteratorStatus
  87966. * The current status of the iterator.
  87967. */
  87968. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87969. /** Initialize the iterator to point to the first metadata block in the
  87970. * given FLAC file.
  87971. *
  87972. * \param iterator A pointer to an existing iterator.
  87973. * \param filename The path to the FLAC file.
  87974. * \param read_only If \c true, the FLAC file will be opened
  87975. * in read-only mode; if \c false, the FLAC
  87976. * file will be opened for edit even if no
  87977. * edits are performed.
  87978. * \param preserve_file_stats If \c true, the owner and modification
  87979. * time will be preserved even if the FLAC
  87980. * file is written to.
  87981. * \assert
  87982. * \code iterator != NULL \endcode
  87983. * \code filename != NULL \endcode
  87984. * \retval FLAC__bool
  87985. * \c false if a memory allocation error occurs, the file can't be
  87986. * opened, or another error occurs, else \c true.
  87987. */
  87988. 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);
  87989. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87990. * FLAC__metadata_simple_iterator_set_block() and
  87991. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87992. *
  87993. * \param iterator A pointer to an existing iterator.
  87994. * \assert
  87995. * \code iterator != NULL \endcode
  87996. * \retval FLAC__bool
  87997. * See above.
  87998. */
  87999. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  88000. /** Moves the iterator forward one metadata block, returning \c false if
  88001. * already at the end.
  88002. *
  88003. * \param iterator A pointer to an existing initialized iterator.
  88004. * \assert
  88005. * \code iterator != NULL \endcode
  88006. * \a iterator has been successfully initialized with
  88007. * FLAC__metadata_simple_iterator_init()
  88008. * \retval FLAC__bool
  88009. * \c false if already at the last metadata block of the chain, else
  88010. * \c true.
  88011. */
  88012. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  88013. /** Moves the iterator backward one metadata block, returning \c false if
  88014. * already at the beginning.
  88015. *
  88016. * \param iterator A pointer to an existing initialized iterator.
  88017. * \assert
  88018. * \code iterator != NULL \endcode
  88019. * \a iterator has been successfully initialized with
  88020. * FLAC__metadata_simple_iterator_init()
  88021. * \retval FLAC__bool
  88022. * \c false if already at the first metadata block of the chain, else
  88023. * \c true.
  88024. */
  88025. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  88026. /** Returns a flag telling if the current metadata block is the last.
  88027. *
  88028. * \param iterator A pointer to an existing initialized iterator.
  88029. * \assert
  88030. * \code iterator != NULL \endcode
  88031. * \a iterator has been successfully initialized with
  88032. * FLAC__metadata_simple_iterator_init()
  88033. * \retval FLAC__bool
  88034. * \c true if the current metadata block is the last in the file,
  88035. * else \c false.
  88036. */
  88037. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  88038. /** Get the offset of the metadata block at the current position. This
  88039. * avoids reading the actual block data which can save time for large
  88040. * blocks.
  88041. *
  88042. * \param iterator A pointer to an existing initialized iterator.
  88043. * \assert
  88044. * \code iterator != NULL \endcode
  88045. * \a iterator has been successfully initialized with
  88046. * FLAC__metadata_simple_iterator_init()
  88047. * \retval off_t
  88048. * The offset of the metadata block at the current iterator position.
  88049. * This is the byte offset relative to the beginning of the file of
  88050. * the current metadata block's header.
  88051. */
  88052. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  88053. /** Get the type of the metadata block at the current position. This
  88054. * avoids reading the actual block data which can save time for large
  88055. * blocks.
  88056. *
  88057. * \param iterator A pointer to an existing initialized iterator.
  88058. * \assert
  88059. * \code iterator != NULL \endcode
  88060. * \a iterator has been successfully initialized with
  88061. * FLAC__metadata_simple_iterator_init()
  88062. * \retval FLAC__MetadataType
  88063. * The type of the metadata block at the current iterator position.
  88064. */
  88065. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  88066. /** Get the length of the metadata block at the current position. This
  88067. * avoids reading the actual block data which can save time for large
  88068. * blocks.
  88069. *
  88070. * \param iterator A pointer to an existing initialized iterator.
  88071. * \assert
  88072. * \code iterator != NULL \endcode
  88073. * \a iterator has been successfully initialized with
  88074. * FLAC__metadata_simple_iterator_init()
  88075. * \retval unsigned
  88076. * The length of the metadata block at the current iterator position.
  88077. * The is same length as that in the
  88078. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  88079. * i.e. the length of the metadata body that follows the header.
  88080. */
  88081. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  88082. /** Get the application ID of the \c APPLICATION block at the current
  88083. * position. This avoids reading the actual block data which can save
  88084. * time for large blocks.
  88085. *
  88086. * \param iterator A pointer to an existing initialized iterator.
  88087. * \param id A pointer to a buffer of at least \c 4 bytes where
  88088. * the ID will be stored.
  88089. * \assert
  88090. * \code iterator != NULL \endcode
  88091. * \code id != NULL \endcode
  88092. * \a iterator has been successfully initialized with
  88093. * FLAC__metadata_simple_iterator_init()
  88094. * \retval FLAC__bool
  88095. * \c true if the ID was successfully read, else \c false, in which
  88096. * case you should check FLAC__metadata_simple_iterator_status() to
  88097. * find out why. If the status is
  88098. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  88099. * current metadata block is not an \c APPLICATION block. Otherwise
  88100. * if the status is
  88101. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  88102. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  88103. * occurred and the iterator can no longer be used.
  88104. */
  88105. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  88106. /** Get the metadata block at the current position. You can modify the
  88107. * block but must use FLAC__metadata_simple_iterator_set_block() to
  88108. * write it back to the FLAC file.
  88109. *
  88110. * You must call FLAC__metadata_object_delete() on the returned object
  88111. * when you are finished with it.
  88112. *
  88113. * \param iterator A pointer to an existing initialized iterator.
  88114. * \assert
  88115. * \code iterator != NULL \endcode
  88116. * \a iterator has been successfully initialized with
  88117. * FLAC__metadata_simple_iterator_init()
  88118. * \retval FLAC__StreamMetadata*
  88119. * The current metadata block, or \c NULL if there was a memory
  88120. * allocation error.
  88121. */
  88122. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  88123. /** Write a block back to the FLAC file. This function tries to be
  88124. * as efficient as possible; how the block is actually written is
  88125. * shown by the following:
  88126. *
  88127. * Existing block is a STREAMINFO block and the new block is a
  88128. * STREAMINFO block: the new block is written in place. Make sure
  88129. * you know what you're doing when changing the values of a
  88130. * STREAMINFO block.
  88131. *
  88132. * Existing block is a STREAMINFO block and the new block is a
  88133. * not a STREAMINFO block: this is an error since the first block
  88134. * must be a STREAMINFO block. Returns \c false without altering the
  88135. * file.
  88136. *
  88137. * Existing block is not a STREAMINFO block and the new block is a
  88138. * STREAMINFO block: this is an error since there may be only one
  88139. * STREAMINFO block. Returns \c false without altering the file.
  88140. *
  88141. * Existing block and new block are the same length: the existing
  88142. * block will be replaced by the new block, written in place.
  88143. *
  88144. * Existing block is longer than new block: if use_padding is \c true,
  88145. * the existing block will be overwritten in place with the new
  88146. * block followed by a PADDING block, if possible, to make the total
  88147. * size the same as the existing block. Remember that a padding
  88148. * block requires at least four bytes so if the difference in size
  88149. * between the new block and existing block is less than that, the
  88150. * entire file will have to be rewritten, using the new block's
  88151. * exact size. If use_padding is \c false, the entire file will be
  88152. * rewritten, replacing the existing block by the new block.
  88153. *
  88154. * Existing block is shorter than new block: if use_padding is \c true,
  88155. * the function will try and expand the new block into the following
  88156. * PADDING block, if it exists and doing so won't shrink the PADDING
  88157. * block to less than 4 bytes. If there is no following PADDING
  88158. * block, or it will shrink to less than 4 bytes, or use_padding is
  88159. * \c false, the entire file is rewritten, replacing the existing block
  88160. * with the new block. Note that in this case any following PADDING
  88161. * block is preserved as is.
  88162. *
  88163. * After writing the block, the iterator will remain in the same
  88164. * place, i.e. pointing to the new block.
  88165. *
  88166. * \param iterator A pointer to an existing initialized iterator.
  88167. * \param block The block to set.
  88168. * \param use_padding See above.
  88169. * \assert
  88170. * \code iterator != NULL \endcode
  88171. * \a iterator has been successfully initialized with
  88172. * FLAC__metadata_simple_iterator_init()
  88173. * \code block != NULL \endcode
  88174. * \retval FLAC__bool
  88175. * \c true if successful, else \c false.
  88176. */
  88177. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88178. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88179. * except that instead of writing over an existing block, it appends
  88180. * a block after the existing block. \a use_padding is again used to
  88181. * tell the function to try an expand into following padding in an
  88182. * attempt to avoid rewriting the entire file.
  88183. *
  88184. * This function will fail and return \c false if given a STREAMINFO
  88185. * block.
  88186. *
  88187. * After writing the block, the iterator will be pointing to the
  88188. * new block.
  88189. *
  88190. * \param iterator A pointer to an existing initialized iterator.
  88191. * \param block The block to set.
  88192. * \param use_padding See above.
  88193. * \assert
  88194. * \code iterator != NULL \endcode
  88195. * \a iterator has been successfully initialized with
  88196. * FLAC__metadata_simple_iterator_init()
  88197. * \code block != NULL \endcode
  88198. * \retval FLAC__bool
  88199. * \c true if successful, else \c false.
  88200. */
  88201. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88202. /** Deletes the block at the current position. This will cause the
  88203. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88204. * in which case the block will be replaced by an equal-sized PADDING
  88205. * block. The iterator will be left pointing to the block before the
  88206. * one just deleted.
  88207. *
  88208. * You may not delete the STREAMINFO block.
  88209. *
  88210. * \param iterator A pointer to an existing initialized iterator.
  88211. * \param use_padding See above.
  88212. * \assert
  88213. * \code iterator != NULL \endcode
  88214. * \a iterator has been successfully initialized with
  88215. * FLAC__metadata_simple_iterator_init()
  88216. * \retval FLAC__bool
  88217. * \c true if successful, else \c false.
  88218. */
  88219. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88220. /* \} */
  88221. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88222. * \ingroup flac_metadata
  88223. *
  88224. * \brief
  88225. * The level 2 interface provides read-write access to FLAC file metadata;
  88226. * all metadata is read into memory, operated on in memory, and then written
  88227. * to file, which is more efficient than level 1 when editing multiple blocks.
  88228. *
  88229. * Currently Ogg FLAC is supported for read only, via
  88230. * FLAC__metadata_chain_read_ogg() but a subsequent
  88231. * FLAC__metadata_chain_write() will fail.
  88232. *
  88233. * The general usage of this interface is:
  88234. *
  88235. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88236. * linked list of FLAC metadata blocks.
  88237. * - Read all metadata into the the chain from a FLAC file using
  88238. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88239. * check the status.
  88240. * - Optionally, consolidate the padding using
  88241. * FLAC__metadata_chain_merge_padding() or
  88242. * FLAC__metadata_chain_sort_padding().
  88243. * - Create a new iterator using FLAC__metadata_iterator_new()
  88244. * - Initialize the iterator to point to the first element in the chain
  88245. * using FLAC__metadata_iterator_init()
  88246. * - Traverse the chain using FLAC__metadata_iterator_next and
  88247. * FLAC__metadata_iterator_prev().
  88248. * - Get a block for reading or modification using
  88249. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88250. * inside the chain is returned, so the block is yours to modify.
  88251. * Changes will be reflected in the FLAC file when you write the
  88252. * chain. You can also add and delete blocks (see functions below).
  88253. * - When done, write out the chain using FLAC__metadata_chain_write().
  88254. * Make sure to read the whole comment to the function below.
  88255. * - Delete the chain using FLAC__metadata_chain_delete().
  88256. *
  88257. * \note
  88258. * Even though the FLAC file is not open while the chain is being
  88259. * manipulated, you must not alter the file externally during
  88260. * this time. The chain assumes the FLAC file will not change
  88261. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88262. * and FLAC__metadata_chain_write().
  88263. *
  88264. * \note
  88265. * Do not modify the is_last, length, or type fields of returned
  88266. * FLAC__StreamMetadata objects. These are managed automatically.
  88267. *
  88268. * \note
  88269. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88270. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88271. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88272. * become owned by the chain and they will be deleted when the chain is
  88273. * deleted.
  88274. *
  88275. * \{
  88276. */
  88277. struct FLAC__Metadata_Chain;
  88278. /** The opaque structure definition for the level 2 chain type.
  88279. */
  88280. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88281. struct FLAC__Metadata_Iterator;
  88282. /** The opaque structure definition for the level 2 iterator type.
  88283. */
  88284. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88285. typedef enum {
  88286. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88287. /**< The chain is in the normal OK state */
  88288. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88289. /**< The data passed into a function violated the function's usage criteria */
  88290. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88291. /**< The chain could not open the target file */
  88292. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88293. /**< The chain could not find the FLAC signature at the start of the file */
  88294. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88295. /**< The chain tried to write to a file that was not writable */
  88296. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88297. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88298. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88299. /**< The chain encountered an error while reading the FLAC file */
  88300. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88301. /**< The chain encountered an error while seeking in the FLAC file */
  88302. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88303. /**< The chain encountered an error while writing the FLAC file */
  88304. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88305. /**< The chain encountered an error renaming the FLAC file */
  88306. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88307. /**< The chain encountered an error removing the temporary file */
  88308. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88309. /**< Memory allocation failed */
  88310. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88311. /**< The caller violated an assertion or an unexpected error occurred */
  88312. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88313. /**< One or more of the required callbacks was NULL */
  88314. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88315. /**< FLAC__metadata_chain_write() was called on a chain read by
  88316. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88317. * or
  88318. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88319. * was called on a chain read by
  88320. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88321. * Matching read/write methods must always be used. */
  88322. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88323. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88324. * chain write requires a tempfile; use
  88325. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88326. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88327. * called when the chain write does not require a tempfile; use
  88328. * FLAC__metadata_chain_write_with_callbacks() instead.
  88329. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88330. * before writing via callbacks. */
  88331. } FLAC__Metadata_ChainStatus;
  88332. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88333. *
  88334. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88335. * will give the string equivalent. The contents should not be modified.
  88336. */
  88337. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88338. /*********** FLAC__Metadata_Chain ***********/
  88339. /** Create a new chain instance.
  88340. *
  88341. * \retval FLAC__Metadata_Chain*
  88342. * \c NULL if there was an error allocating memory, else the new instance.
  88343. */
  88344. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88345. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88346. *
  88347. * \param chain A pointer to an existing chain.
  88348. * \assert
  88349. * \code chain != NULL \endcode
  88350. */
  88351. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88352. /** Get the current status of the chain. Call this after a function
  88353. * returns \c false to get the reason for the error. Also resets the
  88354. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88355. *
  88356. * \param chain A pointer to an existing chain.
  88357. * \assert
  88358. * \code chain != NULL \endcode
  88359. * \retval FLAC__Metadata_ChainStatus
  88360. * The current status of the chain.
  88361. */
  88362. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88363. /** Read all metadata from a FLAC file into the chain.
  88364. *
  88365. * \param chain A pointer to an existing chain.
  88366. * \param filename The path to the FLAC file to read.
  88367. * \assert
  88368. * \code chain != NULL \endcode
  88369. * \code filename != NULL \endcode
  88370. * \retval FLAC__bool
  88371. * \c true if a valid list of metadata blocks was read from
  88372. * \a filename, else \c false. On failure, check the status with
  88373. * FLAC__metadata_chain_status().
  88374. */
  88375. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88376. /** Read all metadata from an Ogg FLAC file into the chain.
  88377. *
  88378. * \note Ogg FLAC metadata data writing is not supported yet and
  88379. * FLAC__metadata_chain_write() will fail.
  88380. *
  88381. * \param chain A pointer to an existing chain.
  88382. * \param filename The path to the Ogg FLAC file to read.
  88383. * \assert
  88384. * \code chain != NULL \endcode
  88385. * \code filename != NULL \endcode
  88386. * \retval FLAC__bool
  88387. * \c true if a valid list of metadata blocks was read from
  88388. * \a filename, else \c false. On failure, check the status with
  88389. * FLAC__metadata_chain_status().
  88390. */
  88391. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88392. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88393. *
  88394. * The \a handle need only be open for reading, but must be seekable.
  88395. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88396. * for Windows).
  88397. *
  88398. * \param chain A pointer to an existing chain.
  88399. * \param handle The I/O handle of the FLAC stream to read. The
  88400. * handle will NOT be closed after the metadata is read;
  88401. * that is the duty of the caller.
  88402. * \param callbacks
  88403. * A set of callbacks to use for I/O. The mandatory
  88404. * callbacks are \a read, \a seek, and \a tell.
  88405. * \assert
  88406. * \code chain != NULL \endcode
  88407. * \retval FLAC__bool
  88408. * \c true if a valid list of metadata blocks was read from
  88409. * \a handle, else \c false. On failure, check the status with
  88410. * FLAC__metadata_chain_status().
  88411. */
  88412. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88413. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88414. *
  88415. * The \a handle need only be open for reading, but must be seekable.
  88416. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88417. * for Windows).
  88418. *
  88419. * \note Ogg FLAC metadata data writing is not supported yet and
  88420. * FLAC__metadata_chain_write() will fail.
  88421. *
  88422. * \param chain A pointer to an existing chain.
  88423. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88424. * handle will NOT be closed after the metadata is read;
  88425. * that is the duty of the caller.
  88426. * \param callbacks
  88427. * A set of callbacks to use for I/O. The mandatory
  88428. * callbacks are \a read, \a seek, and \a tell.
  88429. * \assert
  88430. * \code chain != NULL \endcode
  88431. * \retval FLAC__bool
  88432. * \c true if a valid list of metadata blocks was read from
  88433. * \a handle, else \c false. On failure, check the status with
  88434. * FLAC__metadata_chain_status().
  88435. */
  88436. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88437. /** Checks if writing the given chain would require the use of a
  88438. * temporary file, or if it could be written in place.
  88439. *
  88440. * Under certain conditions, padding can be utilized so that writing
  88441. * edited metadata back to the FLAC file does not require rewriting the
  88442. * entire file. If rewriting is required, then a temporary workfile is
  88443. * required. When writing metadata using callbacks, you must check
  88444. * this function to know whether to call
  88445. * FLAC__metadata_chain_write_with_callbacks() or
  88446. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88447. * writing with FLAC__metadata_chain_write(), the temporary file is
  88448. * handled internally.
  88449. *
  88450. * \param chain A pointer to an existing chain.
  88451. * \param use_padding
  88452. * Whether or not padding will be allowed to be used
  88453. * during the write. The value of \a use_padding given
  88454. * here must match the value later passed to
  88455. * FLAC__metadata_chain_write_with_callbacks() or
  88456. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88457. * \assert
  88458. * \code chain != NULL \endcode
  88459. * \retval FLAC__bool
  88460. * \c true if writing the current chain would require a tempfile, or
  88461. * \c false if metadata can be written in place.
  88462. */
  88463. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88464. /** Write all metadata out to the FLAC file. This function tries to be as
  88465. * efficient as possible; how the metadata is actually written is shown by
  88466. * the following:
  88467. *
  88468. * If the current chain is the same size as the existing metadata, the new
  88469. * data is written in place.
  88470. *
  88471. * If the current chain is longer than the existing metadata, and
  88472. * \a use_padding is \c true, and the last block is a PADDING block of
  88473. * sufficient length, the function will truncate the final padding block
  88474. * so that the overall size of the metadata is the same as the existing
  88475. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88476. * the above conditions are met, the entire FLAC file must be rewritten.
  88477. * If you want to use padding this way it is a good idea to call
  88478. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88479. * amount of padding to work with, unless you need to preserve ordering
  88480. * of the PADDING blocks for some reason.
  88481. *
  88482. * If the current chain is shorter than the existing metadata, and
  88483. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88484. * is extended to make the overall size the same as the existing data. If
  88485. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88486. * PADDING block is added to the end of the new data to make it the same
  88487. * size as the existing data (if possible, see the note to
  88488. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88489. * and the new data is written in place. If none of the above apply or
  88490. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88491. *
  88492. * If \a preserve_file_stats is \c true, the owner and modification time will
  88493. * be preserved even if the FLAC file is written.
  88494. *
  88495. * For this write function to be used, the chain must have been read with
  88496. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88497. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88498. *
  88499. * \param chain A pointer to an existing chain.
  88500. * \param use_padding See above.
  88501. * \param preserve_file_stats See above.
  88502. * \assert
  88503. * \code chain != NULL \endcode
  88504. * \retval FLAC__bool
  88505. * \c true if the write succeeded, else \c false. On failure,
  88506. * check the status with FLAC__metadata_chain_status().
  88507. */
  88508. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88509. /** Write all metadata out to a FLAC stream via callbacks.
  88510. *
  88511. * (See FLAC__metadata_chain_write() for the details on how padding is
  88512. * used to write metadata in place if possible.)
  88513. *
  88514. * The \a handle must be open for updating and be seekable. The
  88515. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88516. * for Windows).
  88517. *
  88518. * For this write function to be used, the chain must have been read with
  88519. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88520. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88521. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88522. * \c false.
  88523. *
  88524. * \param chain A pointer to an existing chain.
  88525. * \param use_padding See FLAC__metadata_chain_write()
  88526. * \param handle The I/O handle of the FLAC stream to write. The
  88527. * handle will NOT be closed after the metadata is
  88528. * written; that is the duty of the caller.
  88529. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88530. * callbacks are \a write and \a seek.
  88531. * \assert
  88532. * \code chain != NULL \endcode
  88533. * \retval FLAC__bool
  88534. * \c true if the write succeeded, else \c false. On failure,
  88535. * check the status with FLAC__metadata_chain_status().
  88536. */
  88537. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88538. /** Write all metadata out to a FLAC stream via callbacks.
  88539. *
  88540. * (See FLAC__metadata_chain_write() for the details on how padding is
  88541. * used to write metadata in place if possible.)
  88542. *
  88543. * This version of the write-with-callbacks function must be used when
  88544. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88545. * this function, you must supply an I/O handle corresponding to the
  88546. * FLAC file to edit, and a temporary handle to which the new FLAC
  88547. * file will be written. It is the caller's job to move this temporary
  88548. * FLAC file on top of the original FLAC file to complete the metadata
  88549. * edit.
  88550. *
  88551. * The \a handle must be open for reading and be seekable. The
  88552. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88553. * for Windows).
  88554. *
  88555. * The \a temp_handle must be open for writing. The
  88556. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88557. * for Windows). It should be an empty stream, or at least positioned
  88558. * at the start-of-file (in which case it is the caller's duty to
  88559. * truncate it on return).
  88560. *
  88561. * For this write function to be used, the chain must have been read with
  88562. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88563. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88564. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88565. * \c true.
  88566. *
  88567. * \param chain A pointer to an existing chain.
  88568. * \param use_padding See FLAC__metadata_chain_write()
  88569. * \param handle The I/O handle of the original FLAC stream to read.
  88570. * The handle will NOT be closed after the metadata is
  88571. * written; that is the duty of the caller.
  88572. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88573. * The mandatory callbacks are \a read, \a seek, and
  88574. * \a eof.
  88575. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88576. * handle will NOT be closed after the metadata is
  88577. * written; that is the duty of the caller.
  88578. * \param temp_callbacks
  88579. * A set of callbacks to use for I/O on temp_handle.
  88580. * The only mandatory callback is \a write.
  88581. * \assert
  88582. * \code chain != NULL \endcode
  88583. * \retval FLAC__bool
  88584. * \c true if the write succeeded, else \c false. On failure,
  88585. * check the status with FLAC__metadata_chain_status().
  88586. */
  88587. 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);
  88588. /** Merge adjacent PADDING blocks into a single block.
  88589. *
  88590. * \note This function does not write to the FLAC file, it only
  88591. * modifies the chain.
  88592. *
  88593. * \warning Any iterator on the current chain will become invalid after this
  88594. * call. You should delete the iterator and get a new one.
  88595. *
  88596. * \param chain A pointer to an existing chain.
  88597. * \assert
  88598. * \code chain != NULL \endcode
  88599. */
  88600. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88601. /** This function will move all PADDING blocks to the end on the metadata,
  88602. * then merge them into a single block.
  88603. *
  88604. * \note This function does not write to the FLAC file, it only
  88605. * modifies the chain.
  88606. *
  88607. * \warning Any iterator on the current chain will become invalid after this
  88608. * call. You should delete the iterator and get a new one.
  88609. *
  88610. * \param chain A pointer to an existing chain.
  88611. * \assert
  88612. * \code chain != NULL \endcode
  88613. */
  88614. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88615. /*********** FLAC__Metadata_Iterator ***********/
  88616. /** Create a new iterator instance.
  88617. *
  88618. * \retval FLAC__Metadata_Iterator*
  88619. * \c NULL if there was an error allocating memory, else the new instance.
  88620. */
  88621. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88622. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88623. *
  88624. * \param iterator A pointer to an existing iterator.
  88625. * \assert
  88626. * \code iterator != NULL \endcode
  88627. */
  88628. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88629. /** Initialize the iterator to point to the first metadata block in the
  88630. * given chain.
  88631. *
  88632. * \param iterator A pointer to an existing iterator.
  88633. * \param chain A pointer to an existing and initialized (read) chain.
  88634. * \assert
  88635. * \code iterator != NULL \endcode
  88636. * \code chain != NULL \endcode
  88637. */
  88638. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88639. /** Moves the iterator forward one metadata block, returning \c false if
  88640. * already at the end.
  88641. *
  88642. * \param iterator A pointer to an existing initialized iterator.
  88643. * \assert
  88644. * \code iterator != NULL \endcode
  88645. * \a iterator has been successfully initialized with
  88646. * FLAC__metadata_iterator_init()
  88647. * \retval FLAC__bool
  88648. * \c false if already at the last metadata block of the chain, else
  88649. * \c true.
  88650. */
  88651. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88652. /** Moves the iterator backward one metadata block, returning \c false if
  88653. * already at the beginning.
  88654. *
  88655. * \param iterator A pointer to an existing initialized iterator.
  88656. * \assert
  88657. * \code iterator != NULL \endcode
  88658. * \a iterator has been successfully initialized with
  88659. * FLAC__metadata_iterator_init()
  88660. * \retval FLAC__bool
  88661. * \c false if already at the first metadata block of the chain, else
  88662. * \c true.
  88663. */
  88664. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88665. /** Get the type of the metadata block at the current position.
  88666. *
  88667. * \param iterator A pointer to an existing initialized iterator.
  88668. * \assert
  88669. * \code iterator != NULL \endcode
  88670. * \a iterator has been successfully initialized with
  88671. * FLAC__metadata_iterator_init()
  88672. * \retval FLAC__MetadataType
  88673. * The type of the metadata block at the current iterator position.
  88674. */
  88675. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88676. /** Get the metadata block at the current position. You can modify
  88677. * the block in place but must write the chain before the changes
  88678. * are reflected to the FLAC file. You do not need to call
  88679. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88680. * the pointer returned by FLAC__metadata_iterator_get_block()
  88681. * points directly into the chain.
  88682. *
  88683. * \warning
  88684. * Do not call FLAC__metadata_object_delete() on the returned object;
  88685. * to delete a block use FLAC__metadata_iterator_delete_block().
  88686. *
  88687. * \param iterator A pointer to an existing initialized iterator.
  88688. * \assert
  88689. * \code iterator != NULL \endcode
  88690. * \a iterator has been successfully initialized with
  88691. * FLAC__metadata_iterator_init()
  88692. * \retval FLAC__StreamMetadata*
  88693. * The current metadata block.
  88694. */
  88695. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88696. /** Set the metadata block at the current position, replacing the existing
  88697. * block. The new block passed in becomes owned by the chain and it will be
  88698. * deleted when the chain is deleted.
  88699. *
  88700. * \param iterator A pointer to an existing initialized iterator.
  88701. * \param block A pointer to a metadata block.
  88702. * \assert
  88703. * \code iterator != NULL \endcode
  88704. * \a iterator has been successfully initialized with
  88705. * FLAC__metadata_iterator_init()
  88706. * \code block != NULL \endcode
  88707. * \retval FLAC__bool
  88708. * \c false if the conditions in the above description are not met, or
  88709. * a memory allocation error occurs, otherwise \c true.
  88710. */
  88711. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88712. /** Removes the current block from the chain. If \a replace_with_padding is
  88713. * \c true, the block will instead be replaced with a padding block of equal
  88714. * size. You can not delete the STREAMINFO block. The iterator will be
  88715. * left pointing to the block before the one just "deleted", even if
  88716. * \a replace_with_padding is \c true.
  88717. *
  88718. * \param iterator A pointer to an existing initialized iterator.
  88719. * \param replace_with_padding See above.
  88720. * \assert
  88721. * \code iterator != NULL \endcode
  88722. * \a iterator has been successfully initialized with
  88723. * FLAC__metadata_iterator_init()
  88724. * \retval FLAC__bool
  88725. * \c false if the conditions in the above description are not met,
  88726. * otherwise \c true.
  88727. */
  88728. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88729. /** Insert a new block before the current block. You cannot insert a block
  88730. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88731. * as there can be only one, the one that already exists at the head when you
  88732. * read in a chain. The chain takes ownership of the new block and it will be
  88733. * deleted when the chain is deleted. The iterator will be left pointing to
  88734. * the new block.
  88735. *
  88736. * \param iterator A pointer to an existing initialized iterator.
  88737. * \param block A pointer to a metadata block to insert.
  88738. * \assert
  88739. * \code iterator != NULL \endcode
  88740. * \a iterator has been successfully initialized with
  88741. * FLAC__metadata_iterator_init()
  88742. * \retval FLAC__bool
  88743. * \c false if the conditions in the above description are not met, or
  88744. * a memory allocation error occurs, otherwise \c true.
  88745. */
  88746. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88747. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88748. * block as there can be only one, the one that already exists at the head when
  88749. * you read in a chain. The chain takes ownership of the new block and it will
  88750. * be deleted when the chain is deleted. The iterator will be left pointing to
  88751. * the new block.
  88752. *
  88753. * \param iterator A pointer to an existing initialized iterator.
  88754. * \param block A pointer to a metadata block to insert.
  88755. * \assert
  88756. * \code iterator != NULL \endcode
  88757. * \a iterator has been successfully initialized with
  88758. * FLAC__metadata_iterator_init()
  88759. * \retval FLAC__bool
  88760. * \c false if the conditions in the above description are not met, or
  88761. * a memory allocation error occurs, otherwise \c true.
  88762. */
  88763. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88764. /* \} */
  88765. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88766. * \ingroup flac_metadata
  88767. *
  88768. * \brief
  88769. * This module contains methods for manipulating FLAC metadata objects.
  88770. *
  88771. * Since many are variable length we have to be careful about the memory
  88772. * management. We decree that all pointers to data in the object are
  88773. * owned by the object and memory-managed by the object.
  88774. *
  88775. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88776. * functions to create all instances. When using the
  88777. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88778. * \a copy to \c true to have the function make it's own copy of the data, or
  88779. * to \c false to give the object ownership of your data. In the latter case
  88780. * your pointer must be freeable by free() and will be free()d when the object
  88781. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88782. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88783. * the length argument is 0 and the \a copy argument is \c false.
  88784. *
  88785. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88786. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88787. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88788. * case of a memory allocation error.
  88789. *
  88790. * We don't have the convenience of C++ here, so note that the library relies
  88791. * on you to keep the types straight. In other words, if you pass, for
  88792. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88793. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88794. * failure.
  88795. *
  88796. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88797. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88798. * toward the length or stored in the stream, but it can make working with plain
  88799. * comments (those that don't contain embedded-NULs in the value) easier.
  88800. * Entries passed into these functions have trailing NULs added if missing, and
  88801. * returned entries are guaranteed to have a trailing NUL.
  88802. *
  88803. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88804. * comment entry/name/value will first validate that it complies with the Vorbis
  88805. * comment specification and return false if it does not.
  88806. *
  88807. * There is no need to recalculate the length field on metadata blocks you
  88808. * have modified. They will be calculated automatically before they are
  88809. * written back to a file.
  88810. *
  88811. * \{
  88812. */
  88813. /** Create a new metadata object instance of the given type.
  88814. *
  88815. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88816. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88817. * the vendor string set (but zero comments).
  88818. *
  88819. * Do not pass in a value greater than or equal to
  88820. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88821. * doing.
  88822. *
  88823. * \param type Type of object to create
  88824. * \retval FLAC__StreamMetadata*
  88825. * \c NULL if there was an error allocating memory or the type code is
  88826. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88827. */
  88828. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88829. /** Create a copy of an existing metadata object.
  88830. *
  88831. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88832. * object is also copied. The caller takes ownership of the new block and
  88833. * is responsible for freeing it with FLAC__metadata_object_delete().
  88834. *
  88835. * \param object Pointer to object to copy.
  88836. * \assert
  88837. * \code object != NULL \endcode
  88838. * \retval FLAC__StreamMetadata*
  88839. * \c NULL if there was an error allocating memory, else the new instance.
  88840. */
  88841. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88842. /** Free a metadata object. Deletes the object pointed to by \a object.
  88843. *
  88844. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88845. * object is also deleted.
  88846. *
  88847. * \param object A pointer to an existing object.
  88848. * \assert
  88849. * \code object != NULL \endcode
  88850. */
  88851. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88852. /** Compares two metadata objects.
  88853. *
  88854. * The compare is "deep", i.e. dynamically allocated data within the
  88855. * object is also compared.
  88856. *
  88857. * \param block1 A pointer to an existing object.
  88858. * \param block2 A pointer to an existing object.
  88859. * \assert
  88860. * \code block1 != NULL \endcode
  88861. * \code block2 != NULL \endcode
  88862. * \retval FLAC__bool
  88863. * \c true if objects are identical, else \c false.
  88864. */
  88865. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88866. /** Sets the application data of an APPLICATION block.
  88867. *
  88868. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88869. * takes ownership of the pointer. The existing data will be freed if this
  88870. * function is successful, otherwise the original data will remain if \a copy
  88871. * is \c true and malloc() fails.
  88872. *
  88873. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88874. *
  88875. * \param object A pointer to an existing APPLICATION object.
  88876. * \param data A pointer to the data to set.
  88877. * \param length The length of \a data in bytes.
  88878. * \param copy See above.
  88879. * \assert
  88880. * \code object != NULL \endcode
  88881. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88882. * \code (data != NULL && length > 0) ||
  88883. * (data == NULL && length == 0 && copy == false) \endcode
  88884. * \retval FLAC__bool
  88885. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88886. */
  88887. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88888. /** Resize the seekpoint array.
  88889. *
  88890. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88891. * points will be added to the end.
  88892. *
  88893. * \param object A pointer to an existing SEEKTABLE object.
  88894. * \param new_num_points The desired length of the array; may be \c 0.
  88895. * \assert
  88896. * \code object != NULL \endcode
  88897. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88898. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88899. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88900. * \retval FLAC__bool
  88901. * \c false if memory allocation error, else \c true.
  88902. */
  88903. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88904. /** Set a seekpoint in a seektable.
  88905. *
  88906. * \param object A pointer to an existing SEEKTABLE object.
  88907. * \param point_num Index into seekpoint array to set.
  88908. * \param point The point to set.
  88909. * \assert
  88910. * \code object != NULL \endcode
  88911. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88912. * \code object->data.seek_table.num_points > point_num \endcode
  88913. */
  88914. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88915. /** Insert a seekpoint into a seektable.
  88916. *
  88917. * \param object A pointer to an existing SEEKTABLE object.
  88918. * \param point_num Index into seekpoint array to set.
  88919. * \param point The point to set.
  88920. * \assert
  88921. * \code object != NULL \endcode
  88922. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88923. * \code object->data.seek_table.num_points >= point_num \endcode
  88924. * \retval FLAC__bool
  88925. * \c false if memory allocation error, else \c true.
  88926. */
  88927. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88928. /** Delete a seekpoint from a seektable.
  88929. *
  88930. * \param object A pointer to an existing SEEKTABLE object.
  88931. * \param point_num Index into seekpoint array to set.
  88932. * \assert
  88933. * \code object != NULL \endcode
  88934. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88935. * \code object->data.seek_table.num_points > point_num \endcode
  88936. * \retval FLAC__bool
  88937. * \c false if memory allocation error, else \c true.
  88938. */
  88939. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88940. /** Check a seektable to see if it conforms to the FLAC specification.
  88941. * See the format specification for limits on the contents of the
  88942. * seektable.
  88943. *
  88944. * \param object A pointer to an existing SEEKTABLE object.
  88945. * \assert
  88946. * \code object != NULL \endcode
  88947. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88948. * \retval FLAC__bool
  88949. * \c false if seek table is illegal, else \c true.
  88950. */
  88951. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88952. /** Append a number of placeholder points to the end of a seek table.
  88953. *
  88954. * \note
  88955. * As with the other ..._seektable_template_... functions, you should
  88956. * call FLAC__metadata_object_seektable_template_sort() when finished
  88957. * to make the seek table legal.
  88958. *
  88959. * \param object A pointer to an existing SEEKTABLE object.
  88960. * \param num The number of placeholder points to append.
  88961. * \assert
  88962. * \code object != NULL \endcode
  88963. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88964. * \retval FLAC__bool
  88965. * \c false if memory allocation fails, else \c true.
  88966. */
  88967. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88968. /** Append a specific seek point template to the end of a seek table.
  88969. *
  88970. * \note
  88971. * As with the other ..._seektable_template_... functions, you should
  88972. * call FLAC__metadata_object_seektable_template_sort() when finished
  88973. * to make the seek table legal.
  88974. *
  88975. * \param object A pointer to an existing SEEKTABLE object.
  88976. * \param sample_number The sample number of the seek point template.
  88977. * \assert
  88978. * \code object != NULL \endcode
  88979. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88980. * \retval FLAC__bool
  88981. * \c false if memory allocation fails, else \c true.
  88982. */
  88983. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88984. /** Append specific seek point templates to the end of a seek table.
  88985. *
  88986. * \note
  88987. * As with the other ..._seektable_template_... functions, you should
  88988. * call FLAC__metadata_object_seektable_template_sort() when finished
  88989. * to make the seek table legal.
  88990. *
  88991. * \param object A pointer to an existing SEEKTABLE object.
  88992. * \param sample_numbers An array of sample numbers for the seek points.
  88993. * \param num The number of seek point templates to append.
  88994. * \assert
  88995. * \code object != NULL \endcode
  88996. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88997. * \retval FLAC__bool
  88998. * \c false if memory allocation fails, else \c true.
  88999. */
  89000. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  89001. /** Append a set of evenly-spaced seek point templates to the end of a
  89002. * seek table.
  89003. *
  89004. * \note
  89005. * As with the other ..._seektable_template_... functions, you should
  89006. * call FLAC__metadata_object_seektable_template_sort() when finished
  89007. * to make the seek table legal.
  89008. *
  89009. * \param object A pointer to an existing SEEKTABLE object.
  89010. * \param num The number of placeholder points to append.
  89011. * \param total_samples The total number of samples to be encoded;
  89012. * the seekpoints will be spaced approximately
  89013. * \a total_samples / \a num samples apart.
  89014. * \assert
  89015. * \code object != NULL \endcode
  89016. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89017. * \code total_samples > 0 \endcode
  89018. * \retval FLAC__bool
  89019. * \c false if memory allocation fails, else \c true.
  89020. */
  89021. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  89022. /** Append a set of evenly-spaced seek point templates to the end of a
  89023. * seek table.
  89024. *
  89025. * \note
  89026. * As with the other ..._seektable_template_... functions, you should
  89027. * call FLAC__metadata_object_seektable_template_sort() when finished
  89028. * to make the seek table legal.
  89029. *
  89030. * \param object A pointer to an existing SEEKTABLE object.
  89031. * \param samples The number of samples apart to space the placeholder
  89032. * points. The first point will be at sample \c 0, the
  89033. * second at sample \a samples, then 2*\a samples, and
  89034. * so on. As long as \a samples and \a total_samples
  89035. * are greater than \c 0, there will always be at least
  89036. * one seekpoint at sample \c 0.
  89037. * \param total_samples The total number of samples to be encoded;
  89038. * the seekpoints will be spaced
  89039. * \a samples samples apart.
  89040. * \assert
  89041. * \code object != NULL \endcode
  89042. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89043. * \code samples > 0 \endcode
  89044. * \code total_samples > 0 \endcode
  89045. * \retval FLAC__bool
  89046. * \c false if memory allocation fails, else \c true.
  89047. */
  89048. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  89049. /** Sort a seek table's seek points according to the format specification,
  89050. * removing duplicates.
  89051. *
  89052. * \param object A pointer to a seek table to be sorted.
  89053. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  89054. * If \c true, duplicates are deleted and the seek table is
  89055. * shrunk appropriately; the number of placeholder points
  89056. * present in the seek table will be the same after the call
  89057. * as before.
  89058. * \assert
  89059. * \code object != NULL \endcode
  89060. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89061. * \retval FLAC__bool
  89062. * \c false if realloc() fails, else \c true.
  89063. */
  89064. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  89065. /** Sets the vendor string in a VORBIS_COMMENT block.
  89066. *
  89067. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89068. * one already.
  89069. *
  89070. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89071. * takes ownership of the \c entry.entry pointer.
  89072. *
  89073. * \note If this function returns \c false, the caller still owns the
  89074. * pointer.
  89075. *
  89076. * \param object A pointer to an existing VORBIS_COMMENT object.
  89077. * \param entry The entry to set the vendor string to.
  89078. * \param copy See above.
  89079. * \assert
  89080. * \code object != NULL \endcode
  89081. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89082. * \code (entry.entry != NULL && entry.length > 0) ||
  89083. * (entry.entry == NULL && entry.length == 0) \endcode
  89084. * \retval FLAC__bool
  89085. * \c false if memory allocation fails or \a entry does not comply with the
  89086. * Vorbis comment specification, else \c true.
  89087. */
  89088. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89089. /** Resize the comment array.
  89090. *
  89091. * If the size shrinks, elements will truncated; if it grows, new empty
  89092. * fields will be added to the end.
  89093. *
  89094. * \param object A pointer to an existing VORBIS_COMMENT object.
  89095. * \param new_num_comments The desired length of the array; may be \c 0.
  89096. * \assert
  89097. * \code object != NULL \endcode
  89098. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89099. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  89100. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  89101. * \retval FLAC__bool
  89102. * \c false if memory allocation fails, else \c true.
  89103. */
  89104. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  89105. /** Sets a comment in a VORBIS_COMMENT block.
  89106. *
  89107. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89108. * one already.
  89109. *
  89110. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89111. * takes ownership of the \c entry.entry pointer.
  89112. *
  89113. * \note If this function returns \c false, the caller still owns the
  89114. * pointer.
  89115. *
  89116. * \param object A pointer to an existing VORBIS_COMMENT object.
  89117. * \param comment_num Index into comment array to set.
  89118. * \param entry The entry to set the comment to.
  89119. * \param copy See above.
  89120. * \assert
  89121. * \code object != NULL \endcode
  89122. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89123. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  89124. * \code (entry.entry != NULL && entry.length > 0) ||
  89125. * (entry.entry == NULL && entry.length == 0) \endcode
  89126. * \retval FLAC__bool
  89127. * \c false if memory allocation fails or \a entry does not comply with the
  89128. * Vorbis comment specification, else \c true.
  89129. */
  89130. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89131. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  89132. *
  89133. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89134. * one already.
  89135. *
  89136. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89137. * takes ownership of the \c entry.entry pointer.
  89138. *
  89139. * \note If this function returns \c false, the caller still owns the
  89140. * pointer.
  89141. *
  89142. * \param object A pointer to an existing VORBIS_COMMENT object.
  89143. * \param comment_num The index at which to insert the comment. The comments
  89144. * at and after \a comment_num move right one position.
  89145. * To append a comment to the end, set \a comment_num to
  89146. * \c object->data.vorbis_comment.num_comments .
  89147. * \param entry The comment to insert.
  89148. * \param copy See above.
  89149. * \assert
  89150. * \code object != NULL \endcode
  89151. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89152. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  89153. * \code (entry.entry != NULL && entry.length > 0) ||
  89154. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89155. * \retval FLAC__bool
  89156. * \c false if memory allocation fails or \a entry does not comply with the
  89157. * Vorbis comment specification, else \c true.
  89158. */
  89159. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89160. /** Appends a comment to a VORBIS_COMMENT block.
  89161. *
  89162. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89163. * one already.
  89164. *
  89165. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89166. * takes ownership of the \c entry.entry pointer.
  89167. *
  89168. * \note If this function returns \c false, the caller still owns the
  89169. * pointer.
  89170. *
  89171. * \param object A pointer to an existing VORBIS_COMMENT object.
  89172. * \param entry The comment to insert.
  89173. * \param copy See above.
  89174. * \assert
  89175. * \code object != NULL \endcode
  89176. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89177. * \code (entry.entry != NULL && entry.length > 0) ||
  89178. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89179. * \retval FLAC__bool
  89180. * \c false if memory allocation fails or \a entry does not comply with the
  89181. * Vorbis comment specification, else \c true.
  89182. */
  89183. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89184. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89185. *
  89186. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89187. * one already.
  89188. *
  89189. * Depending on the the value of \a all, either all or just the first comment
  89190. * whose field name(s) match the given entry's name will be replaced by the
  89191. * given entry. If no comments match, \a entry will simply be appended.
  89192. *
  89193. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89194. * takes ownership of the \c entry.entry pointer.
  89195. *
  89196. * \note If this function returns \c false, the caller still owns the
  89197. * pointer.
  89198. *
  89199. * \param object A pointer to an existing VORBIS_COMMENT object.
  89200. * \param entry The comment to insert.
  89201. * \param all If \c true, all comments whose field name matches
  89202. * \a entry's field name will be removed, and \a entry will
  89203. * be inserted at the position of the first matching
  89204. * comment. If \c false, only the first comment whose
  89205. * field name matches \a entry's field name will be
  89206. * replaced with \a entry.
  89207. * \param copy See above.
  89208. * \assert
  89209. * \code object != NULL \endcode
  89210. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89211. * \code (entry.entry != NULL && entry.length > 0) ||
  89212. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89213. * \retval FLAC__bool
  89214. * \c false if memory allocation fails or \a entry does not comply with the
  89215. * Vorbis comment specification, else \c true.
  89216. */
  89217. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89218. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89219. *
  89220. * \param object A pointer to an existing VORBIS_COMMENT object.
  89221. * \param comment_num The index of the comment to delete.
  89222. * \assert
  89223. * \code object != NULL \endcode
  89224. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89225. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89226. * \retval FLAC__bool
  89227. * \c false if realloc() fails, else \c true.
  89228. */
  89229. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89230. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89231. *
  89232. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89233. * memory and shall be owned by the caller. For convenience the entry will
  89234. * have a terminating NUL.
  89235. *
  89236. * \param entry A pointer to a Vorbis comment entry. The entry's
  89237. * \c entry pointer should not point to allocated
  89238. * memory as it will be overwritten.
  89239. * \param field_name The field name in ASCII, \c NUL terminated.
  89240. * \param field_value The field value in UTF-8, \c NUL terminated.
  89241. * \assert
  89242. * \code entry != NULL \endcode
  89243. * \code field_name != NULL \endcode
  89244. * \code field_value != NULL \endcode
  89245. * \retval FLAC__bool
  89246. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89247. * not comply with the Vorbis comment specification, else \c true.
  89248. */
  89249. 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);
  89250. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89251. *
  89252. * The returned pointers to name and value will be allocated by malloc()
  89253. * and shall be owned by the caller.
  89254. *
  89255. * \param entry An existing Vorbis comment entry.
  89256. * \param field_name The address of where the returned pointer to the
  89257. * field name will be stored.
  89258. * \param field_value The address of where the returned pointer to the
  89259. * field value will be stored.
  89260. * \assert
  89261. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89262. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89263. * \code field_name != NULL \endcode
  89264. * \code field_value != NULL \endcode
  89265. * \retval FLAC__bool
  89266. * \c false if memory allocation fails or \a entry does not comply with the
  89267. * Vorbis comment specification, else \c true.
  89268. */
  89269. 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);
  89270. /** Check if the given Vorbis comment entry's field name matches the given
  89271. * field name.
  89272. *
  89273. * \param entry An existing Vorbis comment entry.
  89274. * \param field_name The field name to check.
  89275. * \param field_name_length The length of \a field_name, not including the
  89276. * terminating \c NUL.
  89277. * \assert
  89278. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89279. * \retval FLAC__bool
  89280. * \c true if the field names match, else \c false
  89281. */
  89282. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89283. /** Find a Vorbis comment with the given field name.
  89284. *
  89285. * The search begins at entry number \a offset; use an offset of 0 to
  89286. * search from the beginning of the comment array.
  89287. *
  89288. * \param object A pointer to an existing VORBIS_COMMENT object.
  89289. * \param offset The offset into the comment array from where to start
  89290. * the search.
  89291. * \param field_name The field name of the comment to find.
  89292. * \assert
  89293. * \code object != NULL \endcode
  89294. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89295. * \code field_name != NULL \endcode
  89296. * \retval int
  89297. * The offset in the comment array of the first comment whose field
  89298. * name matches \a field_name, or \c -1 if no match was found.
  89299. */
  89300. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89301. /** Remove first Vorbis comment matching the given field name.
  89302. *
  89303. * \param object A pointer to an existing VORBIS_COMMENT object.
  89304. * \param field_name The field name of comment to delete.
  89305. * \assert
  89306. * \code object != NULL \endcode
  89307. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89308. * \retval int
  89309. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89310. * \c 1 for one matching entry deleted.
  89311. */
  89312. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89313. /** Remove all Vorbis comments matching the given field name.
  89314. *
  89315. * \param object A pointer to an existing VORBIS_COMMENT object.
  89316. * \param field_name The field name of comments to delete.
  89317. * \assert
  89318. * \code object != NULL \endcode
  89319. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89320. * \retval int
  89321. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89322. * else the number of matching entries deleted.
  89323. */
  89324. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89325. /** Create a new CUESHEET track instance.
  89326. *
  89327. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89328. *
  89329. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89330. * \c NULL if there was an error allocating memory, else the new instance.
  89331. */
  89332. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89333. /** Create a copy of an existing CUESHEET track object.
  89334. *
  89335. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89336. * object is also copied. The caller takes ownership of the new object and
  89337. * is responsible for freeing it with
  89338. * FLAC__metadata_object_cuesheet_track_delete().
  89339. *
  89340. * \param object Pointer to object to copy.
  89341. * \assert
  89342. * \code object != NULL \endcode
  89343. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89344. * \c NULL if there was an error allocating memory, else the new instance.
  89345. */
  89346. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89347. /** Delete a CUESHEET track object
  89348. *
  89349. * \param object A pointer to an existing CUESHEET track object.
  89350. * \assert
  89351. * \code object != NULL \endcode
  89352. */
  89353. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89354. /** Resize a track's index point array.
  89355. *
  89356. * If the size shrinks, elements will truncated; if it grows, new blank
  89357. * indices will be added to the end.
  89358. *
  89359. * \param object A pointer to an existing CUESHEET object.
  89360. * \param track_num The index of the track to modify. NOTE: this is not
  89361. * necessarily the same as the track's \a number field.
  89362. * \param new_num_indices The desired length of the array; may be \c 0.
  89363. * \assert
  89364. * \code object != NULL \endcode
  89365. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89366. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89367. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89368. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89369. * \retval FLAC__bool
  89370. * \c false if memory allocation error, else \c true.
  89371. */
  89372. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89373. /** Insert an index point in a CUESHEET track at the given index.
  89374. *
  89375. * \param object A pointer to an existing CUESHEET object.
  89376. * \param track_num The index of the track to modify. NOTE: this is not
  89377. * necessarily the same as the track's \a number field.
  89378. * \param index_num The index into the track's index array at which to
  89379. * insert the index point. NOTE: this is not necessarily
  89380. * the same as the index point's \a number field. The
  89381. * indices at and after \a index_num move right one
  89382. * position. To append an index point to the end, set
  89383. * \a index_num to
  89384. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89385. * \param index The index point to insert.
  89386. * \assert
  89387. * \code object != NULL \endcode
  89388. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89389. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89390. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89391. * \retval FLAC__bool
  89392. * \c false if realloc() fails, else \c true.
  89393. */
  89394. 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);
  89395. /** Insert a blank index point in a CUESHEET track at the given index.
  89396. *
  89397. * A blank index point is one in which all field values are zero.
  89398. *
  89399. * \param object A pointer to an existing CUESHEET object.
  89400. * \param track_num The index of the track to modify. NOTE: this is not
  89401. * necessarily the same as the track's \a number field.
  89402. * \param index_num The index into the track's index array at which to
  89403. * insert the index point. NOTE: this is not necessarily
  89404. * the same as the index point's \a number field. The
  89405. * indices at and after \a index_num move right one
  89406. * position. To append an index point to the end, set
  89407. * \a index_num to
  89408. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89409. * \assert
  89410. * \code object != NULL \endcode
  89411. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89412. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89413. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89414. * \retval FLAC__bool
  89415. * \c false if realloc() fails, else \c true.
  89416. */
  89417. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89418. /** Delete an index point in a CUESHEET track at the given index.
  89419. *
  89420. * \param object A pointer to an existing CUESHEET object.
  89421. * \param track_num The index into the track array of the track to
  89422. * modify. NOTE: this is not necessarily the same
  89423. * as the track's \a number field.
  89424. * \param index_num The index into the track's index array of the index
  89425. * to delete. NOTE: this is not necessarily the same
  89426. * as the index's \a number field.
  89427. * \assert
  89428. * \code object != NULL \endcode
  89429. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89430. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89431. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89432. * \retval FLAC__bool
  89433. * \c false if realloc() fails, else \c true.
  89434. */
  89435. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89436. /** Resize the track array.
  89437. *
  89438. * If the size shrinks, elements will truncated; if it grows, new blank
  89439. * tracks will be added to the end.
  89440. *
  89441. * \param object A pointer to an existing CUESHEET object.
  89442. * \param new_num_tracks The desired length of the array; may be \c 0.
  89443. * \assert
  89444. * \code object != NULL \endcode
  89445. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89446. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89447. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89448. * \retval FLAC__bool
  89449. * \c false if memory allocation error, else \c true.
  89450. */
  89451. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89452. /** Sets a track in a CUESHEET block.
  89453. *
  89454. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89455. * takes ownership of the \a track pointer.
  89456. *
  89457. * \param object A pointer to an existing CUESHEET object.
  89458. * \param track_num Index into track array to set. NOTE: this is not
  89459. * necessarily the same as the track's \a number field.
  89460. * \param track The track to set the track to. You may safely pass in
  89461. * a const pointer if \a copy is \c true.
  89462. * \param copy See above.
  89463. * \assert
  89464. * \code object != NULL \endcode
  89465. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89466. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89467. * \code (track->indices != NULL && track->num_indices > 0) ||
  89468. * (track->indices == NULL && track->num_indices == 0)
  89469. * \retval FLAC__bool
  89470. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89471. */
  89472. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89473. /** Insert a track in a CUESHEET block at the given index.
  89474. *
  89475. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89476. * takes ownership of the \a track pointer.
  89477. *
  89478. * \param object A pointer to an existing CUESHEET object.
  89479. * \param track_num The index at which to insert the track. NOTE: this
  89480. * is not necessarily the same as the track's \a number
  89481. * field. The tracks at and after \a track_num move right
  89482. * one position. To append a track to the end, set
  89483. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89484. * \param track The track to insert. You may safely pass in a const
  89485. * pointer if \a copy is \c true.
  89486. * \param copy See above.
  89487. * \assert
  89488. * \code object != NULL \endcode
  89489. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89490. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89491. * \retval FLAC__bool
  89492. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89493. */
  89494. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89495. /** Insert a blank track in a CUESHEET block at the given index.
  89496. *
  89497. * A blank track is one in which all field values are zero.
  89498. *
  89499. * \param object A pointer to an existing CUESHEET object.
  89500. * \param track_num The index at which to insert the track. NOTE: this
  89501. * is not necessarily the same as the track's \a number
  89502. * field. The tracks at and after \a track_num move right
  89503. * one position. To append a track to the end, set
  89504. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89505. * \assert
  89506. * \code object != NULL \endcode
  89507. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89508. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89509. * \retval FLAC__bool
  89510. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89511. */
  89512. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89513. /** Delete a track in a CUESHEET block at the given index.
  89514. *
  89515. * \param object A pointer to an existing CUESHEET object.
  89516. * \param track_num The index into the track array of the track to
  89517. * delete. NOTE: this is not necessarily the same
  89518. * as the track's \a number field.
  89519. * \assert
  89520. * \code object != NULL \endcode
  89521. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89522. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89523. * \retval FLAC__bool
  89524. * \c false if realloc() fails, else \c true.
  89525. */
  89526. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89527. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89528. * See the format specification for limits on the contents of the
  89529. * cue sheet.
  89530. *
  89531. * \param object A pointer to an existing CUESHEET object.
  89532. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89533. * stringent requirements for a CD-DA (audio) disc.
  89534. * \param violation Address of a pointer to a string. If there is a
  89535. * violation, a pointer to a string explanation of the
  89536. * violation will be returned here. \a violation may be
  89537. * \c NULL if you don't need the returned string. Do not
  89538. * free the returned string; it will always point to static
  89539. * data.
  89540. * \assert
  89541. * \code object != NULL \endcode
  89542. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89543. * \retval FLAC__bool
  89544. * \c false if cue sheet is illegal, else \c true.
  89545. */
  89546. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89547. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89548. * assumes the cue sheet corresponds to a CD; the result is undefined
  89549. * if the cuesheet's is_cd bit is not set.
  89550. *
  89551. * \param object A pointer to an existing CUESHEET object.
  89552. * \assert
  89553. * \code object != NULL \endcode
  89554. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89555. * \retval FLAC__uint32
  89556. * The unsigned integer representation of the CDDB/freedb ID
  89557. */
  89558. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89559. /** Sets the MIME type of a PICTURE block.
  89560. *
  89561. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89562. * takes ownership of the pointer. The existing string will be freed if this
  89563. * function is successful, otherwise the original string will remain if \a copy
  89564. * is \c true and malloc() fails.
  89565. *
  89566. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89567. *
  89568. * \param object A pointer to an existing PICTURE object.
  89569. * \param mime_type A pointer to the MIME type string. The string must be
  89570. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89571. * is done.
  89572. * \param copy See above.
  89573. * \assert
  89574. * \code object != NULL \endcode
  89575. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89576. * \code (mime_type != NULL) \endcode
  89577. * \retval FLAC__bool
  89578. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89579. */
  89580. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89581. /** Sets the description of a PICTURE block.
  89582. *
  89583. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89584. * takes ownership of the pointer. The existing string will be freed if this
  89585. * function is successful, otherwise the original string will remain if \a copy
  89586. * is \c true and malloc() fails.
  89587. *
  89588. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89589. *
  89590. * \param object A pointer to an existing PICTURE object.
  89591. * \param description A pointer to the description string. The string must be
  89592. * valid UTF-8, NUL-terminated. No validation is done.
  89593. * \param copy See above.
  89594. * \assert
  89595. * \code object != NULL \endcode
  89596. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89597. * \code (description != NULL) \endcode
  89598. * \retval FLAC__bool
  89599. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89600. */
  89601. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89602. /** Sets the picture data of a PICTURE block.
  89603. *
  89604. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89605. * takes ownership of the pointer. Also sets the \a data_length field of the
  89606. * metadata object to what is passed in as the \a length parameter. The
  89607. * existing data will be freed if this function is successful, otherwise the
  89608. * original data and data_length will remain if \a copy is \c true and
  89609. * malloc() fails.
  89610. *
  89611. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89612. *
  89613. * \param object A pointer to an existing PICTURE object.
  89614. * \param data A pointer to the data to set.
  89615. * \param length The length of \a data in bytes.
  89616. * \param copy See above.
  89617. * \assert
  89618. * \code object != NULL \endcode
  89619. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89620. * \code (data != NULL && length > 0) ||
  89621. * (data == NULL && length == 0 && copy == false) \endcode
  89622. * \retval FLAC__bool
  89623. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89624. */
  89625. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89626. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89627. * See the format specification for limits on the contents of the
  89628. * PICTURE block.
  89629. *
  89630. * \param object A pointer to existing PICTURE block to be checked.
  89631. * \param violation Address of a pointer to a string. If there is a
  89632. * violation, a pointer to a string explanation of the
  89633. * violation will be returned here. \a violation may be
  89634. * \c NULL if you don't need the returned string. Do not
  89635. * free the returned string; it will always point to static
  89636. * data.
  89637. * \assert
  89638. * \code object != NULL \endcode
  89639. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89640. * \retval FLAC__bool
  89641. * \c false if PICTURE block is illegal, else \c true.
  89642. */
  89643. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89644. /* \} */
  89645. #ifdef __cplusplus
  89646. }
  89647. #endif
  89648. #endif
  89649. /*** End of inlined file: metadata.h ***/
  89650. /*** Start of inlined file: stream_decoder.h ***/
  89651. #ifndef FLAC__STREAM_DECODER_H
  89652. #define FLAC__STREAM_DECODER_H
  89653. #include <stdio.h> /* for FILE */
  89654. #ifdef __cplusplus
  89655. extern "C" {
  89656. #endif
  89657. /** \file include/FLAC/stream_decoder.h
  89658. *
  89659. * \brief
  89660. * This module contains the functions which implement the stream
  89661. * decoder.
  89662. *
  89663. * See the detailed documentation in the
  89664. * \link flac_stream_decoder stream decoder \endlink module.
  89665. */
  89666. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89667. * \ingroup flac
  89668. *
  89669. * \brief
  89670. * This module describes the decoder layers provided by libFLAC.
  89671. *
  89672. * The stream decoder can be used to decode complete streams either from
  89673. * the client via callbacks, or directly from a file, depending on how
  89674. * it is initialized. When decoding via callbacks, the client provides
  89675. * callbacks for reading FLAC data and writing decoded samples, and
  89676. * handling metadata and errors. If the client also supplies seek-related
  89677. * callback, the decoder function for sample-accurate seeking within the
  89678. * FLAC input is also available. When decoding from a file, the client
  89679. * needs only supply a filename or open \c FILE* and write/metadata/error
  89680. * callbacks; the rest of the callbacks are supplied internally. For more
  89681. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89682. */
  89683. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89684. * \ingroup flac_decoder
  89685. *
  89686. * \brief
  89687. * This module contains the functions which implement the stream
  89688. * decoder.
  89689. *
  89690. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89691. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89692. *
  89693. * The basic usage of this decoder is as follows:
  89694. * - The program creates an instance of a decoder using
  89695. * FLAC__stream_decoder_new().
  89696. * - The program overrides the default settings using
  89697. * FLAC__stream_decoder_set_*() functions.
  89698. * - The program initializes the instance to validate the settings and
  89699. * prepare for decoding using
  89700. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89701. * or FLAC__stream_decoder_init_file() for native FLAC,
  89702. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89703. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89704. * - The program calls the FLAC__stream_decoder_process_*() functions
  89705. * to decode data, which subsequently calls the callbacks.
  89706. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89707. * which flushes the input and output and resets the decoder to the
  89708. * uninitialized state.
  89709. * - The instance may be used again or deleted with
  89710. * FLAC__stream_decoder_delete().
  89711. *
  89712. * In more detail, the program will create a new instance by calling
  89713. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89714. * functions to override the default decoder options, and call
  89715. * one of the FLAC__stream_decoder_init_*() functions.
  89716. *
  89717. * There are three initialization functions for native FLAC, one for
  89718. * setting up the decoder to decode FLAC data from the client via
  89719. * callbacks, and two for decoding directly from a FLAC file.
  89720. *
  89721. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89722. * You must also supply several callbacks for handling I/O. Some (like
  89723. * seeking) are optional, depending on the capabilities of the input.
  89724. *
  89725. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89726. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89727. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89728. * the other callbacks internally.
  89729. *
  89730. * There are three similarly-named init functions for decoding from Ogg
  89731. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89732. * library has been built with Ogg support.
  89733. *
  89734. * Once the decoder is initialized, your program will call one of several
  89735. * functions to start the decoding process:
  89736. *
  89737. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89738. * most one metadata block or audio frame and return, calling either the
  89739. * metadata callback or write callback, respectively, once. If the decoder
  89740. * loses sync it will return with only the error callback being called.
  89741. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89742. * to process the stream from the current location and stop upon reaching
  89743. * the first audio frame. The client will get one metadata, write, or error
  89744. * callback per metadata block, audio frame, or sync error, respectively.
  89745. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89746. * to process the stream from the current location until the read callback
  89747. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89748. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89749. * write, or error callback per metadata block, audio frame, or sync error,
  89750. * respectively.
  89751. *
  89752. * When the decoder has finished decoding (normally or through an abort),
  89753. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89754. * ensures the decoder is in the correct state and frees memory. Then the
  89755. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89756. * again to decode another stream.
  89757. *
  89758. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89759. * At any point after the stream decoder has been initialized, the client can
  89760. * call this function to seek to an exact sample within the stream.
  89761. * Subsequently, the first time the write callback is called it will be
  89762. * passed a (possibly partial) block starting at that sample.
  89763. *
  89764. * If the client cannot seek via the callback interface provided, but still
  89765. * has another way of seeking, it can flush the decoder using
  89766. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89767. * through the read callback.
  89768. *
  89769. * The stream decoder also provides MD5 signature checking. If this is
  89770. * turned on before initialization, FLAC__stream_decoder_finish() will
  89771. * report when the decoded MD5 signature does not match the one stored
  89772. * in the STREAMINFO block. MD5 checking is automatically turned off
  89773. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89774. * in the STREAMINFO block or when a seek is attempted.
  89775. *
  89776. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89777. * attention. By default, the decoder only calls the metadata_callback for
  89778. * the STREAMINFO block. These functions allow you to tell the decoder
  89779. * explicitly which blocks to parse and return via the metadata_callback
  89780. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89781. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89782. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89783. * which blocks to return. Remember that metadata blocks can potentially
  89784. * be big (for example, cover art) so filtering out the ones you don't
  89785. * use can reduce the memory requirements of the decoder. Also note the
  89786. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89787. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89788. * filtering APPLICATION blocks based on the application ID.
  89789. *
  89790. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89791. * they still can legally be filtered from the metadata_callback.
  89792. *
  89793. * \note
  89794. * The "set" functions may only be called when the decoder is in the
  89795. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89796. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89797. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89798. * return \c true, otherwise \c false.
  89799. *
  89800. * \note
  89801. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89802. * defaults, including the callbacks.
  89803. *
  89804. * \{
  89805. */
  89806. /** State values for a FLAC__StreamDecoder
  89807. *
  89808. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89809. */
  89810. typedef enum {
  89811. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89812. /**< The decoder is ready to search for metadata. */
  89813. FLAC__STREAM_DECODER_READ_METADATA,
  89814. /**< The decoder is ready to or is in the process of reading metadata. */
  89815. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89816. /**< The decoder is ready to or is in the process of searching for the
  89817. * frame sync code.
  89818. */
  89819. FLAC__STREAM_DECODER_READ_FRAME,
  89820. /**< The decoder is ready to or is in the process of reading a frame. */
  89821. FLAC__STREAM_DECODER_END_OF_STREAM,
  89822. /**< The decoder has reached the end of the stream. */
  89823. FLAC__STREAM_DECODER_OGG_ERROR,
  89824. /**< An error occurred in the underlying Ogg layer. */
  89825. FLAC__STREAM_DECODER_SEEK_ERROR,
  89826. /**< An error occurred while seeking. The decoder must be flushed
  89827. * with FLAC__stream_decoder_flush() or reset with
  89828. * FLAC__stream_decoder_reset() before decoding can continue.
  89829. */
  89830. FLAC__STREAM_DECODER_ABORTED,
  89831. /**< The decoder was aborted by the read callback. */
  89832. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89833. /**< An error occurred allocating memory. The decoder is in an invalid
  89834. * state and can no longer be used.
  89835. */
  89836. FLAC__STREAM_DECODER_UNINITIALIZED
  89837. /**< The decoder is in the uninitialized state; one of the
  89838. * FLAC__stream_decoder_init_*() functions must be called before samples
  89839. * can be processed.
  89840. */
  89841. } FLAC__StreamDecoderState;
  89842. /** Maps a FLAC__StreamDecoderState to a C string.
  89843. *
  89844. * Using a FLAC__StreamDecoderState as the index to this array
  89845. * will give the string equivalent. The contents should not be modified.
  89846. */
  89847. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89848. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89849. */
  89850. typedef enum {
  89851. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89852. /**< Initialization was successful. */
  89853. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89854. /**< The library was not compiled with support for the given container
  89855. * format.
  89856. */
  89857. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89858. /**< A required callback was not supplied. */
  89859. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89860. /**< An error occurred allocating memory. */
  89861. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89862. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89863. * FLAC__stream_decoder_init_ogg_file(). */
  89864. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89865. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89866. * already initialized, usually because
  89867. * FLAC__stream_decoder_finish() was not called.
  89868. */
  89869. } FLAC__StreamDecoderInitStatus;
  89870. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89871. *
  89872. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89873. * will give the string equivalent. The contents should not be modified.
  89874. */
  89875. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89876. /** Return values for the FLAC__StreamDecoder read callback.
  89877. */
  89878. typedef enum {
  89879. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89880. /**< The read was OK and decoding can continue. */
  89881. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89882. /**< The read was attempted while at the end of the stream. Note that
  89883. * the client must only return this value when the read callback was
  89884. * called when already at the end of the stream. Otherwise, if the read
  89885. * itself moves to the end of the stream, the client should still return
  89886. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89887. * the next read callback it should return
  89888. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89889. * of \c 0.
  89890. */
  89891. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89892. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89893. } FLAC__StreamDecoderReadStatus;
  89894. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89895. *
  89896. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89897. * will give the string equivalent. The contents should not be modified.
  89898. */
  89899. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89900. /** Return values for the FLAC__StreamDecoder seek callback.
  89901. */
  89902. typedef enum {
  89903. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89904. /**< The seek was OK and decoding can continue. */
  89905. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89906. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89907. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89908. /**< Client does not support seeking. */
  89909. } FLAC__StreamDecoderSeekStatus;
  89910. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89911. *
  89912. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89913. * will give the string equivalent. The contents should not be modified.
  89914. */
  89915. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89916. /** Return values for the FLAC__StreamDecoder tell callback.
  89917. */
  89918. typedef enum {
  89919. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89920. /**< The tell was OK and decoding can continue. */
  89921. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89922. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89923. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89924. /**< Client does not support telling the position. */
  89925. } FLAC__StreamDecoderTellStatus;
  89926. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89927. *
  89928. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89929. * will give the string equivalent. The contents should not be modified.
  89930. */
  89931. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89932. /** Return values for the FLAC__StreamDecoder length callback.
  89933. */
  89934. typedef enum {
  89935. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89936. /**< The length call was OK and decoding can continue. */
  89937. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89938. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89939. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89940. /**< Client does not support reporting the length. */
  89941. } FLAC__StreamDecoderLengthStatus;
  89942. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89943. *
  89944. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89945. * will give the string equivalent. The contents should not be modified.
  89946. */
  89947. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89948. /** Return values for the FLAC__StreamDecoder write callback.
  89949. */
  89950. typedef enum {
  89951. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89952. /**< The write was OK and decoding can continue. */
  89953. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89954. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89955. } FLAC__StreamDecoderWriteStatus;
  89956. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89957. *
  89958. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89959. * will give the string equivalent. The contents should not be modified.
  89960. */
  89961. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89962. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89963. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89964. * all. The rest could be caused by bad sync (false synchronization on
  89965. * data that is not the start of a frame) or corrupted data. The error
  89966. * itself is the decoder's best guess at what happened assuming a correct
  89967. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89968. * could be caused by a correct sync on the start of a frame, but some
  89969. * data in the frame header was corrupted. Or it could be the result of
  89970. * syncing on a point the stream that looked like the starting of a frame
  89971. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89972. * could be because the decoder encountered a valid frame made by a future
  89973. * version of the encoder which it cannot parse, or because of a false
  89974. * sync making it appear as though an encountered frame was generated by
  89975. * a future encoder.
  89976. */
  89977. typedef enum {
  89978. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89979. /**< An error in the stream caused the decoder to lose synchronization. */
  89980. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89981. /**< The decoder encountered a corrupted frame header. */
  89982. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89983. /**< The frame's data did not match the CRC in the footer. */
  89984. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89985. /**< The decoder encountered reserved fields in use in the stream. */
  89986. } FLAC__StreamDecoderErrorStatus;
  89987. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89988. *
  89989. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89990. * will give the string equivalent. The contents should not be modified.
  89991. */
  89992. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89993. /***********************************************************************
  89994. *
  89995. * class FLAC__StreamDecoder
  89996. *
  89997. ***********************************************************************/
  89998. struct FLAC__StreamDecoderProtected;
  89999. struct FLAC__StreamDecoderPrivate;
  90000. /** The opaque structure definition for the stream decoder type.
  90001. * See the \link flac_stream_decoder stream decoder module \endlink
  90002. * for a detailed description.
  90003. */
  90004. typedef struct {
  90005. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90006. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90007. } FLAC__StreamDecoder;
  90008. /** Signature for the read callback.
  90009. *
  90010. * A function pointer matching this signature must be passed to
  90011. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90012. * called when the decoder needs more input data. The address of the
  90013. * buffer to be filled is supplied, along with the number of bytes the
  90014. * buffer can hold. The callback may choose to supply less data and
  90015. * modify the byte count but must be careful not to overflow the buffer.
  90016. * The callback then returns a status code chosen from
  90017. * FLAC__StreamDecoderReadStatus.
  90018. *
  90019. * Here is an example of a read callback for stdio streams:
  90020. * \code
  90021. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90022. * {
  90023. * FILE *file = ((MyClientData*)client_data)->file;
  90024. * if(*bytes > 0) {
  90025. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90026. * if(ferror(file))
  90027. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  90028. * else if(*bytes == 0)
  90029. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  90030. * else
  90031. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  90032. * }
  90033. * else
  90034. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  90035. * }
  90036. * \endcode
  90037. *
  90038. * \note In general, FLAC__StreamDecoder functions which change the
  90039. * state should not be called on the \a decoder while in the callback.
  90040. *
  90041. * \param decoder The decoder instance calling the callback.
  90042. * \param buffer A pointer to a location for the callee to store
  90043. * data to be decoded.
  90044. * \param bytes A pointer to the size of the buffer. On entry
  90045. * to the callback, it contains the maximum number
  90046. * of bytes that may be stored in \a buffer. The
  90047. * callee must set it to the actual number of bytes
  90048. * stored (0 in case of error or end-of-stream) before
  90049. * returning.
  90050. * \param client_data The callee's client data set through
  90051. * FLAC__stream_decoder_init_*().
  90052. * \retval FLAC__StreamDecoderReadStatus
  90053. * The callee's return status. Note that the callback should return
  90054. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  90055. * zero bytes were read and there is no more data to be read.
  90056. */
  90057. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90058. /** Signature for the seek callback.
  90059. *
  90060. * A function pointer matching this signature may be passed to
  90061. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90062. * called when the decoder needs to seek the input stream. The decoder
  90063. * will pass the absolute byte offset to seek to, 0 meaning the
  90064. * beginning of the stream.
  90065. *
  90066. * Here is an example of a seek callback for stdio streams:
  90067. * \code
  90068. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90069. * {
  90070. * FILE *file = ((MyClientData*)client_data)->file;
  90071. * if(file == stdin)
  90072. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  90073. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90074. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  90075. * else
  90076. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  90077. * }
  90078. * \endcode
  90079. *
  90080. * \note In general, FLAC__StreamDecoder functions which change the
  90081. * state should not be called on the \a decoder while in the callback.
  90082. *
  90083. * \param decoder The decoder instance calling the callback.
  90084. * \param absolute_byte_offset The offset from the beginning of the stream
  90085. * to seek to.
  90086. * \param client_data The callee's client data set through
  90087. * FLAC__stream_decoder_init_*().
  90088. * \retval FLAC__StreamDecoderSeekStatus
  90089. * The callee's return status.
  90090. */
  90091. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90092. /** Signature for the tell callback.
  90093. *
  90094. * A function pointer matching this signature may be passed to
  90095. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90096. * called when the decoder wants to know the current position of the
  90097. * stream. The callback should return the byte offset from the
  90098. * beginning of the stream.
  90099. *
  90100. * Here is an example of a tell callback for stdio streams:
  90101. * \code
  90102. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90103. * {
  90104. * FILE *file = ((MyClientData*)client_data)->file;
  90105. * off_t pos;
  90106. * if(file == stdin)
  90107. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  90108. * else if((pos = ftello(file)) < 0)
  90109. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  90110. * else {
  90111. * *absolute_byte_offset = (FLAC__uint64)pos;
  90112. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  90113. * }
  90114. * }
  90115. * \endcode
  90116. *
  90117. * \note In general, FLAC__StreamDecoder functions which change the
  90118. * state should not be called on the \a decoder while in the callback.
  90119. *
  90120. * \param decoder The decoder instance calling the callback.
  90121. * \param absolute_byte_offset A pointer to storage for the current offset
  90122. * from the beginning of the stream.
  90123. * \param client_data The callee's client data set through
  90124. * FLAC__stream_decoder_init_*().
  90125. * \retval FLAC__StreamDecoderTellStatus
  90126. * The callee's return status.
  90127. */
  90128. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90129. /** Signature for the length callback.
  90130. *
  90131. * A function pointer matching this signature may be passed to
  90132. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90133. * called when the decoder wants to know the total length of the stream
  90134. * in bytes.
  90135. *
  90136. * Here is an example of a length callback for stdio streams:
  90137. * \code
  90138. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  90139. * {
  90140. * FILE *file = ((MyClientData*)client_data)->file;
  90141. * struct stat filestats;
  90142. *
  90143. * if(file == stdin)
  90144. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  90145. * else if(fstat(fileno(file), &filestats) != 0)
  90146. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  90147. * else {
  90148. * *stream_length = (FLAC__uint64)filestats.st_size;
  90149. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  90150. * }
  90151. * }
  90152. * \endcode
  90153. *
  90154. * \note In general, FLAC__StreamDecoder functions which change the
  90155. * state should not be called on the \a decoder while in the callback.
  90156. *
  90157. * \param decoder The decoder instance calling the callback.
  90158. * \param stream_length A pointer to storage for the length of the stream
  90159. * in bytes.
  90160. * \param client_data The callee's client data set through
  90161. * FLAC__stream_decoder_init_*().
  90162. * \retval FLAC__StreamDecoderLengthStatus
  90163. * The callee's return status.
  90164. */
  90165. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  90166. /** Signature for the EOF callback.
  90167. *
  90168. * A function pointer matching this signature may be passed to
  90169. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90170. * called when the decoder needs to know if the end of the stream has
  90171. * been reached.
  90172. *
  90173. * Here is an example of a EOF callback for stdio streams:
  90174. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90175. * \code
  90176. * {
  90177. * FILE *file = ((MyClientData*)client_data)->file;
  90178. * return feof(file)? true : false;
  90179. * }
  90180. * \endcode
  90181. *
  90182. * \note In general, FLAC__StreamDecoder functions which change the
  90183. * state should not be called on the \a decoder while in the callback.
  90184. *
  90185. * \param decoder The decoder instance calling the callback.
  90186. * \param client_data The callee's client data set through
  90187. * FLAC__stream_decoder_init_*().
  90188. * \retval FLAC__bool
  90189. * \c true if the currently at the end of the stream, else \c false.
  90190. */
  90191. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90192. /** Signature for the write callback.
  90193. *
  90194. * A function pointer matching this signature must be passed to one of
  90195. * the FLAC__stream_decoder_init_*() functions.
  90196. * The supplied function will be called when the decoder has decoded a
  90197. * single audio frame. The decoder will pass the frame metadata as well
  90198. * as an array of pointers (one for each channel) pointing to the
  90199. * decoded audio.
  90200. *
  90201. * \note In general, FLAC__StreamDecoder functions which change the
  90202. * state should not be called on the \a decoder while in the callback.
  90203. *
  90204. * \param decoder The decoder instance calling the callback.
  90205. * \param frame The description of the decoded frame. See
  90206. * FLAC__Frame.
  90207. * \param buffer An array of pointers to decoded channels of data.
  90208. * Each pointer will point to an array of signed
  90209. * samples of length \a frame->header.blocksize.
  90210. * Channels will be ordered according to the FLAC
  90211. * specification; see the documentation for the
  90212. * <A HREF="../format.html#frame_header">frame header</A>.
  90213. * \param client_data The callee's client data set through
  90214. * FLAC__stream_decoder_init_*().
  90215. * \retval FLAC__StreamDecoderWriteStatus
  90216. * The callee's return status.
  90217. */
  90218. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90219. /** Signature for the metadata callback.
  90220. *
  90221. * A function pointer matching this signature must be passed to one of
  90222. * the FLAC__stream_decoder_init_*() functions.
  90223. * The supplied function will be called when the decoder has decoded a
  90224. * metadata block. In a valid FLAC file there will always be one
  90225. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90226. * These will be supplied by the decoder in the same order as they
  90227. * appear in the stream and always before the first audio frame (i.e.
  90228. * write callback). The metadata block that is passed in must not be
  90229. * modified, and it doesn't live beyond the callback, so you should make
  90230. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90231. * elsewhere. Since metadata blocks can potentially be large, by
  90232. * default the decoder only calls the metadata callback for the
  90233. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90234. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90235. *
  90236. * \note In general, FLAC__StreamDecoder functions which change the
  90237. * state should not be called on the \a decoder while in the callback.
  90238. *
  90239. * \param decoder The decoder instance calling the callback.
  90240. * \param metadata The decoded metadata block.
  90241. * \param client_data The callee's client data set through
  90242. * FLAC__stream_decoder_init_*().
  90243. */
  90244. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90245. /** Signature for the error callback.
  90246. *
  90247. * A function pointer matching this signature must be passed to one of
  90248. * the FLAC__stream_decoder_init_*() functions.
  90249. * The supplied function will be called whenever an error occurs during
  90250. * decoding.
  90251. *
  90252. * \note In general, FLAC__StreamDecoder functions which change the
  90253. * state should not be called on the \a decoder while in the callback.
  90254. *
  90255. * \param decoder The decoder instance calling the callback.
  90256. * \param status The error encountered by the decoder.
  90257. * \param client_data The callee's client data set through
  90258. * FLAC__stream_decoder_init_*().
  90259. */
  90260. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90261. /***********************************************************************
  90262. *
  90263. * Class constructor/destructor
  90264. *
  90265. ***********************************************************************/
  90266. /** Create a new stream decoder instance. The instance is created with
  90267. * default settings; see the individual FLAC__stream_decoder_set_*()
  90268. * functions for each setting's default.
  90269. *
  90270. * \retval FLAC__StreamDecoder*
  90271. * \c NULL if there was an error allocating memory, else the new instance.
  90272. */
  90273. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90274. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90275. *
  90276. * \param decoder A pointer to an existing decoder.
  90277. * \assert
  90278. * \code decoder != NULL \endcode
  90279. */
  90280. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90281. /***********************************************************************
  90282. *
  90283. * Public class method prototypes
  90284. *
  90285. ***********************************************************************/
  90286. /** Set the serial number for the FLAC stream within the Ogg container.
  90287. * The default behavior is to use the serial number of the first Ogg
  90288. * page. Setting a serial number here will explicitly specify which
  90289. * stream is to be decoded.
  90290. *
  90291. * \note
  90292. * This does not need to be set for native FLAC decoding.
  90293. *
  90294. * \default \c use serial number of first page
  90295. * \param decoder A decoder instance to set.
  90296. * \param serial_number See above.
  90297. * \assert
  90298. * \code decoder != NULL \endcode
  90299. * \retval FLAC__bool
  90300. * \c false if the decoder is already initialized, else \c true.
  90301. */
  90302. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90303. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90304. * compute the MD5 signature of the unencoded audio data while decoding
  90305. * and compare it to the signature from the STREAMINFO block, if it
  90306. * exists, during FLAC__stream_decoder_finish().
  90307. *
  90308. * MD5 signature checking will be turned off (until the next
  90309. * FLAC__stream_decoder_reset()) if there is no signature in the
  90310. * STREAMINFO block or when a seek is attempted.
  90311. *
  90312. * Clients that do not use the MD5 check should leave this off to speed
  90313. * up decoding.
  90314. *
  90315. * \default \c false
  90316. * \param decoder A decoder instance to set.
  90317. * \param value Flag value (see above).
  90318. * \assert
  90319. * \code decoder != NULL \endcode
  90320. * \retval FLAC__bool
  90321. * \c false if the decoder is already initialized, else \c true.
  90322. */
  90323. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90324. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90325. *
  90326. * \default By default, only the \c STREAMINFO block is returned via the
  90327. * metadata callback.
  90328. * \param decoder A decoder instance to set.
  90329. * \param type See above.
  90330. * \assert
  90331. * \code decoder != NULL \endcode
  90332. * \a type is valid
  90333. * \retval FLAC__bool
  90334. * \c false if the decoder is already initialized, else \c true.
  90335. */
  90336. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90337. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90338. * given \a id.
  90339. *
  90340. * \default By default, only the \c STREAMINFO block is returned via the
  90341. * metadata callback.
  90342. * \param decoder A decoder instance to set.
  90343. * \param id See above.
  90344. * \assert
  90345. * \code decoder != NULL \endcode
  90346. * \code id != NULL \endcode
  90347. * \retval FLAC__bool
  90348. * \c false if the decoder is already initialized, else \c true.
  90349. */
  90350. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90351. /** Direct the decoder to pass on all metadata blocks of any type.
  90352. *
  90353. * \default By default, only the \c STREAMINFO block is returned via the
  90354. * metadata callback.
  90355. * \param decoder A decoder instance to set.
  90356. * \assert
  90357. * \code decoder != NULL \endcode
  90358. * \retval FLAC__bool
  90359. * \c false if the decoder is already initialized, else \c true.
  90360. */
  90361. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90362. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90363. *
  90364. * \default By default, only the \c STREAMINFO block is returned via the
  90365. * metadata callback.
  90366. * \param decoder A decoder instance to set.
  90367. * \param type See above.
  90368. * \assert
  90369. * \code decoder != NULL \endcode
  90370. * \a type is valid
  90371. * \retval FLAC__bool
  90372. * \c false if the decoder is already initialized, else \c true.
  90373. */
  90374. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90375. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90376. * the given \a id.
  90377. *
  90378. * \default By default, only the \c STREAMINFO block is returned via the
  90379. * metadata callback.
  90380. * \param decoder A decoder instance to set.
  90381. * \param id See above.
  90382. * \assert
  90383. * \code decoder != NULL \endcode
  90384. * \code id != NULL \endcode
  90385. * \retval FLAC__bool
  90386. * \c false if the decoder is already initialized, else \c true.
  90387. */
  90388. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90389. /** Direct the decoder to filter out all metadata blocks of any type.
  90390. *
  90391. * \default By default, only the \c STREAMINFO block is returned via the
  90392. * metadata callback.
  90393. * \param decoder A decoder instance to set.
  90394. * \assert
  90395. * \code decoder != NULL \endcode
  90396. * \retval FLAC__bool
  90397. * \c false if the decoder is already initialized, else \c true.
  90398. */
  90399. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90400. /** Get the current decoder state.
  90401. *
  90402. * \param decoder A decoder instance to query.
  90403. * \assert
  90404. * \code decoder != NULL \endcode
  90405. * \retval FLAC__StreamDecoderState
  90406. * The current decoder state.
  90407. */
  90408. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90409. /** Get the current decoder state as a C string.
  90410. *
  90411. * \param decoder A decoder instance to query.
  90412. * \assert
  90413. * \code decoder != NULL \endcode
  90414. * \retval const char *
  90415. * The decoder state as a C string. Do not modify the contents.
  90416. */
  90417. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90418. /** Get the "MD5 signature checking" flag.
  90419. * This is the value of the setting, not whether or not the decoder is
  90420. * currently checking the MD5 (remember, it can be turned off automatically
  90421. * by a seek). When the decoder is reset the flag will be restored to the
  90422. * value returned by this function.
  90423. *
  90424. * \param decoder A decoder instance to query.
  90425. * \assert
  90426. * \code decoder != NULL \endcode
  90427. * \retval FLAC__bool
  90428. * See above.
  90429. */
  90430. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90431. /** Get the total number of samples in the stream being decoded.
  90432. * Will only be valid after decoding has started and will contain the
  90433. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90434. *
  90435. * \param decoder A decoder instance to query.
  90436. * \assert
  90437. * \code decoder != NULL \endcode
  90438. * \retval unsigned
  90439. * See above.
  90440. */
  90441. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90442. /** Get the current number of channels in the stream being decoded.
  90443. * Will only be valid after decoding has started and will contain the
  90444. * value from the most recently decoded frame header.
  90445. *
  90446. * \param decoder A decoder instance to query.
  90447. * \assert
  90448. * \code decoder != NULL \endcode
  90449. * \retval unsigned
  90450. * See above.
  90451. */
  90452. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90453. /** Get the current channel assignment in the stream being decoded.
  90454. * Will only be valid after decoding has started and will contain the
  90455. * value from the most recently decoded frame header.
  90456. *
  90457. * \param decoder A decoder instance to query.
  90458. * \assert
  90459. * \code decoder != NULL \endcode
  90460. * \retval FLAC__ChannelAssignment
  90461. * See above.
  90462. */
  90463. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90464. /** Get the current sample resolution in the stream being decoded.
  90465. * Will only be valid after decoding has started and will contain the
  90466. * value from the most recently decoded frame header.
  90467. *
  90468. * \param decoder A decoder instance to query.
  90469. * \assert
  90470. * \code decoder != NULL \endcode
  90471. * \retval unsigned
  90472. * See above.
  90473. */
  90474. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90475. /** Get the current sample rate in Hz of the stream being decoded.
  90476. * Will only be valid after decoding has started and will contain the
  90477. * value from the most recently decoded frame header.
  90478. *
  90479. * \param decoder A decoder instance to query.
  90480. * \assert
  90481. * \code decoder != NULL \endcode
  90482. * \retval unsigned
  90483. * See above.
  90484. */
  90485. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90486. /** Get the current blocksize of the stream being decoded.
  90487. * Will only be valid after decoding has started and will contain the
  90488. * value from the most recently decoded frame header.
  90489. *
  90490. * \param decoder A decoder instance to query.
  90491. * \assert
  90492. * \code decoder != NULL \endcode
  90493. * \retval unsigned
  90494. * See above.
  90495. */
  90496. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90497. /** Returns the decoder's current read position within the stream.
  90498. * The position is the byte offset from the start of the stream.
  90499. * Bytes before this position have been fully decoded. Note that
  90500. * there may still be undecoded bytes in the decoder's read FIFO.
  90501. * The returned position is correct even after a seek.
  90502. *
  90503. * \warning This function currently only works for native FLAC,
  90504. * not Ogg FLAC streams.
  90505. *
  90506. * \param decoder A decoder instance to query.
  90507. * \param position Address at which to return the desired position.
  90508. * \assert
  90509. * \code decoder != NULL \endcode
  90510. * \code position != NULL \endcode
  90511. * \retval FLAC__bool
  90512. * \c true if successful, \c false if the stream is not native FLAC,
  90513. * or there was an error from the 'tell' callback or it returned
  90514. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90515. */
  90516. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90517. /** Initialize the decoder instance to decode native FLAC streams.
  90518. *
  90519. * This flavor of initialization sets up the decoder to decode from a
  90520. * native FLAC stream. I/O is performed via callbacks to the client.
  90521. * For decoding from a plain file via filename or open FILE*,
  90522. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90523. * provide a simpler interface.
  90524. *
  90525. * This function should be called after FLAC__stream_decoder_new() and
  90526. * FLAC__stream_decoder_set_*() but before any of the
  90527. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90528. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90529. * if initialization succeeded.
  90530. *
  90531. * \param decoder An uninitialized decoder instance.
  90532. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90533. * pointer must not be \c NULL.
  90534. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90535. * pointer may be \c NULL if seeking is not
  90536. * supported. If \a seek_callback is not \c NULL then a
  90537. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90538. * Alternatively, a dummy seek callback that just
  90539. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90540. * may also be supplied, all though this is slightly
  90541. * less efficient for the decoder.
  90542. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90543. * pointer may be \c NULL if not supported by the client. If
  90544. * \a seek_callback is not \c NULL then a
  90545. * \a tell_callback must also be supplied.
  90546. * Alternatively, a dummy tell callback that just
  90547. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90548. * may also be supplied, all though this is slightly
  90549. * less efficient for the decoder.
  90550. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90551. * pointer may be \c NULL if not supported by the client. If
  90552. * \a seek_callback is not \c NULL then a
  90553. * \a length_callback must also be supplied.
  90554. * Alternatively, a dummy length callback that just
  90555. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90556. * may also be supplied, all though this is slightly
  90557. * less efficient for the decoder.
  90558. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90559. * pointer may be \c NULL if not supported by the client. If
  90560. * \a seek_callback is not \c NULL then a
  90561. * \a eof_callback must also be supplied.
  90562. * Alternatively, a dummy length callback that just
  90563. * returns \c false
  90564. * may also be supplied, all though this is slightly
  90565. * less efficient for the decoder.
  90566. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90567. * pointer must not be \c NULL.
  90568. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90569. * pointer may be \c NULL if the callback is not
  90570. * desired.
  90571. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90572. * pointer must not be \c NULL.
  90573. * \param client_data This value will be supplied to callbacks in their
  90574. * \a client_data argument.
  90575. * \assert
  90576. * \code decoder != NULL \endcode
  90577. * \retval FLAC__StreamDecoderInitStatus
  90578. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90579. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90580. */
  90581. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90582. FLAC__StreamDecoder *decoder,
  90583. FLAC__StreamDecoderReadCallback read_callback,
  90584. FLAC__StreamDecoderSeekCallback seek_callback,
  90585. FLAC__StreamDecoderTellCallback tell_callback,
  90586. FLAC__StreamDecoderLengthCallback length_callback,
  90587. FLAC__StreamDecoderEofCallback eof_callback,
  90588. FLAC__StreamDecoderWriteCallback write_callback,
  90589. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90590. FLAC__StreamDecoderErrorCallback error_callback,
  90591. void *client_data
  90592. );
  90593. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90594. *
  90595. * This flavor of initialization sets up the decoder to decode from a
  90596. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90597. * client. For decoding from a plain file via filename or open FILE*,
  90598. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90599. * provide a simpler interface.
  90600. *
  90601. * This function should be called after FLAC__stream_decoder_new() and
  90602. * FLAC__stream_decoder_set_*() but before any of the
  90603. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90604. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90605. * if initialization succeeded.
  90606. *
  90607. * \note Support for Ogg FLAC in the library is optional. If this
  90608. * library has been built without support for Ogg FLAC, this function
  90609. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90610. *
  90611. * \param decoder An uninitialized decoder instance.
  90612. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90613. * pointer must not be \c NULL.
  90614. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90615. * pointer may be \c NULL if seeking is not
  90616. * supported. If \a seek_callback is not \c NULL then a
  90617. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90618. * Alternatively, a dummy seek callback that just
  90619. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90620. * may also be supplied, all though this is slightly
  90621. * less efficient for the decoder.
  90622. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90623. * pointer may be \c NULL if not supported by the client. If
  90624. * \a seek_callback is not \c NULL then a
  90625. * \a tell_callback must also be supplied.
  90626. * Alternatively, a dummy tell callback that just
  90627. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90628. * may also be supplied, all though this is slightly
  90629. * less efficient for the decoder.
  90630. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90631. * pointer may be \c NULL if not supported by the client. If
  90632. * \a seek_callback is not \c NULL then a
  90633. * \a length_callback must also be supplied.
  90634. * Alternatively, a dummy length callback that just
  90635. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90636. * may also be supplied, all though this is slightly
  90637. * less efficient for the decoder.
  90638. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90639. * pointer may be \c NULL if not supported by the client. If
  90640. * \a seek_callback is not \c NULL then a
  90641. * \a eof_callback must also be supplied.
  90642. * Alternatively, a dummy length callback that just
  90643. * returns \c false
  90644. * may also be supplied, all though this is slightly
  90645. * less efficient for the decoder.
  90646. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90647. * pointer must not be \c NULL.
  90648. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90649. * pointer may be \c NULL if the callback is not
  90650. * desired.
  90651. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90652. * pointer must not be \c NULL.
  90653. * \param client_data This value will be supplied to callbacks in their
  90654. * \a client_data argument.
  90655. * \assert
  90656. * \code decoder != NULL \endcode
  90657. * \retval FLAC__StreamDecoderInitStatus
  90658. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90659. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90660. */
  90661. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90662. FLAC__StreamDecoder *decoder,
  90663. FLAC__StreamDecoderReadCallback read_callback,
  90664. FLAC__StreamDecoderSeekCallback seek_callback,
  90665. FLAC__StreamDecoderTellCallback tell_callback,
  90666. FLAC__StreamDecoderLengthCallback length_callback,
  90667. FLAC__StreamDecoderEofCallback eof_callback,
  90668. FLAC__StreamDecoderWriteCallback write_callback,
  90669. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90670. FLAC__StreamDecoderErrorCallback error_callback,
  90671. void *client_data
  90672. );
  90673. /** Initialize the decoder instance to decode native FLAC files.
  90674. *
  90675. * This flavor of initialization sets up the decoder to decode from a
  90676. * plain native FLAC file. For non-stdio streams, you must use
  90677. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90678. *
  90679. * This function should be called after FLAC__stream_decoder_new() and
  90680. * FLAC__stream_decoder_set_*() but before any of the
  90681. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90682. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90683. * if initialization succeeded.
  90684. *
  90685. * \param decoder An uninitialized decoder instance.
  90686. * \param file An open FLAC file. The file should have been
  90687. * opened with mode \c "rb" and rewound. The file
  90688. * becomes owned by the decoder and should not be
  90689. * manipulated by the client while decoding.
  90690. * Unless \a file is \c stdin, it will be closed
  90691. * when FLAC__stream_decoder_finish() is called.
  90692. * Note however that seeking will not work when
  90693. * decoding from \c stdout since it is not seekable.
  90694. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90695. * pointer must not be \c NULL.
  90696. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90697. * pointer may be \c NULL if the callback is not
  90698. * desired.
  90699. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90700. * pointer must not be \c NULL.
  90701. * \param client_data This value will be supplied to callbacks in their
  90702. * \a client_data argument.
  90703. * \assert
  90704. * \code decoder != NULL \endcode
  90705. * \code file != NULL \endcode
  90706. * \retval FLAC__StreamDecoderInitStatus
  90707. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90708. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90709. */
  90710. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90711. FLAC__StreamDecoder *decoder,
  90712. FILE *file,
  90713. FLAC__StreamDecoderWriteCallback write_callback,
  90714. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90715. FLAC__StreamDecoderErrorCallback error_callback,
  90716. void *client_data
  90717. );
  90718. /** Initialize the decoder instance to decode Ogg FLAC files.
  90719. *
  90720. * This flavor of initialization sets up the decoder to decode from a
  90721. * plain Ogg FLAC file. For non-stdio streams, you must use
  90722. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90723. *
  90724. * This function should be called after FLAC__stream_decoder_new() and
  90725. * FLAC__stream_decoder_set_*() but before any of the
  90726. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90727. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90728. * if initialization succeeded.
  90729. *
  90730. * \note Support for Ogg FLAC in the library is optional. If this
  90731. * library has been built without support for Ogg FLAC, this function
  90732. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90733. *
  90734. * \param decoder An uninitialized decoder instance.
  90735. * \param file An open FLAC file. The file should have been
  90736. * opened with mode \c "rb" and rewound. The file
  90737. * becomes owned by the decoder and should not be
  90738. * manipulated by the client while decoding.
  90739. * Unless \a file is \c stdin, it will be closed
  90740. * when FLAC__stream_decoder_finish() is called.
  90741. * Note however that seeking will not work when
  90742. * decoding from \c stdout since it is not seekable.
  90743. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90744. * pointer must not be \c NULL.
  90745. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90746. * pointer may be \c NULL if the callback is not
  90747. * desired.
  90748. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90749. * pointer must not be \c NULL.
  90750. * \param client_data This value will be supplied to callbacks in their
  90751. * \a client_data argument.
  90752. * \assert
  90753. * \code decoder != NULL \endcode
  90754. * \code file != NULL \endcode
  90755. * \retval FLAC__StreamDecoderInitStatus
  90756. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90757. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90758. */
  90759. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90760. FLAC__StreamDecoder *decoder,
  90761. FILE *file,
  90762. FLAC__StreamDecoderWriteCallback write_callback,
  90763. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90764. FLAC__StreamDecoderErrorCallback error_callback,
  90765. void *client_data
  90766. );
  90767. /** Initialize the decoder instance to decode native FLAC files.
  90768. *
  90769. * This flavor of initialization sets up the decoder to decode from a plain
  90770. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90771. * example, with Unicode filenames on Windows), you must use
  90772. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90773. * and provide callbacks for the I/O.
  90774. *
  90775. * This function should be called after FLAC__stream_decoder_new() and
  90776. * FLAC__stream_decoder_set_*() but before any of the
  90777. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90778. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90779. * if initialization succeeded.
  90780. *
  90781. * \param decoder An uninitialized decoder instance.
  90782. * \param filename The name of the file to decode from. The file will
  90783. * be opened with fopen(). Use \c NULL to decode from
  90784. * \c stdin. Note that \c stdin is not seekable.
  90785. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90786. * pointer must not be \c NULL.
  90787. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90788. * pointer may be \c NULL if the callback is not
  90789. * desired.
  90790. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90791. * pointer must not be \c NULL.
  90792. * \param client_data This value will be supplied to callbacks in their
  90793. * \a client_data argument.
  90794. * \assert
  90795. * \code decoder != NULL \endcode
  90796. * \retval FLAC__StreamDecoderInitStatus
  90797. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90798. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90799. */
  90800. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90801. FLAC__StreamDecoder *decoder,
  90802. const char *filename,
  90803. FLAC__StreamDecoderWriteCallback write_callback,
  90804. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90805. FLAC__StreamDecoderErrorCallback error_callback,
  90806. void *client_data
  90807. );
  90808. /** Initialize the decoder instance to decode Ogg FLAC files.
  90809. *
  90810. * This flavor of initialization sets up the decoder to decode from a plain
  90811. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90812. * example, with Unicode filenames on Windows), you must use
  90813. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90814. * and provide callbacks for the I/O.
  90815. *
  90816. * This function should be called after FLAC__stream_decoder_new() and
  90817. * FLAC__stream_decoder_set_*() but before any of the
  90818. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90819. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90820. * if initialization succeeded.
  90821. *
  90822. * \note Support for Ogg FLAC in the library is optional. If this
  90823. * library has been built without support for Ogg FLAC, this function
  90824. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90825. *
  90826. * \param decoder An uninitialized decoder instance.
  90827. * \param filename The name of the file to decode from. The file will
  90828. * be opened with fopen(). Use \c NULL to decode from
  90829. * \c stdin. Note that \c stdin is not seekable.
  90830. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90831. * pointer must not be \c NULL.
  90832. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90833. * pointer may be \c NULL if the callback is not
  90834. * desired.
  90835. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90836. * pointer must not be \c NULL.
  90837. * \param client_data This value will be supplied to callbacks in their
  90838. * \a client_data argument.
  90839. * \assert
  90840. * \code decoder != NULL \endcode
  90841. * \retval FLAC__StreamDecoderInitStatus
  90842. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90843. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90844. */
  90845. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90846. FLAC__StreamDecoder *decoder,
  90847. const char *filename,
  90848. FLAC__StreamDecoderWriteCallback write_callback,
  90849. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90850. FLAC__StreamDecoderErrorCallback error_callback,
  90851. void *client_data
  90852. );
  90853. /** Finish the decoding process.
  90854. * Flushes the decoding buffer, releases resources, resets the decoder
  90855. * settings to their defaults, and returns the decoder state to
  90856. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90857. *
  90858. * In the event of a prematurely-terminated decode, it is not strictly
  90859. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90860. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90861. * with a FLAC__stream_decoder_finish().
  90862. *
  90863. * \param decoder An uninitialized decoder instance.
  90864. * \assert
  90865. * \code decoder != NULL \endcode
  90866. * \retval FLAC__bool
  90867. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90868. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90869. * signature does not match the one computed by the decoder; else
  90870. * \c true.
  90871. */
  90872. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90873. /** Flush the stream input.
  90874. * The decoder's input buffer will be cleared and the state set to
  90875. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90876. * off MD5 checking.
  90877. *
  90878. * \param decoder A decoder instance.
  90879. * \assert
  90880. * \code decoder != NULL \endcode
  90881. * \retval FLAC__bool
  90882. * \c true if successful, else \c false if a memory allocation
  90883. * error occurs (in which case the state will be set to
  90884. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90885. */
  90886. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90887. /** Reset the decoding process.
  90888. * The decoder's input buffer will be cleared and the state set to
  90889. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90890. * FLAC__stream_decoder_finish() except that the settings are
  90891. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90892. * before decoding again. MD5 checking will be restored to its original
  90893. * setting.
  90894. *
  90895. * If the decoder is seekable, or was initialized with
  90896. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90897. * the decoder will also attempt to seek to the beginning of the file.
  90898. * If this rewind fails, this function will return \c false. It follows
  90899. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90900. * \c stdin.
  90901. *
  90902. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90903. * and is not seekable (i.e. no seek callback was provided or the seek
  90904. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90905. * is the duty of the client to start feeding data from the beginning of
  90906. * the stream on the next FLAC__stream_decoder_process() or
  90907. * FLAC__stream_decoder_process_interleaved() call.
  90908. *
  90909. * \param decoder A decoder instance.
  90910. * \assert
  90911. * \code decoder != NULL \endcode
  90912. * \retval FLAC__bool
  90913. * \c true if successful, else \c false if a memory allocation occurs
  90914. * (in which case the state will be set to
  90915. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90916. * occurs (the state will be unchanged).
  90917. */
  90918. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90919. /** Decode one metadata block or audio frame.
  90920. * This version instructs the decoder to decode a either a single metadata
  90921. * block or a single frame and stop, unless the callbacks return a fatal
  90922. * error or the read callback returns
  90923. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90924. *
  90925. * As the decoder needs more input it will call the read callback.
  90926. * Depending on what was decoded, the metadata or write callback will be
  90927. * called with the decoded metadata block or audio frame.
  90928. *
  90929. * Unless there is a fatal read error or end of stream, this function
  90930. * will return once one whole frame is decoded. In other words, if the
  90931. * stream is not synchronized or points to a corrupt frame header, the
  90932. * decoder will continue to try and resync until it gets to a valid
  90933. * frame, then decode one frame, then return. If the decoder points to
  90934. * a frame whose frame CRC in the frame footer does not match the
  90935. * computed frame CRC, this function will issue a
  90936. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90937. * error callback, and return, having decoded one complete, although
  90938. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90939. * correct length to the write callback.)
  90940. *
  90941. * \param decoder An initialized decoder instance.
  90942. * \assert
  90943. * \code decoder != NULL \endcode
  90944. * \retval FLAC__bool
  90945. * \c false if any fatal read, write, or memory allocation error
  90946. * occurred (meaning decoding must stop), else \c true; for more
  90947. * information about the decoder, check the decoder state with
  90948. * FLAC__stream_decoder_get_state().
  90949. */
  90950. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90951. /** Decode until the end of the metadata.
  90952. * This version instructs the decoder to decode from the current position
  90953. * and continue until all the metadata has been read, or until the
  90954. * callbacks return a fatal error or the read callback returns
  90955. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90956. *
  90957. * As the decoder needs more input it will call the read callback.
  90958. * As each metadata block is decoded, the metadata callback will be called
  90959. * with the decoded metadata.
  90960. *
  90961. * \param decoder An initialized decoder instance.
  90962. * \assert
  90963. * \code decoder != NULL \endcode
  90964. * \retval FLAC__bool
  90965. * \c false if any fatal read, write, or memory allocation error
  90966. * occurred (meaning decoding must stop), else \c true; for more
  90967. * information about the decoder, check the decoder state with
  90968. * FLAC__stream_decoder_get_state().
  90969. */
  90970. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90971. /** Decode until the end of the stream.
  90972. * This version instructs the decoder to decode from the current position
  90973. * and continue until the end of stream (the read callback returns
  90974. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90975. * callbacks return a fatal error.
  90976. *
  90977. * As the decoder needs more input it will call the read callback.
  90978. * As each metadata block and frame is decoded, the metadata or write
  90979. * callback will be called with the decoded metadata or frame.
  90980. *
  90981. * \param decoder An initialized decoder instance.
  90982. * \assert
  90983. * \code decoder != NULL \endcode
  90984. * \retval FLAC__bool
  90985. * \c false if any fatal read, write, or memory allocation error
  90986. * occurred (meaning decoding must stop), else \c true; for more
  90987. * information about the decoder, check the decoder state with
  90988. * FLAC__stream_decoder_get_state().
  90989. */
  90990. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90991. /** Skip one audio frame.
  90992. * This version instructs the decoder to 'skip' a single frame and stop,
  90993. * unless the callbacks return a fatal error or the read callback returns
  90994. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90995. *
  90996. * The decoding flow is the same as what occurs when
  90997. * FLAC__stream_decoder_process_single() is called to process an audio
  90998. * frame, except that this function does not decode the parsed data into
  90999. * PCM or call the write callback. The integrity of the frame is still
  91000. * checked the same way as in the other process functions.
  91001. *
  91002. * This function will return once one whole frame is skipped, in the
  91003. * same way that FLAC__stream_decoder_process_single() will return once
  91004. * one whole frame is decoded.
  91005. *
  91006. * This function can be used in more quickly determining FLAC frame
  91007. * boundaries when decoding of the actual data is not needed, for
  91008. * example when an application is separating a FLAC stream into frames
  91009. * for editing or storing in a container. To do this, the application
  91010. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  91011. * to the next frame, then use
  91012. * FLAC__stream_decoder_get_decode_position() to find the new frame
  91013. * boundary.
  91014. *
  91015. * This function should only be called when the stream has advanced
  91016. * past all the metadata, otherwise it will return \c false.
  91017. *
  91018. * \param decoder An initialized decoder instance not in a metadata
  91019. * state.
  91020. * \assert
  91021. * \code decoder != NULL \endcode
  91022. * \retval FLAC__bool
  91023. * \c false if any fatal read, write, or memory allocation error
  91024. * occurred (meaning decoding must stop), or if the decoder
  91025. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  91026. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  91027. * information about the decoder, check the decoder state with
  91028. * FLAC__stream_decoder_get_state().
  91029. */
  91030. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  91031. /** Flush the input and seek to an absolute sample.
  91032. * Decoding will resume at the given sample. Note that because of
  91033. * this, the next write callback may contain a partial block. The
  91034. * client must support seeking the input or this function will fail
  91035. * and return \c false. Furthermore, if the decoder state is
  91036. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  91037. * with FLAC__stream_decoder_flush() or reset with
  91038. * FLAC__stream_decoder_reset() before decoding can continue.
  91039. *
  91040. * \param decoder A decoder instance.
  91041. * \param sample The target sample number to seek to.
  91042. * \assert
  91043. * \code decoder != NULL \endcode
  91044. * \retval FLAC__bool
  91045. * \c true if successful, else \c false.
  91046. */
  91047. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  91048. /* \} */
  91049. #ifdef __cplusplus
  91050. }
  91051. #endif
  91052. #endif
  91053. /*** End of inlined file: stream_decoder.h ***/
  91054. /*** Start of inlined file: stream_encoder.h ***/
  91055. #ifndef FLAC__STREAM_ENCODER_H
  91056. #define FLAC__STREAM_ENCODER_H
  91057. #include <stdio.h> /* for FILE */
  91058. #ifdef __cplusplus
  91059. extern "C" {
  91060. #endif
  91061. /** \file include/FLAC/stream_encoder.h
  91062. *
  91063. * \brief
  91064. * This module contains the functions which implement the stream
  91065. * encoder.
  91066. *
  91067. * See the detailed documentation in the
  91068. * \link flac_stream_encoder stream encoder \endlink module.
  91069. */
  91070. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  91071. * \ingroup flac
  91072. *
  91073. * \brief
  91074. * This module describes the encoder layers provided by libFLAC.
  91075. *
  91076. * The stream encoder can be used to encode complete streams either to the
  91077. * client via callbacks, or directly to a file, depending on how it is
  91078. * initialized. When encoding via callbacks, the client provides a write
  91079. * callback which will be called whenever FLAC data is ready to be written.
  91080. * If the client also supplies a seek callback, the encoder will also
  91081. * automatically handle the writing back of metadata discovered while
  91082. * encoding, like stream info, seek points offsets, etc. When encoding to
  91083. * a file, the client needs only supply a filename or open \c FILE* and an
  91084. * optional progress callback for periodic notification of progress; the
  91085. * write and seek callbacks are supplied internally. For more info see the
  91086. * \link flac_stream_encoder stream encoder \endlink module.
  91087. */
  91088. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  91089. * \ingroup flac_encoder
  91090. *
  91091. * \brief
  91092. * This module contains the functions which implement the stream
  91093. * encoder.
  91094. *
  91095. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  91096. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  91097. *
  91098. * The basic usage of this encoder is as follows:
  91099. * - The program creates an instance of an encoder using
  91100. * FLAC__stream_encoder_new().
  91101. * - The program overrides the default settings using
  91102. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  91103. * functions should be called:
  91104. * - FLAC__stream_encoder_set_channels()
  91105. * - FLAC__stream_encoder_set_bits_per_sample()
  91106. * - FLAC__stream_encoder_set_sample_rate()
  91107. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  91108. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  91109. * - If the application wants to control the compression level or set its own
  91110. * metadata, then the following should also be called:
  91111. * - FLAC__stream_encoder_set_compression_level()
  91112. * - FLAC__stream_encoder_set_verify()
  91113. * - FLAC__stream_encoder_set_metadata()
  91114. * - The rest of the set functions should only be called if the client needs
  91115. * exact control over how the audio is compressed; thorough understanding
  91116. * of the FLAC format is necessary to achieve good results.
  91117. * - The program initializes the instance to validate the settings and
  91118. * prepare for encoding using
  91119. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  91120. * or FLAC__stream_encoder_init_file() for native FLAC
  91121. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  91122. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  91123. * - The program calls FLAC__stream_encoder_process() or
  91124. * FLAC__stream_encoder_process_interleaved() to encode data, which
  91125. * subsequently calls the callbacks when there is encoder data ready
  91126. * to be written.
  91127. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  91128. * which causes the encoder to encode any data still in its input pipe,
  91129. * update the metadata with the final encoding statistics if output
  91130. * seeking is possible, and finally reset the encoder to the
  91131. * uninitialized state.
  91132. * - The instance may be used again or deleted with
  91133. * FLAC__stream_encoder_delete().
  91134. *
  91135. * In more detail, the stream encoder functions similarly to the
  91136. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  91137. * callbacks and more options. Typically the client will create a new
  91138. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  91139. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  91140. * calling one of the FLAC__stream_encoder_init_*() functions.
  91141. *
  91142. * Unlike the decoders, the stream encoder has many options that can
  91143. * affect the speed and compression ratio. When setting these parameters
  91144. * you should have some basic knowledge of the format (see the
  91145. * <A HREF="../documentation.html#format">user-level documentation</A>
  91146. * or the <A HREF="../format.html">formal description</A>). The
  91147. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  91148. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  91149. * functions will do this, so make sure to pay attention to the state
  91150. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  91151. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  91152. * before FLAC__stream_encoder_init_*() will take on the defaults from
  91153. * the constructor.
  91154. *
  91155. * There are three initialization functions for native FLAC, one for
  91156. * setting up the encoder to encode FLAC data to the client via
  91157. * callbacks, and two for encoding directly to a file.
  91158. *
  91159. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  91160. * You must also supply a write callback which will be called anytime
  91161. * there is raw encoded data to write. If the client can seek the output
  91162. * it is best to also supply seek and tell callbacks, as this allows the
  91163. * encoder to go back after encoding is finished to write back
  91164. * information that was collected while encoding, like seek point offsets,
  91165. * frame sizes, etc.
  91166. *
  91167. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  91168. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  91169. * filename or open \c FILE*; the encoder will handle all the callbacks
  91170. * internally. You may also supply a progress callback for periodic
  91171. * notification of the encoding progress.
  91172. *
  91173. * There are three similarly-named init functions for encoding to Ogg
  91174. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91175. * library has been built with Ogg support.
  91176. *
  91177. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91178. * call the write callback several times, once with the \c fLaC signature,
  91179. * and once for each encoded metadata block. Note that for Ogg FLAC
  91180. * encoding you will usually get at least twice the number of callbacks than
  91181. * with native FLAC, one for the Ogg page header and one for the page body.
  91182. *
  91183. * After initializing the instance, the client may feed audio data to the
  91184. * encoder in one of two ways:
  91185. *
  91186. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91187. * will pass an array of pointers to buffers, one for each channel, to
  91188. * the encoder, each of the same length. The samples need not be
  91189. * block-aligned, but each channel should have the same number of samples.
  91190. * - Channel interleaved, through
  91191. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91192. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91193. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91194. * Again, the samples need not be block-aligned but they must be
  91195. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91196. * the last value channelN_sampleM.
  91197. *
  91198. * Note that for either process call, each sample in the buffers should be a
  91199. * signed integer, right-justified to the resolution set by
  91200. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91201. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91202. *
  91203. * When the client is finished encoding data, it calls
  91204. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91205. * data still in its input pipe, and call the metadata callback with the
  91206. * final encoding statistics. Then the instance may be deleted with
  91207. * FLAC__stream_encoder_delete() or initialized again to encode another
  91208. * stream.
  91209. *
  91210. * For programs that write their own metadata, but that do not know the
  91211. * actual metadata until after encoding, it is advantageous to instruct
  91212. * the encoder to write a PADDING block of the correct size, so that
  91213. * instead of rewriting the whole stream after encoding, the program can
  91214. * just overwrite the PADDING block. If only the maximum size of the
  91215. * metadata is known, the program can write a slightly larger padding
  91216. * block, then split it after encoding.
  91217. *
  91218. * Make sure you understand how lengths are calculated. All FLAC metadata
  91219. * blocks have a 4 byte header which contains the type and length. This
  91220. * length does not include the 4 bytes of the header. See the format page
  91221. * for the specification of metadata blocks and their lengths.
  91222. *
  91223. * \note
  91224. * If you are writing the FLAC data to a file via callbacks, make sure it
  91225. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91226. * after the first encoding pass, the encoder will try to seek back to the
  91227. * beginning of the stream, to the STREAMINFO block, to write some data
  91228. * there. (If using FLAC__stream_encoder_init*_file() or
  91229. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91230. *
  91231. * \note
  91232. * The "set" functions may only be called when the encoder is in the
  91233. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91234. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91235. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91236. * return \c true, otherwise \c false.
  91237. *
  91238. * \note
  91239. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91240. * defaults.
  91241. *
  91242. * \{
  91243. */
  91244. /** State values for a FLAC__StreamEncoder.
  91245. *
  91246. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91247. *
  91248. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91249. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91250. * must be deleted with FLAC__stream_encoder_delete().
  91251. */
  91252. typedef enum {
  91253. FLAC__STREAM_ENCODER_OK = 0,
  91254. /**< The encoder is in the normal OK state and samples can be processed. */
  91255. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91256. /**< The encoder is in the uninitialized state; one of the
  91257. * FLAC__stream_encoder_init_*() functions must be called before samples
  91258. * can be processed.
  91259. */
  91260. FLAC__STREAM_ENCODER_OGG_ERROR,
  91261. /**< An error occurred in the underlying Ogg layer. */
  91262. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91263. /**< An error occurred in the underlying verify stream decoder;
  91264. * check FLAC__stream_encoder_get_verify_decoder_state().
  91265. */
  91266. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91267. /**< The verify decoder detected a mismatch between the original
  91268. * audio signal and the decoded audio signal.
  91269. */
  91270. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91271. /**< One of the callbacks returned a fatal error. */
  91272. FLAC__STREAM_ENCODER_IO_ERROR,
  91273. /**< An I/O error occurred while opening/reading/writing a file.
  91274. * Check \c errno.
  91275. */
  91276. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91277. /**< An error occurred while writing the stream; usually, the
  91278. * write_callback returned an error.
  91279. */
  91280. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91281. /**< Memory allocation failed. */
  91282. } FLAC__StreamEncoderState;
  91283. /** Maps a FLAC__StreamEncoderState to a C string.
  91284. *
  91285. * Using a FLAC__StreamEncoderState as the index to this array
  91286. * will give the string equivalent. The contents should not be modified.
  91287. */
  91288. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91289. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91290. */
  91291. typedef enum {
  91292. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91293. /**< Initialization was successful. */
  91294. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91295. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91296. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91297. /**< The library was not compiled with support for the given container
  91298. * format.
  91299. */
  91300. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91301. /**< A required callback was not supplied. */
  91302. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91303. /**< The encoder has an invalid setting for number of channels. */
  91304. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91305. /**< The encoder has an invalid setting for bits-per-sample.
  91306. * FLAC supports 4-32 bps but the reference encoder currently supports
  91307. * only up to 24 bps.
  91308. */
  91309. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91310. /**< The encoder has an invalid setting for the input sample rate. */
  91311. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91312. /**< The encoder has an invalid setting for the block size. */
  91313. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91314. /**< The encoder has an invalid setting for the maximum LPC order. */
  91315. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91316. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91317. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91318. /**< The specified block size is less than the maximum LPC order. */
  91319. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91320. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91321. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91322. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91323. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91324. * - One of the metadata blocks contains an undefined type
  91325. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91326. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91327. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91328. */
  91329. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91330. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91331. * already initialized, usually because
  91332. * FLAC__stream_encoder_finish() was not called.
  91333. */
  91334. } FLAC__StreamEncoderInitStatus;
  91335. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91336. *
  91337. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91338. * will give the string equivalent. The contents should not be modified.
  91339. */
  91340. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91341. /** Return values for the FLAC__StreamEncoder read callback.
  91342. */
  91343. typedef enum {
  91344. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91345. /**< The read was OK and decoding can continue. */
  91346. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91347. /**< The read was attempted at the end of the stream. */
  91348. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91349. /**< An unrecoverable error occurred. */
  91350. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91351. /**< Client does not support reading back from the output. */
  91352. } FLAC__StreamEncoderReadStatus;
  91353. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91354. *
  91355. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91356. * will give the string equivalent. The contents should not be modified.
  91357. */
  91358. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91359. /** Return values for the FLAC__StreamEncoder write callback.
  91360. */
  91361. typedef enum {
  91362. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91363. /**< The write was OK and encoding can continue. */
  91364. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91365. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91366. } FLAC__StreamEncoderWriteStatus;
  91367. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91368. *
  91369. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91370. * will give the string equivalent. The contents should not be modified.
  91371. */
  91372. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91373. /** Return values for the FLAC__StreamEncoder seek callback.
  91374. */
  91375. typedef enum {
  91376. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91377. /**< The seek was OK and encoding can continue. */
  91378. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91379. /**< An unrecoverable error occurred. */
  91380. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91381. /**< Client does not support seeking. */
  91382. } FLAC__StreamEncoderSeekStatus;
  91383. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91384. *
  91385. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91386. * will give the string equivalent. The contents should not be modified.
  91387. */
  91388. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91389. /** Return values for the FLAC__StreamEncoder tell callback.
  91390. */
  91391. typedef enum {
  91392. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91393. /**< The tell was OK and encoding can continue. */
  91394. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91395. /**< An unrecoverable error occurred. */
  91396. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91397. /**< Client does not support seeking. */
  91398. } FLAC__StreamEncoderTellStatus;
  91399. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91400. *
  91401. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91402. * will give the string equivalent. The contents should not be modified.
  91403. */
  91404. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91405. /***********************************************************************
  91406. *
  91407. * class FLAC__StreamEncoder
  91408. *
  91409. ***********************************************************************/
  91410. struct FLAC__StreamEncoderProtected;
  91411. struct FLAC__StreamEncoderPrivate;
  91412. /** The opaque structure definition for the stream encoder type.
  91413. * See the \link flac_stream_encoder stream encoder module \endlink
  91414. * for a detailed description.
  91415. */
  91416. typedef struct {
  91417. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91418. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91419. } FLAC__StreamEncoder;
  91420. /** Signature for the read callback.
  91421. *
  91422. * A function pointer matching this signature must be passed to
  91423. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91424. * The supplied function will be called when the encoder needs to read back
  91425. * encoded data. This happens during the metadata callback, when the encoder
  91426. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91427. * while encoding. The address of the buffer to be filled is supplied, along
  91428. * with the number of bytes the buffer can hold. The callback may choose to
  91429. * supply less data and modify the byte count but must be careful not to
  91430. * overflow the buffer. The callback then returns a status code chosen from
  91431. * FLAC__StreamEncoderReadStatus.
  91432. *
  91433. * Here is an example of a read callback for stdio streams:
  91434. * \code
  91435. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91436. * {
  91437. * FILE *file = ((MyClientData*)client_data)->file;
  91438. * if(*bytes > 0) {
  91439. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91440. * if(ferror(file))
  91441. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91442. * else if(*bytes == 0)
  91443. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91444. * else
  91445. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91446. * }
  91447. * else
  91448. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91449. * }
  91450. * \endcode
  91451. *
  91452. * \note In general, FLAC__StreamEncoder functions which change the
  91453. * state should not be called on the \a encoder while in the callback.
  91454. *
  91455. * \param encoder The encoder instance calling the callback.
  91456. * \param buffer A pointer to a location for the callee to store
  91457. * data to be encoded.
  91458. * \param bytes A pointer to the size of the buffer. On entry
  91459. * to the callback, it contains the maximum number
  91460. * of bytes that may be stored in \a buffer. The
  91461. * callee must set it to the actual number of bytes
  91462. * stored (0 in case of error or end-of-stream) before
  91463. * returning.
  91464. * \param client_data The callee's client data set through
  91465. * FLAC__stream_encoder_set_client_data().
  91466. * \retval FLAC__StreamEncoderReadStatus
  91467. * The callee's return status.
  91468. */
  91469. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91470. /** Signature for the write callback.
  91471. *
  91472. * A function pointer matching this signature must be passed to
  91473. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91474. * by the encoder anytime there is raw encoded data ready to write. It may
  91475. * include metadata mixed with encoded audio frames and the data is not
  91476. * guaranteed to be aligned on frame or metadata block boundaries.
  91477. *
  91478. * The only duty of the callback is to write out the \a bytes worth of data
  91479. * in \a buffer to the current position in the output stream. The arguments
  91480. * \a samples and \a current_frame are purely informational. If \a samples
  91481. * is greater than \c 0, then \a current_frame will hold the current frame
  91482. * number that is being written; otherwise it indicates that the write
  91483. * callback is being called to write metadata.
  91484. *
  91485. * \note
  91486. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91487. * write callback will be called twice when writing each audio
  91488. * frame; once for the page header, and once for the page body.
  91489. * When writing the page header, the \a samples argument to the
  91490. * write callback will be \c 0.
  91491. *
  91492. * \note In general, FLAC__StreamEncoder functions which change the
  91493. * state should not be called on the \a encoder while in the callback.
  91494. *
  91495. * \param encoder The encoder instance calling the callback.
  91496. * \param buffer An array of encoded data of length \a bytes.
  91497. * \param bytes The byte length of \a buffer.
  91498. * \param samples The number of samples encoded by \a buffer.
  91499. * \c 0 has a special meaning; see above.
  91500. * \param current_frame The number of the current frame being encoded.
  91501. * \param client_data The callee's client data set through
  91502. * FLAC__stream_encoder_init_*().
  91503. * \retval FLAC__StreamEncoderWriteStatus
  91504. * The callee's return status.
  91505. */
  91506. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91507. /** Signature for the seek callback.
  91508. *
  91509. * A function pointer matching this signature may be passed to
  91510. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91511. * when the encoder needs to seek the output stream. The encoder will pass
  91512. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91513. *
  91514. * Here is an example of a seek callback for stdio streams:
  91515. * \code
  91516. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91517. * {
  91518. * FILE *file = ((MyClientData*)client_data)->file;
  91519. * if(file == stdin)
  91520. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91521. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91522. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91523. * else
  91524. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91525. * }
  91526. * \endcode
  91527. *
  91528. * \note In general, FLAC__StreamEncoder functions which change the
  91529. * state should not be called on the \a encoder while in the callback.
  91530. *
  91531. * \param encoder The encoder instance calling the callback.
  91532. * \param absolute_byte_offset The offset from the beginning of the stream
  91533. * to seek to.
  91534. * \param client_data The callee's client data set through
  91535. * FLAC__stream_encoder_init_*().
  91536. * \retval FLAC__StreamEncoderSeekStatus
  91537. * The callee's return status.
  91538. */
  91539. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91540. /** Signature for the tell callback.
  91541. *
  91542. * A function pointer matching this signature may be passed to
  91543. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91544. * when the encoder needs to know the current position of the output stream.
  91545. *
  91546. * \warning
  91547. * The callback must return the true current byte offset of the output to
  91548. * which the encoder is writing. If you are buffering the output, make
  91549. * sure and take this into account. If you are writing directly to a
  91550. * FILE* from your write callback, ftell() is sufficient. If you are
  91551. * writing directly to a file descriptor from your write callback, you
  91552. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91553. * these points to rewrite metadata after encoding.
  91554. *
  91555. * Here is an example of a tell callback for stdio streams:
  91556. * \code
  91557. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91558. * {
  91559. * FILE *file = ((MyClientData*)client_data)->file;
  91560. * off_t pos;
  91561. * if(file == stdin)
  91562. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91563. * else if((pos = ftello(file)) < 0)
  91564. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91565. * else {
  91566. * *absolute_byte_offset = (FLAC__uint64)pos;
  91567. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91568. * }
  91569. * }
  91570. * \endcode
  91571. *
  91572. * \note In general, FLAC__StreamEncoder functions which change the
  91573. * state should not be called on the \a encoder while in the callback.
  91574. *
  91575. * \param encoder The encoder instance calling the callback.
  91576. * \param absolute_byte_offset The address at which to store the current
  91577. * position of the output.
  91578. * \param client_data The callee's client data set through
  91579. * FLAC__stream_encoder_init_*().
  91580. * \retval FLAC__StreamEncoderTellStatus
  91581. * The callee's return status.
  91582. */
  91583. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91584. /** Signature for the metadata callback.
  91585. *
  91586. * A function pointer matching this signature may be passed to
  91587. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91588. * once at the end of encoding with the populated STREAMINFO structure. This
  91589. * is so the client can seek back to the beginning of the file and write the
  91590. * STREAMINFO block with the correct statistics after encoding (like
  91591. * minimum/maximum frame size and total samples).
  91592. *
  91593. * \note In general, FLAC__StreamEncoder functions which change the
  91594. * state should not be called on the \a encoder while in the callback.
  91595. *
  91596. * \param encoder The encoder instance calling the callback.
  91597. * \param metadata The final populated STREAMINFO block.
  91598. * \param client_data The callee's client data set through
  91599. * FLAC__stream_encoder_init_*().
  91600. */
  91601. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91602. /** Signature for the progress callback.
  91603. *
  91604. * A function pointer matching this signature may be passed to
  91605. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91606. * The supplied function will be called when the encoder has finished
  91607. * writing a frame. The \c total_frames_estimate argument to the
  91608. * callback will be based on the value from
  91609. * FLAC__stream_encoder_set_total_samples_estimate().
  91610. *
  91611. * \note In general, FLAC__StreamEncoder functions which change the
  91612. * state should not be called on the \a encoder while in the callback.
  91613. *
  91614. * \param encoder The encoder instance calling the callback.
  91615. * \param bytes_written Bytes written so far.
  91616. * \param samples_written Samples written so far.
  91617. * \param frames_written Frames written so far.
  91618. * \param total_frames_estimate The estimate of the total number of
  91619. * frames to be written.
  91620. * \param client_data The callee's client data set through
  91621. * FLAC__stream_encoder_init_*().
  91622. */
  91623. 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);
  91624. /***********************************************************************
  91625. *
  91626. * Class constructor/destructor
  91627. *
  91628. ***********************************************************************/
  91629. /** Create a new stream encoder instance. The instance is created with
  91630. * default settings; see the individual FLAC__stream_encoder_set_*()
  91631. * functions for each setting's default.
  91632. *
  91633. * \retval FLAC__StreamEncoder*
  91634. * \c NULL if there was an error allocating memory, else the new instance.
  91635. */
  91636. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91637. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91638. *
  91639. * \param encoder A pointer to an existing encoder.
  91640. * \assert
  91641. * \code encoder != NULL \endcode
  91642. */
  91643. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91644. /***********************************************************************
  91645. *
  91646. * Public class method prototypes
  91647. *
  91648. ***********************************************************************/
  91649. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91650. *
  91651. * \note
  91652. * This does not need to be set for native FLAC encoding.
  91653. *
  91654. * \note
  91655. * It is recommended to set a serial number explicitly as the default of '0'
  91656. * may collide with other streams.
  91657. *
  91658. * \default \c 0
  91659. * \param encoder An encoder instance to set.
  91660. * \param serial_number See above.
  91661. * \assert
  91662. * \code encoder != NULL \endcode
  91663. * \retval FLAC__bool
  91664. * \c false if the encoder is already initialized, else \c true.
  91665. */
  91666. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91667. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91668. * encoded output by feeding it through an internal decoder and comparing
  91669. * the original signal against the decoded signal. If a mismatch occurs,
  91670. * the process call will return \c false. Note that this will slow the
  91671. * encoding process by the extra time required for decoding and comparison.
  91672. *
  91673. * \default \c false
  91674. * \param encoder An encoder instance to set.
  91675. * \param value Flag value (see above).
  91676. * \assert
  91677. * \code encoder != NULL \endcode
  91678. * \retval FLAC__bool
  91679. * \c false if the encoder is already initialized, else \c true.
  91680. */
  91681. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91682. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91683. * the encoder will comply with the Subset and will check the
  91684. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91685. * comply. If \c false, the settings may take advantage of the full
  91686. * range that the format allows.
  91687. *
  91688. * Make sure you know what it entails before setting this to \c false.
  91689. *
  91690. * \default \c true
  91691. * \param encoder An encoder instance to set.
  91692. * \param value Flag value (see above).
  91693. * \assert
  91694. * \code encoder != NULL \endcode
  91695. * \retval FLAC__bool
  91696. * \c false if the encoder is already initialized, else \c true.
  91697. */
  91698. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91699. /** Set the number of channels to be encoded.
  91700. *
  91701. * \default \c 2
  91702. * \param encoder An encoder instance to set.
  91703. * \param value See above.
  91704. * \assert
  91705. * \code encoder != NULL \endcode
  91706. * \retval FLAC__bool
  91707. * \c false if the encoder is already initialized, else \c true.
  91708. */
  91709. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91710. /** Set the sample resolution of the input to be encoded.
  91711. *
  91712. * \warning
  91713. * Do not feed the encoder data that is wider than the value you
  91714. * set here or you will generate an invalid stream.
  91715. *
  91716. * \default \c 16
  91717. * \param encoder An encoder instance to set.
  91718. * \param value See above.
  91719. * \assert
  91720. * \code encoder != NULL \endcode
  91721. * \retval FLAC__bool
  91722. * \c false if the encoder is already initialized, else \c true.
  91723. */
  91724. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91725. /** Set the sample rate (in Hz) of the input to be encoded.
  91726. *
  91727. * \default \c 44100
  91728. * \param encoder An encoder instance to set.
  91729. * \param value See above.
  91730. * \assert
  91731. * \code encoder != NULL \endcode
  91732. * \retval FLAC__bool
  91733. * \c false if the encoder is already initialized, else \c true.
  91734. */
  91735. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91736. /** Set the compression level
  91737. *
  91738. * The compression level is roughly proportional to the amount of effort
  91739. * the encoder expends to compress the file. A higher level usually
  91740. * means more computation but higher compression. The default level is
  91741. * suitable for most applications.
  91742. *
  91743. * Currently the levels range from \c 0 (fastest, least compression) to
  91744. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91745. * treated as \c 8.
  91746. *
  91747. * This function automatically calls the following other \c _set_
  91748. * functions with appropriate values, so the client does not need to
  91749. * unless it specifically wants to override them:
  91750. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91751. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91752. * - FLAC__stream_encoder_set_apodization()
  91753. * - FLAC__stream_encoder_set_max_lpc_order()
  91754. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91755. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91756. * - FLAC__stream_encoder_set_do_escape_coding()
  91757. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91758. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91759. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91760. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91761. *
  91762. * The actual values set for each level are:
  91763. * <table>
  91764. * <tr>
  91765. * <td><b>level</b><td>
  91766. * <td>do mid-side stereo<td>
  91767. * <td>loose mid-side stereo<td>
  91768. * <td>apodization<td>
  91769. * <td>max lpc order<td>
  91770. * <td>qlp coeff precision<td>
  91771. * <td>qlp coeff prec search<td>
  91772. * <td>escape coding<td>
  91773. * <td>exhaustive model search<td>
  91774. * <td>min residual partition order<td>
  91775. * <td>max residual partition order<td>
  91776. * <td>rice parameter search dist<td>
  91777. * </tr>
  91778. * <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>
  91779. * <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>
  91780. * <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>
  91781. * <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>
  91782. * <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>
  91783. * <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>
  91784. * <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>
  91785. * <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>
  91786. * <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>
  91787. * </table>
  91788. *
  91789. * \default \c 5
  91790. * \param encoder An encoder instance to set.
  91791. * \param value See above.
  91792. * \assert
  91793. * \code encoder != NULL \endcode
  91794. * \retval FLAC__bool
  91795. * \c false if the encoder is already initialized, else \c true.
  91796. */
  91797. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91798. /** Set the blocksize to use while encoding.
  91799. *
  91800. * The number of samples to use per frame. Use \c 0 to let the encoder
  91801. * estimate a blocksize; this is usually best.
  91802. *
  91803. * \default \c 0
  91804. * \param encoder An encoder instance to set.
  91805. * \param value See above.
  91806. * \assert
  91807. * \code encoder != NULL \endcode
  91808. * \retval FLAC__bool
  91809. * \c false if the encoder is already initialized, else \c true.
  91810. */
  91811. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91812. /** Set to \c true to enable mid-side encoding on stereo input. The
  91813. * number of channels must be 2 for this to have any effect. Set to
  91814. * \c false to use only independent channel coding.
  91815. *
  91816. * \default \c false
  91817. * \param encoder An encoder instance to set.
  91818. * \param value Flag value (see above).
  91819. * \assert
  91820. * \code encoder != NULL \endcode
  91821. * \retval FLAC__bool
  91822. * \c false if the encoder is already initialized, else \c true.
  91823. */
  91824. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91825. /** Set to \c true to enable adaptive switching between mid-side and
  91826. * left-right encoding on stereo input. Set to \c false to use
  91827. * exhaustive searching. Setting this to \c true requires
  91828. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91829. * \c true in order to have any effect.
  91830. *
  91831. * \default \c false
  91832. * \param encoder An encoder instance to set.
  91833. * \param value Flag value (see above).
  91834. * \assert
  91835. * \code encoder != NULL \endcode
  91836. * \retval FLAC__bool
  91837. * \c false if the encoder is already initialized, else \c true.
  91838. */
  91839. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91840. /** Sets the apodization function(s) the encoder will use when windowing
  91841. * audio data for LPC analysis.
  91842. *
  91843. * The \a specification is a plain ASCII string which specifies exactly
  91844. * which functions to use. There may be more than one (up to 32),
  91845. * separated by \c ';' characters. Some functions take one or more
  91846. * comma-separated arguments in parentheses.
  91847. *
  91848. * The available functions are \c bartlett, \c bartlett_hann,
  91849. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91850. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91851. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91852. *
  91853. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91854. * (0<STDDEV<=0.5).
  91855. *
  91856. * For \c tukey(P), P specifies the fraction of the window that is
  91857. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91858. * corresponds to \c hann.
  91859. *
  91860. * Example specifications are \c "blackman" or
  91861. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91862. *
  91863. * Any function that is specified erroneously is silently dropped. Up
  91864. * to 32 functions are kept, the rest are dropped. If the specification
  91865. * is empty the encoder defaults to \c "tukey(0.5)".
  91866. *
  91867. * When more than one function is specified, then for every subframe the
  91868. * encoder will try each of them separately and choose the window that
  91869. * results in the smallest compressed subframe.
  91870. *
  91871. * Note that each function specified causes the encoder to occupy a
  91872. * floating point array in which to store the window.
  91873. *
  91874. * \default \c "tukey(0.5)"
  91875. * \param encoder An encoder instance to set.
  91876. * \param specification See above.
  91877. * \assert
  91878. * \code encoder != NULL \endcode
  91879. * \code specification != NULL \endcode
  91880. * \retval FLAC__bool
  91881. * \c false if the encoder is already initialized, else \c true.
  91882. */
  91883. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91884. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91885. *
  91886. * \default \c 0
  91887. * \param encoder An encoder instance to set.
  91888. * \param value See above.
  91889. * \assert
  91890. * \code encoder != NULL \endcode
  91891. * \retval FLAC__bool
  91892. * \c false if the encoder is already initialized, else \c true.
  91893. */
  91894. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91895. /** Set the precision, in bits, of the quantized linear predictor
  91896. * coefficients, or \c 0 to let the encoder select it based on the
  91897. * blocksize.
  91898. *
  91899. * \note
  91900. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91901. * be less than 32.
  91902. *
  91903. * \default \c 0
  91904. * \param encoder An encoder instance to set.
  91905. * \param value See above.
  91906. * \assert
  91907. * \code encoder != NULL \endcode
  91908. * \retval FLAC__bool
  91909. * \c false if the encoder is already initialized, else \c true.
  91910. */
  91911. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91912. /** Set to \c false to use only the specified quantized linear predictor
  91913. * coefficient precision, or \c true to search neighboring precision
  91914. * values and use the best one.
  91915. *
  91916. * \default \c false
  91917. * \param encoder An encoder instance to set.
  91918. * \param value See above.
  91919. * \assert
  91920. * \code encoder != NULL \endcode
  91921. * \retval FLAC__bool
  91922. * \c false if the encoder is already initialized, else \c true.
  91923. */
  91924. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91925. /** Deprecated. Setting this value has no effect.
  91926. *
  91927. * \default \c false
  91928. * \param encoder An encoder instance to set.
  91929. * \param value See above.
  91930. * \assert
  91931. * \code encoder != NULL \endcode
  91932. * \retval FLAC__bool
  91933. * \c false if the encoder is already initialized, else \c true.
  91934. */
  91935. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91936. /** Set to \c false to let the encoder estimate the best model order
  91937. * based on the residual signal energy, or \c true to force the
  91938. * encoder to evaluate all order models and select the best.
  91939. *
  91940. * \default \c false
  91941. * \param encoder An encoder instance to set.
  91942. * \param value See above.
  91943. * \assert
  91944. * \code encoder != NULL \endcode
  91945. * \retval FLAC__bool
  91946. * \c false if the encoder is already initialized, else \c true.
  91947. */
  91948. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91949. /** Set the minimum partition order to search when coding the residual.
  91950. * This is used in tandem with
  91951. * FLAC__stream_encoder_set_max_residual_partition_order().
  91952. *
  91953. * The partition order determines the context size in the residual.
  91954. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91955. *
  91956. * Set both min and max values to \c 0 to force a single context,
  91957. * whose Rice parameter is based on the residual signal variance.
  91958. * Otherwise, set a min and max order, and the encoder will search
  91959. * all orders, using the mean of each context for its Rice parameter,
  91960. * and use the best.
  91961. *
  91962. * \default \c 0
  91963. * \param encoder An encoder instance to set.
  91964. * \param value See above.
  91965. * \assert
  91966. * \code encoder != NULL \endcode
  91967. * \retval FLAC__bool
  91968. * \c false if the encoder is already initialized, else \c true.
  91969. */
  91970. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91971. /** Set the maximum partition order to search when coding the residual.
  91972. * This is used in tandem with
  91973. * FLAC__stream_encoder_set_min_residual_partition_order().
  91974. *
  91975. * The partition order determines the context size in the residual.
  91976. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91977. *
  91978. * Set both min and max values to \c 0 to force a single context,
  91979. * whose Rice parameter is based on the residual signal variance.
  91980. * Otherwise, set a min and max order, and the encoder will search
  91981. * all orders, using the mean of each context for its Rice parameter,
  91982. * and use the best.
  91983. *
  91984. * \default \c 0
  91985. * \param encoder An encoder instance to set.
  91986. * \param value See above.
  91987. * \assert
  91988. * \code encoder != NULL \endcode
  91989. * \retval FLAC__bool
  91990. * \c false if the encoder is already initialized, else \c true.
  91991. */
  91992. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91993. /** Deprecated. Setting this value has no effect.
  91994. *
  91995. * \default \c 0
  91996. * \param encoder An encoder instance to set.
  91997. * \param value See above.
  91998. * \assert
  91999. * \code encoder != NULL \endcode
  92000. * \retval FLAC__bool
  92001. * \c false if the encoder is already initialized, else \c true.
  92002. */
  92003. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  92004. /** Set an estimate of the total samples that will be encoded.
  92005. * This is merely an estimate and may be set to \c 0 if unknown.
  92006. * This value will be written to the STREAMINFO block before encoding,
  92007. * and can remove the need for the caller to rewrite the value later
  92008. * if the value is known before encoding.
  92009. *
  92010. * \default \c 0
  92011. * \param encoder An encoder instance to set.
  92012. * \param value See above.
  92013. * \assert
  92014. * \code encoder != NULL \endcode
  92015. * \retval FLAC__bool
  92016. * \c false if the encoder is already initialized, else \c true.
  92017. */
  92018. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  92019. /** Set the metadata blocks to be emitted to the stream before encoding.
  92020. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  92021. * array of pointers to metadata blocks. The array is non-const since
  92022. * the encoder may need to change the \a is_last flag inside them, and
  92023. * in some cases update seek point offsets. Otherwise, the encoder will
  92024. * not modify or free the blocks. It is up to the caller to free the
  92025. * metadata blocks after encoding finishes.
  92026. *
  92027. * \note
  92028. * The encoder stores only copies of the pointers in the \a metadata array;
  92029. * the metadata blocks themselves must survive at least until after
  92030. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  92031. *
  92032. * \note
  92033. * The STREAMINFO block is always written and no STREAMINFO block may
  92034. * occur in the supplied array.
  92035. *
  92036. * \note
  92037. * By default the encoder does not create a SEEKTABLE. If one is supplied
  92038. * in the \a metadata array, but the client has specified that it does not
  92039. * support seeking, then the SEEKTABLE will be written verbatim. However
  92040. * by itself this is not very useful as the client will not know the stream
  92041. * offsets for the seekpoints ahead of time. In order to get a proper
  92042. * seektable the client must support seeking. See next note.
  92043. *
  92044. * \note
  92045. * SEEKTABLE blocks are handled specially. Since you will not know
  92046. * the values for the seek point stream offsets, you should pass in
  92047. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  92048. * required sample numbers (or placeholder points), with \c 0 for the
  92049. * \a frame_samples and \a stream_offset fields for each point. If the
  92050. * client has specified that it supports seeking by providing a seek
  92051. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  92052. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  92053. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  92054. * then while it is encoding the encoder will fill the stream offsets in
  92055. * for you and when encoding is finished, it will seek back and write the
  92056. * real values into the SEEKTABLE block in the stream. There are helper
  92057. * routines for manipulating seektable template blocks; see metadata.h:
  92058. * FLAC__metadata_object_seektable_template_*(). If the client does
  92059. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  92060. * will slow down or remove the ability to seek in the FLAC stream.
  92061. *
  92062. * \note
  92063. * The encoder instance \b will modify the first \c SEEKTABLE block
  92064. * as it transforms the template to a valid seektable while encoding,
  92065. * but it is still up to the caller to free all metadata blocks after
  92066. * encoding.
  92067. *
  92068. * \note
  92069. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  92070. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  92071. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  92072. * will simply write it's own into the stream. If no VORBIS_COMMENT
  92073. * block is present in the \a metadata array, libFLAC will write an
  92074. * empty one, containing only the vendor string.
  92075. *
  92076. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  92077. * the second metadata block of the stream. The encoder already supplies
  92078. * the STREAMINFO block automatically. If \a metadata does not contain a
  92079. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  92080. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  92081. * first, the init function will reorder \a metadata by moving the
  92082. * VORBIS_COMMENT block to the front; the relative ordering of the other
  92083. * blocks will remain as they were.
  92084. *
  92085. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  92086. * stream to \c 65535. If \a num_blocks exceeds this the function will
  92087. * return \c false.
  92088. *
  92089. * \default \c NULL, 0
  92090. * \param encoder An encoder instance to set.
  92091. * \param metadata See above.
  92092. * \param num_blocks See above.
  92093. * \assert
  92094. * \code encoder != NULL \endcode
  92095. * \retval FLAC__bool
  92096. * \c false if the encoder is already initialized, else \c true.
  92097. * \c false if the encoder is already initialized, or if
  92098. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  92099. */
  92100. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  92101. /** Get the current encoder state.
  92102. *
  92103. * \param encoder An encoder instance to query.
  92104. * \assert
  92105. * \code encoder != NULL \endcode
  92106. * \retval FLAC__StreamEncoderState
  92107. * The current encoder state.
  92108. */
  92109. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  92110. /** Get the state of the verify stream decoder.
  92111. * Useful when the stream encoder state is
  92112. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  92113. *
  92114. * \param encoder An encoder instance to query.
  92115. * \assert
  92116. * \code encoder != NULL \endcode
  92117. * \retval FLAC__StreamDecoderState
  92118. * The verify stream decoder state.
  92119. */
  92120. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  92121. /** Get the current encoder state as a C string.
  92122. * This version automatically resolves
  92123. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  92124. * verify decoder's state.
  92125. *
  92126. * \param encoder A encoder instance to query.
  92127. * \assert
  92128. * \code encoder != NULL \endcode
  92129. * \retval const char *
  92130. * The encoder state as a C string. Do not modify the contents.
  92131. */
  92132. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  92133. /** Get relevant values about the nature of a verify decoder error.
  92134. * Useful when the stream encoder state is
  92135. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  92136. * be addresses in which the stats will be returned, or NULL if value
  92137. * is not desired.
  92138. *
  92139. * \param encoder An encoder instance to query.
  92140. * \param absolute_sample The absolute sample number of the mismatch.
  92141. * \param frame_number The number of the frame in which the mismatch occurred.
  92142. * \param channel The channel in which the mismatch occurred.
  92143. * \param sample The number of the sample (relative to the frame) in
  92144. * which the mismatch occurred.
  92145. * \param expected The expected value for the sample in question.
  92146. * \param got The actual value returned by the decoder.
  92147. * \assert
  92148. * \code encoder != NULL \endcode
  92149. */
  92150. 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);
  92151. /** Get the "verify" flag.
  92152. *
  92153. * \param encoder An encoder instance to query.
  92154. * \assert
  92155. * \code encoder != NULL \endcode
  92156. * \retval FLAC__bool
  92157. * See FLAC__stream_encoder_set_verify().
  92158. */
  92159. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  92160. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  92161. *
  92162. * \param encoder An encoder instance to query.
  92163. * \assert
  92164. * \code encoder != NULL \endcode
  92165. * \retval FLAC__bool
  92166. * See FLAC__stream_encoder_set_streamable_subset().
  92167. */
  92168. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  92169. /** Get the number of input channels being processed.
  92170. *
  92171. * \param encoder An encoder instance to query.
  92172. * \assert
  92173. * \code encoder != NULL \endcode
  92174. * \retval unsigned
  92175. * See FLAC__stream_encoder_set_channels().
  92176. */
  92177. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92178. /** Get the input sample resolution setting.
  92179. *
  92180. * \param encoder An encoder instance to query.
  92181. * \assert
  92182. * \code encoder != NULL \endcode
  92183. * \retval unsigned
  92184. * See FLAC__stream_encoder_set_bits_per_sample().
  92185. */
  92186. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92187. /** Get the input sample rate setting.
  92188. *
  92189. * \param encoder An encoder instance to query.
  92190. * \assert
  92191. * \code encoder != NULL \endcode
  92192. * \retval unsigned
  92193. * See FLAC__stream_encoder_set_sample_rate().
  92194. */
  92195. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92196. /** Get the blocksize setting.
  92197. *
  92198. * \param encoder An encoder instance to query.
  92199. * \assert
  92200. * \code encoder != NULL \endcode
  92201. * \retval unsigned
  92202. * See FLAC__stream_encoder_set_blocksize().
  92203. */
  92204. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92205. /** Get the "mid/side stereo coding" flag.
  92206. *
  92207. * \param encoder An encoder instance to query.
  92208. * \assert
  92209. * \code encoder != NULL \endcode
  92210. * \retval FLAC__bool
  92211. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92212. */
  92213. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92214. /** Get the "adaptive mid/side switching" flag.
  92215. *
  92216. * \param encoder An encoder instance to query.
  92217. * \assert
  92218. * \code encoder != NULL \endcode
  92219. * \retval FLAC__bool
  92220. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92221. */
  92222. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92223. /** Get the maximum LPC order setting.
  92224. *
  92225. * \param encoder An encoder instance to query.
  92226. * \assert
  92227. * \code encoder != NULL \endcode
  92228. * \retval unsigned
  92229. * See FLAC__stream_encoder_set_max_lpc_order().
  92230. */
  92231. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92232. /** Get the quantized linear predictor coefficient precision setting.
  92233. *
  92234. * \param encoder An encoder instance to query.
  92235. * \assert
  92236. * \code encoder != NULL \endcode
  92237. * \retval unsigned
  92238. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92239. */
  92240. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92241. /** Get the qlp coefficient precision search flag.
  92242. *
  92243. * \param encoder An encoder instance to query.
  92244. * \assert
  92245. * \code encoder != NULL \endcode
  92246. * \retval FLAC__bool
  92247. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92248. */
  92249. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92250. /** Get the "escape coding" flag.
  92251. *
  92252. * \param encoder An encoder instance to query.
  92253. * \assert
  92254. * \code encoder != NULL \endcode
  92255. * \retval FLAC__bool
  92256. * See FLAC__stream_encoder_set_do_escape_coding().
  92257. */
  92258. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92259. /** Get the exhaustive model search flag.
  92260. *
  92261. * \param encoder An encoder instance to query.
  92262. * \assert
  92263. * \code encoder != NULL \endcode
  92264. * \retval FLAC__bool
  92265. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92266. */
  92267. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92268. /** Get the minimum residual partition order setting.
  92269. *
  92270. * \param encoder An encoder instance to query.
  92271. * \assert
  92272. * \code encoder != NULL \endcode
  92273. * \retval unsigned
  92274. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92275. */
  92276. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92277. /** Get maximum residual partition order setting.
  92278. *
  92279. * \param encoder An encoder instance to query.
  92280. * \assert
  92281. * \code encoder != NULL \endcode
  92282. * \retval unsigned
  92283. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92284. */
  92285. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92286. /** Get the Rice parameter search distance setting.
  92287. *
  92288. * \param encoder An encoder instance to query.
  92289. * \assert
  92290. * \code encoder != NULL \endcode
  92291. * \retval unsigned
  92292. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92293. */
  92294. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92295. /** Get the previously set estimate of the total samples to be encoded.
  92296. * The encoder merely mimics back the value given to
  92297. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92298. * other way of knowing how many samples the client will encode.
  92299. *
  92300. * \param encoder An encoder instance to set.
  92301. * \assert
  92302. * \code encoder != NULL \endcode
  92303. * \retval FLAC__uint64
  92304. * See FLAC__stream_encoder_get_total_samples_estimate().
  92305. */
  92306. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92307. /** Initialize the encoder instance to encode native FLAC streams.
  92308. *
  92309. * This flavor of initialization sets up the encoder to encode to a
  92310. * native FLAC stream. I/O is performed via callbacks to the client.
  92311. * For encoding to a plain file via filename or open \c FILE*,
  92312. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92313. * provide a simpler interface.
  92314. *
  92315. * This function should be called after FLAC__stream_encoder_new() and
  92316. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92317. * or FLAC__stream_encoder_process_interleaved().
  92318. * initialization succeeded.
  92319. *
  92320. * The call to FLAC__stream_encoder_init_stream() currently will also
  92321. * immediately call the write callback several times, once with the \c fLaC
  92322. * signature, and once for each encoded metadata block.
  92323. *
  92324. * \param encoder An uninitialized encoder instance.
  92325. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92326. * pointer must not be \c NULL.
  92327. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92328. * pointer may be \c NULL if seeking is not
  92329. * supported. The encoder uses seeking to go back
  92330. * and write some some stream statistics to the
  92331. * STREAMINFO block; this is recommended but not
  92332. * necessary to create a valid FLAC stream. If
  92333. * \a seek_callback is not \c NULL then a
  92334. * \a tell_callback must also be supplied.
  92335. * Alternatively, a dummy seek callback that just
  92336. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92337. * may also be supplied, all though this is slightly
  92338. * less efficient for the encoder.
  92339. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92340. * pointer may be \c NULL if seeking is not
  92341. * supported. If \a seek_callback is \c NULL then
  92342. * this argument will be ignored. If
  92343. * \a seek_callback is not \c NULL then a
  92344. * \a tell_callback must also be supplied.
  92345. * Alternatively, a dummy tell callback that just
  92346. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92347. * may also be supplied, all though this is slightly
  92348. * less efficient for the encoder.
  92349. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92350. * pointer may be \c NULL if the callback is not
  92351. * desired. If the client provides a seek callback,
  92352. * this function is not necessary as the encoder
  92353. * will automatically seek back and update the
  92354. * STREAMINFO block. It may also be \c NULL if the
  92355. * client does not support seeking, since it will
  92356. * have no way of going back to update the
  92357. * STREAMINFO. However the client can still supply
  92358. * a callback if it would like to know the details
  92359. * from the STREAMINFO.
  92360. * \param client_data This value will be supplied to callbacks in their
  92361. * \a client_data argument.
  92362. * \assert
  92363. * \code encoder != NULL \endcode
  92364. * \retval FLAC__StreamEncoderInitStatus
  92365. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92366. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92367. */
  92368. 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);
  92369. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92370. *
  92371. * This flavor of initialization sets up the encoder to encode to a FLAC
  92372. * stream in an Ogg container. I/O is performed via callbacks to the
  92373. * client. For encoding to a plain file via filename or open \c FILE*,
  92374. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92375. * provide a simpler interface.
  92376. *
  92377. * This function should be called after FLAC__stream_encoder_new() and
  92378. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92379. * or FLAC__stream_encoder_process_interleaved().
  92380. * initialization succeeded.
  92381. *
  92382. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92383. * immediately call the write callback several times to write the metadata
  92384. * packets.
  92385. *
  92386. * \param encoder An uninitialized encoder instance.
  92387. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92388. * pointer must not be \c NULL if \a seek_callback
  92389. * is non-NULL since they are both needed to be
  92390. * able to write data back to the Ogg FLAC stream
  92391. * in the post-encode phase.
  92392. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92393. * pointer must not be \c NULL.
  92394. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92395. * pointer may be \c NULL if seeking is not
  92396. * supported. The encoder uses seeking to go back
  92397. * and write some some stream statistics to the
  92398. * STREAMINFO block; this is recommended but not
  92399. * necessary to create a valid FLAC stream. If
  92400. * \a seek_callback is not \c NULL then a
  92401. * \a tell_callback must also be supplied.
  92402. * Alternatively, a dummy seek callback that just
  92403. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92404. * may also be supplied, all though this is slightly
  92405. * less efficient for the encoder.
  92406. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92407. * pointer may be \c NULL if seeking is not
  92408. * supported. If \a seek_callback is \c NULL then
  92409. * this argument will be ignored. If
  92410. * \a seek_callback is not \c NULL then a
  92411. * \a tell_callback must also be supplied.
  92412. * Alternatively, a dummy tell callback that just
  92413. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92414. * may also be supplied, all though this is slightly
  92415. * less efficient for the encoder.
  92416. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92417. * pointer may be \c NULL if the callback is not
  92418. * desired. If the client provides a seek callback,
  92419. * this function is not necessary as the encoder
  92420. * will automatically seek back and update the
  92421. * STREAMINFO block. It may also be \c NULL if the
  92422. * client does not support seeking, since it will
  92423. * have no way of going back to update the
  92424. * STREAMINFO. However the client can still supply
  92425. * a callback if it would like to know the details
  92426. * from the STREAMINFO.
  92427. * \param client_data This value will be supplied to callbacks in their
  92428. * \a client_data argument.
  92429. * \assert
  92430. * \code encoder != NULL \endcode
  92431. * \retval FLAC__StreamEncoderInitStatus
  92432. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92433. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92434. */
  92435. 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);
  92436. /** Initialize the encoder instance to encode native FLAC files.
  92437. *
  92438. * This flavor of initialization sets up the encoder to encode to a
  92439. * plain native FLAC file. For non-stdio streams, you must use
  92440. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92441. *
  92442. * This function should be called after FLAC__stream_encoder_new() and
  92443. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92444. * or FLAC__stream_encoder_process_interleaved().
  92445. * initialization succeeded.
  92446. *
  92447. * \param encoder An uninitialized encoder instance.
  92448. * \param file An open file. The file should have been opened
  92449. * with mode \c "w+b" and rewound. The file
  92450. * becomes owned by the encoder and should not be
  92451. * manipulated by the client while encoding.
  92452. * Unless \a file is \c stdout, it will be closed
  92453. * when FLAC__stream_encoder_finish() is called.
  92454. * Note however that a proper SEEKTABLE cannot be
  92455. * created when encoding to \c stdout since it is
  92456. * not seekable.
  92457. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92458. * pointer may be \c NULL if the callback is not
  92459. * desired.
  92460. * \param client_data This value will be supplied to callbacks in their
  92461. * \a client_data argument.
  92462. * \assert
  92463. * \code encoder != NULL \endcode
  92464. * \code file != NULL \endcode
  92465. * \retval FLAC__StreamEncoderInitStatus
  92466. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92467. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92468. */
  92469. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92470. /** Initialize the encoder instance to encode Ogg FLAC files.
  92471. *
  92472. * This flavor of initialization sets up the encoder to encode to a
  92473. * plain Ogg FLAC file. For non-stdio streams, you must use
  92474. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92475. *
  92476. * This function should be called after FLAC__stream_encoder_new() and
  92477. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92478. * or FLAC__stream_encoder_process_interleaved().
  92479. * initialization succeeded.
  92480. *
  92481. * \param encoder An uninitialized encoder instance.
  92482. * \param file An open file. The file should have been opened
  92483. * with mode \c "w+b" and rewound. The file
  92484. * becomes owned by the encoder and should not be
  92485. * manipulated by the client while encoding.
  92486. * Unless \a file is \c stdout, it will be closed
  92487. * when FLAC__stream_encoder_finish() is called.
  92488. * Note however that a proper SEEKTABLE cannot be
  92489. * created when encoding to \c stdout since it is
  92490. * not seekable.
  92491. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92492. * pointer may be \c NULL if the callback is not
  92493. * desired.
  92494. * \param client_data This value will be supplied to callbacks in their
  92495. * \a client_data argument.
  92496. * \assert
  92497. * \code encoder != NULL \endcode
  92498. * \code file != NULL \endcode
  92499. * \retval FLAC__StreamEncoderInitStatus
  92500. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92501. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92502. */
  92503. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92504. /** Initialize the encoder instance to encode native FLAC files.
  92505. *
  92506. * This flavor of initialization sets up the encoder to encode to a plain
  92507. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92508. * with Unicode filenames on Windows), you must use
  92509. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92510. * and provide callbacks for the I/O.
  92511. *
  92512. * This function should be called after FLAC__stream_encoder_new() and
  92513. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92514. * or FLAC__stream_encoder_process_interleaved().
  92515. * initialization succeeded.
  92516. *
  92517. * \param encoder An uninitialized encoder instance.
  92518. * \param filename The name of the file to encode to. The file will
  92519. * be opened with fopen(). Use \c NULL to encode to
  92520. * \c stdout. Note however that a proper SEEKTABLE
  92521. * cannot be created when encoding to \c stdout since
  92522. * it is not seekable.
  92523. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92524. * pointer may be \c NULL if the callback is not
  92525. * desired.
  92526. * \param client_data This value will be supplied to callbacks in their
  92527. * \a client_data argument.
  92528. * \assert
  92529. * \code encoder != NULL \endcode
  92530. * \retval FLAC__StreamEncoderInitStatus
  92531. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92532. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92533. */
  92534. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92535. /** Initialize the encoder instance to encode Ogg FLAC files.
  92536. *
  92537. * This flavor of initialization sets up the encoder to encode to a plain
  92538. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92539. * with Unicode filenames on Windows), you must use
  92540. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92541. * and provide callbacks for the I/O.
  92542. *
  92543. * This function should be called after FLAC__stream_encoder_new() and
  92544. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92545. * or FLAC__stream_encoder_process_interleaved().
  92546. * initialization succeeded.
  92547. *
  92548. * \param encoder An uninitialized encoder instance.
  92549. * \param filename The name of the file to encode to. The file will
  92550. * be opened with fopen(). Use \c NULL to encode to
  92551. * \c stdout. Note however that a proper SEEKTABLE
  92552. * cannot be created when encoding to \c stdout since
  92553. * it is not seekable.
  92554. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92555. * pointer may be \c NULL if the callback is not
  92556. * desired.
  92557. * \param client_data This value will be supplied to callbacks in their
  92558. * \a client_data argument.
  92559. * \assert
  92560. * \code encoder != NULL \endcode
  92561. * \retval FLAC__StreamEncoderInitStatus
  92562. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92563. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92564. */
  92565. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92566. /** Finish the encoding process.
  92567. * Flushes the encoding buffer, releases resources, resets the encoder
  92568. * settings to their defaults, and returns the encoder state to
  92569. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92570. * one or more write callbacks before returning, and will generate
  92571. * a metadata callback.
  92572. *
  92573. * Note that in the course of processing the last frame, errors can
  92574. * occur, so the caller should be sure to check the return value to
  92575. * ensure the file was encoded properly.
  92576. *
  92577. * In the event of a prematurely-terminated encode, it is not strictly
  92578. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92579. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92580. * with a FLAC__stream_encoder_finish().
  92581. *
  92582. * \param encoder An uninitialized encoder instance.
  92583. * \assert
  92584. * \code encoder != NULL \endcode
  92585. * \retval FLAC__bool
  92586. * \c false if an error occurred processing the last frame; or if verify
  92587. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92588. * verify mismatch; else \c true. If \c false, caller should check the
  92589. * state with FLAC__stream_encoder_get_state() for more information
  92590. * about the error.
  92591. */
  92592. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92593. /** Submit data for encoding.
  92594. * This version allows you to supply the input data via an array of
  92595. * pointers, each pointer pointing to an array of \a samples samples
  92596. * representing one channel. The samples need not be block-aligned,
  92597. * but each channel should have the same number of samples. Each sample
  92598. * should be a signed integer, right-justified to the resolution set by
  92599. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92600. * resolution is 16 bits per sample, the samples should all be in the
  92601. * range [-32768,32767].
  92602. *
  92603. * For applications where channel order is important, channels must
  92604. * follow the order as described in the
  92605. * <A HREF="../format.html#frame_header">frame header</A>.
  92606. *
  92607. * \param encoder An initialized encoder instance in the OK state.
  92608. * \param buffer An array of pointers to each channel's signal.
  92609. * \param samples The number of samples in one channel.
  92610. * \assert
  92611. * \code encoder != NULL \endcode
  92612. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92613. * \retval FLAC__bool
  92614. * \c true if successful, else \c false; in this case, check the
  92615. * encoder state with FLAC__stream_encoder_get_state() to see what
  92616. * went wrong.
  92617. */
  92618. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92619. /** Submit data for encoding.
  92620. * This version allows you to supply the input data where the channels
  92621. * are interleaved into a single array (i.e. channel0_sample0,
  92622. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92623. * The samples need not be block-aligned but they must be
  92624. * sample-aligned, i.e. the first value should be channel0_sample0
  92625. * and the last value channelN_sampleM. Each sample should be a signed
  92626. * integer, right-justified to the resolution set by
  92627. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92628. * resolution is 16 bits per sample, the samples should all be in the
  92629. * range [-32768,32767].
  92630. *
  92631. * For applications where channel order is important, channels must
  92632. * follow the order as described in the
  92633. * <A HREF="../format.html#frame_header">frame header</A>.
  92634. *
  92635. * \param encoder An initialized encoder instance in the OK state.
  92636. * \param buffer An array of channel-interleaved data (see above).
  92637. * \param samples The number of samples in one channel, the same as for
  92638. * FLAC__stream_encoder_process(). For example, if
  92639. * encoding two channels, \c 1000 \a samples corresponds
  92640. * to a \a buffer of 2000 values.
  92641. * \assert
  92642. * \code encoder != NULL \endcode
  92643. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92644. * \retval FLAC__bool
  92645. * \c true if successful, else \c false; in this case, check the
  92646. * encoder state with FLAC__stream_encoder_get_state() to see what
  92647. * went wrong.
  92648. */
  92649. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92650. /* \} */
  92651. #ifdef __cplusplus
  92652. }
  92653. #endif
  92654. #endif
  92655. /*** End of inlined file: stream_encoder.h ***/
  92656. #ifdef _MSC_VER
  92657. /* OPT: an MSVC built-in would be better */
  92658. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92659. {
  92660. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92661. return (x>>16) | (x<<16);
  92662. }
  92663. #endif
  92664. #if defined(_MSC_VER) && defined(_X86_)
  92665. /* OPT: an MSVC built-in would be better */
  92666. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92667. {
  92668. __asm {
  92669. mov edx, start
  92670. mov ecx, len
  92671. test ecx, ecx
  92672. loop1:
  92673. jz done1
  92674. mov eax, [edx]
  92675. bswap eax
  92676. mov [edx], eax
  92677. add edx, 4
  92678. dec ecx
  92679. jmp short loop1
  92680. done1:
  92681. }
  92682. }
  92683. #endif
  92684. /** \mainpage
  92685. *
  92686. * \section intro Introduction
  92687. *
  92688. * This is the documentation for the FLAC C and C++ APIs. It is
  92689. * highly interconnected; this introduction should give you a top
  92690. * level idea of the structure and how to find the information you
  92691. * need. As a prerequisite you should have at least a basic
  92692. * knowledge of the FLAC format, documented
  92693. * <A HREF="../format.html">here</A>.
  92694. *
  92695. * \section c_api FLAC C API
  92696. *
  92697. * The FLAC C API is the interface to libFLAC, a set of structures
  92698. * describing the components of FLAC streams, and functions for
  92699. * encoding and decoding streams, as well as manipulating FLAC
  92700. * metadata in files. The public include files will be installed
  92701. * in your include area (for example /usr/include/FLAC/...).
  92702. *
  92703. * By writing a little code and linking against libFLAC, it is
  92704. * relatively easy to add FLAC support to another program. The
  92705. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92706. * Complete source code of libFLAC as well as the command-line
  92707. * encoder and plugins is available and is a useful source of
  92708. * examples.
  92709. *
  92710. * Aside from encoders and decoders, libFLAC provides a powerful
  92711. * metadata interface for manipulating metadata in FLAC files. It
  92712. * allows the user to add, delete, and modify FLAC metadata blocks
  92713. * and it can automatically take advantage of PADDING blocks to avoid
  92714. * rewriting the entire FLAC file when changing the size of the
  92715. * metadata.
  92716. *
  92717. * libFLAC usually only requires the standard C library and C math
  92718. * library. In particular, threading is not used so there is no
  92719. * dependency on a thread library. However, libFLAC does not use
  92720. * global variables and should be thread-safe.
  92721. *
  92722. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92723. * However the metadata editing interfaces currently have limited
  92724. * read-only support for Ogg FLAC files.
  92725. *
  92726. * \section cpp_api FLAC C++ API
  92727. *
  92728. * The FLAC C++ API is a set of classes that encapsulate the
  92729. * structures and functions in libFLAC. They provide slightly more
  92730. * functionality with respect to metadata but are otherwise
  92731. * equivalent. For the most part, they share the same usage as
  92732. * their counterparts in libFLAC, and the FLAC C API documentation
  92733. * can be used as a supplement. The public include files
  92734. * for the C++ API will be installed in your include area (for
  92735. * example /usr/include/FLAC++/...).
  92736. *
  92737. * libFLAC++ is also licensed under
  92738. * <A HREF="../license.html">Xiph's BSD license</A>.
  92739. *
  92740. * \section getting_started Getting Started
  92741. *
  92742. * A good starting point for learning the API is to browse through
  92743. * the <A HREF="modules.html">modules</A>. Modules are logical
  92744. * groupings of related functions or classes, which correspond roughly
  92745. * to header files or sections of header files. Each module includes a
  92746. * detailed description of the general usage of its functions or
  92747. * classes.
  92748. *
  92749. * From there you can go on to look at the documentation of
  92750. * individual functions. You can see different views of the individual
  92751. * functions through the links in top bar across this page.
  92752. *
  92753. * If you prefer a more hands-on approach, you can jump right to some
  92754. * <A HREF="../documentation_example_code.html">example code</A>.
  92755. *
  92756. * \section porting_guide Porting Guide
  92757. *
  92758. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92759. * has been introduced which gives detailed instructions on how to
  92760. * port your code to newer versions of FLAC.
  92761. *
  92762. * \section embedded_developers Embedded Developers
  92763. *
  92764. * libFLAC has grown larger over time as more functionality has been
  92765. * included, but much of it may be unnecessary for a particular embedded
  92766. * implementation. Unused parts may be pruned by some simple editing of
  92767. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92768. * metadata interface are all independent from each other.
  92769. *
  92770. * It is easiest to just describe the dependencies:
  92771. *
  92772. * - All modules depend on the \link flac_format Format \endlink module.
  92773. * - The decoders and encoders depend on the bitbuffer.
  92774. * - The decoder is independent of the encoder. The encoder uses the
  92775. * decoder because of the verify feature, but this can be removed if
  92776. * not needed.
  92777. * - Parts of the metadata interface require the stream decoder (but not
  92778. * the encoder).
  92779. * - Ogg support is selectable through the compile time macro
  92780. * \c FLAC__HAS_OGG.
  92781. *
  92782. * For example, if your application only requires the stream decoder, no
  92783. * encoder, and no metadata interface, you can remove the stream encoder
  92784. * and the metadata interface, which will greatly reduce the size of the
  92785. * library.
  92786. *
  92787. * Also, there are several places in the libFLAC code with comments marked
  92788. * with "OPT:" where a #define can be changed to enable code that might be
  92789. * faster on a specific platform. Experimenting with these can yield faster
  92790. * binaries.
  92791. */
  92792. /** \defgroup porting Porting Guide for New Versions
  92793. *
  92794. * This module describes differences in the library interfaces from
  92795. * version to version. It assists in the porting of code that uses
  92796. * the libraries to newer versions of FLAC.
  92797. *
  92798. * One simple facility for making porting easier that has been added
  92799. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92800. * library's includes (e.g. \c include/FLAC/export.h). The
  92801. * \c #defines mirror the libraries'
  92802. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92803. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92804. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92805. * These can be used to support multiple versions of an API during the
  92806. * transition phase, e.g.
  92807. *
  92808. * \code
  92809. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92810. * legacy code
  92811. * #else
  92812. * new code
  92813. * #endif
  92814. * \endcode
  92815. *
  92816. * The the source will work for multiple versions and the legacy code can
  92817. * easily be removed when the transition is complete.
  92818. *
  92819. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92820. * include/FLAC/export.h), which can be used to determine whether or not
  92821. * the library has been compiled with support for Ogg FLAC. This is
  92822. * simpler than trying to call an Ogg init function and catching the
  92823. * error.
  92824. */
  92825. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92826. * \ingroup porting
  92827. *
  92828. * \brief
  92829. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92830. *
  92831. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92832. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92833. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92834. * decoding layers and three encoding layers have been merged into a
  92835. * single stream decoder and stream encoder. That is, the functionality
  92836. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92837. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92838. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92839. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92840. * is there is now a single API that can be used to encode or decode
  92841. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92842. * on both seekable and non-seekable streams.
  92843. *
  92844. * Instead of creating an encoder or decoder of a certain layer, now the
  92845. * client will always create a FLAC__StreamEncoder or
  92846. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92847. * initialization function. For example, for the decoder,
  92848. * FLAC__stream_decoder_init() has been replaced by
  92849. * FLAC__stream_decoder_init_stream(). This init function takes
  92850. * callbacks for the I/O, and the seeking callbacks are optional. This
  92851. * allows the client to use the same object for seekable and
  92852. * non-seekable streams. For decoding a FLAC file directly, the client
  92853. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92854. * and fewer callbacks; most of the other callbacks are supplied
  92855. * internally. For situations where fopen()ing by filename is not
  92856. * possible (e.g. Unicode filenames on Windows) the client can instead
  92857. * open the file itself and supply the FILE* to
  92858. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92859. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92860. * Since the callbacks and client data are now passed to the init
  92861. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92862. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92863. * rest of the calls to the decoder are the same as before.
  92864. *
  92865. * There are counterpart init functions for Ogg FLAC, e.g.
  92866. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92867. * and callbacks are the same as for native FLAC.
  92868. *
  92869. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92870. * been set up like so:
  92871. *
  92872. * \code
  92873. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92874. * if(decoder == NULL) do_something;
  92875. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92876. * [... other settings ...]
  92877. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92878. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92879. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92880. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92881. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92882. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92883. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92884. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92885. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92886. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92887. * \endcode
  92888. *
  92889. * In FLAC 1.1.3 it is like this:
  92890. *
  92891. * \code
  92892. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92893. * if(decoder == NULL) do_something;
  92894. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92895. * [... other settings ...]
  92896. * if(FLAC__stream_decoder_init_stream(
  92897. * decoder,
  92898. * my_read_callback,
  92899. * my_seek_callback, // or NULL
  92900. * my_tell_callback, // or NULL
  92901. * my_length_callback, // or NULL
  92902. * my_eof_callback, // or NULL
  92903. * my_write_callback,
  92904. * my_metadata_callback, // or NULL
  92905. * my_error_callback,
  92906. * my_client_data
  92907. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92908. * \endcode
  92909. *
  92910. * or you could do;
  92911. *
  92912. * \code
  92913. * [...]
  92914. * FILE *file = fopen("somefile.flac","rb");
  92915. * if(file == NULL) do_somthing;
  92916. * if(FLAC__stream_decoder_init_FILE(
  92917. * decoder,
  92918. * file,
  92919. * my_write_callback,
  92920. * my_metadata_callback, // or NULL
  92921. * my_error_callback,
  92922. * my_client_data
  92923. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92924. * \endcode
  92925. *
  92926. * or just:
  92927. *
  92928. * \code
  92929. * [...]
  92930. * if(FLAC__stream_decoder_init_file(
  92931. * decoder,
  92932. * "somefile.flac",
  92933. * my_write_callback,
  92934. * my_metadata_callback, // or NULL
  92935. * my_error_callback,
  92936. * my_client_data
  92937. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92938. * \endcode
  92939. *
  92940. * Another small change to the decoder is in how it handles unparseable
  92941. * streams. Before, when the decoder found an unparseable stream
  92942. * (reserved for when the decoder encounters a stream from a future
  92943. * encoder that it can't parse), it changed the state to
  92944. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92945. * drops sync and calls the error callback with a new error code
  92946. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92947. * more robust. If your error callback does not discriminate on the the
  92948. * error state, your code does not need to be changed.
  92949. *
  92950. * The encoder now has a new setting:
  92951. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92952. * method used to window the data before LPC analysis. You only need to
  92953. * add a call to this function if the default is not suitable. There
  92954. * are also two new convenience functions that may be useful:
  92955. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92956. * FLAC__metadata_get_cuesheet().
  92957. *
  92958. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92959. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92960. * is now \c size_t instead of \c unsigned.
  92961. */
  92962. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92963. * \ingroup porting
  92964. *
  92965. * \brief
  92966. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92967. *
  92968. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92969. * There was a slight change in the implementation of
  92970. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92971. * of the \a metadata array of pointers so the client no longer needs
  92972. * to maintain it after the call. The objects themselves that are
  92973. * pointed to by the array are still not copied though and must be
  92974. * maintained until the call to FLAC__stream_encoder_finish().
  92975. */
  92976. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92977. * \ingroup porting
  92978. *
  92979. * \brief
  92980. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92981. *
  92982. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92983. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92984. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92985. *
  92986. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92987. * has changed to reflect the conversion of one of the reserved bits
  92988. * into active use. It used to be \c 2 and now is \c 1. However the
  92989. * FLAC frame header length has not changed, so to skip the proper
  92990. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92991. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92992. */
  92993. /** \defgroup flac FLAC C API
  92994. *
  92995. * The FLAC C API is the interface to libFLAC, a set of structures
  92996. * describing the components of FLAC streams, and functions for
  92997. * encoding and decoding streams, as well as manipulating FLAC
  92998. * metadata in files.
  92999. *
  93000. * You should start with the format components as all other modules
  93001. * are dependent on it.
  93002. */
  93003. #endif
  93004. /*** End of inlined file: all.h ***/
  93005. /*** Start of inlined file: bitmath.c ***/
  93006. /*** Start of inlined file: juce_FlacHeader.h ***/
  93007. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93008. // tasks..
  93009. #define VERSION "1.2.1"
  93010. #define FLAC__NO_DLL 1
  93011. #if JUCE_MSVC
  93012. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93013. #endif
  93014. #if JUCE_MAC
  93015. #define FLAC__SYS_DARWIN 1
  93016. #endif
  93017. /*** End of inlined file: juce_FlacHeader.h ***/
  93018. #if JUCE_USE_FLAC
  93019. #if HAVE_CONFIG_H
  93020. # include <config.h>
  93021. #endif
  93022. /*** Start of inlined file: bitmath.h ***/
  93023. #ifndef FLAC__PRIVATE__BITMATH_H
  93024. #define FLAC__PRIVATE__BITMATH_H
  93025. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  93026. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  93027. unsigned FLAC__bitmath_silog2(int v);
  93028. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  93029. #endif
  93030. /*** End of inlined file: bitmath.h ***/
  93031. /* An example of what FLAC__bitmath_ilog2() computes:
  93032. *
  93033. * ilog2( 0) = assertion failure
  93034. * ilog2( 1) = 0
  93035. * ilog2( 2) = 1
  93036. * ilog2( 3) = 1
  93037. * ilog2( 4) = 2
  93038. * ilog2( 5) = 2
  93039. * ilog2( 6) = 2
  93040. * ilog2( 7) = 2
  93041. * ilog2( 8) = 3
  93042. * ilog2( 9) = 3
  93043. * ilog2(10) = 3
  93044. * ilog2(11) = 3
  93045. * ilog2(12) = 3
  93046. * ilog2(13) = 3
  93047. * ilog2(14) = 3
  93048. * ilog2(15) = 3
  93049. * ilog2(16) = 4
  93050. * ilog2(17) = 4
  93051. * ilog2(18) = 4
  93052. */
  93053. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  93054. {
  93055. unsigned l = 0;
  93056. FLAC__ASSERT(v > 0);
  93057. while(v >>= 1)
  93058. l++;
  93059. return l;
  93060. }
  93061. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  93062. {
  93063. unsigned l = 0;
  93064. FLAC__ASSERT(v > 0);
  93065. while(v >>= 1)
  93066. l++;
  93067. return l;
  93068. }
  93069. /* An example of what FLAC__bitmath_silog2() computes:
  93070. *
  93071. * silog2(-10) = 5
  93072. * silog2(- 9) = 5
  93073. * silog2(- 8) = 4
  93074. * silog2(- 7) = 4
  93075. * silog2(- 6) = 4
  93076. * silog2(- 5) = 4
  93077. * silog2(- 4) = 3
  93078. * silog2(- 3) = 3
  93079. * silog2(- 2) = 2
  93080. * silog2(- 1) = 2
  93081. * silog2( 0) = 0
  93082. * silog2( 1) = 2
  93083. * silog2( 2) = 3
  93084. * silog2( 3) = 3
  93085. * silog2( 4) = 4
  93086. * silog2( 5) = 4
  93087. * silog2( 6) = 4
  93088. * silog2( 7) = 4
  93089. * silog2( 8) = 5
  93090. * silog2( 9) = 5
  93091. * silog2( 10) = 5
  93092. */
  93093. unsigned FLAC__bitmath_silog2(int v)
  93094. {
  93095. while(1) {
  93096. if(v == 0) {
  93097. return 0;
  93098. }
  93099. else if(v > 0) {
  93100. unsigned l = 0;
  93101. while(v) {
  93102. l++;
  93103. v >>= 1;
  93104. }
  93105. return l+1;
  93106. }
  93107. else if(v == -1) {
  93108. return 2;
  93109. }
  93110. else {
  93111. v++;
  93112. v = -v;
  93113. }
  93114. }
  93115. }
  93116. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  93117. {
  93118. while(1) {
  93119. if(v == 0) {
  93120. return 0;
  93121. }
  93122. else if(v > 0) {
  93123. unsigned l = 0;
  93124. while(v) {
  93125. l++;
  93126. v >>= 1;
  93127. }
  93128. return l+1;
  93129. }
  93130. else if(v == -1) {
  93131. return 2;
  93132. }
  93133. else {
  93134. v++;
  93135. v = -v;
  93136. }
  93137. }
  93138. }
  93139. #endif
  93140. /*** End of inlined file: bitmath.c ***/
  93141. /*** Start of inlined file: bitreader.c ***/
  93142. /*** Start of inlined file: juce_FlacHeader.h ***/
  93143. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93144. // tasks..
  93145. #define VERSION "1.2.1"
  93146. #define FLAC__NO_DLL 1
  93147. #if JUCE_MSVC
  93148. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93149. #endif
  93150. #if JUCE_MAC
  93151. #define FLAC__SYS_DARWIN 1
  93152. #endif
  93153. /*** End of inlined file: juce_FlacHeader.h ***/
  93154. #if JUCE_USE_FLAC
  93155. #if HAVE_CONFIG_H
  93156. # include <config.h>
  93157. #endif
  93158. #include <stdlib.h> /* for malloc() */
  93159. #include <string.h> /* for memcpy(), memset() */
  93160. #ifdef _MSC_VER
  93161. #include <winsock.h> /* for ntohl() */
  93162. #elif defined FLAC__SYS_DARWIN
  93163. #include <machine/endian.h> /* for ntohl() */
  93164. #elif defined __MINGW32__
  93165. #include <winsock.h> /* for ntohl() */
  93166. #else
  93167. #include <netinet/in.h> /* for ntohl() */
  93168. #endif
  93169. /*** Start of inlined file: bitreader.h ***/
  93170. #ifndef FLAC__PRIVATE__BITREADER_H
  93171. #define FLAC__PRIVATE__BITREADER_H
  93172. #include <stdio.h> /* for FILE */
  93173. /*** Start of inlined file: cpu.h ***/
  93174. #ifndef FLAC__PRIVATE__CPU_H
  93175. #define FLAC__PRIVATE__CPU_H
  93176. #ifdef HAVE_CONFIG_H
  93177. #include <config.h>
  93178. #endif
  93179. typedef enum {
  93180. FLAC__CPUINFO_TYPE_IA32,
  93181. FLAC__CPUINFO_TYPE_PPC,
  93182. FLAC__CPUINFO_TYPE_UNKNOWN
  93183. } FLAC__CPUInfo_Type;
  93184. typedef struct {
  93185. FLAC__bool cpuid;
  93186. FLAC__bool bswap;
  93187. FLAC__bool cmov;
  93188. FLAC__bool mmx;
  93189. FLAC__bool fxsr;
  93190. FLAC__bool sse;
  93191. FLAC__bool sse2;
  93192. FLAC__bool sse3;
  93193. FLAC__bool ssse3;
  93194. FLAC__bool _3dnow;
  93195. FLAC__bool ext3dnow;
  93196. FLAC__bool extmmx;
  93197. } FLAC__CPUInfo_IA32;
  93198. typedef struct {
  93199. FLAC__bool altivec;
  93200. FLAC__bool ppc64;
  93201. } FLAC__CPUInfo_PPC;
  93202. typedef struct {
  93203. FLAC__bool use_asm;
  93204. FLAC__CPUInfo_Type type;
  93205. union {
  93206. FLAC__CPUInfo_IA32 ia32;
  93207. FLAC__CPUInfo_PPC ppc;
  93208. } data;
  93209. } FLAC__CPUInfo;
  93210. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93211. #ifndef FLAC__NO_ASM
  93212. #ifdef FLAC__CPU_IA32
  93213. #ifdef FLAC__HAS_NASM
  93214. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93215. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93216. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93217. #endif
  93218. #endif
  93219. #endif
  93220. #endif
  93221. /*** End of inlined file: cpu.h ***/
  93222. /*
  93223. * opaque structure definition
  93224. */
  93225. struct FLAC__BitReader;
  93226. typedef struct FLAC__BitReader FLAC__BitReader;
  93227. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93228. /*
  93229. * construction, deletion, initialization, etc functions
  93230. */
  93231. FLAC__BitReader *FLAC__bitreader_new(void);
  93232. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93233. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93234. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93235. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93236. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93237. /*
  93238. * CRC functions
  93239. */
  93240. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93241. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93242. /*
  93243. * info functions
  93244. */
  93245. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93246. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93247. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93248. /*
  93249. * read functions
  93250. */
  93251. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93252. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93253. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93254. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93255. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93256. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93257. 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! */
  93258. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93259. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93260. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93261. #ifndef FLAC__NO_ASM
  93262. # ifdef FLAC__CPU_IA32
  93263. # ifdef FLAC__HAS_NASM
  93264. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93265. # endif
  93266. # endif
  93267. #endif
  93268. #if 0 /* UNUSED */
  93269. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93270. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93271. #endif
  93272. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93273. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93274. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93275. #endif
  93276. /*** End of inlined file: bitreader.h ***/
  93277. /*** Start of inlined file: crc.h ***/
  93278. #ifndef FLAC__PRIVATE__CRC_H
  93279. #define FLAC__PRIVATE__CRC_H
  93280. /* 8 bit CRC generator, MSB shifted first
  93281. ** polynomial = x^8 + x^2 + x^1 + x^0
  93282. ** init = 0
  93283. */
  93284. extern FLAC__byte const FLAC__crc8_table[256];
  93285. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93286. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93287. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93288. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93289. /* 16 bit CRC generator, MSB shifted first
  93290. ** polynomial = x^16 + x^15 + x^2 + x^0
  93291. ** init = 0
  93292. */
  93293. extern unsigned FLAC__crc16_table[256];
  93294. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93295. /* this alternate may be faster on some systems/compilers */
  93296. #if 0
  93297. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93298. #endif
  93299. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93300. #endif
  93301. /*** End of inlined file: crc.h ***/
  93302. /* Things should be fastest when this matches the machine word size */
  93303. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93304. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93305. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93306. typedef FLAC__uint32 brword;
  93307. #define FLAC__BYTES_PER_WORD 4
  93308. #define FLAC__BITS_PER_WORD 32
  93309. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93310. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93311. #if WORDS_BIGENDIAN
  93312. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93313. #else
  93314. #if defined (_MSC_VER) && defined (_X86_)
  93315. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93316. #else
  93317. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93318. #endif
  93319. #endif
  93320. /* counts the # of zero MSBs in a word */
  93321. #define COUNT_ZERO_MSBS(word) ( \
  93322. (word) <= 0xffff ? \
  93323. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93324. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93325. )
  93326. /* this alternate might be slightly faster on some systems/compilers: */
  93327. #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])) )
  93328. /*
  93329. * This should be at least twice as large as the largest number of words
  93330. * required to represent any 'number' (in any encoding) you are going to
  93331. * read. With FLAC this is on the order of maybe a few hundred bits.
  93332. * If the buffer is smaller than that, the decoder won't be able to read
  93333. * in a whole number that is in a variable length encoding (e.g. Rice).
  93334. * But to be practical it should be at least 1K bytes.
  93335. *
  93336. * Increase this number to decrease the number of read callbacks, at the
  93337. * expense of using more memory. Or decrease for the reverse effect,
  93338. * keeping in mind the limit from the first paragraph. The optimal size
  93339. * also depends on the CPU cache size and other factors; some twiddling
  93340. * may be necessary to squeeze out the best performance.
  93341. */
  93342. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93343. static const unsigned char byte_to_unary_table[] = {
  93344. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93345. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93346. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93347. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93348. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93349. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93350. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93351. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93360. };
  93361. #ifdef min
  93362. #undef min
  93363. #endif
  93364. #define min(x,y) ((x)<(y)?(x):(y))
  93365. #ifdef max
  93366. #undef max
  93367. #endif
  93368. #define max(x,y) ((x)>(y)?(x):(y))
  93369. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93370. #ifdef _MSC_VER
  93371. #define FLAC__U64L(x) x
  93372. #else
  93373. #define FLAC__U64L(x) x##LLU
  93374. #endif
  93375. #ifndef FLaC__INLINE
  93376. #define FLaC__INLINE
  93377. #endif
  93378. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93379. struct FLAC__BitReader {
  93380. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93381. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93382. brword *buffer;
  93383. unsigned capacity; /* in words */
  93384. unsigned words; /* # of completed words in buffer */
  93385. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93386. unsigned consumed_words; /* #words ... */
  93387. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93388. unsigned read_crc16; /* the running frame CRC */
  93389. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93390. FLAC__BitReaderReadCallback read_callback;
  93391. void *client_data;
  93392. FLAC__CPUInfo cpu_info;
  93393. };
  93394. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93395. {
  93396. register unsigned crc = br->read_crc16;
  93397. #if FLAC__BYTES_PER_WORD == 4
  93398. switch(br->crc16_align) {
  93399. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93400. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93401. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93402. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93403. }
  93404. #elif FLAC__BYTES_PER_WORD == 8
  93405. switch(br->crc16_align) {
  93406. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93407. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93408. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93409. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93410. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93411. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93412. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93413. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93414. }
  93415. #else
  93416. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93417. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93418. br->read_crc16 = crc;
  93419. #endif
  93420. br->crc16_align = 0;
  93421. }
  93422. /* would be static except it needs to be called by asm routines */
  93423. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93424. {
  93425. unsigned start, end;
  93426. size_t bytes;
  93427. FLAC__byte *target;
  93428. /* first shift the unconsumed buffer data toward the front as much as possible */
  93429. if(br->consumed_words > 0) {
  93430. start = br->consumed_words;
  93431. end = br->words + (br->bytes? 1:0);
  93432. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93433. br->words -= start;
  93434. br->consumed_words = 0;
  93435. }
  93436. /*
  93437. * set the target for reading, taking into account word alignment and endianness
  93438. */
  93439. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93440. if(bytes == 0)
  93441. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93442. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93443. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93444. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93445. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93446. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93447. * ^^-------target, bytes=3
  93448. * on LE machines, have to byteswap the odd tail word so nothing is
  93449. * overwritten:
  93450. */
  93451. #if WORDS_BIGENDIAN
  93452. #else
  93453. if(br->bytes)
  93454. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93455. #endif
  93456. /* now it looks like:
  93457. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93458. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93459. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93460. * ^^-------target, bytes=3
  93461. */
  93462. /* read in the data; note that the callback may return a smaller number of bytes */
  93463. if(!br->read_callback(target, &bytes, br->client_data))
  93464. return false;
  93465. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93466. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93467. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93468. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93469. * now have to byteswap on LE machines:
  93470. */
  93471. #if WORDS_BIGENDIAN
  93472. #else
  93473. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93474. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93475. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93476. start = br->words;
  93477. local_swap32_block_(br->buffer + start, end - start);
  93478. }
  93479. else
  93480. # endif
  93481. for(start = br->words; start < end; start++)
  93482. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93483. #endif
  93484. /* now it looks like:
  93485. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93486. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93487. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93488. * finally we'll update the reader values:
  93489. */
  93490. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93491. br->words = end / FLAC__BYTES_PER_WORD;
  93492. br->bytes = end % FLAC__BYTES_PER_WORD;
  93493. return true;
  93494. }
  93495. /***********************************************************************
  93496. *
  93497. * Class constructor/destructor
  93498. *
  93499. ***********************************************************************/
  93500. FLAC__BitReader *FLAC__bitreader_new(void)
  93501. {
  93502. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93503. /* calloc() implies:
  93504. memset(br, 0, sizeof(FLAC__BitReader));
  93505. br->buffer = 0;
  93506. br->capacity = 0;
  93507. br->words = br->bytes = 0;
  93508. br->consumed_words = br->consumed_bits = 0;
  93509. br->read_callback = 0;
  93510. br->client_data = 0;
  93511. */
  93512. return br;
  93513. }
  93514. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93515. {
  93516. FLAC__ASSERT(0 != br);
  93517. FLAC__bitreader_free(br);
  93518. free(br);
  93519. }
  93520. /***********************************************************************
  93521. *
  93522. * Public class methods
  93523. *
  93524. ***********************************************************************/
  93525. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93526. {
  93527. FLAC__ASSERT(0 != br);
  93528. br->words = br->bytes = 0;
  93529. br->consumed_words = br->consumed_bits = 0;
  93530. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93531. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93532. if(br->buffer == 0)
  93533. return false;
  93534. br->read_callback = rcb;
  93535. br->client_data = cd;
  93536. br->cpu_info = cpu;
  93537. return true;
  93538. }
  93539. void FLAC__bitreader_free(FLAC__BitReader *br)
  93540. {
  93541. FLAC__ASSERT(0 != br);
  93542. if(0 != br->buffer)
  93543. free(br->buffer);
  93544. br->buffer = 0;
  93545. br->capacity = 0;
  93546. br->words = br->bytes = 0;
  93547. br->consumed_words = br->consumed_bits = 0;
  93548. br->read_callback = 0;
  93549. br->client_data = 0;
  93550. }
  93551. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93552. {
  93553. br->words = br->bytes = 0;
  93554. br->consumed_words = br->consumed_bits = 0;
  93555. return true;
  93556. }
  93557. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93558. {
  93559. unsigned i, j;
  93560. if(br == 0) {
  93561. fprintf(out, "bitreader is NULL\n");
  93562. }
  93563. else {
  93564. 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);
  93565. for(i = 0; i < br->words; i++) {
  93566. fprintf(out, "%08X: ", i);
  93567. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93568. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93569. fprintf(out, ".");
  93570. else
  93571. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93572. fprintf(out, "\n");
  93573. }
  93574. if(br->bytes > 0) {
  93575. fprintf(out, "%08X: ", i);
  93576. for(j = 0; j < br->bytes*8; j++)
  93577. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93578. fprintf(out, ".");
  93579. else
  93580. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93581. fprintf(out, "\n");
  93582. }
  93583. }
  93584. }
  93585. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93586. {
  93587. FLAC__ASSERT(0 != br);
  93588. FLAC__ASSERT(0 != br->buffer);
  93589. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93590. br->read_crc16 = (unsigned)seed;
  93591. br->crc16_align = br->consumed_bits;
  93592. }
  93593. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93594. {
  93595. FLAC__ASSERT(0 != br);
  93596. FLAC__ASSERT(0 != br->buffer);
  93597. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93598. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93599. /* CRC any tail bytes in a partially-consumed word */
  93600. if(br->consumed_bits) {
  93601. const brword tail = br->buffer[br->consumed_words];
  93602. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93603. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93604. }
  93605. return br->read_crc16;
  93606. }
  93607. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93608. {
  93609. return ((br->consumed_bits & 7) == 0);
  93610. }
  93611. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93612. {
  93613. return 8 - (br->consumed_bits & 7);
  93614. }
  93615. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93616. {
  93617. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93618. }
  93619. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93620. {
  93621. FLAC__ASSERT(0 != br);
  93622. FLAC__ASSERT(0 != br->buffer);
  93623. FLAC__ASSERT(bits <= 32);
  93624. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93625. FLAC__ASSERT(br->consumed_words <= br->words);
  93626. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93627. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93628. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93629. *val = 0;
  93630. return true;
  93631. }
  93632. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93633. if(!bitreader_read_from_client_(br))
  93634. return false;
  93635. }
  93636. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93637. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93638. if(br->consumed_bits) {
  93639. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93640. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93641. const brword word = br->buffer[br->consumed_words];
  93642. if(bits < n) {
  93643. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93644. br->consumed_bits += bits;
  93645. return true;
  93646. }
  93647. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93648. bits -= n;
  93649. crc16_update_word_(br, word);
  93650. br->consumed_words++;
  93651. br->consumed_bits = 0;
  93652. 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 */
  93653. *val <<= bits;
  93654. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93655. br->consumed_bits = bits;
  93656. }
  93657. return true;
  93658. }
  93659. else {
  93660. const brword word = br->buffer[br->consumed_words];
  93661. if(bits < FLAC__BITS_PER_WORD) {
  93662. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93663. br->consumed_bits = bits;
  93664. return true;
  93665. }
  93666. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93667. *val = word;
  93668. crc16_update_word_(br, word);
  93669. br->consumed_words++;
  93670. return true;
  93671. }
  93672. }
  93673. else {
  93674. /* in this case we're starting our read at a partial tail word;
  93675. * the reader has guaranteed that we have at least 'bits' bits
  93676. * available to read, which makes this case simpler.
  93677. */
  93678. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93679. if(br->consumed_bits) {
  93680. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93681. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93682. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93683. br->consumed_bits += bits;
  93684. return true;
  93685. }
  93686. else {
  93687. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93688. br->consumed_bits += bits;
  93689. return true;
  93690. }
  93691. }
  93692. }
  93693. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93694. {
  93695. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93696. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93697. return false;
  93698. /* sign-extend: */
  93699. *val <<= (32-bits);
  93700. *val >>= (32-bits);
  93701. return true;
  93702. }
  93703. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93704. {
  93705. FLAC__uint32 hi, lo;
  93706. if(bits > 32) {
  93707. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93708. return false;
  93709. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93710. return false;
  93711. *val = hi;
  93712. *val <<= 32;
  93713. *val |= lo;
  93714. }
  93715. else {
  93716. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93717. return false;
  93718. *val = lo;
  93719. }
  93720. return true;
  93721. }
  93722. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93723. {
  93724. FLAC__uint32 x8, x32 = 0;
  93725. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93726. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93727. return false;
  93728. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93729. return false;
  93730. x32 |= (x8 << 8);
  93731. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93732. return false;
  93733. x32 |= (x8 << 16);
  93734. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93735. return false;
  93736. x32 |= (x8 << 24);
  93737. *val = x32;
  93738. return true;
  93739. }
  93740. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93741. {
  93742. /*
  93743. * OPT: a faster implementation is possible but probably not that useful
  93744. * since this is only called a couple of times in the metadata readers.
  93745. */
  93746. FLAC__ASSERT(0 != br);
  93747. FLAC__ASSERT(0 != br->buffer);
  93748. if(bits > 0) {
  93749. const unsigned n = br->consumed_bits & 7;
  93750. unsigned m;
  93751. FLAC__uint32 x;
  93752. if(n != 0) {
  93753. m = min(8-n, bits);
  93754. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93755. return false;
  93756. bits -= m;
  93757. }
  93758. m = bits / 8;
  93759. if(m > 0) {
  93760. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93761. return false;
  93762. bits %= 8;
  93763. }
  93764. if(bits > 0) {
  93765. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93766. return false;
  93767. }
  93768. }
  93769. return true;
  93770. }
  93771. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93772. {
  93773. FLAC__uint32 x;
  93774. FLAC__ASSERT(0 != br);
  93775. FLAC__ASSERT(0 != br->buffer);
  93776. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93777. /* step 1: skip over partial head word to get word aligned */
  93778. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93779. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93780. return false;
  93781. nvals--;
  93782. }
  93783. if(0 == nvals)
  93784. return true;
  93785. /* step 2: skip whole words in chunks */
  93786. while(nvals >= FLAC__BYTES_PER_WORD) {
  93787. if(br->consumed_words < br->words) {
  93788. br->consumed_words++;
  93789. nvals -= FLAC__BYTES_PER_WORD;
  93790. }
  93791. else if(!bitreader_read_from_client_(br))
  93792. return false;
  93793. }
  93794. /* step 3: skip any remainder from partial tail bytes */
  93795. while(nvals) {
  93796. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93797. return false;
  93798. nvals--;
  93799. }
  93800. return true;
  93801. }
  93802. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93803. {
  93804. FLAC__uint32 x;
  93805. FLAC__ASSERT(0 != br);
  93806. FLAC__ASSERT(0 != br->buffer);
  93807. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93808. /* step 1: read from partial head word to get word aligned */
  93809. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93810. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93811. return false;
  93812. *val++ = (FLAC__byte)x;
  93813. nvals--;
  93814. }
  93815. if(0 == nvals)
  93816. return true;
  93817. /* step 2: read whole words in chunks */
  93818. while(nvals >= FLAC__BYTES_PER_WORD) {
  93819. if(br->consumed_words < br->words) {
  93820. const brword word = br->buffer[br->consumed_words++];
  93821. #if FLAC__BYTES_PER_WORD == 4
  93822. val[0] = (FLAC__byte)(word >> 24);
  93823. val[1] = (FLAC__byte)(word >> 16);
  93824. val[2] = (FLAC__byte)(word >> 8);
  93825. val[3] = (FLAC__byte)word;
  93826. #elif FLAC__BYTES_PER_WORD == 8
  93827. val[0] = (FLAC__byte)(word >> 56);
  93828. val[1] = (FLAC__byte)(word >> 48);
  93829. val[2] = (FLAC__byte)(word >> 40);
  93830. val[3] = (FLAC__byte)(word >> 32);
  93831. val[4] = (FLAC__byte)(word >> 24);
  93832. val[5] = (FLAC__byte)(word >> 16);
  93833. val[6] = (FLAC__byte)(word >> 8);
  93834. val[7] = (FLAC__byte)word;
  93835. #else
  93836. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93837. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93838. #endif
  93839. val += FLAC__BYTES_PER_WORD;
  93840. nvals -= FLAC__BYTES_PER_WORD;
  93841. }
  93842. else if(!bitreader_read_from_client_(br))
  93843. return false;
  93844. }
  93845. /* step 3: read any remainder from partial tail bytes */
  93846. while(nvals) {
  93847. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93848. return false;
  93849. *val++ = (FLAC__byte)x;
  93850. nvals--;
  93851. }
  93852. return true;
  93853. }
  93854. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93855. #if 0 /* slow but readable version */
  93856. {
  93857. unsigned bit;
  93858. FLAC__ASSERT(0 != br);
  93859. FLAC__ASSERT(0 != br->buffer);
  93860. *val = 0;
  93861. while(1) {
  93862. if(!FLAC__bitreader_read_bit(br, &bit))
  93863. return false;
  93864. if(bit)
  93865. break;
  93866. else
  93867. *val++;
  93868. }
  93869. return true;
  93870. }
  93871. #else
  93872. {
  93873. unsigned i;
  93874. FLAC__ASSERT(0 != br);
  93875. FLAC__ASSERT(0 != br->buffer);
  93876. *val = 0;
  93877. while(1) {
  93878. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93879. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93880. if(b) {
  93881. i = COUNT_ZERO_MSBS(b);
  93882. *val += i;
  93883. i++;
  93884. br->consumed_bits += i;
  93885. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93886. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93887. br->consumed_words++;
  93888. br->consumed_bits = 0;
  93889. }
  93890. return true;
  93891. }
  93892. else {
  93893. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93894. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93895. br->consumed_words++;
  93896. br->consumed_bits = 0;
  93897. /* didn't find stop bit yet, have to keep going... */
  93898. }
  93899. }
  93900. /* at this point we've eaten up all the whole words; have to try
  93901. * reading through any tail bytes before calling the read callback.
  93902. * this is a repeat of the above logic adjusted for the fact we
  93903. * don't have a whole word. note though if the client is feeding
  93904. * us data a byte at a time (unlikely), br->consumed_bits may not
  93905. * be zero.
  93906. */
  93907. if(br->bytes) {
  93908. const unsigned end = br->bytes * 8;
  93909. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93910. if(b) {
  93911. i = COUNT_ZERO_MSBS(b);
  93912. *val += i;
  93913. i++;
  93914. br->consumed_bits += i;
  93915. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93916. return true;
  93917. }
  93918. else {
  93919. *val += end - br->consumed_bits;
  93920. br->consumed_bits += end;
  93921. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93922. /* didn't find stop bit yet, have to keep going... */
  93923. }
  93924. }
  93925. if(!bitreader_read_from_client_(br))
  93926. return false;
  93927. }
  93928. }
  93929. #endif
  93930. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93931. {
  93932. FLAC__uint32 lsbs = 0, msbs = 0;
  93933. unsigned uval;
  93934. FLAC__ASSERT(0 != br);
  93935. FLAC__ASSERT(0 != br->buffer);
  93936. FLAC__ASSERT(parameter <= 31);
  93937. /* read the unary MSBs and end bit */
  93938. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93939. return false;
  93940. /* read the binary LSBs */
  93941. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93942. return false;
  93943. /* compose the value */
  93944. uval = (msbs << parameter) | lsbs;
  93945. if(uval & 1)
  93946. *val = -((int)(uval >> 1)) - 1;
  93947. else
  93948. *val = (int)(uval >> 1);
  93949. return true;
  93950. }
  93951. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93952. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93953. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93954. /* OPT: possibly faster version for use with MSVC */
  93955. #ifdef _MSC_VER
  93956. {
  93957. unsigned i;
  93958. unsigned uval = 0;
  93959. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93960. /* try and get br->consumed_words and br->consumed_bits into register;
  93961. * must remember to flush them back to *br before calling other
  93962. * bitwriter functions that use them, and before returning */
  93963. register unsigned cwords;
  93964. register unsigned cbits;
  93965. FLAC__ASSERT(0 != br);
  93966. FLAC__ASSERT(0 != br->buffer);
  93967. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93968. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93969. FLAC__ASSERT(parameter < 32);
  93970. /* 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 */
  93971. if(nvals == 0)
  93972. return true;
  93973. cbits = br->consumed_bits;
  93974. cwords = br->consumed_words;
  93975. while(1) {
  93976. /* read unary part */
  93977. while(1) {
  93978. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93979. brword b = br->buffer[cwords] << cbits;
  93980. if(b) {
  93981. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93982. __asm {
  93983. bsr eax, b
  93984. not eax
  93985. and eax, 31
  93986. mov i, eax
  93987. }
  93988. #else
  93989. i = COUNT_ZERO_MSBS(b);
  93990. #endif
  93991. uval += i;
  93992. bits = parameter;
  93993. i++;
  93994. cbits += i;
  93995. if(cbits == FLAC__BITS_PER_WORD) {
  93996. crc16_update_word_(br, br->buffer[cwords]);
  93997. cwords++;
  93998. cbits = 0;
  93999. }
  94000. goto break1;
  94001. }
  94002. else {
  94003. uval += FLAC__BITS_PER_WORD - cbits;
  94004. crc16_update_word_(br, br->buffer[cwords]);
  94005. cwords++;
  94006. cbits = 0;
  94007. /* didn't find stop bit yet, have to keep going... */
  94008. }
  94009. }
  94010. /* at this point we've eaten up all the whole words; have to try
  94011. * reading through any tail bytes before calling the read callback.
  94012. * this is a repeat of the above logic adjusted for the fact we
  94013. * don't have a whole word. note though if the client is feeding
  94014. * us data a byte at a time (unlikely), br->consumed_bits may not
  94015. * be zero.
  94016. */
  94017. if(br->bytes) {
  94018. const unsigned end = br->bytes * 8;
  94019. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  94020. if(b) {
  94021. i = COUNT_ZERO_MSBS(b);
  94022. uval += i;
  94023. bits = parameter;
  94024. i++;
  94025. cbits += i;
  94026. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94027. goto break1;
  94028. }
  94029. else {
  94030. uval += end - cbits;
  94031. cbits += end;
  94032. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94033. /* didn't find stop bit yet, have to keep going... */
  94034. }
  94035. }
  94036. /* flush registers and read; bitreader_read_from_client_() does
  94037. * not touch br->consumed_bits at all but we still need to set
  94038. * it in case it fails and we have to return false.
  94039. */
  94040. br->consumed_bits = cbits;
  94041. br->consumed_words = cwords;
  94042. if(!bitreader_read_from_client_(br))
  94043. return false;
  94044. cwords = br->consumed_words;
  94045. }
  94046. break1:
  94047. /* read binary part */
  94048. FLAC__ASSERT(cwords <= br->words);
  94049. if(bits) {
  94050. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  94051. /* flush registers and read; bitreader_read_from_client_() does
  94052. * not touch br->consumed_bits at all but we still need to set
  94053. * it in case it fails and we have to return false.
  94054. */
  94055. br->consumed_bits = cbits;
  94056. br->consumed_words = cwords;
  94057. if(!bitreader_read_from_client_(br))
  94058. return false;
  94059. cwords = br->consumed_words;
  94060. }
  94061. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94062. if(cbits) {
  94063. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94064. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94065. const brword word = br->buffer[cwords];
  94066. if(bits < n) {
  94067. uval <<= bits;
  94068. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  94069. cbits += bits;
  94070. goto break2;
  94071. }
  94072. uval <<= n;
  94073. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94074. bits -= n;
  94075. crc16_update_word_(br, word);
  94076. cwords++;
  94077. cbits = 0;
  94078. 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 */
  94079. uval <<= bits;
  94080. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  94081. cbits = bits;
  94082. }
  94083. goto break2;
  94084. }
  94085. else {
  94086. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  94087. uval <<= bits;
  94088. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94089. cbits = bits;
  94090. goto break2;
  94091. }
  94092. }
  94093. else {
  94094. /* in this case we're starting our read at a partial tail word;
  94095. * the reader has guaranteed that we have at least 'bits' bits
  94096. * available to read, which makes this case simpler.
  94097. */
  94098. uval <<= bits;
  94099. if(cbits) {
  94100. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94101. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  94102. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  94103. cbits += bits;
  94104. goto break2;
  94105. }
  94106. else {
  94107. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94108. cbits += bits;
  94109. goto break2;
  94110. }
  94111. }
  94112. }
  94113. break2:
  94114. /* compose the value */
  94115. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94116. /* are we done? */
  94117. --nvals;
  94118. if(nvals == 0) {
  94119. br->consumed_bits = cbits;
  94120. br->consumed_words = cwords;
  94121. return true;
  94122. }
  94123. uval = 0;
  94124. ++vals;
  94125. }
  94126. }
  94127. #else
  94128. {
  94129. unsigned i;
  94130. unsigned uval = 0;
  94131. /* try and get br->consumed_words and br->consumed_bits into register;
  94132. * must remember to flush them back to *br before calling other
  94133. * bitwriter functions that use them, and before returning */
  94134. register unsigned cwords;
  94135. register unsigned cbits;
  94136. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  94137. FLAC__ASSERT(0 != br);
  94138. FLAC__ASSERT(0 != br->buffer);
  94139. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94140. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94141. FLAC__ASSERT(parameter < 32);
  94142. /* 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 */
  94143. if(nvals == 0)
  94144. return true;
  94145. cbits = br->consumed_bits;
  94146. cwords = br->consumed_words;
  94147. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94148. while(1) {
  94149. /* read unary part */
  94150. while(1) {
  94151. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94152. brword b = br->buffer[cwords] << cbits;
  94153. if(b) {
  94154. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  94155. asm volatile (
  94156. "bsrl %1, %0;"
  94157. "notl %0;"
  94158. "andl $31, %0;"
  94159. : "=r"(i)
  94160. : "r"(b)
  94161. );
  94162. #else
  94163. i = COUNT_ZERO_MSBS(b);
  94164. #endif
  94165. uval += i;
  94166. cbits += i;
  94167. cbits++; /* skip over stop bit */
  94168. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  94169. crc16_update_word_(br, br->buffer[cwords]);
  94170. cwords++;
  94171. cbits = 0;
  94172. }
  94173. goto break1;
  94174. }
  94175. else {
  94176. uval += FLAC__BITS_PER_WORD - cbits;
  94177. crc16_update_word_(br, br->buffer[cwords]);
  94178. cwords++;
  94179. cbits = 0;
  94180. /* didn't find stop bit yet, have to keep going... */
  94181. }
  94182. }
  94183. /* at this point we've eaten up all the whole words; have to try
  94184. * reading through any tail bytes before calling the read callback.
  94185. * this is a repeat of the above logic adjusted for the fact we
  94186. * don't have a whole word. note though if the client is feeding
  94187. * us data a byte at a time (unlikely), br->consumed_bits may not
  94188. * be zero.
  94189. */
  94190. if(br->bytes) {
  94191. const unsigned end = br->bytes * 8;
  94192. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94193. if(b) {
  94194. i = COUNT_ZERO_MSBS(b);
  94195. uval += i;
  94196. cbits += i;
  94197. cbits++; /* skip over stop bit */
  94198. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94199. goto break1;
  94200. }
  94201. else {
  94202. uval += end - cbits;
  94203. cbits += end;
  94204. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94205. /* didn't find stop bit yet, have to keep going... */
  94206. }
  94207. }
  94208. /* flush registers and read; bitreader_read_from_client_() does
  94209. * not touch br->consumed_bits at all but we still need to set
  94210. * it in case it fails and we have to return false.
  94211. */
  94212. br->consumed_bits = cbits;
  94213. br->consumed_words = cwords;
  94214. if(!bitreader_read_from_client_(br))
  94215. return false;
  94216. cwords = br->consumed_words;
  94217. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94218. /* + uval to offset our count by the # of unary bits already
  94219. * consumed before the read, because we will add these back
  94220. * in all at once at break1
  94221. */
  94222. }
  94223. break1:
  94224. ucbits -= uval;
  94225. ucbits--; /* account for stop bit */
  94226. /* read binary part */
  94227. FLAC__ASSERT(cwords <= br->words);
  94228. if(parameter) {
  94229. while(ucbits < parameter) {
  94230. /* flush registers and read; bitreader_read_from_client_() does
  94231. * not touch br->consumed_bits at all but we still need to set
  94232. * it in case it fails and we have to return false.
  94233. */
  94234. br->consumed_bits = cbits;
  94235. br->consumed_words = cwords;
  94236. if(!bitreader_read_from_client_(br))
  94237. return false;
  94238. cwords = br->consumed_words;
  94239. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94240. }
  94241. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94242. if(cbits) {
  94243. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94244. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94245. const brword word = br->buffer[cwords];
  94246. if(parameter < n) {
  94247. uval <<= parameter;
  94248. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94249. cbits += parameter;
  94250. }
  94251. else {
  94252. uval <<= n;
  94253. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94254. crc16_update_word_(br, word);
  94255. cwords++;
  94256. cbits = parameter - n;
  94257. 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 */
  94258. uval <<= cbits;
  94259. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94260. }
  94261. }
  94262. }
  94263. else {
  94264. cbits = parameter;
  94265. uval <<= parameter;
  94266. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94267. }
  94268. }
  94269. else {
  94270. /* in this case we're starting our read at a partial tail word;
  94271. * the reader has guaranteed that we have at least 'parameter'
  94272. * bits available to read, which makes this case simpler.
  94273. */
  94274. uval <<= parameter;
  94275. if(cbits) {
  94276. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94277. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94278. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94279. cbits += parameter;
  94280. }
  94281. else {
  94282. cbits = parameter;
  94283. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94284. }
  94285. }
  94286. }
  94287. ucbits -= parameter;
  94288. /* compose the value */
  94289. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94290. /* are we done? */
  94291. --nvals;
  94292. if(nvals == 0) {
  94293. br->consumed_bits = cbits;
  94294. br->consumed_words = cwords;
  94295. return true;
  94296. }
  94297. uval = 0;
  94298. ++vals;
  94299. }
  94300. }
  94301. #endif
  94302. #if 0 /* UNUSED */
  94303. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94304. {
  94305. FLAC__uint32 lsbs = 0, msbs = 0;
  94306. unsigned bit, uval, k;
  94307. FLAC__ASSERT(0 != br);
  94308. FLAC__ASSERT(0 != br->buffer);
  94309. k = FLAC__bitmath_ilog2(parameter);
  94310. /* read the unary MSBs and end bit */
  94311. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94312. return false;
  94313. /* read the binary LSBs */
  94314. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94315. return false;
  94316. if(parameter == 1u<<k) {
  94317. /* compose the value */
  94318. uval = (msbs << k) | lsbs;
  94319. }
  94320. else {
  94321. unsigned d = (1 << (k+1)) - parameter;
  94322. if(lsbs >= d) {
  94323. if(!FLAC__bitreader_read_bit(br, &bit))
  94324. return false;
  94325. lsbs <<= 1;
  94326. lsbs |= bit;
  94327. lsbs -= d;
  94328. }
  94329. /* compose the value */
  94330. uval = msbs * parameter + lsbs;
  94331. }
  94332. /* unfold unsigned to signed */
  94333. if(uval & 1)
  94334. *val = -((int)(uval >> 1)) - 1;
  94335. else
  94336. *val = (int)(uval >> 1);
  94337. return true;
  94338. }
  94339. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94340. {
  94341. FLAC__uint32 lsbs, msbs = 0;
  94342. unsigned bit, k;
  94343. FLAC__ASSERT(0 != br);
  94344. FLAC__ASSERT(0 != br->buffer);
  94345. k = FLAC__bitmath_ilog2(parameter);
  94346. /* read the unary MSBs and end bit */
  94347. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94348. return false;
  94349. /* read the binary LSBs */
  94350. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94351. return false;
  94352. if(parameter == 1u<<k) {
  94353. /* compose the value */
  94354. *val = (msbs << k) | lsbs;
  94355. }
  94356. else {
  94357. unsigned d = (1 << (k+1)) - parameter;
  94358. if(lsbs >= d) {
  94359. if(!FLAC__bitreader_read_bit(br, &bit))
  94360. return false;
  94361. lsbs <<= 1;
  94362. lsbs |= bit;
  94363. lsbs -= d;
  94364. }
  94365. /* compose the value */
  94366. *val = msbs * parameter + lsbs;
  94367. }
  94368. return true;
  94369. }
  94370. #endif /* UNUSED */
  94371. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94372. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94373. {
  94374. FLAC__uint32 v = 0;
  94375. FLAC__uint32 x;
  94376. unsigned i;
  94377. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94378. return false;
  94379. if(raw)
  94380. raw[(*rawlen)++] = (FLAC__byte)x;
  94381. if(!(x & 0x80)) { /* 0xxxxxxx */
  94382. v = x;
  94383. i = 0;
  94384. }
  94385. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94386. v = x & 0x1F;
  94387. i = 1;
  94388. }
  94389. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94390. v = x & 0x0F;
  94391. i = 2;
  94392. }
  94393. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94394. v = x & 0x07;
  94395. i = 3;
  94396. }
  94397. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94398. v = x & 0x03;
  94399. i = 4;
  94400. }
  94401. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94402. v = x & 0x01;
  94403. i = 5;
  94404. }
  94405. else {
  94406. *val = 0xffffffff;
  94407. return true;
  94408. }
  94409. for( ; i; i--) {
  94410. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94411. return false;
  94412. if(raw)
  94413. raw[(*rawlen)++] = (FLAC__byte)x;
  94414. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94415. *val = 0xffffffff;
  94416. return true;
  94417. }
  94418. v <<= 6;
  94419. v |= (x & 0x3F);
  94420. }
  94421. *val = v;
  94422. return true;
  94423. }
  94424. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94425. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94426. {
  94427. FLAC__uint64 v = 0;
  94428. FLAC__uint32 x;
  94429. unsigned i;
  94430. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94431. return false;
  94432. if(raw)
  94433. raw[(*rawlen)++] = (FLAC__byte)x;
  94434. if(!(x & 0x80)) { /* 0xxxxxxx */
  94435. v = x;
  94436. i = 0;
  94437. }
  94438. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94439. v = x & 0x1F;
  94440. i = 1;
  94441. }
  94442. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94443. v = x & 0x0F;
  94444. i = 2;
  94445. }
  94446. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94447. v = x & 0x07;
  94448. i = 3;
  94449. }
  94450. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94451. v = x & 0x03;
  94452. i = 4;
  94453. }
  94454. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94455. v = x & 0x01;
  94456. i = 5;
  94457. }
  94458. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94459. v = 0;
  94460. i = 6;
  94461. }
  94462. else {
  94463. *val = FLAC__U64L(0xffffffffffffffff);
  94464. return true;
  94465. }
  94466. for( ; i; i--) {
  94467. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94468. return false;
  94469. if(raw)
  94470. raw[(*rawlen)++] = (FLAC__byte)x;
  94471. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94472. *val = FLAC__U64L(0xffffffffffffffff);
  94473. return true;
  94474. }
  94475. v <<= 6;
  94476. v |= (x & 0x3F);
  94477. }
  94478. *val = v;
  94479. return true;
  94480. }
  94481. #endif
  94482. /*** End of inlined file: bitreader.c ***/
  94483. /*** Start of inlined file: bitwriter.c ***/
  94484. /*** Start of inlined file: juce_FlacHeader.h ***/
  94485. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94486. // tasks..
  94487. #define VERSION "1.2.1"
  94488. #define FLAC__NO_DLL 1
  94489. #if JUCE_MSVC
  94490. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94491. #endif
  94492. #if JUCE_MAC
  94493. #define FLAC__SYS_DARWIN 1
  94494. #endif
  94495. /*** End of inlined file: juce_FlacHeader.h ***/
  94496. #if JUCE_USE_FLAC
  94497. #if HAVE_CONFIG_H
  94498. # include <config.h>
  94499. #endif
  94500. #include <stdlib.h> /* for malloc() */
  94501. #include <string.h> /* for memcpy(), memset() */
  94502. #ifdef _MSC_VER
  94503. #include <winsock.h> /* for ntohl() */
  94504. #elif defined FLAC__SYS_DARWIN
  94505. #include <machine/endian.h> /* for ntohl() */
  94506. #elif defined __MINGW32__
  94507. #include <winsock.h> /* for ntohl() */
  94508. #else
  94509. #include <netinet/in.h> /* for ntohl() */
  94510. #endif
  94511. #if 0 /* UNUSED */
  94512. #endif
  94513. /*** Start of inlined file: bitwriter.h ***/
  94514. #ifndef FLAC__PRIVATE__BITWRITER_H
  94515. #define FLAC__PRIVATE__BITWRITER_H
  94516. #include <stdio.h> /* for FILE */
  94517. /*
  94518. * opaque structure definition
  94519. */
  94520. struct FLAC__BitWriter;
  94521. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94522. /*
  94523. * construction, deletion, initialization, etc functions
  94524. */
  94525. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94526. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94527. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94528. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94529. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94530. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94531. /*
  94532. * CRC functions
  94533. *
  94534. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94535. */
  94536. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94537. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94538. /*
  94539. * info functions
  94540. */
  94541. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94542. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94543. /*
  94544. * direct buffer access
  94545. *
  94546. * there may be no calls on the bitwriter between get and release.
  94547. * the bitwriter continues to own the returned buffer.
  94548. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94549. */
  94550. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94551. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94552. /*
  94553. * write functions
  94554. */
  94555. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94556. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94557. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94558. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94559. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94560. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94561. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94562. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94563. #if 0 /* UNUSED */
  94564. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94565. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94566. #endif
  94567. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94568. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94569. #if 0 /* UNUSED */
  94570. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94571. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94572. #endif
  94573. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94574. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94575. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94576. #endif
  94577. /*** End of inlined file: bitwriter.h ***/
  94578. /*** Start of inlined file: alloc.h ***/
  94579. #ifndef FLAC__SHARE__ALLOC_H
  94580. #define FLAC__SHARE__ALLOC_H
  94581. #if HAVE_CONFIG_H
  94582. # include <config.h>
  94583. #endif
  94584. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94585. * before #including this file, otherwise SIZE_MAX might not be defined
  94586. */
  94587. #include <limits.h> /* for SIZE_MAX */
  94588. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94589. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94590. #endif
  94591. #include <stdlib.h> /* for size_t, malloc(), etc */
  94592. #ifndef SIZE_MAX
  94593. # ifndef SIZE_T_MAX
  94594. # ifdef _MSC_VER
  94595. # define SIZE_T_MAX UINT_MAX
  94596. # else
  94597. # error
  94598. # endif
  94599. # endif
  94600. # define SIZE_MAX SIZE_T_MAX
  94601. #endif
  94602. #ifndef FLaC__INLINE
  94603. #define FLaC__INLINE
  94604. #endif
  94605. /* avoid malloc()ing 0 bytes, see:
  94606. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94607. */
  94608. static FLaC__INLINE void *safe_malloc_(size_t size)
  94609. {
  94610. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94611. if(!size)
  94612. size++;
  94613. return malloc(size);
  94614. }
  94615. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94616. {
  94617. if(!nmemb || !size)
  94618. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94619. return calloc(nmemb, size);
  94620. }
  94621. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94622. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94623. {
  94624. size2 += size1;
  94625. if(size2 < size1)
  94626. return 0;
  94627. return safe_malloc_(size2);
  94628. }
  94629. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94630. {
  94631. size2 += size1;
  94632. if(size2 < size1)
  94633. return 0;
  94634. size3 += size2;
  94635. if(size3 < size2)
  94636. return 0;
  94637. return safe_malloc_(size3);
  94638. }
  94639. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94640. {
  94641. size2 += size1;
  94642. if(size2 < size1)
  94643. return 0;
  94644. size3 += size2;
  94645. if(size3 < size2)
  94646. return 0;
  94647. size4 += size3;
  94648. if(size4 < size3)
  94649. return 0;
  94650. return safe_malloc_(size4);
  94651. }
  94652. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94653. #if 0
  94654. needs support for cases where sizeof(size_t) != 4
  94655. {
  94656. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94657. if(sizeof(size_t) == 4) {
  94658. if ((double)size1 * (double)size2 < 4294967296.0)
  94659. return malloc(size1*size2);
  94660. }
  94661. return 0;
  94662. }
  94663. #else
  94664. /* better? */
  94665. {
  94666. if(!size1 || !size2)
  94667. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94668. if(size1 > SIZE_MAX / size2)
  94669. return 0;
  94670. return malloc(size1*size2);
  94671. }
  94672. #endif
  94673. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94674. {
  94675. if(!size1 || !size2 || !size3)
  94676. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94677. if(size1 > SIZE_MAX / size2)
  94678. return 0;
  94679. size1 *= size2;
  94680. if(size1 > SIZE_MAX / size3)
  94681. return 0;
  94682. return malloc(size1*size3);
  94683. }
  94684. /* size1*size2 + size3 */
  94685. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94686. {
  94687. if(!size1 || !size2)
  94688. return safe_malloc_(size3);
  94689. if(size1 > SIZE_MAX / size2)
  94690. return 0;
  94691. return safe_malloc_add_2op_(size1*size2, size3);
  94692. }
  94693. /* size1 * (size2 + size3) */
  94694. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94695. {
  94696. if(!size1 || (!size2 && !size3))
  94697. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94698. size2 += size3;
  94699. if(size2 < size3)
  94700. return 0;
  94701. return safe_malloc_mul_2op_(size1, size2);
  94702. }
  94703. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94704. {
  94705. size2 += size1;
  94706. if(size2 < size1)
  94707. return 0;
  94708. return realloc(ptr, size2);
  94709. }
  94710. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94711. {
  94712. size2 += size1;
  94713. if(size2 < size1)
  94714. return 0;
  94715. size3 += size2;
  94716. if(size3 < size2)
  94717. return 0;
  94718. return realloc(ptr, size3);
  94719. }
  94720. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94721. {
  94722. size2 += size1;
  94723. if(size2 < size1)
  94724. return 0;
  94725. size3 += size2;
  94726. if(size3 < size2)
  94727. return 0;
  94728. size4 += size3;
  94729. if(size4 < size3)
  94730. return 0;
  94731. return realloc(ptr, size4);
  94732. }
  94733. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94734. {
  94735. if(!size1 || !size2)
  94736. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94737. if(size1 > SIZE_MAX / size2)
  94738. return 0;
  94739. return realloc(ptr, size1*size2);
  94740. }
  94741. /* size1 * (size2 + size3) */
  94742. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94743. {
  94744. if(!size1 || (!size2 && !size3))
  94745. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94746. size2 += size3;
  94747. if(size2 < size3)
  94748. return 0;
  94749. return safe_realloc_mul_2op_(ptr, size1, size2);
  94750. }
  94751. #endif
  94752. /*** End of inlined file: alloc.h ***/
  94753. /* Things should be fastest when this matches the machine word size */
  94754. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94755. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94756. typedef FLAC__uint32 bwword;
  94757. #define FLAC__BYTES_PER_WORD 4
  94758. #define FLAC__BITS_PER_WORD 32
  94759. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94760. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94761. #if WORDS_BIGENDIAN
  94762. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94763. #else
  94764. #ifdef _MSC_VER
  94765. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94766. #else
  94767. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94768. #endif
  94769. #endif
  94770. /*
  94771. * The default capacity here doesn't matter too much. The buffer always grows
  94772. * to hold whatever is written to it. Usually the encoder will stop adding at
  94773. * a frame or metadata block, then write that out and clear the buffer for the
  94774. * next one.
  94775. */
  94776. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94777. /* When growing, increment 4K at a time */
  94778. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94779. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94780. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94781. #ifdef min
  94782. #undef min
  94783. #endif
  94784. #define min(x,y) ((x)<(y)?(x):(y))
  94785. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94786. #ifdef _MSC_VER
  94787. #define FLAC__U64L(x) x
  94788. #else
  94789. #define FLAC__U64L(x) x##LLU
  94790. #endif
  94791. #ifndef FLaC__INLINE
  94792. #define FLaC__INLINE
  94793. #endif
  94794. struct FLAC__BitWriter {
  94795. bwword *buffer;
  94796. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94797. unsigned capacity; /* capacity of buffer in words */
  94798. unsigned words; /* # of complete words in buffer */
  94799. unsigned bits; /* # of used bits in accum */
  94800. };
  94801. /* * WATCHOUT: The current implementation only grows the buffer. */
  94802. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94803. {
  94804. unsigned new_capacity;
  94805. bwword *new_buffer;
  94806. FLAC__ASSERT(0 != bw);
  94807. FLAC__ASSERT(0 != bw->buffer);
  94808. /* calculate total words needed to store 'bits_to_add' additional bits */
  94809. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94810. /* it's possible (due to pessimism in the growth estimation that
  94811. * leads to this call) that we don't actually need to grow
  94812. */
  94813. if(bw->capacity >= new_capacity)
  94814. return true;
  94815. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94816. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94817. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94818. /* make sure we got everything right */
  94819. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94820. FLAC__ASSERT(new_capacity > bw->capacity);
  94821. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94822. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94823. if(new_buffer == 0)
  94824. return false;
  94825. bw->buffer = new_buffer;
  94826. bw->capacity = new_capacity;
  94827. return true;
  94828. }
  94829. /***********************************************************************
  94830. *
  94831. * Class constructor/destructor
  94832. *
  94833. ***********************************************************************/
  94834. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94835. {
  94836. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94837. /* note that calloc() sets all members to 0 for us */
  94838. return bw;
  94839. }
  94840. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94841. {
  94842. FLAC__ASSERT(0 != bw);
  94843. FLAC__bitwriter_free(bw);
  94844. free(bw);
  94845. }
  94846. /***********************************************************************
  94847. *
  94848. * Public class methods
  94849. *
  94850. ***********************************************************************/
  94851. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94852. {
  94853. FLAC__ASSERT(0 != bw);
  94854. bw->words = bw->bits = 0;
  94855. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94856. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94857. if(bw->buffer == 0)
  94858. return false;
  94859. return true;
  94860. }
  94861. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94862. {
  94863. FLAC__ASSERT(0 != bw);
  94864. if(0 != bw->buffer)
  94865. free(bw->buffer);
  94866. bw->buffer = 0;
  94867. bw->capacity = 0;
  94868. bw->words = bw->bits = 0;
  94869. }
  94870. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94871. {
  94872. bw->words = bw->bits = 0;
  94873. }
  94874. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94875. {
  94876. unsigned i, j;
  94877. if(bw == 0) {
  94878. fprintf(out, "bitwriter is NULL\n");
  94879. }
  94880. else {
  94881. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94882. for(i = 0; i < bw->words; i++) {
  94883. fprintf(out, "%08X: ", i);
  94884. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94885. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94886. fprintf(out, "\n");
  94887. }
  94888. if(bw->bits > 0) {
  94889. fprintf(out, "%08X: ", i);
  94890. for(j = 0; j < bw->bits; j++)
  94891. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94892. fprintf(out, "\n");
  94893. }
  94894. }
  94895. }
  94896. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94897. {
  94898. const FLAC__byte *buffer;
  94899. size_t bytes;
  94900. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94901. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94902. return false;
  94903. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94904. FLAC__bitwriter_release_buffer(bw);
  94905. return true;
  94906. }
  94907. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94908. {
  94909. const FLAC__byte *buffer;
  94910. size_t bytes;
  94911. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94912. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94913. return false;
  94914. *crc = FLAC__crc8(buffer, bytes);
  94915. FLAC__bitwriter_release_buffer(bw);
  94916. return true;
  94917. }
  94918. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94919. {
  94920. return ((bw->bits & 7) == 0);
  94921. }
  94922. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94923. {
  94924. return FLAC__TOTAL_BITS(bw);
  94925. }
  94926. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94927. {
  94928. FLAC__ASSERT((bw->bits & 7) == 0);
  94929. /* double protection */
  94930. if(bw->bits & 7)
  94931. return false;
  94932. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94933. if(bw->bits) {
  94934. FLAC__ASSERT(bw->words <= bw->capacity);
  94935. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94936. return false;
  94937. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94938. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94939. }
  94940. /* now we can just return what we have */
  94941. *buffer = (FLAC__byte*)bw->buffer;
  94942. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94943. return true;
  94944. }
  94945. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94946. {
  94947. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94948. * get-mode' flag could be added everywhere and then cleared here
  94949. */
  94950. (void)bw;
  94951. }
  94952. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94953. {
  94954. unsigned n;
  94955. FLAC__ASSERT(0 != bw);
  94956. FLAC__ASSERT(0 != bw->buffer);
  94957. if(bits == 0)
  94958. return true;
  94959. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94960. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94961. return false;
  94962. /* first part gets to word alignment */
  94963. if(bw->bits) {
  94964. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94965. bw->accum <<= n;
  94966. bits -= n;
  94967. bw->bits += n;
  94968. if(bw->bits == FLAC__BITS_PER_WORD) {
  94969. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94970. bw->bits = 0;
  94971. }
  94972. else
  94973. return true;
  94974. }
  94975. /* do whole words */
  94976. while(bits >= FLAC__BITS_PER_WORD) {
  94977. bw->buffer[bw->words++] = 0;
  94978. bits -= FLAC__BITS_PER_WORD;
  94979. }
  94980. /* do any leftovers */
  94981. if(bits > 0) {
  94982. bw->accum = 0;
  94983. bw->bits = bits;
  94984. }
  94985. return true;
  94986. }
  94987. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94988. {
  94989. register unsigned left;
  94990. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94991. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94992. FLAC__ASSERT(0 != bw);
  94993. FLAC__ASSERT(0 != bw->buffer);
  94994. FLAC__ASSERT(bits <= 32);
  94995. if(bits == 0)
  94996. return true;
  94997. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94998. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94999. return false;
  95000. left = FLAC__BITS_PER_WORD - bw->bits;
  95001. if(bits < left) {
  95002. bw->accum <<= bits;
  95003. bw->accum |= val;
  95004. bw->bits += bits;
  95005. }
  95006. 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 */
  95007. bw->accum <<= left;
  95008. bw->accum |= val >> (bw->bits = bits - left);
  95009. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95010. bw->accum = val;
  95011. }
  95012. else {
  95013. bw->accum = val;
  95014. bw->bits = 0;
  95015. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  95016. }
  95017. return true;
  95018. }
  95019. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  95020. {
  95021. /* zero-out unused bits */
  95022. if(bits < 32)
  95023. val &= (~(0xffffffff << bits));
  95024. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  95025. }
  95026. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  95027. {
  95028. /* this could be a little faster but it's not used for much */
  95029. if(bits > 32) {
  95030. return
  95031. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  95032. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  95033. }
  95034. else
  95035. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  95036. }
  95037. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  95038. {
  95039. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  95040. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  95041. return false;
  95042. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  95043. return false;
  95044. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  95045. return false;
  95046. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  95047. return false;
  95048. return true;
  95049. }
  95050. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  95051. {
  95052. unsigned i;
  95053. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  95054. for(i = 0; i < nvals; i++) {
  95055. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  95056. return false;
  95057. }
  95058. return true;
  95059. }
  95060. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  95061. {
  95062. if(val < 32)
  95063. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  95064. else
  95065. return
  95066. FLAC__bitwriter_write_zeroes(bw, val) &&
  95067. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  95068. }
  95069. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  95070. {
  95071. FLAC__uint32 uval;
  95072. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  95073. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95074. uval = (val<<1) ^ (val>>31);
  95075. return 1 + parameter + (uval >> parameter);
  95076. }
  95077. #if 0 /* UNUSED */
  95078. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  95079. {
  95080. unsigned bits, msbs, uval;
  95081. unsigned k;
  95082. FLAC__ASSERT(parameter > 0);
  95083. /* fold signed to unsigned */
  95084. if(val < 0)
  95085. uval = (unsigned)(((-(++val)) << 1) + 1);
  95086. else
  95087. uval = (unsigned)(val << 1);
  95088. k = FLAC__bitmath_ilog2(parameter);
  95089. if(parameter == 1u<<k) {
  95090. FLAC__ASSERT(k <= 30);
  95091. msbs = uval >> k;
  95092. bits = 1 + k + msbs;
  95093. }
  95094. else {
  95095. unsigned q, r, d;
  95096. d = (1 << (k+1)) - parameter;
  95097. q = uval / parameter;
  95098. r = uval - (q * parameter);
  95099. bits = 1 + q + k;
  95100. if(r >= d)
  95101. bits++;
  95102. }
  95103. return bits;
  95104. }
  95105. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  95106. {
  95107. unsigned bits, msbs;
  95108. unsigned k;
  95109. FLAC__ASSERT(parameter > 0);
  95110. k = FLAC__bitmath_ilog2(parameter);
  95111. if(parameter == 1u<<k) {
  95112. FLAC__ASSERT(k <= 30);
  95113. msbs = uval >> k;
  95114. bits = 1 + k + msbs;
  95115. }
  95116. else {
  95117. unsigned q, r, d;
  95118. d = (1 << (k+1)) - parameter;
  95119. q = uval / parameter;
  95120. r = uval - (q * parameter);
  95121. bits = 1 + q + k;
  95122. if(r >= d)
  95123. bits++;
  95124. }
  95125. return bits;
  95126. }
  95127. #endif /* UNUSED */
  95128. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  95129. {
  95130. unsigned total_bits, interesting_bits, msbs;
  95131. FLAC__uint32 uval, pattern;
  95132. FLAC__ASSERT(0 != bw);
  95133. FLAC__ASSERT(0 != bw->buffer);
  95134. FLAC__ASSERT(parameter < 8*sizeof(uval));
  95135. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95136. uval = (val<<1) ^ (val>>31);
  95137. msbs = uval >> parameter;
  95138. interesting_bits = 1 + parameter;
  95139. total_bits = interesting_bits + msbs;
  95140. pattern = 1 << parameter; /* the unary end bit */
  95141. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  95142. if(total_bits <= 32)
  95143. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  95144. else
  95145. return
  95146. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  95147. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  95148. }
  95149. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  95150. {
  95151. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  95152. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  95153. FLAC__uint32 uval;
  95154. unsigned left;
  95155. const unsigned lsbits = 1 + parameter;
  95156. unsigned msbits;
  95157. FLAC__ASSERT(0 != bw);
  95158. FLAC__ASSERT(0 != bw->buffer);
  95159. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  95160. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  95161. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  95162. while(nvals) {
  95163. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95164. uval = (*vals<<1) ^ (*vals>>31);
  95165. msbits = uval >> parameter;
  95166. #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) */
  95167. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95168. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95169. bw->bits = bw->bits + msbits + lsbits;
  95170. uval |= mask1; /* set stop bit */
  95171. uval &= mask2; /* mask off unused top bits */
  95172. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  95173. bw->accum <<= msbits;
  95174. bw->accum <<= lsbits;
  95175. bw->accum |= uval;
  95176. if(bw->bits == FLAC__BITS_PER_WORD) {
  95177. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95178. bw->bits = 0;
  95179. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95180. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95181. FLAC__ASSERT(bw->capacity == bw->words);
  95182. return false;
  95183. }
  95184. }
  95185. }
  95186. else {
  95187. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95188. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95189. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95190. bw->bits = bw->bits + msbits + lsbits;
  95191. uval |= mask1; /* set stop bit */
  95192. uval &= mask2; /* mask off unused top bits */
  95193. bw->accum <<= msbits + lsbits;
  95194. bw->accum |= uval;
  95195. }
  95196. else {
  95197. #endif
  95198. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95199. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95200. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95201. return false;
  95202. if(msbits) {
  95203. /* first part gets to word alignment */
  95204. if(bw->bits) {
  95205. left = FLAC__BITS_PER_WORD - bw->bits;
  95206. if(msbits < left) {
  95207. bw->accum <<= msbits;
  95208. bw->bits += msbits;
  95209. goto break1;
  95210. }
  95211. else {
  95212. bw->accum <<= left;
  95213. msbits -= left;
  95214. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95215. bw->bits = 0;
  95216. }
  95217. }
  95218. /* do whole words */
  95219. while(msbits >= FLAC__BITS_PER_WORD) {
  95220. bw->buffer[bw->words++] = 0;
  95221. msbits -= FLAC__BITS_PER_WORD;
  95222. }
  95223. /* do any leftovers */
  95224. if(msbits > 0) {
  95225. bw->accum = 0;
  95226. bw->bits = msbits;
  95227. }
  95228. }
  95229. break1:
  95230. uval |= mask1; /* set stop bit */
  95231. uval &= mask2; /* mask off unused top bits */
  95232. left = FLAC__BITS_PER_WORD - bw->bits;
  95233. if(lsbits < left) {
  95234. bw->accum <<= lsbits;
  95235. bw->accum |= uval;
  95236. bw->bits += lsbits;
  95237. }
  95238. else {
  95239. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95240. * be > lsbits (because of previous assertions) so it would have
  95241. * triggered the (lsbits<left) case above.
  95242. */
  95243. FLAC__ASSERT(bw->bits);
  95244. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95245. bw->accum <<= left;
  95246. bw->accum |= uval >> (bw->bits = lsbits - left);
  95247. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95248. bw->accum = uval;
  95249. }
  95250. #if 1
  95251. }
  95252. #endif
  95253. vals++;
  95254. nvals--;
  95255. }
  95256. return true;
  95257. }
  95258. #if 0 /* UNUSED */
  95259. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95260. {
  95261. unsigned total_bits, msbs, uval;
  95262. unsigned k;
  95263. FLAC__ASSERT(0 != bw);
  95264. FLAC__ASSERT(0 != bw->buffer);
  95265. FLAC__ASSERT(parameter > 0);
  95266. /* fold signed to unsigned */
  95267. if(val < 0)
  95268. uval = (unsigned)(((-(++val)) << 1) + 1);
  95269. else
  95270. uval = (unsigned)(val << 1);
  95271. k = FLAC__bitmath_ilog2(parameter);
  95272. if(parameter == 1u<<k) {
  95273. unsigned pattern;
  95274. FLAC__ASSERT(k <= 30);
  95275. msbs = uval >> k;
  95276. total_bits = 1 + k + msbs;
  95277. pattern = 1 << k; /* the unary end bit */
  95278. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95279. if(total_bits <= 32) {
  95280. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95281. return false;
  95282. }
  95283. else {
  95284. /* write the unary MSBs */
  95285. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95286. return false;
  95287. /* write the unary end bit and binary LSBs */
  95288. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95289. return false;
  95290. }
  95291. }
  95292. else {
  95293. unsigned q, r, d;
  95294. d = (1 << (k+1)) - parameter;
  95295. q = uval / parameter;
  95296. r = uval - (q * parameter);
  95297. /* write the unary MSBs */
  95298. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95299. return false;
  95300. /* write the unary end bit */
  95301. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95302. return false;
  95303. /* write the binary LSBs */
  95304. if(r >= d) {
  95305. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95306. return false;
  95307. }
  95308. else {
  95309. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95310. return false;
  95311. }
  95312. }
  95313. return true;
  95314. }
  95315. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95316. {
  95317. unsigned total_bits, msbs;
  95318. unsigned k;
  95319. FLAC__ASSERT(0 != bw);
  95320. FLAC__ASSERT(0 != bw->buffer);
  95321. FLAC__ASSERT(parameter > 0);
  95322. k = FLAC__bitmath_ilog2(parameter);
  95323. if(parameter == 1u<<k) {
  95324. unsigned pattern;
  95325. FLAC__ASSERT(k <= 30);
  95326. msbs = uval >> k;
  95327. total_bits = 1 + k + msbs;
  95328. pattern = 1 << k; /* the unary end bit */
  95329. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95330. if(total_bits <= 32) {
  95331. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95332. return false;
  95333. }
  95334. else {
  95335. /* write the unary MSBs */
  95336. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95337. return false;
  95338. /* write the unary end bit and binary LSBs */
  95339. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95340. return false;
  95341. }
  95342. }
  95343. else {
  95344. unsigned q, r, d;
  95345. d = (1 << (k+1)) - parameter;
  95346. q = uval / parameter;
  95347. r = uval - (q * parameter);
  95348. /* write the unary MSBs */
  95349. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95350. return false;
  95351. /* write the unary end bit */
  95352. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95353. return false;
  95354. /* write the binary LSBs */
  95355. if(r >= d) {
  95356. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95357. return false;
  95358. }
  95359. else {
  95360. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95361. return false;
  95362. }
  95363. }
  95364. return true;
  95365. }
  95366. #endif /* UNUSED */
  95367. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95368. {
  95369. FLAC__bool ok = 1;
  95370. FLAC__ASSERT(0 != bw);
  95371. FLAC__ASSERT(0 != bw->buffer);
  95372. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95373. if(val < 0x80) {
  95374. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95375. }
  95376. else if(val < 0x800) {
  95377. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95378. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95379. }
  95380. else if(val < 0x10000) {
  95381. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95382. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95383. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95384. }
  95385. else if(val < 0x200000) {
  95386. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95387. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95388. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95389. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95390. }
  95391. else if(val < 0x4000000) {
  95392. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95393. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95394. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95395. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95396. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95397. }
  95398. else {
  95399. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95400. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95401. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95402. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95403. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95404. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95405. }
  95406. return ok;
  95407. }
  95408. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95409. {
  95410. FLAC__bool ok = 1;
  95411. FLAC__ASSERT(0 != bw);
  95412. FLAC__ASSERT(0 != bw->buffer);
  95413. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95414. if(val < 0x80) {
  95415. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95416. }
  95417. else if(val < 0x800) {
  95418. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95419. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95420. }
  95421. else if(val < 0x10000) {
  95422. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95423. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95424. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95425. }
  95426. else if(val < 0x200000) {
  95427. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95428. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95429. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95430. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95431. }
  95432. else if(val < 0x4000000) {
  95433. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95434. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95435. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95436. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95437. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95438. }
  95439. else if(val < 0x80000000) {
  95440. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95441. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95442. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95443. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95444. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95445. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95446. }
  95447. else {
  95448. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95449. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95450. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95451. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95452. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95453. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95454. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95455. }
  95456. return ok;
  95457. }
  95458. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95459. {
  95460. /* 0-pad to byte boundary */
  95461. if(bw->bits & 7u)
  95462. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95463. else
  95464. return true;
  95465. }
  95466. #endif
  95467. /*** End of inlined file: bitwriter.c ***/
  95468. /*** Start of inlined file: cpu.c ***/
  95469. /*** Start of inlined file: juce_FlacHeader.h ***/
  95470. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95471. // tasks..
  95472. #define VERSION "1.2.1"
  95473. #define FLAC__NO_DLL 1
  95474. #if JUCE_MSVC
  95475. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95476. #endif
  95477. #if JUCE_MAC
  95478. #define FLAC__SYS_DARWIN 1
  95479. #endif
  95480. /*** End of inlined file: juce_FlacHeader.h ***/
  95481. #if JUCE_USE_FLAC
  95482. #if HAVE_CONFIG_H
  95483. # include <config.h>
  95484. #endif
  95485. #include <stdlib.h>
  95486. #include <stdio.h>
  95487. #if defined FLAC__CPU_IA32
  95488. # include <signal.h>
  95489. #elif defined FLAC__CPU_PPC
  95490. # if !defined FLAC__NO_ASM
  95491. # if defined FLAC__SYS_DARWIN
  95492. # include <sys/sysctl.h>
  95493. # include <mach/mach.h>
  95494. # include <mach/mach_host.h>
  95495. # include <mach/host_info.h>
  95496. # include <mach/machine.h>
  95497. # ifndef CPU_SUBTYPE_POWERPC_970
  95498. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95499. # endif
  95500. # else /* FLAC__SYS_DARWIN */
  95501. # include <signal.h>
  95502. # include <setjmp.h>
  95503. static sigjmp_buf jmpbuf;
  95504. static volatile sig_atomic_t canjump = 0;
  95505. static void sigill_handler (int sig)
  95506. {
  95507. if (!canjump) {
  95508. signal (sig, SIG_DFL);
  95509. raise (sig);
  95510. }
  95511. canjump = 0;
  95512. siglongjmp (jmpbuf, 1);
  95513. }
  95514. # endif /* FLAC__SYS_DARWIN */
  95515. # endif /* FLAC__NO_ASM */
  95516. #endif /* FLAC__CPU_PPC */
  95517. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95518. #include <sys/param.h>
  95519. #include <sys/sysctl.h>
  95520. #include <machine/cpu.h>
  95521. #endif
  95522. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95523. #include <sys/types.h>
  95524. #include <sys/sysctl.h>
  95525. #endif
  95526. #if defined(__APPLE__)
  95527. /* how to get sysctlbyname()? */
  95528. #endif
  95529. /* these are flags in EDX of CPUID AX=00000001 */
  95530. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95531. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95532. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95533. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95534. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95535. /* these are flags in ECX of CPUID AX=00000001 */
  95536. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95537. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95538. /* these are flags in EDX of CPUID AX=80000001 */
  95539. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95540. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95541. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95542. /*
  95543. * Extra stuff needed for detection of OS support for SSE on IA-32
  95544. */
  95545. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95546. # if defined(__linux__)
  95547. /*
  95548. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95549. * modify the return address to jump over the offending SSE instruction
  95550. * and also the operation following it that indicates the instruction
  95551. * executed successfully. In this way we use no global variables and
  95552. * stay thread-safe.
  95553. *
  95554. * 3 + 3 + 6:
  95555. * 3 bytes for "xorps xmm0,xmm0"
  95556. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95557. * 6 bytes extra in case our estimate is wrong
  95558. * 12 bytes puts us in the NOP "landing zone"
  95559. */
  95560. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95561. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95562. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95563. {
  95564. (void)signal;
  95565. sc.eip += 3 + 3 + 6;
  95566. }
  95567. # else
  95568. # include <sys/ucontext.h>
  95569. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95570. {
  95571. (void)signal, (void)si;
  95572. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95573. }
  95574. # endif
  95575. # elif defined(_MSC_VER)
  95576. # include <windows.h>
  95577. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95578. # ifdef USE_TRY_CATCH_FLAVOR
  95579. # else
  95580. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95581. {
  95582. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95583. ep->ContextRecord->Eip += 3 + 3 + 6;
  95584. return EXCEPTION_CONTINUE_EXECUTION;
  95585. }
  95586. return EXCEPTION_CONTINUE_SEARCH;
  95587. }
  95588. # endif
  95589. # endif
  95590. #endif
  95591. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95592. {
  95593. /*
  95594. * IA32-specific
  95595. */
  95596. #ifdef FLAC__CPU_IA32
  95597. info->type = FLAC__CPUINFO_TYPE_IA32;
  95598. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95599. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95600. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95601. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95602. info->data.ia32.cmov = false;
  95603. info->data.ia32.mmx = false;
  95604. info->data.ia32.fxsr = false;
  95605. info->data.ia32.sse = false;
  95606. info->data.ia32.sse2 = false;
  95607. info->data.ia32.sse3 = false;
  95608. info->data.ia32.ssse3 = false;
  95609. info->data.ia32._3dnow = false;
  95610. info->data.ia32.ext3dnow = false;
  95611. info->data.ia32.extmmx = false;
  95612. if(info->data.ia32.cpuid) {
  95613. /* http://www.sandpile.org/ia32/cpuid.htm */
  95614. FLAC__uint32 flags_edx, flags_ecx;
  95615. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95616. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95617. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95618. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95619. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95620. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95621. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95622. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95623. #ifdef FLAC__USE_3DNOW
  95624. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95625. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95626. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95627. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95628. #else
  95629. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95630. #endif
  95631. #ifdef DEBUG
  95632. fprintf(stderr, "CPU info (IA-32):\n");
  95633. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95634. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95635. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95636. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95637. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95638. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95639. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95640. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95641. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95642. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95643. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95644. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95645. #endif
  95646. /*
  95647. * now have to check for OS support of SSE/SSE2
  95648. */
  95649. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95650. #if defined FLAC__NO_SSE_OS
  95651. /* assume user knows better than us; turn it off */
  95652. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95653. #elif defined FLAC__SSE_OS
  95654. /* assume user knows better than us; leave as detected above */
  95655. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95656. int sse = 0;
  95657. size_t len;
  95658. /* at least one of these must work: */
  95659. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95660. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95661. if(!sse)
  95662. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95663. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95664. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95665. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95666. size_t len = sizeof(val);
  95667. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95668. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95669. else { /* double-check SSE2 */
  95670. mib[1] = CPU_SSE2;
  95671. len = sizeof(val);
  95672. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95673. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95674. }
  95675. # else
  95676. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95677. # endif
  95678. #elif defined(__linux__)
  95679. int sse = 0;
  95680. struct sigaction sigill_save;
  95681. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95682. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95683. #else
  95684. struct sigaction sigill_sse;
  95685. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95686. __sigemptyset(&sigill_sse.sa_mask);
  95687. 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 */
  95688. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95689. #endif
  95690. {
  95691. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95692. /* see sigill_handler_sse_os() for an explanation of the following: */
  95693. asm volatile (
  95694. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95695. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95696. "incl %0\n\t" /* SIGILL handler will jump over this */
  95697. /* landing zone */
  95698. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95699. "nop\n\t"
  95700. "nop\n\t"
  95701. "nop\n\t"
  95702. "nop\n\t"
  95703. "nop\n\t"
  95704. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95705. "nop\n\t"
  95706. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95707. : "=r"(sse)
  95708. : "r"(sse)
  95709. );
  95710. sigaction(SIGILL, &sigill_save, NULL);
  95711. }
  95712. if(!sse)
  95713. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95714. #elif defined(_MSC_VER)
  95715. # ifdef USE_TRY_CATCH_FLAVOR
  95716. _try {
  95717. __asm {
  95718. # if _MSC_VER <= 1200
  95719. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95720. _emit 0x0F
  95721. _emit 0x57
  95722. _emit 0xC0
  95723. # else
  95724. xorps xmm0,xmm0
  95725. # endif
  95726. }
  95727. }
  95728. _except(EXCEPTION_EXECUTE_HANDLER) {
  95729. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95730. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95731. }
  95732. # else
  95733. int sse = 0;
  95734. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95735. /* see GCC version above for explanation */
  95736. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95737. /* http://www.codeproject.com/cpp/gccasm.asp */
  95738. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95739. __asm {
  95740. # if _MSC_VER <= 1200
  95741. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95742. _emit 0x0F
  95743. _emit 0x57
  95744. _emit 0xC0
  95745. # else
  95746. xorps xmm0,xmm0
  95747. # endif
  95748. inc sse
  95749. nop
  95750. nop
  95751. nop
  95752. nop
  95753. nop
  95754. nop
  95755. nop
  95756. nop
  95757. nop
  95758. }
  95759. SetUnhandledExceptionFilter(save);
  95760. if(!sse)
  95761. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95762. # endif
  95763. #else
  95764. /* no way to test, disable to be safe */
  95765. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95766. #endif
  95767. #ifdef DEBUG
  95768. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95769. #endif
  95770. }
  95771. }
  95772. #else
  95773. info->use_asm = false;
  95774. #endif
  95775. /*
  95776. * PPC-specific
  95777. */
  95778. #elif defined FLAC__CPU_PPC
  95779. info->type = FLAC__CPUINFO_TYPE_PPC;
  95780. # if !defined FLAC__NO_ASM
  95781. info->use_asm = true;
  95782. # ifdef FLAC__USE_ALTIVEC
  95783. # if defined FLAC__SYS_DARWIN
  95784. {
  95785. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95786. size_t len = sizeof(val);
  95787. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95788. }
  95789. {
  95790. host_basic_info_data_t hostInfo;
  95791. mach_msg_type_number_t infoCount;
  95792. infoCount = HOST_BASIC_INFO_COUNT;
  95793. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95794. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95795. }
  95796. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95797. {
  95798. /* no Darwin, do it the brute-force way */
  95799. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95800. info->data.ppc.altivec = 0;
  95801. info->data.ppc.ppc64 = 0;
  95802. signal (SIGILL, sigill_handler);
  95803. canjump = 0;
  95804. if (!sigsetjmp (jmpbuf, 1)) {
  95805. canjump = 1;
  95806. asm volatile (
  95807. "mtspr 256, %0\n\t"
  95808. "vand %%v0, %%v0, %%v0"
  95809. :
  95810. : "r" (-1)
  95811. );
  95812. info->data.ppc.altivec = 1;
  95813. }
  95814. canjump = 0;
  95815. if (!sigsetjmp (jmpbuf, 1)) {
  95816. int x = 0;
  95817. canjump = 1;
  95818. /* PPC64 hardware implements the cntlzd instruction */
  95819. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95820. info->data.ppc.ppc64 = 1;
  95821. }
  95822. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95823. }
  95824. # endif
  95825. # else /* !FLAC__USE_ALTIVEC */
  95826. info->data.ppc.altivec = 0;
  95827. info->data.ppc.ppc64 = 0;
  95828. # endif
  95829. # else
  95830. info->use_asm = false;
  95831. # endif
  95832. /*
  95833. * unknown CPI
  95834. */
  95835. #else
  95836. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95837. info->use_asm = false;
  95838. #endif
  95839. }
  95840. #endif
  95841. /*** End of inlined file: cpu.c ***/
  95842. /*** Start of inlined file: crc.c ***/
  95843. /*** Start of inlined file: juce_FlacHeader.h ***/
  95844. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95845. // tasks..
  95846. #define VERSION "1.2.1"
  95847. #define FLAC__NO_DLL 1
  95848. #if JUCE_MSVC
  95849. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95850. #endif
  95851. #if JUCE_MAC
  95852. #define FLAC__SYS_DARWIN 1
  95853. #endif
  95854. /*** End of inlined file: juce_FlacHeader.h ***/
  95855. #if JUCE_USE_FLAC
  95856. #if HAVE_CONFIG_H
  95857. # include <config.h>
  95858. #endif
  95859. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95860. FLAC__byte const FLAC__crc8_table[256] = {
  95861. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95862. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95863. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95864. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95865. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95866. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95867. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95868. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95869. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95870. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95871. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95872. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95873. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95874. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95875. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95876. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95877. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95878. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95879. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95880. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95881. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95882. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95883. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95884. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95885. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95886. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95887. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95888. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95889. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95890. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95891. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95892. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95893. };
  95894. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95895. unsigned FLAC__crc16_table[256] = {
  95896. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95897. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95898. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95899. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95900. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95901. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95902. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95903. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95904. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95905. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95906. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95907. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95908. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95909. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95910. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95911. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95912. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95913. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95914. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95915. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95916. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95917. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95918. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95919. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95920. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95921. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95922. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95923. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95924. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95925. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95926. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95927. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95928. };
  95929. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95930. {
  95931. *crc = FLAC__crc8_table[*crc ^ data];
  95932. }
  95933. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95934. {
  95935. while(len--)
  95936. *crc = FLAC__crc8_table[*crc ^ *data++];
  95937. }
  95938. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95939. {
  95940. FLAC__uint8 crc = 0;
  95941. while(len--)
  95942. crc = FLAC__crc8_table[crc ^ *data++];
  95943. return crc;
  95944. }
  95945. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95946. {
  95947. unsigned crc = 0;
  95948. while(len--)
  95949. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95950. return crc;
  95951. }
  95952. #endif
  95953. /*** End of inlined file: crc.c ***/
  95954. /*** Start of inlined file: fixed.c ***/
  95955. /*** Start of inlined file: juce_FlacHeader.h ***/
  95956. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95957. // tasks..
  95958. #define VERSION "1.2.1"
  95959. #define FLAC__NO_DLL 1
  95960. #if JUCE_MSVC
  95961. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95962. #endif
  95963. #if JUCE_MAC
  95964. #define FLAC__SYS_DARWIN 1
  95965. #endif
  95966. /*** End of inlined file: juce_FlacHeader.h ***/
  95967. #if JUCE_USE_FLAC
  95968. #if HAVE_CONFIG_H
  95969. # include <config.h>
  95970. #endif
  95971. #include <math.h>
  95972. #include <string.h>
  95973. /*** Start of inlined file: fixed.h ***/
  95974. #ifndef FLAC__PRIVATE__FIXED_H
  95975. #define FLAC__PRIVATE__FIXED_H
  95976. #ifdef HAVE_CONFIG_H
  95977. #include <config.h>
  95978. #endif
  95979. /*** Start of inlined file: float.h ***/
  95980. #ifndef FLAC__PRIVATE__FLOAT_H
  95981. #define FLAC__PRIVATE__FLOAT_H
  95982. #ifdef HAVE_CONFIG_H
  95983. #include <config.h>
  95984. #endif
  95985. /*
  95986. * These typedefs make it easier to ensure that integer versions of
  95987. * the library really only contain integer operations. All the code
  95988. * in libFLAC should use FLAC__float and FLAC__double in place of
  95989. * float and double, and be protected by checks of the macro
  95990. * FLAC__INTEGER_ONLY_LIBRARY.
  95991. *
  95992. * FLAC__real is the basic floating point type used in LPC analysis.
  95993. */
  95994. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95995. typedef double FLAC__double;
  95996. typedef float FLAC__float;
  95997. /*
  95998. * WATCHOUT: changing FLAC__real will change the signatures of many
  95999. * functions that have assembly language equivalents and break them.
  96000. */
  96001. typedef float FLAC__real;
  96002. #else
  96003. /*
  96004. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  96005. * for the integer part and lower 16 bits for the fractional part.
  96006. */
  96007. typedef FLAC__int32 FLAC__fixedpoint;
  96008. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  96009. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  96010. extern const FLAC__fixedpoint FLAC__FP_ONE;
  96011. extern const FLAC__fixedpoint FLAC__FP_LN2;
  96012. extern const FLAC__fixedpoint FLAC__FP_E;
  96013. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  96014. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  96015. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  96016. /*
  96017. * FLAC__fixedpoint_log2()
  96018. * --------------------------------------------------------------------
  96019. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  96020. * algorithm by Knuth for x >= 1.0
  96021. *
  96022. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  96023. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  96024. *
  96025. * 'precision' roughly limits the number of iterations that are done;
  96026. * use (unsigned)(-1) for maximum precision.
  96027. *
  96028. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  96029. * function will punt and return 0.
  96030. *
  96031. * The return value will also have 'fracbits' fractional bits.
  96032. */
  96033. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  96034. #endif
  96035. #endif
  96036. /*** End of inlined file: float.h ***/
  96037. /*** Start of inlined file: format.h ***/
  96038. #ifndef FLAC__PRIVATE__FORMAT_H
  96039. #define FLAC__PRIVATE__FORMAT_H
  96040. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  96041. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  96042. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  96043. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  96044. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  96045. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  96046. #endif
  96047. /*** End of inlined file: format.h ***/
  96048. /*
  96049. * FLAC__fixed_compute_best_predictor()
  96050. * --------------------------------------------------------------------
  96051. * Compute the best fixed predictor and the expected bits-per-sample
  96052. * of the residual signal for each order. The _wide() version uses
  96053. * 64-bit integers which is statistically necessary when bits-per-
  96054. * sample + log2(blocksize) > 30
  96055. *
  96056. * IN data[0,data_len-1]
  96057. * IN data_len
  96058. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  96059. */
  96060. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96061. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96062. # ifndef FLAC__NO_ASM
  96063. # ifdef FLAC__CPU_IA32
  96064. # ifdef FLAC__HAS_NASM
  96065. 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]);
  96066. # endif
  96067. # endif
  96068. # endif
  96069. 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]);
  96070. #else
  96071. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96072. 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]);
  96073. #endif
  96074. /*
  96075. * FLAC__fixed_compute_residual()
  96076. * --------------------------------------------------------------------
  96077. * Compute the residual signal obtained from sutracting the predicted
  96078. * signal from the original.
  96079. *
  96080. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96081. * IN data_len length of original signal
  96082. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96083. * OUT residual[0,data_len-1] residual signal
  96084. */
  96085. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  96086. /*
  96087. * FLAC__fixed_restore_signal()
  96088. * --------------------------------------------------------------------
  96089. * Restore the original signal by summing the residual and the
  96090. * predictor.
  96091. *
  96092. * IN residual[0,data_len-1] residual signal
  96093. * IN data_len length of original signal
  96094. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96095. * *** IMPORTANT: the caller must pass in the historical samples:
  96096. * IN data[-order,-1] previously-reconstructed historical samples
  96097. * OUT data[0,data_len-1] original signal
  96098. */
  96099. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  96100. #endif
  96101. /*** End of inlined file: fixed.h ***/
  96102. #ifndef M_LN2
  96103. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96104. #define M_LN2 0.69314718055994530942
  96105. #endif
  96106. #ifdef min
  96107. #undef min
  96108. #endif
  96109. #define min(x,y) ((x) < (y)? (x) : (y))
  96110. #ifdef local_abs
  96111. #undef local_abs
  96112. #endif
  96113. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  96114. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96115. /* rbps stands for residual bits per sample
  96116. *
  96117. * (ln(2) * err)
  96118. * rbps = log (-----------)
  96119. * 2 ( n )
  96120. */
  96121. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  96122. {
  96123. FLAC__uint32 rbps;
  96124. unsigned bits; /* the number of bits required to represent a number */
  96125. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96126. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96127. FLAC__ASSERT(err > 0);
  96128. FLAC__ASSERT(n > 0);
  96129. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96130. if(err <= n)
  96131. return 0;
  96132. /*
  96133. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96134. * These allow us later to know we won't lose too much precision in the
  96135. * fixed-point division (err<<fracbits)/n.
  96136. */
  96137. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  96138. err <<= fracbits;
  96139. err /= n;
  96140. /* err now holds err/n with fracbits fractional bits */
  96141. /*
  96142. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96143. * our purposes.
  96144. */
  96145. FLAC__ASSERT(err > 0);
  96146. bits = FLAC__bitmath_ilog2(err)+1;
  96147. if(bits > 16) {
  96148. err >>= (bits-16);
  96149. fracbits -= (bits-16);
  96150. }
  96151. rbps = (FLAC__uint32)err;
  96152. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96153. rbps *= FLAC__FP_LN2;
  96154. fracbits += 16;
  96155. FLAC__ASSERT(fracbits >= 0);
  96156. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96157. {
  96158. const int f = fracbits & 3;
  96159. if(f) {
  96160. rbps >>= f;
  96161. fracbits -= f;
  96162. }
  96163. }
  96164. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96165. if(rbps == 0)
  96166. return 0;
  96167. /*
  96168. * The return value must have 16 fractional bits. Since the whole part
  96169. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96170. * must be >= -3, these assertion allows us to be able to shift rbps
  96171. * left if necessary to get 16 fracbits without losing any bits of the
  96172. * whole part of rbps.
  96173. *
  96174. * There is a slight chance due to accumulated error that the whole part
  96175. * will require 6 bits, so we use 6 in the assertion. Really though as
  96176. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96177. */
  96178. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96179. FLAC__ASSERT(fracbits >= -3);
  96180. /* now shift the decimal point into place */
  96181. if(fracbits < 16)
  96182. return rbps << (16-fracbits);
  96183. else if(fracbits > 16)
  96184. return rbps >> (fracbits-16);
  96185. else
  96186. return rbps;
  96187. }
  96188. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96189. {
  96190. FLAC__uint32 rbps;
  96191. unsigned bits; /* the number of bits required to represent a number */
  96192. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96193. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96194. FLAC__ASSERT(err > 0);
  96195. FLAC__ASSERT(n > 0);
  96196. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96197. if(err <= n)
  96198. return 0;
  96199. /*
  96200. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96201. * These allow us later to know we won't lose too much precision in the
  96202. * fixed-point division (err<<fracbits)/n.
  96203. */
  96204. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96205. err <<= fracbits;
  96206. err /= n;
  96207. /* err now holds err/n with fracbits fractional bits */
  96208. /*
  96209. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96210. * our purposes.
  96211. */
  96212. FLAC__ASSERT(err > 0);
  96213. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96214. if(bits > 16) {
  96215. err >>= (bits-16);
  96216. fracbits -= (bits-16);
  96217. }
  96218. rbps = (FLAC__uint32)err;
  96219. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96220. rbps *= FLAC__FP_LN2;
  96221. fracbits += 16;
  96222. FLAC__ASSERT(fracbits >= 0);
  96223. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96224. {
  96225. const int f = fracbits & 3;
  96226. if(f) {
  96227. rbps >>= f;
  96228. fracbits -= f;
  96229. }
  96230. }
  96231. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96232. if(rbps == 0)
  96233. return 0;
  96234. /*
  96235. * The return value must have 16 fractional bits. Since the whole part
  96236. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96237. * must be >= -3, these assertion allows us to be able to shift rbps
  96238. * left if necessary to get 16 fracbits without losing any bits of the
  96239. * whole part of rbps.
  96240. *
  96241. * There is a slight chance due to accumulated error that the whole part
  96242. * will require 6 bits, so we use 6 in the assertion. Really though as
  96243. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96244. */
  96245. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96246. FLAC__ASSERT(fracbits >= -3);
  96247. /* now shift the decimal point into place */
  96248. if(fracbits < 16)
  96249. return rbps << (16-fracbits);
  96250. else if(fracbits > 16)
  96251. return rbps >> (fracbits-16);
  96252. else
  96253. return rbps;
  96254. }
  96255. #endif
  96256. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96257. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96258. #else
  96259. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96260. #endif
  96261. {
  96262. FLAC__int32 last_error_0 = data[-1];
  96263. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96264. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96265. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96266. FLAC__int32 error, save;
  96267. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96268. unsigned i, order;
  96269. for(i = 0; i < data_len; i++) {
  96270. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96271. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96272. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96273. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96274. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96275. }
  96276. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96277. order = 0;
  96278. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96279. order = 1;
  96280. else if(total_error_2 < min(total_error_3, total_error_4))
  96281. order = 2;
  96282. else if(total_error_3 < total_error_4)
  96283. order = 3;
  96284. else
  96285. order = 4;
  96286. /* Estimate the expected number of bits per residual signal sample. */
  96287. /* 'total_error*' is linearly related to the variance of the residual */
  96288. /* signal, so we use it directly to compute E(|x|) */
  96289. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96290. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96291. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96292. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96293. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96294. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96295. 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);
  96296. 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);
  96297. 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);
  96298. 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);
  96299. 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);
  96300. #else
  96301. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96302. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96303. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96304. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96305. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96306. #endif
  96307. return order;
  96308. }
  96309. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96310. 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])
  96311. #else
  96312. 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])
  96313. #endif
  96314. {
  96315. FLAC__int32 last_error_0 = data[-1];
  96316. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96317. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96318. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96319. FLAC__int32 error, save;
  96320. /* total_error_* are 64-bits to avoid overflow when encoding
  96321. * erratic signals when the bits-per-sample and blocksize are
  96322. * large.
  96323. */
  96324. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96325. unsigned i, order;
  96326. for(i = 0; i < data_len; i++) {
  96327. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96328. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96329. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96330. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96331. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96332. }
  96333. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96334. order = 0;
  96335. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96336. order = 1;
  96337. else if(total_error_2 < min(total_error_3, total_error_4))
  96338. order = 2;
  96339. else if(total_error_3 < total_error_4)
  96340. order = 3;
  96341. else
  96342. order = 4;
  96343. /* Estimate the expected number of bits per residual signal sample. */
  96344. /* 'total_error*' is linearly related to the variance of the residual */
  96345. /* signal, so we use it directly to compute E(|x|) */
  96346. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96347. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96348. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96349. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96350. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96351. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96352. #if defined _MSC_VER || defined __MINGW32__
  96353. /* with MSVC you have to spoon feed it the casting */
  96354. 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);
  96355. 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);
  96356. 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);
  96357. 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);
  96358. 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);
  96359. #else
  96360. 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);
  96361. 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);
  96362. 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);
  96363. 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);
  96364. 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);
  96365. #endif
  96366. #else
  96367. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96368. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96369. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96370. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96371. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96372. #endif
  96373. return order;
  96374. }
  96375. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96376. {
  96377. const int idata_len = (int)data_len;
  96378. int i;
  96379. switch(order) {
  96380. case 0:
  96381. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96382. memcpy(residual, data, sizeof(residual[0])*data_len);
  96383. break;
  96384. case 1:
  96385. for(i = 0; i < idata_len; i++)
  96386. residual[i] = data[i] - data[i-1];
  96387. break;
  96388. case 2:
  96389. for(i = 0; i < idata_len; i++)
  96390. #if 1 /* OPT: may be faster with some compilers on some systems */
  96391. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96392. #else
  96393. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96394. #endif
  96395. break;
  96396. case 3:
  96397. for(i = 0; i < idata_len; i++)
  96398. #if 1 /* OPT: may be faster with some compilers on some systems */
  96399. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96400. #else
  96401. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96402. #endif
  96403. break;
  96404. case 4:
  96405. for(i = 0; i < idata_len; i++)
  96406. #if 1 /* OPT: may be faster with some compilers on some systems */
  96407. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96408. #else
  96409. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96410. #endif
  96411. break;
  96412. default:
  96413. FLAC__ASSERT(0);
  96414. }
  96415. }
  96416. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96417. {
  96418. int i, idata_len = (int)data_len;
  96419. switch(order) {
  96420. case 0:
  96421. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96422. memcpy(data, residual, sizeof(residual[0])*data_len);
  96423. break;
  96424. case 1:
  96425. for(i = 0; i < idata_len; i++)
  96426. data[i] = residual[i] + data[i-1];
  96427. break;
  96428. case 2:
  96429. for(i = 0; i < idata_len; i++)
  96430. #if 1 /* OPT: may be faster with some compilers on some systems */
  96431. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96432. #else
  96433. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96434. #endif
  96435. break;
  96436. case 3:
  96437. for(i = 0; i < idata_len; i++)
  96438. #if 1 /* OPT: may be faster with some compilers on some systems */
  96439. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96440. #else
  96441. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96442. #endif
  96443. break;
  96444. case 4:
  96445. for(i = 0; i < idata_len; i++)
  96446. #if 1 /* OPT: may be faster with some compilers on some systems */
  96447. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96448. #else
  96449. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96450. #endif
  96451. break;
  96452. default:
  96453. FLAC__ASSERT(0);
  96454. }
  96455. }
  96456. #endif
  96457. /*** End of inlined file: fixed.c ***/
  96458. /*** Start of inlined file: float.c ***/
  96459. /*** Start of inlined file: juce_FlacHeader.h ***/
  96460. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96461. // tasks..
  96462. #define VERSION "1.2.1"
  96463. #define FLAC__NO_DLL 1
  96464. #if JUCE_MSVC
  96465. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96466. #endif
  96467. #if JUCE_MAC
  96468. #define FLAC__SYS_DARWIN 1
  96469. #endif
  96470. /*** End of inlined file: juce_FlacHeader.h ***/
  96471. #if JUCE_USE_FLAC
  96472. #if HAVE_CONFIG_H
  96473. # include <config.h>
  96474. #endif
  96475. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96476. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96477. #ifdef _MSC_VER
  96478. #define FLAC__U64L(x) x
  96479. #else
  96480. #define FLAC__U64L(x) x##LLU
  96481. #endif
  96482. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96483. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96484. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96485. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96486. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96487. /* Lookup tables for Knuth's logarithm algorithm */
  96488. #define LOG2_LOOKUP_PRECISION 16
  96489. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96490. {
  96491. /*
  96492. * 0 fraction bits
  96493. */
  96494. /* undefined */ 0x00000000,
  96495. /* lg(2/1) = */ 0x00000001,
  96496. /* lg(4/3) = */ 0x00000000,
  96497. /* lg(8/7) = */ 0x00000000,
  96498. /* lg(16/15) = */ 0x00000000,
  96499. /* lg(32/31) = */ 0x00000000,
  96500. /* lg(64/63) = */ 0x00000000,
  96501. /* lg(128/127) = */ 0x00000000,
  96502. /* lg(256/255) = */ 0x00000000,
  96503. /* lg(512/511) = */ 0x00000000,
  96504. /* lg(1024/1023) = */ 0x00000000,
  96505. /* lg(2048/2047) = */ 0x00000000,
  96506. /* lg(4096/4095) = */ 0x00000000,
  96507. /* lg(8192/8191) = */ 0x00000000,
  96508. /* lg(16384/16383) = */ 0x00000000,
  96509. /* lg(32768/32767) = */ 0x00000000
  96510. },
  96511. {
  96512. /*
  96513. * 4 fraction bits
  96514. */
  96515. /* undefined */ 0x00000000,
  96516. /* lg(2/1) = */ 0x00000010,
  96517. /* lg(4/3) = */ 0x00000007,
  96518. /* lg(8/7) = */ 0x00000003,
  96519. /* lg(16/15) = */ 0x00000001,
  96520. /* lg(32/31) = */ 0x00000001,
  96521. /* lg(64/63) = */ 0x00000000,
  96522. /* lg(128/127) = */ 0x00000000,
  96523. /* lg(256/255) = */ 0x00000000,
  96524. /* lg(512/511) = */ 0x00000000,
  96525. /* lg(1024/1023) = */ 0x00000000,
  96526. /* lg(2048/2047) = */ 0x00000000,
  96527. /* lg(4096/4095) = */ 0x00000000,
  96528. /* lg(8192/8191) = */ 0x00000000,
  96529. /* lg(16384/16383) = */ 0x00000000,
  96530. /* lg(32768/32767) = */ 0x00000000
  96531. },
  96532. {
  96533. /*
  96534. * 8 fraction bits
  96535. */
  96536. /* undefined */ 0x00000000,
  96537. /* lg(2/1) = */ 0x00000100,
  96538. /* lg(4/3) = */ 0x0000006a,
  96539. /* lg(8/7) = */ 0x00000031,
  96540. /* lg(16/15) = */ 0x00000018,
  96541. /* lg(32/31) = */ 0x0000000c,
  96542. /* lg(64/63) = */ 0x00000006,
  96543. /* lg(128/127) = */ 0x00000003,
  96544. /* lg(256/255) = */ 0x00000001,
  96545. /* lg(512/511) = */ 0x00000001,
  96546. /* lg(1024/1023) = */ 0x00000000,
  96547. /* lg(2048/2047) = */ 0x00000000,
  96548. /* lg(4096/4095) = */ 0x00000000,
  96549. /* lg(8192/8191) = */ 0x00000000,
  96550. /* lg(16384/16383) = */ 0x00000000,
  96551. /* lg(32768/32767) = */ 0x00000000
  96552. },
  96553. {
  96554. /*
  96555. * 12 fraction bits
  96556. */
  96557. /* undefined */ 0x00000000,
  96558. /* lg(2/1) = */ 0x00001000,
  96559. /* lg(4/3) = */ 0x000006a4,
  96560. /* lg(8/7) = */ 0x00000315,
  96561. /* lg(16/15) = */ 0x0000017d,
  96562. /* lg(32/31) = */ 0x000000bc,
  96563. /* lg(64/63) = */ 0x0000005d,
  96564. /* lg(128/127) = */ 0x0000002e,
  96565. /* lg(256/255) = */ 0x00000017,
  96566. /* lg(512/511) = */ 0x0000000c,
  96567. /* lg(1024/1023) = */ 0x00000006,
  96568. /* lg(2048/2047) = */ 0x00000003,
  96569. /* lg(4096/4095) = */ 0x00000001,
  96570. /* lg(8192/8191) = */ 0x00000001,
  96571. /* lg(16384/16383) = */ 0x00000000,
  96572. /* lg(32768/32767) = */ 0x00000000
  96573. },
  96574. {
  96575. /*
  96576. * 16 fraction bits
  96577. */
  96578. /* undefined */ 0x00000000,
  96579. /* lg(2/1) = */ 0x00010000,
  96580. /* lg(4/3) = */ 0x00006a40,
  96581. /* lg(8/7) = */ 0x00003151,
  96582. /* lg(16/15) = */ 0x000017d6,
  96583. /* lg(32/31) = */ 0x00000bba,
  96584. /* lg(64/63) = */ 0x000005d1,
  96585. /* lg(128/127) = */ 0x000002e6,
  96586. /* lg(256/255) = */ 0x00000172,
  96587. /* lg(512/511) = */ 0x000000b9,
  96588. /* lg(1024/1023) = */ 0x0000005c,
  96589. /* lg(2048/2047) = */ 0x0000002e,
  96590. /* lg(4096/4095) = */ 0x00000017,
  96591. /* lg(8192/8191) = */ 0x0000000c,
  96592. /* lg(16384/16383) = */ 0x00000006,
  96593. /* lg(32768/32767) = */ 0x00000003
  96594. },
  96595. {
  96596. /*
  96597. * 20 fraction bits
  96598. */
  96599. /* undefined */ 0x00000000,
  96600. /* lg(2/1) = */ 0x00100000,
  96601. /* lg(4/3) = */ 0x0006a3fe,
  96602. /* lg(8/7) = */ 0x00031513,
  96603. /* lg(16/15) = */ 0x00017d60,
  96604. /* lg(32/31) = */ 0x0000bb9d,
  96605. /* lg(64/63) = */ 0x00005d10,
  96606. /* lg(128/127) = */ 0x00002e59,
  96607. /* lg(256/255) = */ 0x00001721,
  96608. /* lg(512/511) = */ 0x00000b8e,
  96609. /* lg(1024/1023) = */ 0x000005c6,
  96610. /* lg(2048/2047) = */ 0x000002e3,
  96611. /* lg(4096/4095) = */ 0x00000171,
  96612. /* lg(8192/8191) = */ 0x000000b9,
  96613. /* lg(16384/16383) = */ 0x0000005c,
  96614. /* lg(32768/32767) = */ 0x0000002e
  96615. },
  96616. {
  96617. /*
  96618. * 24 fraction bits
  96619. */
  96620. /* undefined */ 0x00000000,
  96621. /* lg(2/1) = */ 0x01000000,
  96622. /* lg(4/3) = */ 0x006a3fe6,
  96623. /* lg(8/7) = */ 0x00315130,
  96624. /* lg(16/15) = */ 0x0017d605,
  96625. /* lg(32/31) = */ 0x000bb9ca,
  96626. /* lg(64/63) = */ 0x0005d0fc,
  96627. /* lg(128/127) = */ 0x0002e58f,
  96628. /* lg(256/255) = */ 0x0001720e,
  96629. /* lg(512/511) = */ 0x0000b8d8,
  96630. /* lg(1024/1023) = */ 0x00005c61,
  96631. /* lg(2048/2047) = */ 0x00002e2d,
  96632. /* lg(4096/4095) = */ 0x00001716,
  96633. /* lg(8192/8191) = */ 0x00000b8b,
  96634. /* lg(16384/16383) = */ 0x000005c5,
  96635. /* lg(32768/32767) = */ 0x000002e3
  96636. },
  96637. {
  96638. /*
  96639. * 28 fraction bits
  96640. */
  96641. /* undefined */ 0x00000000,
  96642. /* lg(2/1) = */ 0x10000000,
  96643. /* lg(4/3) = */ 0x06a3fe5c,
  96644. /* lg(8/7) = */ 0x03151301,
  96645. /* lg(16/15) = */ 0x017d6049,
  96646. /* lg(32/31) = */ 0x00bb9ca6,
  96647. /* lg(64/63) = */ 0x005d0fba,
  96648. /* lg(128/127) = */ 0x002e58f7,
  96649. /* lg(256/255) = */ 0x001720da,
  96650. /* lg(512/511) = */ 0x000b8d87,
  96651. /* lg(1024/1023) = */ 0x0005c60b,
  96652. /* lg(2048/2047) = */ 0x0002e2d7,
  96653. /* lg(4096/4095) = */ 0x00017160,
  96654. /* lg(8192/8191) = */ 0x0000b8ad,
  96655. /* lg(16384/16383) = */ 0x00005c56,
  96656. /* lg(32768/32767) = */ 0x00002e2b
  96657. }
  96658. };
  96659. #if 0
  96660. static const FLAC__uint64 log2_lookup_wide[] = {
  96661. {
  96662. /*
  96663. * 32 fraction bits
  96664. */
  96665. /* undefined */ 0x00000000,
  96666. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96667. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96668. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96669. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96670. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96671. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96672. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96673. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96674. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96675. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96676. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96677. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96678. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96679. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96680. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96681. },
  96682. {
  96683. /*
  96684. * 48 fraction bits
  96685. */
  96686. /* undefined */ 0x00000000,
  96687. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96688. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96689. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96690. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96691. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96692. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96693. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96694. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96695. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96696. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96697. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96698. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96699. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96700. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96701. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96702. }
  96703. };
  96704. #endif
  96705. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96706. {
  96707. const FLAC__uint32 ONE = (1u << fracbits);
  96708. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96709. FLAC__ASSERT(fracbits < 32);
  96710. FLAC__ASSERT((fracbits & 0x3) == 0);
  96711. if(x < ONE)
  96712. return 0;
  96713. if(precision > LOG2_LOOKUP_PRECISION)
  96714. precision = LOG2_LOOKUP_PRECISION;
  96715. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96716. {
  96717. FLAC__uint32 y = 0;
  96718. FLAC__uint32 z = x >> 1, k = 1;
  96719. while (x > ONE && k < precision) {
  96720. if (x - z >= ONE) {
  96721. x -= z;
  96722. z = x >> k;
  96723. y += table[k];
  96724. }
  96725. else {
  96726. z >>= 1;
  96727. k++;
  96728. }
  96729. }
  96730. return y;
  96731. }
  96732. }
  96733. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96734. #endif
  96735. /*** End of inlined file: float.c ***/
  96736. /*** Start of inlined file: format.c ***/
  96737. /*** Start of inlined file: juce_FlacHeader.h ***/
  96738. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96739. // tasks..
  96740. #define VERSION "1.2.1"
  96741. #define FLAC__NO_DLL 1
  96742. #if JUCE_MSVC
  96743. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96744. #endif
  96745. #if JUCE_MAC
  96746. #define FLAC__SYS_DARWIN 1
  96747. #endif
  96748. /*** End of inlined file: juce_FlacHeader.h ***/
  96749. #if JUCE_USE_FLAC
  96750. #if HAVE_CONFIG_H
  96751. # include <config.h>
  96752. #endif
  96753. #include <stdio.h>
  96754. #include <stdlib.h> /* for qsort() */
  96755. #include <string.h> /* for memset() */
  96756. #ifndef FLaC__INLINE
  96757. #define FLaC__INLINE
  96758. #endif
  96759. #ifdef min
  96760. #undef min
  96761. #endif
  96762. #define min(a,b) ((a)<(b)?(a):(b))
  96763. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96764. #ifdef _MSC_VER
  96765. #define FLAC__U64L(x) x
  96766. #else
  96767. #define FLAC__U64L(x) x##LLU
  96768. #endif
  96769. /* VERSION should come from configure */
  96770. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96771. ;
  96772. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96773. /* yet one more hack because of MSVC6: */
  96774. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96775. #else
  96776. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96777. #endif
  96778. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96779. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96780. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96781. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96782. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96783. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96784. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96785. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96786. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96787. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96788. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96789. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96790. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96791. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96792. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96793. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96794. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96795. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96796. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96797. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96798. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96799. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96800. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96801. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96802. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96803. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96804. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96805. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96806. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96807. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96808. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96809. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96810. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96811. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96812. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96813. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96814. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96815. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96816. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96817. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96818. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96819. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96820. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96821. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96822. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96823. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96824. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96825. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96826. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96827. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96828. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96829. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96830. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96831. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96832. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96833. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96834. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96835. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96836. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96837. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96838. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96839. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96840. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96841. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96842. "PARTITIONED_RICE",
  96843. "PARTITIONED_RICE2"
  96844. };
  96845. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96846. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96847. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96848. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96849. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96850. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96851. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96852. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96853. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96854. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96855. "CONSTANT",
  96856. "VERBATIM",
  96857. "FIXED",
  96858. "LPC"
  96859. };
  96860. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96861. "INDEPENDENT",
  96862. "LEFT_SIDE",
  96863. "RIGHT_SIDE",
  96864. "MID_SIDE"
  96865. };
  96866. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96867. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96868. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96869. };
  96870. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96871. "STREAMINFO",
  96872. "PADDING",
  96873. "APPLICATION",
  96874. "SEEKTABLE",
  96875. "VORBIS_COMMENT",
  96876. "CUESHEET",
  96877. "PICTURE"
  96878. };
  96879. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96880. "Other",
  96881. "32x32 pixels 'file icon' (PNG only)",
  96882. "Other file icon",
  96883. "Cover (front)",
  96884. "Cover (back)",
  96885. "Leaflet page",
  96886. "Media (e.g. label side of CD)",
  96887. "Lead artist/lead performer/soloist",
  96888. "Artist/performer",
  96889. "Conductor",
  96890. "Band/Orchestra",
  96891. "Composer",
  96892. "Lyricist/text writer",
  96893. "Recording Location",
  96894. "During recording",
  96895. "During performance",
  96896. "Movie/video screen capture",
  96897. "A bright coloured fish",
  96898. "Illustration",
  96899. "Band/artist logotype",
  96900. "Publisher/Studio logotype"
  96901. };
  96902. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96903. {
  96904. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96905. return false;
  96906. }
  96907. else
  96908. return true;
  96909. }
  96910. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96911. {
  96912. if(
  96913. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96914. (
  96915. sample_rate >= (1u << 16) &&
  96916. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96917. )
  96918. ) {
  96919. return false;
  96920. }
  96921. else
  96922. return true;
  96923. }
  96924. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96925. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96926. {
  96927. unsigned i;
  96928. FLAC__uint64 prev_sample_number = 0;
  96929. FLAC__bool got_prev = false;
  96930. FLAC__ASSERT(0 != seek_table);
  96931. for(i = 0; i < seek_table->num_points; i++) {
  96932. if(got_prev) {
  96933. if(
  96934. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96935. seek_table->points[i].sample_number <= prev_sample_number
  96936. )
  96937. return false;
  96938. }
  96939. prev_sample_number = seek_table->points[i].sample_number;
  96940. got_prev = true;
  96941. }
  96942. return true;
  96943. }
  96944. /* used as the sort predicate for qsort() */
  96945. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96946. {
  96947. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96948. if(l->sample_number == r->sample_number)
  96949. return 0;
  96950. else if(l->sample_number < r->sample_number)
  96951. return -1;
  96952. else
  96953. return 1;
  96954. }
  96955. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96956. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96957. {
  96958. unsigned i, j;
  96959. FLAC__bool first;
  96960. FLAC__ASSERT(0 != seek_table);
  96961. /* sort the seekpoints */
  96962. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96963. /* uniquify the seekpoints */
  96964. first = true;
  96965. for(i = j = 0; i < seek_table->num_points; i++) {
  96966. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96967. if(!first) {
  96968. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96969. continue;
  96970. }
  96971. }
  96972. first = false;
  96973. seek_table->points[j++] = seek_table->points[i];
  96974. }
  96975. for(i = j; i < seek_table->num_points; i++) {
  96976. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96977. seek_table->points[i].stream_offset = 0;
  96978. seek_table->points[i].frame_samples = 0;
  96979. }
  96980. return j;
  96981. }
  96982. /*
  96983. * also disallows non-shortest-form encodings, c.f.
  96984. * http://www.unicode.org/versions/corrigendum1.html
  96985. * and a more clear explanation at the end of this section:
  96986. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96987. */
  96988. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96989. {
  96990. FLAC__ASSERT(0 != utf8);
  96991. if ((utf8[0] & 0x80) == 0) {
  96992. return 1;
  96993. }
  96994. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96995. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96996. return 0;
  96997. return 2;
  96998. }
  96999. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  97000. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  97001. return 0;
  97002. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  97003. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  97004. return 0;
  97005. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  97006. return 0;
  97007. return 3;
  97008. }
  97009. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  97010. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  97011. return 0;
  97012. return 4;
  97013. }
  97014. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  97015. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  97016. return 0;
  97017. return 5;
  97018. }
  97019. 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) {
  97020. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  97021. return 0;
  97022. return 6;
  97023. }
  97024. else {
  97025. return 0;
  97026. }
  97027. }
  97028. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  97029. {
  97030. char c;
  97031. for(c = *name; c; c = *(++name))
  97032. if(c < 0x20 || c == 0x3d || c > 0x7d)
  97033. return false;
  97034. return true;
  97035. }
  97036. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  97037. {
  97038. if(length == (unsigned)(-1)) {
  97039. while(*value) {
  97040. unsigned n = utf8len_(value);
  97041. if(n == 0)
  97042. return false;
  97043. value += n;
  97044. }
  97045. }
  97046. else {
  97047. const FLAC__byte *end = value + length;
  97048. while(value < end) {
  97049. unsigned n = utf8len_(value);
  97050. if(n == 0)
  97051. return false;
  97052. value += n;
  97053. }
  97054. if(value != end)
  97055. return false;
  97056. }
  97057. return true;
  97058. }
  97059. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  97060. {
  97061. const FLAC__byte *s, *end;
  97062. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  97063. if(*s < 0x20 || *s > 0x7D)
  97064. return false;
  97065. }
  97066. if(s == end)
  97067. return false;
  97068. s++; /* skip '=' */
  97069. while(s < end) {
  97070. unsigned n = utf8len_(s);
  97071. if(n == 0)
  97072. return false;
  97073. s += n;
  97074. }
  97075. if(s != end)
  97076. return false;
  97077. return true;
  97078. }
  97079. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97080. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  97081. {
  97082. unsigned i, j;
  97083. if(check_cd_da_subset) {
  97084. if(cue_sheet->lead_in < 2 * 44100) {
  97085. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  97086. return false;
  97087. }
  97088. if(cue_sheet->lead_in % 588 != 0) {
  97089. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  97090. return false;
  97091. }
  97092. }
  97093. if(cue_sheet->num_tracks == 0) {
  97094. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  97095. return false;
  97096. }
  97097. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  97098. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  97099. return false;
  97100. }
  97101. for(i = 0; i < cue_sheet->num_tracks; i++) {
  97102. if(cue_sheet->tracks[i].number == 0) {
  97103. if(violation) *violation = "cue sheet may not have a track number 0";
  97104. return false;
  97105. }
  97106. if(check_cd_da_subset) {
  97107. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  97108. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  97109. return false;
  97110. }
  97111. }
  97112. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  97113. if(violation) {
  97114. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  97115. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  97116. else
  97117. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  97118. }
  97119. return false;
  97120. }
  97121. if(i < cue_sheet->num_tracks - 1) {
  97122. if(cue_sheet->tracks[i].num_indices == 0) {
  97123. if(violation) *violation = "cue sheet track must have at least one index point";
  97124. return false;
  97125. }
  97126. if(cue_sheet->tracks[i].indices[0].number > 1) {
  97127. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  97128. return false;
  97129. }
  97130. }
  97131. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  97132. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  97133. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  97134. return false;
  97135. }
  97136. if(j > 0) {
  97137. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  97138. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  97139. return false;
  97140. }
  97141. }
  97142. }
  97143. }
  97144. return true;
  97145. }
  97146. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97147. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  97148. {
  97149. char *p;
  97150. FLAC__byte *b;
  97151. for(p = picture->mime_type; *p; p++) {
  97152. if(*p < 0x20 || *p > 0x7e) {
  97153. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  97154. return false;
  97155. }
  97156. }
  97157. for(b = picture->description; *b; ) {
  97158. unsigned n = utf8len_(b);
  97159. if(n == 0) {
  97160. if(violation) *violation = "description string must be valid UTF-8";
  97161. return false;
  97162. }
  97163. b += n;
  97164. }
  97165. return true;
  97166. }
  97167. /*
  97168. * These routines are private to libFLAC
  97169. */
  97170. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  97171. {
  97172. return
  97173. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97174. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97175. blocksize,
  97176. predictor_order
  97177. );
  97178. }
  97179. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97180. {
  97181. unsigned max_rice_partition_order = 0;
  97182. while(!(blocksize & 1)) {
  97183. max_rice_partition_order++;
  97184. blocksize >>= 1;
  97185. }
  97186. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97187. }
  97188. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97189. {
  97190. unsigned max_rice_partition_order = limit;
  97191. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97192. max_rice_partition_order--;
  97193. FLAC__ASSERT(
  97194. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97195. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97196. );
  97197. return max_rice_partition_order;
  97198. }
  97199. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97200. {
  97201. FLAC__ASSERT(0 != object);
  97202. object->parameters = 0;
  97203. object->raw_bits = 0;
  97204. object->capacity_by_order = 0;
  97205. }
  97206. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97207. {
  97208. FLAC__ASSERT(0 != object);
  97209. if(0 != object->parameters)
  97210. free(object->parameters);
  97211. if(0 != object->raw_bits)
  97212. free(object->raw_bits);
  97213. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97214. }
  97215. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97216. {
  97217. FLAC__ASSERT(0 != object);
  97218. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97219. if(object->capacity_by_order < max_partition_order) {
  97220. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97221. return false;
  97222. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97223. return false;
  97224. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97225. object->capacity_by_order = max_partition_order;
  97226. }
  97227. return true;
  97228. }
  97229. #endif
  97230. /*** End of inlined file: format.c ***/
  97231. /*** Start of inlined file: lpc_flac.c ***/
  97232. /*** Start of inlined file: juce_FlacHeader.h ***/
  97233. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97234. // tasks..
  97235. #define VERSION "1.2.1"
  97236. #define FLAC__NO_DLL 1
  97237. #if JUCE_MSVC
  97238. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97239. #endif
  97240. #if JUCE_MAC
  97241. #define FLAC__SYS_DARWIN 1
  97242. #endif
  97243. /*** End of inlined file: juce_FlacHeader.h ***/
  97244. #if JUCE_USE_FLAC
  97245. #if HAVE_CONFIG_H
  97246. # include <config.h>
  97247. #endif
  97248. #include <math.h>
  97249. /*** Start of inlined file: lpc.h ***/
  97250. #ifndef FLAC__PRIVATE__LPC_H
  97251. #define FLAC__PRIVATE__LPC_H
  97252. #ifdef HAVE_CONFIG_H
  97253. #include <config.h>
  97254. #endif
  97255. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97256. /*
  97257. * FLAC__lpc_window_data()
  97258. * --------------------------------------------------------------------
  97259. * Applies the given window to the data.
  97260. * OPT: asm implementation
  97261. *
  97262. * IN in[0,data_len-1]
  97263. * IN window[0,data_len-1]
  97264. * OUT out[0,lag-1]
  97265. * IN data_len
  97266. */
  97267. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97268. /*
  97269. * FLAC__lpc_compute_autocorrelation()
  97270. * --------------------------------------------------------------------
  97271. * Compute the autocorrelation for lags between 0 and lag-1.
  97272. * Assumes data[] outside of [0,data_len-1] == 0.
  97273. * Asserts that lag > 0.
  97274. *
  97275. * IN data[0,data_len-1]
  97276. * IN data_len
  97277. * IN 0 < lag <= data_len
  97278. * OUT autoc[0,lag-1]
  97279. */
  97280. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97281. #ifndef FLAC__NO_ASM
  97282. # ifdef FLAC__CPU_IA32
  97283. # ifdef FLAC__HAS_NASM
  97284. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97285. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97286. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97287. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97288. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97289. # endif
  97290. # endif
  97291. #endif
  97292. /*
  97293. * FLAC__lpc_compute_lp_coefficients()
  97294. * --------------------------------------------------------------------
  97295. * Computes LP coefficients for orders 1..max_order.
  97296. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97297. * and there is no point in calculating a predictor.
  97298. *
  97299. * IN autoc[0,max_order] autocorrelation values
  97300. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97301. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97302. * *** IMPORTANT:
  97303. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97304. * OUT error[0,max_order-1] error for each order (more
  97305. * specifically, the variance of
  97306. * the error signal times # of
  97307. * samples in the signal)
  97308. *
  97309. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97310. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97311. * in lp_coeff[7][0,7], etc.
  97312. */
  97313. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97314. /*
  97315. * FLAC__lpc_quantize_coefficients()
  97316. * --------------------------------------------------------------------
  97317. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97318. * must be less than 32 (sizeof(FLAC__int32)*8).
  97319. *
  97320. * IN lp_coeff[0,order-1] LP coefficients
  97321. * IN order LP order
  97322. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97323. * desired precision (in bits, including sign
  97324. * bit) of largest coefficient
  97325. * OUT qlp_coeff[0,order-1] quantized coefficients
  97326. * OUT shift # of bits to shift right to get approximated
  97327. * LP coefficients. NOTE: could be negative.
  97328. * RETURN 0 => quantization OK
  97329. * 1 => coefficients require too much shifting for *shift to
  97330. * fit in the LPC subframe header. 'shift' is unset.
  97331. * 2 => coefficients are all zero, which is bad. 'shift' is
  97332. * unset.
  97333. */
  97334. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97335. /*
  97336. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97337. * --------------------------------------------------------------------
  97338. * Compute the residual signal obtained from sutracting the predicted
  97339. * signal from the original.
  97340. *
  97341. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97342. * IN data_len length of original signal
  97343. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97344. * IN order > 0 LP order
  97345. * IN lp_quantization quantization of LP coefficients in bits
  97346. * OUT residual[0,data_len-1] residual signal
  97347. */
  97348. 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[]);
  97349. 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[]);
  97350. #ifndef FLAC__NO_ASM
  97351. # ifdef FLAC__CPU_IA32
  97352. # ifdef FLAC__HAS_NASM
  97353. 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[]);
  97354. 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[]);
  97355. # endif
  97356. # endif
  97357. #endif
  97358. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97359. /*
  97360. * FLAC__lpc_restore_signal()
  97361. * --------------------------------------------------------------------
  97362. * Restore the original signal by summing the residual and the
  97363. * predictor.
  97364. *
  97365. * IN residual[0,data_len-1] residual signal
  97366. * IN data_len length of original signal
  97367. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97368. * IN order > 0 LP order
  97369. * IN lp_quantization quantization of LP coefficients in bits
  97370. * *** IMPORTANT: the caller must pass in the historical samples:
  97371. * IN data[-order,-1] previously-reconstructed historical samples
  97372. * OUT data[0,data_len-1] original signal
  97373. */
  97374. 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[]);
  97375. 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[]);
  97376. #ifndef FLAC__NO_ASM
  97377. # ifdef FLAC__CPU_IA32
  97378. # ifdef FLAC__HAS_NASM
  97379. 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[]);
  97380. 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[]);
  97381. # endif /* FLAC__HAS_NASM */
  97382. # elif defined FLAC__CPU_PPC
  97383. 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[]);
  97384. 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[]);
  97385. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97386. #endif /* FLAC__NO_ASM */
  97387. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97388. /*
  97389. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97390. * --------------------------------------------------------------------
  97391. * Compute the expected number of bits per residual signal sample
  97392. * based on the LP error (which is related to the residual variance).
  97393. *
  97394. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97395. * IN total_samples > 0 # of samples in residual signal
  97396. * RETURN expected bits per sample
  97397. */
  97398. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97399. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97400. /*
  97401. * FLAC__lpc_compute_best_order()
  97402. * --------------------------------------------------------------------
  97403. * Compute the best order from the array of signal errors returned
  97404. * during coefficient computation.
  97405. *
  97406. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97407. * IN max_order > 0 max LP order
  97408. * IN total_samples > 0 # of samples in residual signal
  97409. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97410. * (includes warmup sample size and quantized LP coefficient)
  97411. * RETURN [1,max_order] best order
  97412. */
  97413. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97414. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97415. #endif
  97416. /*** End of inlined file: lpc.h ***/
  97417. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97418. #include <stdio.h>
  97419. #endif
  97420. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97421. #ifndef M_LN2
  97422. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97423. #define M_LN2 0.69314718055994530942
  97424. #endif
  97425. /* OPT: #undef'ing this may improve the speed on some architectures */
  97426. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97427. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97428. {
  97429. unsigned i;
  97430. for(i = 0; i < data_len; i++)
  97431. out[i] = in[i] * window[i];
  97432. }
  97433. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97434. {
  97435. /* a readable, but slower, version */
  97436. #if 0
  97437. FLAC__real d;
  97438. unsigned i;
  97439. FLAC__ASSERT(lag > 0);
  97440. FLAC__ASSERT(lag <= data_len);
  97441. /*
  97442. * Technically we should subtract the mean first like so:
  97443. * for(i = 0; i < data_len; i++)
  97444. * data[i] -= mean;
  97445. * but it appears not to make enough of a difference to matter, and
  97446. * most signals are already closely centered around zero
  97447. */
  97448. while(lag--) {
  97449. for(i = lag, d = 0.0; i < data_len; i++)
  97450. d += data[i] * data[i - lag];
  97451. autoc[lag] = d;
  97452. }
  97453. #endif
  97454. /*
  97455. * this version tends to run faster because of better data locality
  97456. * ('data_len' is usually much larger than 'lag')
  97457. */
  97458. FLAC__real d;
  97459. unsigned sample, coeff;
  97460. const unsigned limit = data_len - lag;
  97461. FLAC__ASSERT(lag > 0);
  97462. FLAC__ASSERT(lag <= data_len);
  97463. for(coeff = 0; coeff < lag; coeff++)
  97464. autoc[coeff] = 0.0;
  97465. for(sample = 0; sample <= limit; sample++) {
  97466. d = data[sample];
  97467. for(coeff = 0; coeff < lag; coeff++)
  97468. autoc[coeff] += d * data[sample+coeff];
  97469. }
  97470. for(; sample < data_len; sample++) {
  97471. d = data[sample];
  97472. for(coeff = 0; coeff < data_len - sample; coeff++)
  97473. autoc[coeff] += d * data[sample+coeff];
  97474. }
  97475. }
  97476. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97477. {
  97478. unsigned i, j;
  97479. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97480. FLAC__ASSERT(0 != max_order);
  97481. FLAC__ASSERT(0 < *max_order);
  97482. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97483. FLAC__ASSERT(autoc[0] != 0.0);
  97484. err = autoc[0];
  97485. for(i = 0; i < *max_order; i++) {
  97486. /* Sum up this iteration's reflection coefficient. */
  97487. r = -autoc[i+1];
  97488. for(j = 0; j < i; j++)
  97489. r -= lpc[j] * autoc[i-j];
  97490. ref[i] = (r/=err);
  97491. /* Update LPC coefficients and total error. */
  97492. lpc[i]=r;
  97493. for(j = 0; j < (i>>1); j++) {
  97494. FLAC__double tmp = lpc[j];
  97495. lpc[j] += r * lpc[i-1-j];
  97496. lpc[i-1-j] += r * tmp;
  97497. }
  97498. if(i & 1)
  97499. lpc[j] += lpc[j] * r;
  97500. err *= (1.0 - r * r);
  97501. /* save this order */
  97502. for(j = 0; j <= i; j++)
  97503. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97504. error[i] = err;
  97505. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97506. if(err == 0.0) {
  97507. *max_order = i+1;
  97508. return;
  97509. }
  97510. }
  97511. }
  97512. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97513. {
  97514. unsigned i;
  97515. FLAC__double cmax;
  97516. FLAC__int32 qmax, qmin;
  97517. FLAC__ASSERT(precision > 0);
  97518. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97519. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97520. precision--;
  97521. qmax = 1 << precision;
  97522. qmin = -qmax;
  97523. qmax--;
  97524. /* calc cmax = max( |lp_coeff[i]| ) */
  97525. cmax = 0.0;
  97526. for(i = 0; i < order; i++) {
  97527. const FLAC__double d = fabs(lp_coeff[i]);
  97528. if(d > cmax)
  97529. cmax = d;
  97530. }
  97531. if(cmax <= 0.0) {
  97532. /* => coefficients are all 0, which means our constant-detect didn't work */
  97533. return 2;
  97534. }
  97535. else {
  97536. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97537. const int min_shiftlimit = -max_shiftlimit - 1;
  97538. int log2cmax;
  97539. (void)frexp(cmax, &log2cmax);
  97540. log2cmax--;
  97541. *shift = (int)precision - log2cmax - 1;
  97542. if(*shift > max_shiftlimit)
  97543. *shift = max_shiftlimit;
  97544. else if(*shift < min_shiftlimit)
  97545. return 1;
  97546. }
  97547. if(*shift >= 0) {
  97548. FLAC__double error = 0.0;
  97549. FLAC__int32 q;
  97550. for(i = 0; i < order; i++) {
  97551. error += lp_coeff[i] * (1 << *shift);
  97552. #if 1 /* unfortunately lround() is C99 */
  97553. if(error >= 0.0)
  97554. q = (FLAC__int32)(error + 0.5);
  97555. else
  97556. q = (FLAC__int32)(error - 0.5);
  97557. #else
  97558. q = lround(error);
  97559. #endif
  97560. #ifdef FLAC__OVERFLOW_DETECT
  97561. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97562. 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]);
  97563. else if(q < qmin)
  97564. 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]);
  97565. #endif
  97566. if(q > qmax)
  97567. q = qmax;
  97568. else if(q < qmin)
  97569. q = qmin;
  97570. error -= q;
  97571. qlp_coeff[i] = q;
  97572. }
  97573. }
  97574. /* negative shift is very rare but due to design flaw, negative shift is
  97575. * a NOP in the decoder, so it must be handled specially by scaling down
  97576. * coeffs
  97577. */
  97578. else {
  97579. const int nshift = -(*shift);
  97580. FLAC__double error = 0.0;
  97581. FLAC__int32 q;
  97582. #ifdef DEBUG
  97583. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97584. #endif
  97585. for(i = 0; i < order; i++) {
  97586. error += lp_coeff[i] / (1 << nshift);
  97587. #if 1 /* unfortunately lround() is C99 */
  97588. if(error >= 0.0)
  97589. q = (FLAC__int32)(error + 0.5);
  97590. else
  97591. q = (FLAC__int32)(error - 0.5);
  97592. #else
  97593. q = lround(error);
  97594. #endif
  97595. #ifdef FLAC__OVERFLOW_DETECT
  97596. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97597. 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]);
  97598. else if(q < qmin)
  97599. 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]);
  97600. #endif
  97601. if(q > qmax)
  97602. q = qmax;
  97603. else if(q < qmin)
  97604. q = qmin;
  97605. error -= q;
  97606. qlp_coeff[i] = q;
  97607. }
  97608. *shift = 0;
  97609. }
  97610. return 0;
  97611. }
  97612. 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[])
  97613. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97614. {
  97615. FLAC__int64 sumo;
  97616. unsigned i, j;
  97617. FLAC__int32 sum;
  97618. const FLAC__int32 *history;
  97619. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97620. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97621. for(i=0;i<order;i++)
  97622. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97623. fprintf(stderr,"\n");
  97624. #endif
  97625. FLAC__ASSERT(order > 0);
  97626. for(i = 0; i < data_len; i++) {
  97627. sumo = 0;
  97628. sum = 0;
  97629. history = data;
  97630. for(j = 0; j < order; j++) {
  97631. sum += qlp_coeff[j] * (*(--history));
  97632. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97633. #if defined _MSC_VER
  97634. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97635. 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);
  97636. #else
  97637. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97638. 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);
  97639. #endif
  97640. }
  97641. *(residual++) = *(data++) - (sum >> lp_quantization);
  97642. }
  97643. /* Here's a slower but clearer version:
  97644. for(i = 0; i < data_len; i++) {
  97645. sum = 0;
  97646. for(j = 0; j < order; j++)
  97647. sum += qlp_coeff[j] * data[i-j-1];
  97648. residual[i] = data[i] - (sum >> lp_quantization);
  97649. }
  97650. */
  97651. }
  97652. #else /* fully unrolled version for normal use */
  97653. {
  97654. int i;
  97655. FLAC__int32 sum;
  97656. FLAC__ASSERT(order > 0);
  97657. FLAC__ASSERT(order <= 32);
  97658. /*
  97659. * We do unique versions up to 12th order since that's the subset limit.
  97660. * Also they are roughly ordered to match frequency of occurrence to
  97661. * minimize branching.
  97662. */
  97663. if(order <= 12) {
  97664. if(order > 8) {
  97665. if(order > 10) {
  97666. if(order == 12) {
  97667. for(i = 0; i < (int)data_len; i++) {
  97668. sum = 0;
  97669. sum += qlp_coeff[11] * data[i-12];
  97670. sum += qlp_coeff[10] * data[i-11];
  97671. sum += qlp_coeff[9] * data[i-10];
  97672. sum += qlp_coeff[8] * data[i-9];
  97673. sum += qlp_coeff[7] * data[i-8];
  97674. sum += qlp_coeff[6] * data[i-7];
  97675. sum += qlp_coeff[5] * data[i-6];
  97676. sum += qlp_coeff[4] * data[i-5];
  97677. sum += qlp_coeff[3] * data[i-4];
  97678. sum += qlp_coeff[2] * data[i-3];
  97679. sum += qlp_coeff[1] * data[i-2];
  97680. sum += qlp_coeff[0] * data[i-1];
  97681. residual[i] = data[i] - (sum >> lp_quantization);
  97682. }
  97683. }
  97684. else { /* order == 11 */
  97685. for(i = 0; i < (int)data_len; i++) {
  97686. sum = 0;
  97687. sum += qlp_coeff[10] * data[i-11];
  97688. sum += qlp_coeff[9] * data[i-10];
  97689. sum += qlp_coeff[8] * data[i-9];
  97690. sum += qlp_coeff[7] * data[i-8];
  97691. sum += qlp_coeff[6] * data[i-7];
  97692. sum += qlp_coeff[5] * data[i-6];
  97693. sum += qlp_coeff[4] * data[i-5];
  97694. sum += qlp_coeff[3] * data[i-4];
  97695. sum += qlp_coeff[2] * data[i-3];
  97696. sum += qlp_coeff[1] * data[i-2];
  97697. sum += qlp_coeff[0] * data[i-1];
  97698. residual[i] = data[i] - (sum >> lp_quantization);
  97699. }
  97700. }
  97701. }
  97702. else {
  97703. if(order == 10) {
  97704. for(i = 0; i < (int)data_len; i++) {
  97705. sum = 0;
  97706. sum += qlp_coeff[9] * data[i-10];
  97707. sum += qlp_coeff[8] * data[i-9];
  97708. sum += qlp_coeff[7] * data[i-8];
  97709. sum += qlp_coeff[6] * data[i-7];
  97710. sum += qlp_coeff[5] * data[i-6];
  97711. sum += qlp_coeff[4] * data[i-5];
  97712. sum += qlp_coeff[3] * data[i-4];
  97713. sum += qlp_coeff[2] * data[i-3];
  97714. sum += qlp_coeff[1] * data[i-2];
  97715. sum += qlp_coeff[0] * data[i-1];
  97716. residual[i] = data[i] - (sum >> lp_quantization);
  97717. }
  97718. }
  97719. else { /* order == 9 */
  97720. for(i = 0; i < (int)data_len; i++) {
  97721. sum = 0;
  97722. sum += qlp_coeff[8] * data[i-9];
  97723. sum += qlp_coeff[7] * data[i-8];
  97724. sum += qlp_coeff[6] * data[i-7];
  97725. sum += qlp_coeff[5] * data[i-6];
  97726. sum += qlp_coeff[4] * data[i-5];
  97727. sum += qlp_coeff[3] * data[i-4];
  97728. sum += qlp_coeff[2] * data[i-3];
  97729. sum += qlp_coeff[1] * data[i-2];
  97730. sum += qlp_coeff[0] * data[i-1];
  97731. residual[i] = data[i] - (sum >> lp_quantization);
  97732. }
  97733. }
  97734. }
  97735. }
  97736. else if(order > 4) {
  97737. if(order > 6) {
  97738. if(order == 8) {
  97739. for(i = 0; i < (int)data_len; i++) {
  97740. sum = 0;
  97741. sum += qlp_coeff[7] * data[i-8];
  97742. sum += qlp_coeff[6] * data[i-7];
  97743. sum += qlp_coeff[5] * data[i-6];
  97744. sum += qlp_coeff[4] * data[i-5];
  97745. sum += qlp_coeff[3] * data[i-4];
  97746. sum += qlp_coeff[2] * data[i-3];
  97747. sum += qlp_coeff[1] * data[i-2];
  97748. sum += qlp_coeff[0] * data[i-1];
  97749. residual[i] = data[i] - (sum >> lp_quantization);
  97750. }
  97751. }
  97752. else { /* order == 7 */
  97753. for(i = 0; i < (int)data_len; i++) {
  97754. sum = 0;
  97755. sum += qlp_coeff[6] * data[i-7];
  97756. sum += qlp_coeff[5] * data[i-6];
  97757. sum += qlp_coeff[4] * data[i-5];
  97758. sum += qlp_coeff[3] * data[i-4];
  97759. sum += qlp_coeff[2] * data[i-3];
  97760. sum += qlp_coeff[1] * data[i-2];
  97761. sum += qlp_coeff[0] * data[i-1];
  97762. residual[i] = data[i] - (sum >> lp_quantization);
  97763. }
  97764. }
  97765. }
  97766. else {
  97767. if(order == 6) {
  97768. for(i = 0; i < (int)data_len; i++) {
  97769. sum = 0;
  97770. sum += qlp_coeff[5] * data[i-6];
  97771. sum += qlp_coeff[4] * data[i-5];
  97772. sum += qlp_coeff[3] * data[i-4];
  97773. sum += qlp_coeff[2] * data[i-3];
  97774. sum += qlp_coeff[1] * data[i-2];
  97775. sum += qlp_coeff[0] * data[i-1];
  97776. residual[i] = data[i] - (sum >> lp_quantization);
  97777. }
  97778. }
  97779. else { /* order == 5 */
  97780. for(i = 0; i < (int)data_len; i++) {
  97781. sum = 0;
  97782. sum += qlp_coeff[4] * data[i-5];
  97783. sum += qlp_coeff[3] * data[i-4];
  97784. sum += qlp_coeff[2] * data[i-3];
  97785. sum += qlp_coeff[1] * data[i-2];
  97786. sum += qlp_coeff[0] * data[i-1];
  97787. residual[i] = data[i] - (sum >> lp_quantization);
  97788. }
  97789. }
  97790. }
  97791. }
  97792. else {
  97793. if(order > 2) {
  97794. if(order == 4) {
  97795. for(i = 0; i < (int)data_len; i++) {
  97796. sum = 0;
  97797. sum += qlp_coeff[3] * data[i-4];
  97798. sum += qlp_coeff[2] * data[i-3];
  97799. sum += qlp_coeff[1] * data[i-2];
  97800. sum += qlp_coeff[0] * data[i-1];
  97801. residual[i] = data[i] - (sum >> lp_quantization);
  97802. }
  97803. }
  97804. else { /* order == 3 */
  97805. for(i = 0; i < (int)data_len; i++) {
  97806. sum = 0;
  97807. sum += qlp_coeff[2] * data[i-3];
  97808. sum += qlp_coeff[1] * data[i-2];
  97809. sum += qlp_coeff[0] * data[i-1];
  97810. residual[i] = data[i] - (sum >> lp_quantization);
  97811. }
  97812. }
  97813. }
  97814. else {
  97815. if(order == 2) {
  97816. for(i = 0; i < (int)data_len; i++) {
  97817. sum = 0;
  97818. sum += qlp_coeff[1] * data[i-2];
  97819. sum += qlp_coeff[0] * data[i-1];
  97820. residual[i] = data[i] - (sum >> lp_quantization);
  97821. }
  97822. }
  97823. else { /* order == 1 */
  97824. for(i = 0; i < (int)data_len; i++)
  97825. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97826. }
  97827. }
  97828. }
  97829. }
  97830. else { /* order > 12 */
  97831. for(i = 0; i < (int)data_len; i++) {
  97832. sum = 0;
  97833. switch(order) {
  97834. case 32: sum += qlp_coeff[31] * data[i-32];
  97835. case 31: sum += qlp_coeff[30] * data[i-31];
  97836. case 30: sum += qlp_coeff[29] * data[i-30];
  97837. case 29: sum += qlp_coeff[28] * data[i-29];
  97838. case 28: sum += qlp_coeff[27] * data[i-28];
  97839. case 27: sum += qlp_coeff[26] * data[i-27];
  97840. case 26: sum += qlp_coeff[25] * data[i-26];
  97841. case 25: sum += qlp_coeff[24] * data[i-25];
  97842. case 24: sum += qlp_coeff[23] * data[i-24];
  97843. case 23: sum += qlp_coeff[22] * data[i-23];
  97844. case 22: sum += qlp_coeff[21] * data[i-22];
  97845. case 21: sum += qlp_coeff[20] * data[i-21];
  97846. case 20: sum += qlp_coeff[19] * data[i-20];
  97847. case 19: sum += qlp_coeff[18] * data[i-19];
  97848. case 18: sum += qlp_coeff[17] * data[i-18];
  97849. case 17: sum += qlp_coeff[16] * data[i-17];
  97850. case 16: sum += qlp_coeff[15] * data[i-16];
  97851. case 15: sum += qlp_coeff[14] * data[i-15];
  97852. case 14: sum += qlp_coeff[13] * data[i-14];
  97853. case 13: sum += qlp_coeff[12] * data[i-13];
  97854. sum += qlp_coeff[11] * data[i-12];
  97855. sum += qlp_coeff[10] * data[i-11];
  97856. sum += qlp_coeff[ 9] * data[i-10];
  97857. sum += qlp_coeff[ 8] * data[i- 9];
  97858. sum += qlp_coeff[ 7] * data[i- 8];
  97859. sum += qlp_coeff[ 6] * data[i- 7];
  97860. sum += qlp_coeff[ 5] * data[i- 6];
  97861. sum += qlp_coeff[ 4] * data[i- 5];
  97862. sum += qlp_coeff[ 3] * data[i- 4];
  97863. sum += qlp_coeff[ 2] * data[i- 3];
  97864. sum += qlp_coeff[ 1] * data[i- 2];
  97865. sum += qlp_coeff[ 0] * data[i- 1];
  97866. }
  97867. residual[i] = data[i] - (sum >> lp_quantization);
  97868. }
  97869. }
  97870. }
  97871. #endif
  97872. 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[])
  97873. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97874. {
  97875. unsigned i, j;
  97876. FLAC__int64 sum;
  97877. const FLAC__int32 *history;
  97878. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97879. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97880. for(i=0;i<order;i++)
  97881. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97882. fprintf(stderr,"\n");
  97883. #endif
  97884. FLAC__ASSERT(order > 0);
  97885. for(i = 0; i < data_len; i++) {
  97886. sum = 0;
  97887. history = data;
  97888. for(j = 0; j < order; j++)
  97889. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97890. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97891. #if defined _MSC_VER
  97892. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97893. #else
  97894. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97895. #endif
  97896. break;
  97897. }
  97898. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97899. #if defined _MSC_VER
  97900. 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));
  97901. #else
  97902. 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)));
  97903. #endif
  97904. break;
  97905. }
  97906. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97907. }
  97908. }
  97909. #else /* fully unrolled version for normal use */
  97910. {
  97911. int i;
  97912. FLAC__int64 sum;
  97913. FLAC__ASSERT(order > 0);
  97914. FLAC__ASSERT(order <= 32);
  97915. /*
  97916. * We do unique versions up to 12th order since that's the subset limit.
  97917. * Also they are roughly ordered to match frequency of occurrence to
  97918. * minimize branching.
  97919. */
  97920. if(order <= 12) {
  97921. if(order > 8) {
  97922. if(order > 10) {
  97923. if(order == 12) {
  97924. for(i = 0; i < (int)data_len; i++) {
  97925. sum = 0;
  97926. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97927. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97928. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97929. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97930. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97931. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97932. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97933. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97934. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97935. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97936. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97937. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97938. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97939. }
  97940. }
  97941. else { /* order == 11 */
  97942. for(i = 0; i < (int)data_len; i++) {
  97943. sum = 0;
  97944. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97945. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97946. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97947. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97948. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97949. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97950. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97951. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97952. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97953. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97954. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97955. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97956. }
  97957. }
  97958. }
  97959. else {
  97960. if(order == 10) {
  97961. for(i = 0; i < (int)data_len; i++) {
  97962. sum = 0;
  97963. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97964. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97965. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97966. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97967. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97968. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97969. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97970. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97971. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97972. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97973. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97974. }
  97975. }
  97976. else { /* order == 9 */
  97977. for(i = 0; i < (int)data_len; i++) {
  97978. sum = 0;
  97979. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97980. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97981. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97982. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97983. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97984. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97985. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97986. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97987. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97988. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97989. }
  97990. }
  97991. }
  97992. }
  97993. else if(order > 4) {
  97994. if(order > 6) {
  97995. if(order == 8) {
  97996. for(i = 0; i < (int)data_len; i++) {
  97997. sum = 0;
  97998. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97999. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98000. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98001. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98002. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98003. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98004. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98005. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98006. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98007. }
  98008. }
  98009. else { /* order == 7 */
  98010. for(i = 0; i < (int)data_len; i++) {
  98011. sum = 0;
  98012. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98013. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98014. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98015. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98016. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98017. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98018. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98019. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98020. }
  98021. }
  98022. }
  98023. else {
  98024. if(order == 6) {
  98025. for(i = 0; i < (int)data_len; i++) {
  98026. sum = 0;
  98027. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98028. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98029. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98030. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98031. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98032. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98033. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98034. }
  98035. }
  98036. else { /* order == 5 */
  98037. for(i = 0; i < (int)data_len; i++) {
  98038. sum = 0;
  98039. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98040. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98041. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98042. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98043. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98044. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98045. }
  98046. }
  98047. }
  98048. }
  98049. else {
  98050. if(order > 2) {
  98051. if(order == 4) {
  98052. for(i = 0; i < (int)data_len; i++) {
  98053. sum = 0;
  98054. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98055. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98056. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98057. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98058. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98059. }
  98060. }
  98061. else { /* order == 3 */
  98062. for(i = 0; i < (int)data_len; i++) {
  98063. sum = 0;
  98064. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98065. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98066. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98067. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98068. }
  98069. }
  98070. }
  98071. else {
  98072. if(order == 2) {
  98073. for(i = 0; i < (int)data_len; i++) {
  98074. sum = 0;
  98075. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98076. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98077. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98078. }
  98079. }
  98080. else { /* order == 1 */
  98081. for(i = 0; i < (int)data_len; i++)
  98082. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98083. }
  98084. }
  98085. }
  98086. }
  98087. else { /* order > 12 */
  98088. for(i = 0; i < (int)data_len; i++) {
  98089. sum = 0;
  98090. switch(order) {
  98091. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98092. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98093. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98094. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98095. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98096. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98097. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98098. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98099. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98100. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98101. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98102. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98103. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98104. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98105. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98106. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98107. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98108. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98109. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98110. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98111. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98112. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98113. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98114. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98115. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98116. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98117. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98118. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98119. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98120. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98121. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98122. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98123. }
  98124. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98125. }
  98126. }
  98127. }
  98128. #endif
  98129. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98130. 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[])
  98131. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98132. {
  98133. FLAC__int64 sumo;
  98134. unsigned i, j;
  98135. FLAC__int32 sum;
  98136. const FLAC__int32 *r = residual, *history;
  98137. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98138. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98139. for(i=0;i<order;i++)
  98140. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98141. fprintf(stderr,"\n");
  98142. #endif
  98143. FLAC__ASSERT(order > 0);
  98144. for(i = 0; i < data_len; i++) {
  98145. sumo = 0;
  98146. sum = 0;
  98147. history = data;
  98148. for(j = 0; j < order; j++) {
  98149. sum += qlp_coeff[j] * (*(--history));
  98150. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  98151. #if defined _MSC_VER
  98152. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  98153. 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);
  98154. #else
  98155. if(sumo > 2147483647ll || sumo < -2147483648ll)
  98156. 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);
  98157. #endif
  98158. }
  98159. *(data++) = *(r++) + (sum >> lp_quantization);
  98160. }
  98161. /* Here's a slower but clearer version:
  98162. for(i = 0; i < data_len; i++) {
  98163. sum = 0;
  98164. for(j = 0; j < order; j++)
  98165. sum += qlp_coeff[j] * data[i-j-1];
  98166. data[i] = residual[i] + (sum >> lp_quantization);
  98167. }
  98168. */
  98169. }
  98170. #else /* fully unrolled version for normal use */
  98171. {
  98172. int i;
  98173. FLAC__int32 sum;
  98174. FLAC__ASSERT(order > 0);
  98175. FLAC__ASSERT(order <= 32);
  98176. /*
  98177. * We do unique versions up to 12th order since that's the subset limit.
  98178. * Also they are roughly ordered to match frequency of occurrence to
  98179. * minimize branching.
  98180. */
  98181. if(order <= 12) {
  98182. if(order > 8) {
  98183. if(order > 10) {
  98184. if(order == 12) {
  98185. for(i = 0; i < (int)data_len; i++) {
  98186. sum = 0;
  98187. sum += qlp_coeff[11] * data[i-12];
  98188. sum += qlp_coeff[10] * data[i-11];
  98189. sum += qlp_coeff[9] * data[i-10];
  98190. sum += qlp_coeff[8] * data[i-9];
  98191. sum += qlp_coeff[7] * data[i-8];
  98192. sum += qlp_coeff[6] * data[i-7];
  98193. sum += qlp_coeff[5] * data[i-6];
  98194. sum += qlp_coeff[4] * data[i-5];
  98195. sum += qlp_coeff[3] * data[i-4];
  98196. sum += qlp_coeff[2] * data[i-3];
  98197. sum += qlp_coeff[1] * data[i-2];
  98198. sum += qlp_coeff[0] * data[i-1];
  98199. data[i] = residual[i] + (sum >> lp_quantization);
  98200. }
  98201. }
  98202. else { /* order == 11 */
  98203. for(i = 0; i < (int)data_len; i++) {
  98204. sum = 0;
  98205. sum += qlp_coeff[10] * data[i-11];
  98206. sum += qlp_coeff[9] * data[i-10];
  98207. sum += qlp_coeff[8] * data[i-9];
  98208. sum += qlp_coeff[7] * data[i-8];
  98209. sum += qlp_coeff[6] * data[i-7];
  98210. sum += qlp_coeff[5] * data[i-6];
  98211. sum += qlp_coeff[4] * data[i-5];
  98212. sum += qlp_coeff[3] * data[i-4];
  98213. sum += qlp_coeff[2] * data[i-3];
  98214. sum += qlp_coeff[1] * data[i-2];
  98215. sum += qlp_coeff[0] * data[i-1];
  98216. data[i] = residual[i] + (sum >> lp_quantization);
  98217. }
  98218. }
  98219. }
  98220. else {
  98221. if(order == 10) {
  98222. for(i = 0; i < (int)data_len; i++) {
  98223. sum = 0;
  98224. sum += qlp_coeff[9] * data[i-10];
  98225. sum += qlp_coeff[8] * data[i-9];
  98226. sum += qlp_coeff[7] * data[i-8];
  98227. sum += qlp_coeff[6] * data[i-7];
  98228. sum += qlp_coeff[5] * data[i-6];
  98229. sum += qlp_coeff[4] * data[i-5];
  98230. sum += qlp_coeff[3] * data[i-4];
  98231. sum += qlp_coeff[2] * data[i-3];
  98232. sum += qlp_coeff[1] * data[i-2];
  98233. sum += qlp_coeff[0] * data[i-1];
  98234. data[i] = residual[i] + (sum >> lp_quantization);
  98235. }
  98236. }
  98237. else { /* order == 9 */
  98238. for(i = 0; i < (int)data_len; i++) {
  98239. sum = 0;
  98240. sum += qlp_coeff[8] * data[i-9];
  98241. sum += qlp_coeff[7] * data[i-8];
  98242. sum += qlp_coeff[6] * data[i-7];
  98243. sum += qlp_coeff[5] * data[i-6];
  98244. sum += qlp_coeff[4] * data[i-5];
  98245. sum += qlp_coeff[3] * data[i-4];
  98246. sum += qlp_coeff[2] * data[i-3];
  98247. sum += qlp_coeff[1] * data[i-2];
  98248. sum += qlp_coeff[0] * data[i-1];
  98249. data[i] = residual[i] + (sum >> lp_quantization);
  98250. }
  98251. }
  98252. }
  98253. }
  98254. else if(order > 4) {
  98255. if(order > 6) {
  98256. if(order == 8) {
  98257. for(i = 0; i < (int)data_len; i++) {
  98258. sum = 0;
  98259. sum += qlp_coeff[7] * data[i-8];
  98260. sum += qlp_coeff[6] * data[i-7];
  98261. sum += qlp_coeff[5] * data[i-6];
  98262. sum += qlp_coeff[4] * data[i-5];
  98263. sum += qlp_coeff[3] * data[i-4];
  98264. sum += qlp_coeff[2] * data[i-3];
  98265. sum += qlp_coeff[1] * data[i-2];
  98266. sum += qlp_coeff[0] * data[i-1];
  98267. data[i] = residual[i] + (sum >> lp_quantization);
  98268. }
  98269. }
  98270. else { /* order == 7 */
  98271. for(i = 0; i < (int)data_len; i++) {
  98272. sum = 0;
  98273. sum += qlp_coeff[6] * data[i-7];
  98274. sum += qlp_coeff[5] * data[i-6];
  98275. sum += qlp_coeff[4] * data[i-5];
  98276. sum += qlp_coeff[3] * data[i-4];
  98277. sum += qlp_coeff[2] * data[i-3];
  98278. sum += qlp_coeff[1] * data[i-2];
  98279. sum += qlp_coeff[0] * data[i-1];
  98280. data[i] = residual[i] + (sum >> lp_quantization);
  98281. }
  98282. }
  98283. }
  98284. else {
  98285. if(order == 6) {
  98286. for(i = 0; i < (int)data_len; i++) {
  98287. sum = 0;
  98288. sum += qlp_coeff[5] * data[i-6];
  98289. sum += qlp_coeff[4] * data[i-5];
  98290. sum += qlp_coeff[3] * data[i-4];
  98291. sum += qlp_coeff[2] * data[i-3];
  98292. sum += qlp_coeff[1] * data[i-2];
  98293. sum += qlp_coeff[0] * data[i-1];
  98294. data[i] = residual[i] + (sum >> lp_quantization);
  98295. }
  98296. }
  98297. else { /* order == 5 */
  98298. for(i = 0; i < (int)data_len; i++) {
  98299. sum = 0;
  98300. sum += qlp_coeff[4] * data[i-5];
  98301. sum += qlp_coeff[3] * data[i-4];
  98302. sum += qlp_coeff[2] * data[i-3];
  98303. sum += qlp_coeff[1] * data[i-2];
  98304. sum += qlp_coeff[0] * data[i-1];
  98305. data[i] = residual[i] + (sum >> lp_quantization);
  98306. }
  98307. }
  98308. }
  98309. }
  98310. else {
  98311. if(order > 2) {
  98312. if(order == 4) {
  98313. for(i = 0; i < (int)data_len; i++) {
  98314. sum = 0;
  98315. sum += qlp_coeff[3] * data[i-4];
  98316. sum += qlp_coeff[2] * data[i-3];
  98317. sum += qlp_coeff[1] * data[i-2];
  98318. sum += qlp_coeff[0] * data[i-1];
  98319. data[i] = residual[i] + (sum >> lp_quantization);
  98320. }
  98321. }
  98322. else { /* order == 3 */
  98323. for(i = 0; i < (int)data_len; i++) {
  98324. sum = 0;
  98325. sum += qlp_coeff[2] * data[i-3];
  98326. sum += qlp_coeff[1] * data[i-2];
  98327. sum += qlp_coeff[0] * data[i-1];
  98328. data[i] = residual[i] + (sum >> lp_quantization);
  98329. }
  98330. }
  98331. }
  98332. else {
  98333. if(order == 2) {
  98334. for(i = 0; i < (int)data_len; i++) {
  98335. sum = 0;
  98336. sum += qlp_coeff[1] * data[i-2];
  98337. sum += qlp_coeff[0] * data[i-1];
  98338. data[i] = residual[i] + (sum >> lp_quantization);
  98339. }
  98340. }
  98341. else { /* order == 1 */
  98342. for(i = 0; i < (int)data_len; i++)
  98343. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98344. }
  98345. }
  98346. }
  98347. }
  98348. else { /* order > 12 */
  98349. for(i = 0; i < (int)data_len; i++) {
  98350. sum = 0;
  98351. switch(order) {
  98352. case 32: sum += qlp_coeff[31] * data[i-32];
  98353. case 31: sum += qlp_coeff[30] * data[i-31];
  98354. case 30: sum += qlp_coeff[29] * data[i-30];
  98355. case 29: sum += qlp_coeff[28] * data[i-29];
  98356. case 28: sum += qlp_coeff[27] * data[i-28];
  98357. case 27: sum += qlp_coeff[26] * data[i-27];
  98358. case 26: sum += qlp_coeff[25] * data[i-26];
  98359. case 25: sum += qlp_coeff[24] * data[i-25];
  98360. case 24: sum += qlp_coeff[23] * data[i-24];
  98361. case 23: sum += qlp_coeff[22] * data[i-23];
  98362. case 22: sum += qlp_coeff[21] * data[i-22];
  98363. case 21: sum += qlp_coeff[20] * data[i-21];
  98364. case 20: sum += qlp_coeff[19] * data[i-20];
  98365. case 19: sum += qlp_coeff[18] * data[i-19];
  98366. case 18: sum += qlp_coeff[17] * data[i-18];
  98367. case 17: sum += qlp_coeff[16] * data[i-17];
  98368. case 16: sum += qlp_coeff[15] * data[i-16];
  98369. case 15: sum += qlp_coeff[14] * data[i-15];
  98370. case 14: sum += qlp_coeff[13] * data[i-14];
  98371. case 13: sum += qlp_coeff[12] * data[i-13];
  98372. sum += qlp_coeff[11] * data[i-12];
  98373. sum += qlp_coeff[10] * data[i-11];
  98374. sum += qlp_coeff[ 9] * data[i-10];
  98375. sum += qlp_coeff[ 8] * data[i- 9];
  98376. sum += qlp_coeff[ 7] * data[i- 8];
  98377. sum += qlp_coeff[ 6] * data[i- 7];
  98378. sum += qlp_coeff[ 5] * data[i- 6];
  98379. sum += qlp_coeff[ 4] * data[i- 5];
  98380. sum += qlp_coeff[ 3] * data[i- 4];
  98381. sum += qlp_coeff[ 2] * data[i- 3];
  98382. sum += qlp_coeff[ 1] * data[i- 2];
  98383. sum += qlp_coeff[ 0] * data[i- 1];
  98384. }
  98385. data[i] = residual[i] + (sum >> lp_quantization);
  98386. }
  98387. }
  98388. }
  98389. #endif
  98390. 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[])
  98391. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98392. {
  98393. unsigned i, j;
  98394. FLAC__int64 sum;
  98395. const FLAC__int32 *r = residual, *history;
  98396. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98397. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98398. for(i=0;i<order;i++)
  98399. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98400. fprintf(stderr,"\n");
  98401. #endif
  98402. FLAC__ASSERT(order > 0);
  98403. for(i = 0; i < data_len; i++) {
  98404. sum = 0;
  98405. history = data;
  98406. for(j = 0; j < order; j++)
  98407. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98408. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98409. #ifdef _MSC_VER
  98410. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98411. #else
  98412. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98413. #endif
  98414. break;
  98415. }
  98416. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98417. #ifdef _MSC_VER
  98418. 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));
  98419. #else
  98420. 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)));
  98421. #endif
  98422. break;
  98423. }
  98424. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98425. }
  98426. }
  98427. #else /* fully unrolled version for normal use */
  98428. {
  98429. int i;
  98430. FLAC__int64 sum;
  98431. FLAC__ASSERT(order > 0);
  98432. FLAC__ASSERT(order <= 32);
  98433. /*
  98434. * We do unique versions up to 12th order since that's the subset limit.
  98435. * Also they are roughly ordered to match frequency of occurrence to
  98436. * minimize branching.
  98437. */
  98438. if(order <= 12) {
  98439. if(order > 8) {
  98440. if(order > 10) {
  98441. if(order == 12) {
  98442. for(i = 0; i < (int)data_len; i++) {
  98443. sum = 0;
  98444. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98445. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98446. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98447. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98448. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98449. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98450. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98451. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98452. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98453. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98454. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98455. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98456. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98457. }
  98458. }
  98459. else { /* order == 11 */
  98460. for(i = 0; i < (int)data_len; i++) {
  98461. sum = 0;
  98462. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98463. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98464. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98465. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98466. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98467. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98468. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98469. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98470. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98471. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98472. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98473. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98474. }
  98475. }
  98476. }
  98477. else {
  98478. if(order == 10) {
  98479. for(i = 0; i < (int)data_len; i++) {
  98480. sum = 0;
  98481. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98482. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98483. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98484. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98485. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98486. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98487. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98488. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98489. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98490. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98491. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98492. }
  98493. }
  98494. else { /* order == 9 */
  98495. for(i = 0; i < (int)data_len; i++) {
  98496. sum = 0;
  98497. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98498. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98499. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98500. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98501. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98502. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98503. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98504. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98505. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98506. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98507. }
  98508. }
  98509. }
  98510. }
  98511. else if(order > 4) {
  98512. if(order > 6) {
  98513. if(order == 8) {
  98514. for(i = 0; i < (int)data_len; i++) {
  98515. sum = 0;
  98516. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98517. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98518. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98519. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98520. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98521. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98522. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98523. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98524. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98525. }
  98526. }
  98527. else { /* order == 7 */
  98528. for(i = 0; i < (int)data_len; i++) {
  98529. sum = 0;
  98530. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98531. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98532. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98533. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98534. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98535. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98536. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98537. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98538. }
  98539. }
  98540. }
  98541. else {
  98542. if(order == 6) {
  98543. for(i = 0; i < (int)data_len; i++) {
  98544. sum = 0;
  98545. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98546. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98547. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98548. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98549. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98550. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98551. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98552. }
  98553. }
  98554. else { /* order == 5 */
  98555. for(i = 0; i < (int)data_len; i++) {
  98556. sum = 0;
  98557. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98558. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98559. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98560. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98561. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98562. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98563. }
  98564. }
  98565. }
  98566. }
  98567. else {
  98568. if(order > 2) {
  98569. if(order == 4) {
  98570. for(i = 0; i < (int)data_len; i++) {
  98571. sum = 0;
  98572. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98573. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98574. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98575. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98576. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98577. }
  98578. }
  98579. else { /* order == 3 */
  98580. for(i = 0; i < (int)data_len; i++) {
  98581. sum = 0;
  98582. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98583. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98584. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98585. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98586. }
  98587. }
  98588. }
  98589. else {
  98590. if(order == 2) {
  98591. for(i = 0; i < (int)data_len; i++) {
  98592. sum = 0;
  98593. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98594. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98595. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98596. }
  98597. }
  98598. else { /* order == 1 */
  98599. for(i = 0; i < (int)data_len; i++)
  98600. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98601. }
  98602. }
  98603. }
  98604. }
  98605. else { /* order > 12 */
  98606. for(i = 0; i < (int)data_len; i++) {
  98607. sum = 0;
  98608. switch(order) {
  98609. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98610. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98611. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98612. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98613. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98614. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98615. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98616. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98617. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98618. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98619. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98620. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98621. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98622. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98623. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98624. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98625. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98626. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98627. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98628. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98629. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98630. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98631. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98632. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98633. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98634. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98635. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98636. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98637. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98638. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98639. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98640. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98641. }
  98642. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98643. }
  98644. }
  98645. }
  98646. #endif
  98647. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98648. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98649. {
  98650. FLAC__double error_scale;
  98651. FLAC__ASSERT(total_samples > 0);
  98652. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98653. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98654. }
  98655. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98656. {
  98657. if(lpc_error > 0.0) {
  98658. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98659. if(bps >= 0.0)
  98660. return bps;
  98661. else
  98662. return 0.0;
  98663. }
  98664. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98665. return 1e32;
  98666. }
  98667. else {
  98668. return 0.0;
  98669. }
  98670. }
  98671. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98672. {
  98673. 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 */
  98674. FLAC__double bits, best_bits, error_scale;
  98675. FLAC__ASSERT(max_order > 0);
  98676. FLAC__ASSERT(total_samples > 0);
  98677. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98678. best_index = 0;
  98679. best_bits = (unsigned)(-1);
  98680. for(index = 0, order = 1; index < max_order; index++, order++) {
  98681. 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);
  98682. if(bits < best_bits) {
  98683. best_index = index;
  98684. best_bits = bits;
  98685. }
  98686. }
  98687. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98688. }
  98689. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98690. #endif
  98691. /*** End of inlined file: lpc_flac.c ***/
  98692. /*** Start of inlined file: md5.c ***/
  98693. /*** Start of inlined file: juce_FlacHeader.h ***/
  98694. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98695. // tasks..
  98696. #define VERSION "1.2.1"
  98697. #define FLAC__NO_DLL 1
  98698. #if JUCE_MSVC
  98699. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98700. #endif
  98701. #if JUCE_MAC
  98702. #define FLAC__SYS_DARWIN 1
  98703. #endif
  98704. /*** End of inlined file: juce_FlacHeader.h ***/
  98705. #if JUCE_USE_FLAC
  98706. #if HAVE_CONFIG_H
  98707. # include <config.h>
  98708. #endif
  98709. #include <stdlib.h> /* for malloc() */
  98710. #include <string.h> /* for memcpy() */
  98711. /*** Start of inlined file: md5.h ***/
  98712. #ifndef FLAC__PRIVATE__MD5_H
  98713. #define FLAC__PRIVATE__MD5_H
  98714. /*
  98715. * This is the header file for the MD5 message-digest algorithm.
  98716. * The algorithm is due to Ron Rivest. This code was
  98717. * written by Colin Plumb in 1993, no copyright is claimed.
  98718. * This code is in the public domain; do with it what you wish.
  98719. *
  98720. * Equivalent code is available from RSA Data Security, Inc.
  98721. * This code has been tested against that, and is equivalent,
  98722. * except that you don't need to include two pages of legalese
  98723. * with every copy.
  98724. *
  98725. * To compute the message digest of a chunk of bytes, declare an
  98726. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98727. * needed on buffers full of bytes, and then call MD5Final, which
  98728. * will fill a supplied 16-byte array with the digest.
  98729. *
  98730. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98731. * header definitions; now uses stuff from dpkg's config.h
  98732. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98733. * Still in the public domain.
  98734. *
  98735. * Josh Coalson: made some changes to integrate with libFLAC.
  98736. * Still in the public domain, with no warranty.
  98737. */
  98738. typedef struct {
  98739. FLAC__uint32 in[16];
  98740. FLAC__uint32 buf[4];
  98741. FLAC__uint32 bytes[2];
  98742. FLAC__byte *internal_buf;
  98743. size_t capacity;
  98744. } FLAC__MD5Context;
  98745. void FLAC__MD5Init(FLAC__MD5Context *context);
  98746. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98747. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98748. #endif
  98749. /*** End of inlined file: md5.h ***/
  98750. #ifndef FLaC__INLINE
  98751. #define FLaC__INLINE
  98752. #endif
  98753. /*
  98754. * This code implements the MD5 message-digest algorithm.
  98755. * The algorithm is due to Ron Rivest. This code was
  98756. * written by Colin Plumb in 1993, no copyright is claimed.
  98757. * This code is in the public domain; do with it what you wish.
  98758. *
  98759. * Equivalent code is available from RSA Data Security, Inc.
  98760. * This code has been tested against that, and is equivalent,
  98761. * except that you don't need to include two pages of legalese
  98762. * with every copy.
  98763. *
  98764. * To compute the message digest of a chunk of bytes, declare an
  98765. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98766. * needed on buffers full of bytes, and then call MD5Final, which
  98767. * will fill a supplied 16-byte array with the digest.
  98768. *
  98769. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98770. * definitions; now uses stuff from dpkg's config.h.
  98771. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98772. * Still in the public domain.
  98773. *
  98774. * Josh Coalson: made some changes to integrate with libFLAC.
  98775. * Still in the public domain.
  98776. */
  98777. /* The four core functions - F1 is optimized somewhat */
  98778. /* #define F1(x, y, z) (x & y | ~x & z) */
  98779. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98780. #define F2(x, y, z) F1(z, x, y)
  98781. #define F3(x, y, z) (x ^ y ^ z)
  98782. #define F4(x, y, z) (y ^ (x | ~z))
  98783. /* This is the central step in the MD5 algorithm. */
  98784. #define MD5STEP(f,w,x,y,z,in,s) \
  98785. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98786. /*
  98787. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98788. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98789. * the data and converts bytes into longwords for this routine.
  98790. */
  98791. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98792. {
  98793. register FLAC__uint32 a, b, c, d;
  98794. a = buf[0];
  98795. b = buf[1];
  98796. c = buf[2];
  98797. d = buf[3];
  98798. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98799. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98800. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98801. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98802. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98803. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98804. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98805. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98806. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98807. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98808. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98809. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98810. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98811. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98812. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98813. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98814. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98815. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98816. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98817. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98818. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98819. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98820. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98821. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98822. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98823. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98824. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98825. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98826. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98827. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98828. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98829. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98830. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98831. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98832. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98833. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98834. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98835. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98836. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98837. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98838. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98839. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98840. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98841. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98842. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98843. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98844. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98845. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98846. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98847. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98848. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98849. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98850. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98851. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98852. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98853. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98854. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98855. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98856. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98857. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98858. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98859. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98860. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98861. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98862. buf[0] += a;
  98863. buf[1] += b;
  98864. buf[2] += c;
  98865. buf[3] += d;
  98866. }
  98867. #if WORDS_BIGENDIAN
  98868. //@@@@@@ OPT: use bswap/intrinsics
  98869. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98870. {
  98871. register FLAC__uint32 x;
  98872. do {
  98873. x = *buf;
  98874. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98875. *buf++ = (x >> 16) | (x << 16);
  98876. } while (--words);
  98877. }
  98878. static void byteSwapX16(FLAC__uint32 *buf)
  98879. {
  98880. register FLAC__uint32 x;
  98881. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98882. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98883. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98884. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98885. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98886. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98887. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98888. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98889. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98890. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98891. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98892. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98893. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98894. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98895. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98896. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98897. }
  98898. #else
  98899. #define byteSwap(buf, words)
  98900. #define byteSwapX16(buf)
  98901. #endif
  98902. /*
  98903. * Update context to reflect the concatenation of another buffer full
  98904. * of bytes.
  98905. */
  98906. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98907. {
  98908. FLAC__uint32 t;
  98909. /* Update byte count */
  98910. t = ctx->bytes[0];
  98911. if ((ctx->bytes[0] = t + len) < t)
  98912. ctx->bytes[1]++; /* Carry from low to high */
  98913. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98914. if (t > len) {
  98915. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98916. return;
  98917. }
  98918. /* First chunk is an odd size */
  98919. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98920. byteSwapX16(ctx->in);
  98921. FLAC__MD5Transform(ctx->buf, ctx->in);
  98922. buf += t;
  98923. len -= t;
  98924. /* Process data in 64-byte chunks */
  98925. while (len >= 64) {
  98926. memcpy(ctx->in, buf, 64);
  98927. byteSwapX16(ctx->in);
  98928. FLAC__MD5Transform(ctx->buf, ctx->in);
  98929. buf += 64;
  98930. len -= 64;
  98931. }
  98932. /* Handle any remaining bytes of data. */
  98933. memcpy(ctx->in, buf, len);
  98934. }
  98935. /*
  98936. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98937. * initialization constants.
  98938. */
  98939. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98940. {
  98941. ctx->buf[0] = 0x67452301;
  98942. ctx->buf[1] = 0xefcdab89;
  98943. ctx->buf[2] = 0x98badcfe;
  98944. ctx->buf[3] = 0x10325476;
  98945. ctx->bytes[0] = 0;
  98946. ctx->bytes[1] = 0;
  98947. ctx->internal_buf = 0;
  98948. ctx->capacity = 0;
  98949. }
  98950. /*
  98951. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98952. * 1 0* (64-bit count of bits processed, MSB-first)
  98953. */
  98954. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98955. {
  98956. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98957. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98958. /* Set the first char of padding to 0x80. There is always room. */
  98959. *p++ = 0x80;
  98960. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98961. count = 56 - 1 - count;
  98962. if (count < 0) { /* Padding forces an extra block */
  98963. memset(p, 0, count + 8);
  98964. byteSwapX16(ctx->in);
  98965. FLAC__MD5Transform(ctx->buf, ctx->in);
  98966. p = (FLAC__byte *)ctx->in;
  98967. count = 56;
  98968. }
  98969. memset(p, 0, count);
  98970. byteSwap(ctx->in, 14);
  98971. /* Append length in bits and transform */
  98972. ctx->in[14] = ctx->bytes[0] << 3;
  98973. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98974. FLAC__MD5Transform(ctx->buf, ctx->in);
  98975. byteSwap(ctx->buf, 4);
  98976. memcpy(digest, ctx->buf, 16);
  98977. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98978. if(0 != ctx->internal_buf) {
  98979. free(ctx->internal_buf);
  98980. ctx->internal_buf = 0;
  98981. ctx->capacity = 0;
  98982. }
  98983. }
  98984. /*
  98985. * Convert the incoming audio signal to a byte stream
  98986. */
  98987. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98988. {
  98989. unsigned channel, sample;
  98990. register FLAC__int32 a_word;
  98991. register FLAC__byte *buf_ = buf;
  98992. #if WORDS_BIGENDIAN
  98993. #else
  98994. if(channels == 2 && bytes_per_sample == 2) {
  98995. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98996. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98997. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98998. *buf1_ = (FLAC__int16)signal[1][sample];
  98999. }
  99000. else if(channels == 1 && bytes_per_sample == 2) {
  99001. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  99002. for(sample = 0; sample < samples; sample++)
  99003. *buf1_++ = (FLAC__int16)signal[0][sample];
  99004. }
  99005. else
  99006. #endif
  99007. if(bytes_per_sample == 2) {
  99008. if(channels == 2) {
  99009. for(sample = 0; sample < samples; sample++) {
  99010. a_word = signal[0][sample];
  99011. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99012. *buf_++ = (FLAC__byte)a_word;
  99013. a_word = signal[1][sample];
  99014. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99015. *buf_++ = (FLAC__byte)a_word;
  99016. }
  99017. }
  99018. else if(channels == 1) {
  99019. for(sample = 0; sample < samples; sample++) {
  99020. a_word = signal[0][sample];
  99021. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99022. *buf_++ = (FLAC__byte)a_word;
  99023. }
  99024. }
  99025. else {
  99026. for(sample = 0; sample < samples; sample++) {
  99027. for(channel = 0; channel < channels; channel++) {
  99028. a_word = signal[channel][sample];
  99029. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99030. *buf_++ = (FLAC__byte)a_word;
  99031. }
  99032. }
  99033. }
  99034. }
  99035. else if(bytes_per_sample == 3) {
  99036. if(channels == 2) {
  99037. for(sample = 0; sample < samples; sample++) {
  99038. a_word = signal[0][sample];
  99039. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99040. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99041. *buf_++ = (FLAC__byte)a_word;
  99042. a_word = signal[1][sample];
  99043. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99044. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99045. *buf_++ = (FLAC__byte)a_word;
  99046. }
  99047. }
  99048. else if(channels == 1) {
  99049. for(sample = 0; sample < samples; sample++) {
  99050. a_word = signal[0][sample];
  99051. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99052. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99053. *buf_++ = (FLAC__byte)a_word;
  99054. }
  99055. }
  99056. else {
  99057. for(sample = 0; sample < samples; sample++) {
  99058. for(channel = 0; channel < channels; channel++) {
  99059. a_word = signal[channel][sample];
  99060. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99061. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99062. *buf_++ = (FLAC__byte)a_word;
  99063. }
  99064. }
  99065. }
  99066. }
  99067. else if(bytes_per_sample == 1) {
  99068. if(channels == 2) {
  99069. for(sample = 0; sample < samples; sample++) {
  99070. a_word = signal[0][sample];
  99071. *buf_++ = (FLAC__byte)a_word;
  99072. a_word = signal[1][sample];
  99073. *buf_++ = (FLAC__byte)a_word;
  99074. }
  99075. }
  99076. else if(channels == 1) {
  99077. for(sample = 0; sample < samples; sample++) {
  99078. a_word = signal[0][sample];
  99079. *buf_++ = (FLAC__byte)a_word;
  99080. }
  99081. }
  99082. else {
  99083. for(sample = 0; sample < samples; sample++) {
  99084. for(channel = 0; channel < channels; channel++) {
  99085. a_word = signal[channel][sample];
  99086. *buf_++ = (FLAC__byte)a_word;
  99087. }
  99088. }
  99089. }
  99090. }
  99091. else { /* bytes_per_sample == 4, maybe optimize more later */
  99092. for(sample = 0; sample < samples; sample++) {
  99093. for(channel = 0; channel < channels; channel++) {
  99094. a_word = signal[channel][sample];
  99095. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99096. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99097. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99098. *buf_++ = (FLAC__byte)a_word;
  99099. }
  99100. }
  99101. }
  99102. }
  99103. /*
  99104. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  99105. */
  99106. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  99107. {
  99108. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  99109. /* overflow check */
  99110. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  99111. return false;
  99112. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  99113. return false;
  99114. if(ctx->capacity < bytes_needed) {
  99115. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  99116. if(0 == tmp) {
  99117. free(ctx->internal_buf);
  99118. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  99119. return false;
  99120. }
  99121. ctx->internal_buf = tmp;
  99122. ctx->capacity = bytes_needed;
  99123. }
  99124. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  99125. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  99126. return true;
  99127. }
  99128. #endif
  99129. /*** End of inlined file: md5.c ***/
  99130. /*** Start of inlined file: memory.c ***/
  99131. /*** Start of inlined file: juce_FlacHeader.h ***/
  99132. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99133. // tasks..
  99134. #define VERSION "1.2.1"
  99135. #define FLAC__NO_DLL 1
  99136. #if JUCE_MSVC
  99137. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99138. #endif
  99139. #if JUCE_MAC
  99140. #define FLAC__SYS_DARWIN 1
  99141. #endif
  99142. /*** End of inlined file: juce_FlacHeader.h ***/
  99143. #if JUCE_USE_FLAC
  99144. #if HAVE_CONFIG_H
  99145. # include <config.h>
  99146. #endif
  99147. /*** Start of inlined file: memory.h ***/
  99148. #ifndef FLAC__PRIVATE__MEMORY_H
  99149. #define FLAC__PRIVATE__MEMORY_H
  99150. #ifdef HAVE_CONFIG_H
  99151. #include <config.h>
  99152. #endif
  99153. #include <stdlib.h> /* for size_t */
  99154. /* Returns the unaligned address returned by malloc.
  99155. * Use free() on this address to deallocate.
  99156. */
  99157. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  99158. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  99159. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  99160. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  99161. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  99162. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99163. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  99164. #endif
  99165. #endif
  99166. /*** End of inlined file: memory.h ***/
  99167. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  99168. {
  99169. void *x;
  99170. FLAC__ASSERT(0 != aligned_address);
  99171. #ifdef FLAC__ALIGN_MALLOC_DATA
  99172. /* align on 32-byte (256-bit) boundary */
  99173. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99174. #ifdef SIZEOF_VOIDP
  99175. #if SIZEOF_VOIDP == 4
  99176. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99177. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99178. #elif SIZEOF_VOIDP == 8
  99179. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99180. #else
  99181. # error Unsupported sizeof(void*)
  99182. #endif
  99183. #else
  99184. /* there's got to be a better way to do this right for all archs */
  99185. if(sizeof(void*) == sizeof(unsigned))
  99186. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99187. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99188. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99189. else
  99190. return 0;
  99191. #endif
  99192. #else
  99193. x = safe_malloc_(bytes);
  99194. *aligned_address = x;
  99195. #endif
  99196. return x;
  99197. }
  99198. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99199. {
  99200. FLAC__int32 *pu; /* unaligned pointer */
  99201. union { /* union needed to comply with C99 pointer aliasing rules */
  99202. FLAC__int32 *pa; /* aligned pointer */
  99203. void *pv; /* aligned pointer alias */
  99204. } u;
  99205. FLAC__ASSERT(elements > 0);
  99206. FLAC__ASSERT(0 != unaligned_pointer);
  99207. FLAC__ASSERT(0 != aligned_pointer);
  99208. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99209. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99210. if(0 == pu) {
  99211. return false;
  99212. }
  99213. else {
  99214. if(*unaligned_pointer != 0)
  99215. free(*unaligned_pointer);
  99216. *unaligned_pointer = pu;
  99217. *aligned_pointer = u.pa;
  99218. return true;
  99219. }
  99220. }
  99221. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99222. {
  99223. FLAC__uint32 *pu; /* unaligned pointer */
  99224. union { /* union needed to comply with C99 pointer aliasing rules */
  99225. FLAC__uint32 *pa; /* aligned pointer */
  99226. void *pv; /* aligned pointer alias */
  99227. } u;
  99228. FLAC__ASSERT(elements > 0);
  99229. FLAC__ASSERT(0 != unaligned_pointer);
  99230. FLAC__ASSERT(0 != aligned_pointer);
  99231. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99232. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99233. if(0 == pu) {
  99234. return false;
  99235. }
  99236. else {
  99237. if(*unaligned_pointer != 0)
  99238. free(*unaligned_pointer);
  99239. *unaligned_pointer = pu;
  99240. *aligned_pointer = u.pa;
  99241. return true;
  99242. }
  99243. }
  99244. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99245. {
  99246. FLAC__uint64 *pu; /* unaligned pointer */
  99247. union { /* union needed to comply with C99 pointer aliasing rules */
  99248. FLAC__uint64 *pa; /* aligned pointer */
  99249. void *pv; /* aligned pointer alias */
  99250. } u;
  99251. FLAC__ASSERT(elements > 0);
  99252. FLAC__ASSERT(0 != unaligned_pointer);
  99253. FLAC__ASSERT(0 != aligned_pointer);
  99254. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99255. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99256. if(0 == pu) {
  99257. return false;
  99258. }
  99259. else {
  99260. if(*unaligned_pointer != 0)
  99261. free(*unaligned_pointer);
  99262. *unaligned_pointer = pu;
  99263. *aligned_pointer = u.pa;
  99264. return true;
  99265. }
  99266. }
  99267. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99268. {
  99269. unsigned *pu; /* unaligned pointer */
  99270. union { /* union needed to comply with C99 pointer aliasing rules */
  99271. unsigned *pa; /* aligned pointer */
  99272. void *pv; /* aligned pointer alias */
  99273. } u;
  99274. FLAC__ASSERT(elements > 0);
  99275. FLAC__ASSERT(0 != unaligned_pointer);
  99276. FLAC__ASSERT(0 != aligned_pointer);
  99277. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99278. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99279. if(0 == pu) {
  99280. return false;
  99281. }
  99282. else {
  99283. if(*unaligned_pointer != 0)
  99284. free(*unaligned_pointer);
  99285. *unaligned_pointer = pu;
  99286. *aligned_pointer = u.pa;
  99287. return true;
  99288. }
  99289. }
  99290. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99291. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99292. {
  99293. FLAC__real *pu; /* unaligned pointer */
  99294. union { /* union needed to comply with C99 pointer aliasing rules */
  99295. FLAC__real *pa; /* aligned pointer */
  99296. void *pv; /* aligned pointer alias */
  99297. } u;
  99298. FLAC__ASSERT(elements > 0);
  99299. FLAC__ASSERT(0 != unaligned_pointer);
  99300. FLAC__ASSERT(0 != aligned_pointer);
  99301. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99302. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99303. if(0 == pu) {
  99304. return false;
  99305. }
  99306. else {
  99307. if(*unaligned_pointer != 0)
  99308. free(*unaligned_pointer);
  99309. *unaligned_pointer = pu;
  99310. *aligned_pointer = u.pa;
  99311. return true;
  99312. }
  99313. }
  99314. #endif
  99315. #endif
  99316. /*** End of inlined file: memory.c ***/
  99317. /*** Start of inlined file: stream_decoder.c ***/
  99318. /*** Start of inlined file: juce_FlacHeader.h ***/
  99319. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99320. // tasks..
  99321. #define VERSION "1.2.1"
  99322. #define FLAC__NO_DLL 1
  99323. #if JUCE_MSVC
  99324. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99325. #endif
  99326. #if JUCE_MAC
  99327. #define FLAC__SYS_DARWIN 1
  99328. #endif
  99329. /*** End of inlined file: juce_FlacHeader.h ***/
  99330. #if JUCE_USE_FLAC
  99331. #if HAVE_CONFIG_H
  99332. # include <config.h>
  99333. #endif
  99334. #if defined _MSC_VER || defined __MINGW32__
  99335. #include <io.h> /* for _setmode() */
  99336. #include <fcntl.h> /* for _O_BINARY */
  99337. #endif
  99338. #if defined __CYGWIN__ || defined __EMX__
  99339. #include <io.h> /* for setmode(), O_BINARY */
  99340. #include <fcntl.h> /* for _O_BINARY */
  99341. #endif
  99342. #include <stdio.h>
  99343. #include <stdlib.h> /* for malloc() */
  99344. #include <string.h> /* for memset/memcpy() */
  99345. #include <sys/stat.h> /* for stat() */
  99346. #include <sys/types.h> /* for off_t */
  99347. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99348. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99349. #define fseeko fseek
  99350. #define ftello ftell
  99351. #endif
  99352. #endif
  99353. /*** Start of inlined file: stream_decoder.h ***/
  99354. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99355. #define FLAC__PROTECTED__STREAM_DECODER_H
  99356. #if FLAC__HAS_OGG
  99357. #include "include/private/ogg_decoder_aspect.h"
  99358. #endif
  99359. typedef struct FLAC__StreamDecoderProtected {
  99360. FLAC__StreamDecoderState state;
  99361. unsigned channels;
  99362. FLAC__ChannelAssignment channel_assignment;
  99363. unsigned bits_per_sample;
  99364. unsigned sample_rate; /* in Hz */
  99365. unsigned blocksize; /* in samples (per channel) */
  99366. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99367. #if FLAC__HAS_OGG
  99368. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99369. #endif
  99370. } FLAC__StreamDecoderProtected;
  99371. /*
  99372. * return the number of input bytes consumed
  99373. */
  99374. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99375. #endif
  99376. /*** End of inlined file: stream_decoder.h ***/
  99377. #ifdef max
  99378. #undef max
  99379. #endif
  99380. #define max(a,b) ((a)>(b)?(a):(b))
  99381. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99382. #ifdef _MSC_VER
  99383. #define FLAC__U64L(x) x
  99384. #else
  99385. #define FLAC__U64L(x) x##LLU
  99386. #endif
  99387. /* technically this should be in an "export.c" but this is convenient enough */
  99388. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99389. #if FLAC__HAS_OGG
  99390. 1
  99391. #else
  99392. 0
  99393. #endif
  99394. ;
  99395. /***********************************************************************
  99396. *
  99397. * Private static data
  99398. *
  99399. ***********************************************************************/
  99400. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99401. /***********************************************************************
  99402. *
  99403. * Private class method prototypes
  99404. *
  99405. ***********************************************************************/
  99406. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99407. static FILE *get_binary_stdin_(void);
  99408. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99409. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99410. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99411. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99412. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99413. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99414. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99415. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99416. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99417. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99418. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99419. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99420. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99421. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99422. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99423. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99424. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99425. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99426. 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);
  99427. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99428. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99429. #if FLAC__HAS_OGG
  99430. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99431. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99432. #endif
  99433. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99434. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99435. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99436. #if FLAC__HAS_OGG
  99437. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99438. #endif
  99439. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99440. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99441. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99442. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99443. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99444. /***********************************************************************
  99445. *
  99446. * Private class data
  99447. *
  99448. ***********************************************************************/
  99449. typedef struct FLAC__StreamDecoderPrivate {
  99450. #if FLAC__HAS_OGG
  99451. FLAC__bool is_ogg;
  99452. #endif
  99453. FLAC__StreamDecoderReadCallback read_callback;
  99454. FLAC__StreamDecoderSeekCallback seek_callback;
  99455. FLAC__StreamDecoderTellCallback tell_callback;
  99456. FLAC__StreamDecoderLengthCallback length_callback;
  99457. FLAC__StreamDecoderEofCallback eof_callback;
  99458. FLAC__StreamDecoderWriteCallback write_callback;
  99459. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99460. FLAC__StreamDecoderErrorCallback error_callback;
  99461. /* generic 32-bit datapath: */
  99462. 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[]);
  99463. /* generic 64-bit datapath: */
  99464. 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[]);
  99465. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99466. 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[]);
  99467. /* 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: */
  99468. 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[]);
  99469. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99470. void *client_data;
  99471. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99472. FLAC__BitReader *input;
  99473. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99474. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99475. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99476. unsigned output_capacity, output_channels;
  99477. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99478. FLAC__uint64 samples_decoded;
  99479. FLAC__bool has_stream_info, has_seek_table;
  99480. FLAC__StreamMetadata stream_info;
  99481. FLAC__StreamMetadata seek_table;
  99482. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99483. FLAC__byte *metadata_filter_ids;
  99484. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99485. FLAC__Frame frame;
  99486. FLAC__bool cached; /* true if there is a byte in lookahead */
  99487. FLAC__CPUInfo cpuinfo;
  99488. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99489. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99490. /* unaligned (original) pointers to allocated data */
  99491. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99492. 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 */
  99493. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99494. FLAC__bool is_seeking;
  99495. FLAC__MD5Context md5context;
  99496. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99497. /* (the rest of these are only used for seeking) */
  99498. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99499. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99500. FLAC__uint64 target_sample;
  99501. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99502. #if FLAC__HAS_OGG
  99503. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99504. #endif
  99505. } FLAC__StreamDecoderPrivate;
  99506. /***********************************************************************
  99507. *
  99508. * Public static class data
  99509. *
  99510. ***********************************************************************/
  99511. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99512. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99513. "FLAC__STREAM_DECODER_READ_METADATA",
  99514. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99515. "FLAC__STREAM_DECODER_READ_FRAME",
  99516. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99517. "FLAC__STREAM_DECODER_OGG_ERROR",
  99518. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99519. "FLAC__STREAM_DECODER_ABORTED",
  99520. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99521. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99522. };
  99523. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99524. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99525. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99526. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99527. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99528. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99529. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99530. };
  99531. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99532. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99533. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99534. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99535. };
  99536. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99537. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99538. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99539. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99540. };
  99541. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99542. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99543. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99544. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99545. };
  99546. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99547. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99548. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99549. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99550. };
  99551. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99552. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99553. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99554. };
  99555. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99556. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99557. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99558. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99559. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99560. };
  99561. /***********************************************************************
  99562. *
  99563. * Class constructor/destructor
  99564. *
  99565. ***********************************************************************/
  99566. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99567. {
  99568. FLAC__StreamDecoder *decoder;
  99569. unsigned i;
  99570. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99571. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99572. if(decoder == 0) {
  99573. return 0;
  99574. }
  99575. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99576. if(decoder->protected_ == 0) {
  99577. free(decoder);
  99578. return 0;
  99579. }
  99580. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99581. if(decoder->private_ == 0) {
  99582. free(decoder->protected_);
  99583. free(decoder);
  99584. return 0;
  99585. }
  99586. decoder->private_->input = FLAC__bitreader_new();
  99587. if(decoder->private_->input == 0) {
  99588. free(decoder->private_);
  99589. free(decoder->protected_);
  99590. free(decoder);
  99591. return 0;
  99592. }
  99593. decoder->private_->metadata_filter_ids_capacity = 16;
  99594. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99595. FLAC__bitreader_delete(decoder->private_->input);
  99596. free(decoder->private_);
  99597. free(decoder->protected_);
  99598. free(decoder);
  99599. return 0;
  99600. }
  99601. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99602. decoder->private_->output[i] = 0;
  99603. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99604. }
  99605. decoder->private_->output_capacity = 0;
  99606. decoder->private_->output_channels = 0;
  99607. decoder->private_->has_seek_table = false;
  99608. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99609. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99610. decoder->private_->file = 0;
  99611. set_defaults_dec(decoder);
  99612. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99613. return decoder;
  99614. }
  99615. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99616. {
  99617. unsigned i;
  99618. FLAC__ASSERT(0 != decoder);
  99619. FLAC__ASSERT(0 != decoder->protected_);
  99620. FLAC__ASSERT(0 != decoder->private_);
  99621. FLAC__ASSERT(0 != decoder->private_->input);
  99622. (void)FLAC__stream_decoder_finish(decoder);
  99623. if(0 != decoder->private_->metadata_filter_ids)
  99624. free(decoder->private_->metadata_filter_ids);
  99625. FLAC__bitreader_delete(decoder->private_->input);
  99626. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99627. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99628. free(decoder->private_);
  99629. free(decoder->protected_);
  99630. free(decoder);
  99631. }
  99632. /***********************************************************************
  99633. *
  99634. * Public class methods
  99635. *
  99636. ***********************************************************************/
  99637. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99638. FLAC__StreamDecoder *decoder,
  99639. FLAC__StreamDecoderReadCallback read_callback,
  99640. FLAC__StreamDecoderSeekCallback seek_callback,
  99641. FLAC__StreamDecoderTellCallback tell_callback,
  99642. FLAC__StreamDecoderLengthCallback length_callback,
  99643. FLAC__StreamDecoderEofCallback eof_callback,
  99644. FLAC__StreamDecoderWriteCallback write_callback,
  99645. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99646. FLAC__StreamDecoderErrorCallback error_callback,
  99647. void *client_data,
  99648. FLAC__bool is_ogg
  99649. )
  99650. {
  99651. FLAC__ASSERT(0 != decoder);
  99652. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99653. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99654. #if !FLAC__HAS_OGG
  99655. if(is_ogg)
  99656. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99657. #endif
  99658. if(
  99659. 0 == read_callback ||
  99660. 0 == write_callback ||
  99661. 0 == error_callback ||
  99662. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99663. )
  99664. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99665. #if FLAC__HAS_OGG
  99666. decoder->private_->is_ogg = is_ogg;
  99667. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99668. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99669. #endif
  99670. /*
  99671. * get the CPU info and set the function pointers
  99672. */
  99673. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99674. /* first default to the non-asm routines */
  99675. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99676. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99677. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99678. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99679. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99680. /* now override with asm where appropriate */
  99681. #ifndef FLAC__NO_ASM
  99682. if(decoder->private_->cpuinfo.use_asm) {
  99683. #ifdef FLAC__CPU_IA32
  99684. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99685. #ifdef FLAC__HAS_NASM
  99686. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99687. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99688. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99689. #endif
  99690. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99691. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99692. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99693. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99694. }
  99695. else {
  99696. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99697. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99698. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99699. }
  99700. #endif
  99701. #elif defined FLAC__CPU_PPC
  99702. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99703. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99704. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99705. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99706. }
  99707. #endif
  99708. }
  99709. #endif
  99710. /* from here on, errors are fatal */
  99711. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99712. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99713. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99714. }
  99715. decoder->private_->read_callback = read_callback;
  99716. decoder->private_->seek_callback = seek_callback;
  99717. decoder->private_->tell_callback = tell_callback;
  99718. decoder->private_->length_callback = length_callback;
  99719. decoder->private_->eof_callback = eof_callback;
  99720. decoder->private_->write_callback = write_callback;
  99721. decoder->private_->metadata_callback = metadata_callback;
  99722. decoder->private_->error_callback = error_callback;
  99723. decoder->private_->client_data = client_data;
  99724. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99725. decoder->private_->samples_decoded = 0;
  99726. decoder->private_->has_stream_info = false;
  99727. decoder->private_->cached = false;
  99728. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99729. decoder->private_->is_seeking = false;
  99730. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99731. if(!FLAC__stream_decoder_reset(decoder)) {
  99732. /* above call sets the state for us */
  99733. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99734. }
  99735. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99736. }
  99737. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99738. FLAC__StreamDecoder *decoder,
  99739. FLAC__StreamDecoderReadCallback read_callback,
  99740. FLAC__StreamDecoderSeekCallback seek_callback,
  99741. FLAC__StreamDecoderTellCallback tell_callback,
  99742. FLAC__StreamDecoderLengthCallback length_callback,
  99743. FLAC__StreamDecoderEofCallback eof_callback,
  99744. FLAC__StreamDecoderWriteCallback write_callback,
  99745. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99746. FLAC__StreamDecoderErrorCallback error_callback,
  99747. void *client_data
  99748. )
  99749. {
  99750. return init_stream_internal_dec(
  99751. decoder,
  99752. read_callback,
  99753. seek_callback,
  99754. tell_callback,
  99755. length_callback,
  99756. eof_callback,
  99757. write_callback,
  99758. metadata_callback,
  99759. error_callback,
  99760. client_data,
  99761. /*is_ogg=*/false
  99762. );
  99763. }
  99764. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99765. FLAC__StreamDecoder *decoder,
  99766. FLAC__StreamDecoderReadCallback read_callback,
  99767. FLAC__StreamDecoderSeekCallback seek_callback,
  99768. FLAC__StreamDecoderTellCallback tell_callback,
  99769. FLAC__StreamDecoderLengthCallback length_callback,
  99770. FLAC__StreamDecoderEofCallback eof_callback,
  99771. FLAC__StreamDecoderWriteCallback write_callback,
  99772. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99773. FLAC__StreamDecoderErrorCallback error_callback,
  99774. void *client_data
  99775. )
  99776. {
  99777. return init_stream_internal_dec(
  99778. decoder,
  99779. read_callback,
  99780. seek_callback,
  99781. tell_callback,
  99782. length_callback,
  99783. eof_callback,
  99784. write_callback,
  99785. metadata_callback,
  99786. error_callback,
  99787. client_data,
  99788. /*is_ogg=*/true
  99789. );
  99790. }
  99791. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99792. FLAC__StreamDecoder *decoder,
  99793. FILE *file,
  99794. FLAC__StreamDecoderWriteCallback write_callback,
  99795. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99796. FLAC__StreamDecoderErrorCallback error_callback,
  99797. void *client_data,
  99798. FLAC__bool is_ogg
  99799. )
  99800. {
  99801. FLAC__ASSERT(0 != decoder);
  99802. FLAC__ASSERT(0 != file);
  99803. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99804. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99805. if(0 == write_callback || 0 == error_callback)
  99806. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99807. /*
  99808. * To make sure that our file does not go unclosed after an error, we
  99809. * must assign the FILE pointer before any further error can occur in
  99810. * this routine.
  99811. */
  99812. if(file == stdin)
  99813. file = get_binary_stdin_(); /* just to be safe */
  99814. decoder->private_->file = file;
  99815. return init_stream_internal_dec(
  99816. decoder,
  99817. file_read_callback_dec,
  99818. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99819. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99820. decoder->private_->file == stdin? 0: file_length_callback_,
  99821. file_eof_callback_,
  99822. write_callback,
  99823. metadata_callback,
  99824. error_callback,
  99825. client_data,
  99826. is_ogg
  99827. );
  99828. }
  99829. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99830. FLAC__StreamDecoder *decoder,
  99831. FILE *file,
  99832. FLAC__StreamDecoderWriteCallback write_callback,
  99833. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99834. FLAC__StreamDecoderErrorCallback error_callback,
  99835. void *client_data
  99836. )
  99837. {
  99838. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99839. }
  99840. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99841. FLAC__StreamDecoder *decoder,
  99842. FILE *file,
  99843. FLAC__StreamDecoderWriteCallback write_callback,
  99844. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99845. FLAC__StreamDecoderErrorCallback error_callback,
  99846. void *client_data
  99847. )
  99848. {
  99849. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99850. }
  99851. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99852. FLAC__StreamDecoder *decoder,
  99853. const char *filename,
  99854. FLAC__StreamDecoderWriteCallback write_callback,
  99855. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99856. FLAC__StreamDecoderErrorCallback error_callback,
  99857. void *client_data,
  99858. FLAC__bool is_ogg
  99859. )
  99860. {
  99861. FILE *file;
  99862. FLAC__ASSERT(0 != decoder);
  99863. /*
  99864. * To make sure that our file does not go unclosed after an error, we
  99865. * have to do the same entrance checks here that are later performed
  99866. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99867. */
  99868. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99869. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99870. if(0 == write_callback || 0 == error_callback)
  99871. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99872. file = filename? fopen(filename, "rb") : stdin;
  99873. if(0 == file)
  99874. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99875. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99876. }
  99877. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99878. FLAC__StreamDecoder *decoder,
  99879. const char *filename,
  99880. FLAC__StreamDecoderWriteCallback write_callback,
  99881. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99882. FLAC__StreamDecoderErrorCallback error_callback,
  99883. void *client_data
  99884. )
  99885. {
  99886. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99887. }
  99888. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99889. FLAC__StreamDecoder *decoder,
  99890. const char *filename,
  99891. FLAC__StreamDecoderWriteCallback write_callback,
  99892. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99893. FLAC__StreamDecoderErrorCallback error_callback,
  99894. void *client_data
  99895. )
  99896. {
  99897. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99898. }
  99899. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99900. {
  99901. FLAC__bool md5_failed = false;
  99902. unsigned i;
  99903. FLAC__ASSERT(0 != decoder);
  99904. FLAC__ASSERT(0 != decoder->private_);
  99905. FLAC__ASSERT(0 != decoder->protected_);
  99906. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99907. return true;
  99908. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99909. * always call FLAC__MD5Final()
  99910. */
  99911. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99912. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99913. free(decoder->private_->seek_table.data.seek_table.points);
  99914. decoder->private_->seek_table.data.seek_table.points = 0;
  99915. decoder->private_->has_seek_table = false;
  99916. }
  99917. FLAC__bitreader_free(decoder->private_->input);
  99918. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99919. /* WATCHOUT:
  99920. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99921. * output arrays have a buffer of up to 3 zeroes in front
  99922. * (at negative indices) for alignment purposes; we use 4
  99923. * to keep the data well-aligned.
  99924. */
  99925. if(0 != decoder->private_->output[i]) {
  99926. free(decoder->private_->output[i]-4);
  99927. decoder->private_->output[i] = 0;
  99928. }
  99929. if(0 != decoder->private_->residual_unaligned[i]) {
  99930. free(decoder->private_->residual_unaligned[i]);
  99931. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99932. }
  99933. }
  99934. decoder->private_->output_capacity = 0;
  99935. decoder->private_->output_channels = 0;
  99936. #if FLAC__HAS_OGG
  99937. if(decoder->private_->is_ogg)
  99938. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99939. #endif
  99940. if(0 != decoder->private_->file) {
  99941. if(decoder->private_->file != stdin)
  99942. fclose(decoder->private_->file);
  99943. decoder->private_->file = 0;
  99944. }
  99945. if(decoder->private_->do_md5_checking) {
  99946. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99947. md5_failed = true;
  99948. }
  99949. decoder->private_->is_seeking = false;
  99950. set_defaults_dec(decoder);
  99951. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99952. return !md5_failed;
  99953. }
  99954. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99955. {
  99956. FLAC__ASSERT(0 != decoder);
  99957. FLAC__ASSERT(0 != decoder->private_);
  99958. FLAC__ASSERT(0 != decoder->protected_);
  99959. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99960. return false;
  99961. #if FLAC__HAS_OGG
  99962. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99963. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99964. return true;
  99965. #else
  99966. (void)value;
  99967. return false;
  99968. #endif
  99969. }
  99970. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99971. {
  99972. FLAC__ASSERT(0 != decoder);
  99973. FLAC__ASSERT(0 != decoder->protected_);
  99974. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99975. return false;
  99976. decoder->protected_->md5_checking = value;
  99977. return true;
  99978. }
  99979. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99980. {
  99981. FLAC__ASSERT(0 != decoder);
  99982. FLAC__ASSERT(0 != decoder->private_);
  99983. FLAC__ASSERT(0 != decoder->protected_);
  99984. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99985. /* double protection */
  99986. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99987. return false;
  99988. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99989. return false;
  99990. decoder->private_->metadata_filter[type] = true;
  99991. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99992. decoder->private_->metadata_filter_ids_count = 0;
  99993. return true;
  99994. }
  99995. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99996. {
  99997. FLAC__ASSERT(0 != decoder);
  99998. FLAC__ASSERT(0 != decoder->private_);
  99999. FLAC__ASSERT(0 != decoder->protected_);
  100000. FLAC__ASSERT(0 != id);
  100001. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100002. return false;
  100003. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  100004. return true;
  100005. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  100006. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  100007. 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))) {
  100008. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100009. return false;
  100010. }
  100011. decoder->private_->metadata_filter_ids_capacity *= 2;
  100012. }
  100013. 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));
  100014. decoder->private_->metadata_filter_ids_count++;
  100015. return true;
  100016. }
  100017. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  100018. {
  100019. unsigned i;
  100020. FLAC__ASSERT(0 != decoder);
  100021. FLAC__ASSERT(0 != decoder->private_);
  100022. FLAC__ASSERT(0 != decoder->protected_);
  100023. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100024. return false;
  100025. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  100026. decoder->private_->metadata_filter[i] = true;
  100027. decoder->private_->metadata_filter_ids_count = 0;
  100028. return true;
  100029. }
  100030. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  100031. {
  100032. FLAC__ASSERT(0 != decoder);
  100033. FLAC__ASSERT(0 != decoder->private_);
  100034. FLAC__ASSERT(0 != decoder->protected_);
  100035. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  100036. /* double protection */
  100037. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  100038. return false;
  100039. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100040. return false;
  100041. decoder->private_->metadata_filter[type] = false;
  100042. if(type == FLAC__METADATA_TYPE_APPLICATION)
  100043. decoder->private_->metadata_filter_ids_count = 0;
  100044. return true;
  100045. }
  100046. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  100047. {
  100048. FLAC__ASSERT(0 != decoder);
  100049. FLAC__ASSERT(0 != decoder->private_);
  100050. FLAC__ASSERT(0 != decoder->protected_);
  100051. FLAC__ASSERT(0 != id);
  100052. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100053. return false;
  100054. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  100055. return true;
  100056. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  100057. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  100058. 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))) {
  100059. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100060. return false;
  100061. }
  100062. decoder->private_->metadata_filter_ids_capacity *= 2;
  100063. }
  100064. 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));
  100065. decoder->private_->metadata_filter_ids_count++;
  100066. return true;
  100067. }
  100068. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  100069. {
  100070. FLAC__ASSERT(0 != decoder);
  100071. FLAC__ASSERT(0 != decoder->private_);
  100072. FLAC__ASSERT(0 != decoder->protected_);
  100073. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100074. return false;
  100075. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100076. decoder->private_->metadata_filter_ids_count = 0;
  100077. return true;
  100078. }
  100079. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  100080. {
  100081. FLAC__ASSERT(0 != decoder);
  100082. FLAC__ASSERT(0 != decoder->protected_);
  100083. return decoder->protected_->state;
  100084. }
  100085. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  100086. {
  100087. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  100088. }
  100089. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  100090. {
  100091. FLAC__ASSERT(0 != decoder);
  100092. FLAC__ASSERT(0 != decoder->protected_);
  100093. return decoder->protected_->md5_checking;
  100094. }
  100095. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  100096. {
  100097. FLAC__ASSERT(0 != decoder);
  100098. FLAC__ASSERT(0 != decoder->protected_);
  100099. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  100100. }
  100101. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  100102. {
  100103. FLAC__ASSERT(0 != decoder);
  100104. FLAC__ASSERT(0 != decoder->protected_);
  100105. return decoder->protected_->channels;
  100106. }
  100107. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  100108. {
  100109. FLAC__ASSERT(0 != decoder);
  100110. FLAC__ASSERT(0 != decoder->protected_);
  100111. return decoder->protected_->channel_assignment;
  100112. }
  100113. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  100114. {
  100115. FLAC__ASSERT(0 != decoder);
  100116. FLAC__ASSERT(0 != decoder->protected_);
  100117. return decoder->protected_->bits_per_sample;
  100118. }
  100119. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  100120. {
  100121. FLAC__ASSERT(0 != decoder);
  100122. FLAC__ASSERT(0 != decoder->protected_);
  100123. return decoder->protected_->sample_rate;
  100124. }
  100125. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  100126. {
  100127. FLAC__ASSERT(0 != decoder);
  100128. FLAC__ASSERT(0 != decoder->protected_);
  100129. return decoder->protected_->blocksize;
  100130. }
  100131. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  100132. {
  100133. FLAC__ASSERT(0 != decoder);
  100134. FLAC__ASSERT(0 != decoder->private_);
  100135. FLAC__ASSERT(0 != position);
  100136. #if FLAC__HAS_OGG
  100137. if(decoder->private_->is_ogg)
  100138. return false;
  100139. #endif
  100140. if(0 == decoder->private_->tell_callback)
  100141. return false;
  100142. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  100143. return false;
  100144. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  100145. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  100146. return false;
  100147. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  100148. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  100149. return true;
  100150. }
  100151. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  100152. {
  100153. FLAC__ASSERT(0 != decoder);
  100154. FLAC__ASSERT(0 != decoder->private_);
  100155. FLAC__ASSERT(0 != decoder->protected_);
  100156. decoder->private_->samples_decoded = 0;
  100157. decoder->private_->do_md5_checking = false;
  100158. #if FLAC__HAS_OGG
  100159. if(decoder->private_->is_ogg)
  100160. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  100161. #endif
  100162. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  100163. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100164. return false;
  100165. }
  100166. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100167. return true;
  100168. }
  100169. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  100170. {
  100171. FLAC__ASSERT(0 != decoder);
  100172. FLAC__ASSERT(0 != decoder->private_);
  100173. FLAC__ASSERT(0 != decoder->protected_);
  100174. if(!FLAC__stream_decoder_flush(decoder)) {
  100175. /* above call sets the state for us */
  100176. return false;
  100177. }
  100178. #if FLAC__HAS_OGG
  100179. /*@@@ could go in !internal_reset_hack block below */
  100180. if(decoder->private_->is_ogg)
  100181. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100182. #endif
  100183. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100184. * (internal_reset_hack) don't try to rewind since we are already at
  100185. * the beginning of the stream and don't want to fail if the input is
  100186. * not seekable.
  100187. */
  100188. if(!decoder->private_->internal_reset_hack) {
  100189. if(decoder->private_->file == stdin)
  100190. return false; /* can't rewind stdin, reset fails */
  100191. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100192. return false; /* seekable and seek fails, reset fails */
  100193. }
  100194. else
  100195. decoder->private_->internal_reset_hack = false;
  100196. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100197. decoder->private_->has_stream_info = false;
  100198. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100199. free(decoder->private_->seek_table.data.seek_table.points);
  100200. decoder->private_->seek_table.data.seek_table.points = 0;
  100201. decoder->private_->has_seek_table = false;
  100202. }
  100203. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100204. /*
  100205. * This goes in reset() and not flush() because according to the spec, a
  100206. * fixed-blocksize stream must stay that way through the whole stream.
  100207. */
  100208. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100209. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100210. * is because md5 checking may be turned on to start and then turned off if
  100211. * a seek occurs. So we init the context here and finalize it in
  100212. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100213. * properly.
  100214. */
  100215. FLAC__MD5Init(&decoder->private_->md5context);
  100216. decoder->private_->first_frame_offset = 0;
  100217. decoder->private_->unparseable_frame_count = 0;
  100218. return true;
  100219. }
  100220. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100221. {
  100222. FLAC__bool got_a_frame;
  100223. FLAC__ASSERT(0 != decoder);
  100224. FLAC__ASSERT(0 != decoder->protected_);
  100225. while(1) {
  100226. switch(decoder->protected_->state) {
  100227. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100228. if(!find_metadata_(decoder))
  100229. return false; /* above function sets the status for us */
  100230. break;
  100231. case FLAC__STREAM_DECODER_READ_METADATA:
  100232. if(!read_metadata_(decoder))
  100233. return false; /* above function sets the status for us */
  100234. else
  100235. return true;
  100236. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100237. if(!frame_sync_(decoder))
  100238. return true; /* above function sets the status for us */
  100239. break;
  100240. case FLAC__STREAM_DECODER_READ_FRAME:
  100241. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100242. return false; /* above function sets the status for us */
  100243. if(got_a_frame)
  100244. return true; /* above function sets the status for us */
  100245. break;
  100246. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100247. case FLAC__STREAM_DECODER_ABORTED:
  100248. return true;
  100249. default:
  100250. FLAC__ASSERT(0);
  100251. return false;
  100252. }
  100253. }
  100254. }
  100255. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100256. {
  100257. FLAC__ASSERT(0 != decoder);
  100258. FLAC__ASSERT(0 != decoder->protected_);
  100259. while(1) {
  100260. switch(decoder->protected_->state) {
  100261. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100262. if(!find_metadata_(decoder))
  100263. return false; /* above function sets the status for us */
  100264. break;
  100265. case FLAC__STREAM_DECODER_READ_METADATA:
  100266. if(!read_metadata_(decoder))
  100267. return false; /* above function sets the status for us */
  100268. break;
  100269. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100270. case FLAC__STREAM_DECODER_READ_FRAME:
  100271. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100272. case FLAC__STREAM_DECODER_ABORTED:
  100273. return true;
  100274. default:
  100275. FLAC__ASSERT(0);
  100276. return false;
  100277. }
  100278. }
  100279. }
  100280. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100281. {
  100282. FLAC__bool dummy;
  100283. FLAC__ASSERT(0 != decoder);
  100284. FLAC__ASSERT(0 != decoder->protected_);
  100285. while(1) {
  100286. switch(decoder->protected_->state) {
  100287. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100288. if(!find_metadata_(decoder))
  100289. return false; /* above function sets the status for us */
  100290. break;
  100291. case FLAC__STREAM_DECODER_READ_METADATA:
  100292. if(!read_metadata_(decoder))
  100293. return false; /* above function sets the status for us */
  100294. break;
  100295. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100296. if(!frame_sync_(decoder))
  100297. return true; /* above function sets the status for us */
  100298. break;
  100299. case FLAC__STREAM_DECODER_READ_FRAME:
  100300. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100301. return false; /* above function sets the status for us */
  100302. break;
  100303. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100304. case FLAC__STREAM_DECODER_ABORTED:
  100305. return true;
  100306. default:
  100307. FLAC__ASSERT(0);
  100308. return false;
  100309. }
  100310. }
  100311. }
  100312. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100313. {
  100314. FLAC__bool got_a_frame;
  100315. FLAC__ASSERT(0 != decoder);
  100316. FLAC__ASSERT(0 != decoder->protected_);
  100317. while(1) {
  100318. switch(decoder->protected_->state) {
  100319. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100320. case FLAC__STREAM_DECODER_READ_METADATA:
  100321. return false; /* above function sets the status for us */
  100322. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100323. if(!frame_sync_(decoder))
  100324. return true; /* above function sets the status for us */
  100325. break;
  100326. case FLAC__STREAM_DECODER_READ_FRAME:
  100327. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100328. return false; /* above function sets the status for us */
  100329. if(got_a_frame)
  100330. return true; /* above function sets the status for us */
  100331. break;
  100332. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100333. case FLAC__STREAM_DECODER_ABORTED:
  100334. return true;
  100335. default:
  100336. FLAC__ASSERT(0);
  100337. return false;
  100338. }
  100339. }
  100340. }
  100341. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100342. {
  100343. FLAC__uint64 length;
  100344. FLAC__ASSERT(0 != decoder);
  100345. if(
  100346. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100347. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100348. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100349. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100350. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100351. )
  100352. return false;
  100353. if(0 == decoder->private_->seek_callback)
  100354. return false;
  100355. FLAC__ASSERT(decoder->private_->seek_callback);
  100356. FLAC__ASSERT(decoder->private_->tell_callback);
  100357. FLAC__ASSERT(decoder->private_->length_callback);
  100358. FLAC__ASSERT(decoder->private_->eof_callback);
  100359. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100360. return false;
  100361. decoder->private_->is_seeking = true;
  100362. /* turn off md5 checking if a seek is attempted */
  100363. decoder->private_->do_md5_checking = false;
  100364. /* 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) */
  100365. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100366. decoder->private_->is_seeking = false;
  100367. return false;
  100368. }
  100369. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100370. if(
  100371. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100372. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100373. ) {
  100374. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100375. /* above call sets the state for us */
  100376. decoder->private_->is_seeking = false;
  100377. return false;
  100378. }
  100379. /* check this again in case we didn't know total_samples the first time */
  100380. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100381. decoder->private_->is_seeking = false;
  100382. return false;
  100383. }
  100384. }
  100385. {
  100386. const FLAC__bool ok =
  100387. #if FLAC__HAS_OGG
  100388. decoder->private_->is_ogg?
  100389. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100390. #endif
  100391. seek_to_absolute_sample_(decoder, length, sample)
  100392. ;
  100393. decoder->private_->is_seeking = false;
  100394. return ok;
  100395. }
  100396. }
  100397. /***********************************************************************
  100398. *
  100399. * Protected class methods
  100400. *
  100401. ***********************************************************************/
  100402. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100403. {
  100404. FLAC__ASSERT(0 != decoder);
  100405. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100406. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100407. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100408. }
  100409. /***********************************************************************
  100410. *
  100411. * Private class methods
  100412. *
  100413. ***********************************************************************/
  100414. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100415. {
  100416. #if FLAC__HAS_OGG
  100417. decoder->private_->is_ogg = false;
  100418. #endif
  100419. decoder->private_->read_callback = 0;
  100420. decoder->private_->seek_callback = 0;
  100421. decoder->private_->tell_callback = 0;
  100422. decoder->private_->length_callback = 0;
  100423. decoder->private_->eof_callback = 0;
  100424. decoder->private_->write_callback = 0;
  100425. decoder->private_->metadata_callback = 0;
  100426. decoder->private_->error_callback = 0;
  100427. decoder->private_->client_data = 0;
  100428. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100429. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100430. decoder->private_->metadata_filter_ids_count = 0;
  100431. decoder->protected_->md5_checking = false;
  100432. #if FLAC__HAS_OGG
  100433. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100434. #endif
  100435. }
  100436. /*
  100437. * This will forcibly set stdin to binary mode (for OSes that require it)
  100438. */
  100439. FILE *get_binary_stdin_(void)
  100440. {
  100441. /* if something breaks here it is probably due to the presence or
  100442. * absence of an underscore before the identifiers 'setmode',
  100443. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100444. */
  100445. #if defined _MSC_VER || defined __MINGW32__
  100446. _setmode(_fileno(stdin), _O_BINARY);
  100447. #elif defined __CYGWIN__
  100448. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100449. setmode(_fileno(stdin), _O_BINARY);
  100450. #elif defined __EMX__
  100451. setmode(fileno(stdin), O_BINARY);
  100452. #endif
  100453. return stdin;
  100454. }
  100455. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100456. {
  100457. unsigned i;
  100458. FLAC__int32 *tmp;
  100459. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100460. return true;
  100461. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100462. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100463. if(0 != decoder->private_->output[i]) {
  100464. free(decoder->private_->output[i]-4);
  100465. decoder->private_->output[i] = 0;
  100466. }
  100467. if(0 != decoder->private_->residual_unaligned[i]) {
  100468. free(decoder->private_->residual_unaligned[i]);
  100469. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100470. }
  100471. }
  100472. for(i = 0; i < channels; i++) {
  100473. /* WATCHOUT:
  100474. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100475. * output arrays have a buffer of up to 3 zeroes in front
  100476. * (at negative indices) for alignment purposes; we use 4
  100477. * to keep the data well-aligned.
  100478. */
  100479. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100480. if(tmp == 0) {
  100481. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100482. return false;
  100483. }
  100484. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100485. decoder->private_->output[i] = tmp + 4;
  100486. /* WATCHOUT:
  100487. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100488. */
  100489. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100490. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100491. return false;
  100492. }
  100493. }
  100494. decoder->private_->output_capacity = size;
  100495. decoder->private_->output_channels = channels;
  100496. return true;
  100497. }
  100498. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100499. {
  100500. size_t i;
  100501. FLAC__ASSERT(0 != decoder);
  100502. FLAC__ASSERT(0 != decoder->private_);
  100503. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100504. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100505. return true;
  100506. return false;
  100507. }
  100508. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100509. {
  100510. FLAC__uint32 x;
  100511. unsigned i, id_;
  100512. FLAC__bool first = true;
  100513. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100514. for(i = id_ = 0; i < 4; ) {
  100515. if(decoder->private_->cached) {
  100516. x = (FLAC__uint32)decoder->private_->lookahead;
  100517. decoder->private_->cached = false;
  100518. }
  100519. else {
  100520. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100521. return false; /* read_callback_ sets the state for us */
  100522. }
  100523. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100524. first = true;
  100525. i++;
  100526. id_ = 0;
  100527. continue;
  100528. }
  100529. if(x == ID3V2_TAG_[id_]) {
  100530. id_++;
  100531. i = 0;
  100532. if(id_ == 3) {
  100533. if(!skip_id3v2_tag_(decoder))
  100534. return false; /* skip_id3v2_tag_ sets the state for us */
  100535. }
  100536. continue;
  100537. }
  100538. id_ = 0;
  100539. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100540. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100541. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100542. return false; /* read_callback_ sets the state for us */
  100543. /* 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 */
  100544. /* else we have to check if the second byte is the end of a sync code */
  100545. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100546. decoder->private_->lookahead = (FLAC__byte)x;
  100547. decoder->private_->cached = true;
  100548. }
  100549. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100550. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100551. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100552. return true;
  100553. }
  100554. }
  100555. i = 0;
  100556. if(first) {
  100557. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100558. first = false;
  100559. }
  100560. }
  100561. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100562. return true;
  100563. }
  100564. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100565. {
  100566. FLAC__bool is_last;
  100567. FLAC__uint32 i, x, type, length;
  100568. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100570. return false; /* read_callback_ sets the state for us */
  100571. is_last = x? true : false;
  100572. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100573. return false; /* read_callback_ sets the state for us */
  100574. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100575. return false; /* read_callback_ sets the state for us */
  100576. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100577. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100578. return false;
  100579. decoder->private_->has_stream_info = true;
  100580. 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))
  100581. decoder->private_->do_md5_checking = false;
  100582. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100583. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100584. }
  100585. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100586. if(!read_metadata_seektable_(decoder, is_last, length))
  100587. return false;
  100588. decoder->private_->has_seek_table = true;
  100589. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100590. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100591. }
  100592. else {
  100593. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100594. unsigned real_length = length;
  100595. FLAC__StreamMetadata block;
  100596. block.is_last = is_last;
  100597. block.type = (FLAC__MetadataType)type;
  100598. block.length = length;
  100599. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100600. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100601. return false; /* read_callback_ sets the state for us */
  100602. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100603. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100604. return false;
  100605. }
  100606. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100607. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100608. skip_it = !skip_it;
  100609. }
  100610. if(skip_it) {
  100611. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100612. return false; /* read_callback_ sets the state for us */
  100613. }
  100614. else {
  100615. switch(type) {
  100616. case FLAC__METADATA_TYPE_PADDING:
  100617. /* skip the padding bytes */
  100618. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100619. return false; /* read_callback_ sets the state for us */
  100620. break;
  100621. case FLAC__METADATA_TYPE_APPLICATION:
  100622. /* remember, we read the ID already */
  100623. if(real_length > 0) {
  100624. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100625. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100626. return false;
  100627. }
  100628. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100629. return false; /* read_callback_ sets the state for us */
  100630. }
  100631. else
  100632. block.data.application.data = 0;
  100633. break;
  100634. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100635. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100636. return false;
  100637. break;
  100638. case FLAC__METADATA_TYPE_CUESHEET:
  100639. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100640. return false;
  100641. break;
  100642. case FLAC__METADATA_TYPE_PICTURE:
  100643. if(!read_metadata_picture_(decoder, &block.data.picture))
  100644. return false;
  100645. break;
  100646. case FLAC__METADATA_TYPE_STREAMINFO:
  100647. case FLAC__METADATA_TYPE_SEEKTABLE:
  100648. FLAC__ASSERT(0);
  100649. break;
  100650. default:
  100651. if(real_length > 0) {
  100652. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100653. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100654. return false;
  100655. }
  100656. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100657. return false; /* read_callback_ sets the state for us */
  100658. }
  100659. else
  100660. block.data.unknown.data = 0;
  100661. break;
  100662. }
  100663. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100664. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100665. /* now we have to free any malloc()ed data in the block */
  100666. switch(type) {
  100667. case FLAC__METADATA_TYPE_PADDING:
  100668. break;
  100669. case FLAC__METADATA_TYPE_APPLICATION:
  100670. if(0 != block.data.application.data)
  100671. free(block.data.application.data);
  100672. break;
  100673. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100674. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100675. free(block.data.vorbis_comment.vendor_string.entry);
  100676. if(block.data.vorbis_comment.num_comments > 0)
  100677. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100678. if(0 != block.data.vorbis_comment.comments[i].entry)
  100679. free(block.data.vorbis_comment.comments[i].entry);
  100680. if(0 != block.data.vorbis_comment.comments)
  100681. free(block.data.vorbis_comment.comments);
  100682. break;
  100683. case FLAC__METADATA_TYPE_CUESHEET:
  100684. if(block.data.cue_sheet.num_tracks > 0)
  100685. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100686. if(0 != block.data.cue_sheet.tracks[i].indices)
  100687. free(block.data.cue_sheet.tracks[i].indices);
  100688. if(0 != block.data.cue_sheet.tracks)
  100689. free(block.data.cue_sheet.tracks);
  100690. break;
  100691. case FLAC__METADATA_TYPE_PICTURE:
  100692. if(0 != block.data.picture.mime_type)
  100693. free(block.data.picture.mime_type);
  100694. if(0 != block.data.picture.description)
  100695. free(block.data.picture.description);
  100696. if(0 != block.data.picture.data)
  100697. free(block.data.picture.data);
  100698. break;
  100699. case FLAC__METADATA_TYPE_STREAMINFO:
  100700. case FLAC__METADATA_TYPE_SEEKTABLE:
  100701. FLAC__ASSERT(0);
  100702. default:
  100703. if(0 != block.data.unknown.data)
  100704. free(block.data.unknown.data);
  100705. break;
  100706. }
  100707. }
  100708. }
  100709. if(is_last) {
  100710. /* if this fails, it's OK, it's just a hint for the seek routine */
  100711. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100712. decoder->private_->first_frame_offset = 0;
  100713. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100714. }
  100715. return true;
  100716. }
  100717. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100718. {
  100719. FLAC__uint32 x;
  100720. unsigned bits, used_bits = 0;
  100721. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100722. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100723. decoder->private_->stream_info.is_last = is_last;
  100724. decoder->private_->stream_info.length = length;
  100725. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100726. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100727. return false; /* read_callback_ sets the state for us */
  100728. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100729. used_bits += bits;
  100730. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100731. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100732. return false; /* read_callback_ sets the state for us */
  100733. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100734. used_bits += bits;
  100735. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100736. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100737. return false; /* read_callback_ sets the state for us */
  100738. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100739. used_bits += bits;
  100740. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100741. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100742. return false; /* read_callback_ sets the state for us */
  100743. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100744. used_bits += bits;
  100745. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100746. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100747. return false; /* read_callback_ sets the state for us */
  100748. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100749. used_bits += bits;
  100750. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100751. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100752. return false; /* read_callback_ sets the state for us */
  100753. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100754. used_bits += bits;
  100755. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100756. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100757. return false; /* read_callback_ sets the state for us */
  100758. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100759. used_bits += bits;
  100760. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100761. 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))
  100762. return false; /* read_callback_ sets the state for us */
  100763. used_bits += bits;
  100764. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100765. return false; /* read_callback_ sets the state for us */
  100766. used_bits += 16*8;
  100767. /* skip the rest of the block */
  100768. FLAC__ASSERT(used_bits % 8 == 0);
  100769. length -= (used_bits / 8);
  100770. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100771. return false; /* read_callback_ sets the state for us */
  100772. return true;
  100773. }
  100774. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100775. {
  100776. FLAC__uint32 i, x;
  100777. FLAC__uint64 xx;
  100778. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100779. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100780. decoder->private_->seek_table.is_last = is_last;
  100781. decoder->private_->seek_table.length = length;
  100782. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100783. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100784. 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)))) {
  100785. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100786. return false;
  100787. }
  100788. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100789. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100790. return false; /* read_callback_ sets the state for us */
  100791. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100792. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100793. return false; /* read_callback_ sets the state for us */
  100794. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100795. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100796. return false; /* read_callback_ sets the state for us */
  100797. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100798. }
  100799. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100800. /* if there is a partial point left, skip over it */
  100801. if(length > 0) {
  100802. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100803. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100804. return false; /* read_callback_ sets the state for us */
  100805. }
  100806. return true;
  100807. }
  100808. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100809. {
  100810. FLAC__uint32 i;
  100811. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100812. /* read vendor string */
  100813. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100814. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100815. return false; /* read_callback_ sets the state for us */
  100816. if(obj->vendor_string.length > 0) {
  100817. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100818. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100819. return false;
  100820. }
  100821. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100822. return false; /* read_callback_ sets the state for us */
  100823. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100824. }
  100825. else
  100826. obj->vendor_string.entry = 0;
  100827. /* read num comments */
  100828. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100829. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100830. return false; /* read_callback_ sets the state for us */
  100831. /* read comments */
  100832. if(obj->num_comments > 0) {
  100833. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100834. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100835. return false;
  100836. }
  100837. for(i = 0; i < obj->num_comments; i++) {
  100838. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100839. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100840. return false; /* read_callback_ sets the state for us */
  100841. if(obj->comments[i].length > 0) {
  100842. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100843. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100844. return false;
  100845. }
  100846. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100847. return false; /* read_callback_ sets the state for us */
  100848. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100849. }
  100850. else
  100851. obj->comments[i].entry = 0;
  100852. }
  100853. }
  100854. else {
  100855. obj->comments = 0;
  100856. }
  100857. return true;
  100858. }
  100859. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100860. {
  100861. FLAC__uint32 i, j, x;
  100862. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100863. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100864. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100865. 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))
  100866. return false; /* read_callback_ sets the state for us */
  100867. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100868. return false; /* read_callback_ sets the state for us */
  100869. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100870. return false; /* read_callback_ sets the state for us */
  100871. obj->is_cd = x? true : false;
  100872. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100873. return false; /* read_callback_ sets the state for us */
  100874. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100875. return false; /* read_callback_ sets the state for us */
  100876. obj->num_tracks = x;
  100877. if(obj->num_tracks > 0) {
  100878. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100879. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100880. return false;
  100881. }
  100882. for(i = 0; i < obj->num_tracks; i++) {
  100883. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100884. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100885. return false; /* read_callback_ sets the state for us */
  100886. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100887. return false; /* read_callback_ sets the state for us */
  100888. track->number = (FLAC__byte)x;
  100889. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100890. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100891. return false; /* read_callback_ sets the state for us */
  100892. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100893. return false; /* read_callback_ sets the state for us */
  100894. track->type = x;
  100895. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100896. return false; /* read_callback_ sets the state for us */
  100897. track->pre_emphasis = x;
  100898. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100899. return false; /* read_callback_ sets the state for us */
  100900. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100901. return false; /* read_callback_ sets the state for us */
  100902. track->num_indices = (FLAC__byte)x;
  100903. if(track->num_indices > 0) {
  100904. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100905. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100906. return false;
  100907. }
  100908. for(j = 0; j < track->num_indices; j++) {
  100909. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100910. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100911. return false; /* read_callback_ sets the state for us */
  100912. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100913. return false; /* read_callback_ sets the state for us */
  100914. index->number = (FLAC__byte)x;
  100915. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100916. return false; /* read_callback_ sets the state for us */
  100917. }
  100918. }
  100919. }
  100920. }
  100921. return true;
  100922. }
  100923. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100924. {
  100925. FLAC__uint32 x;
  100926. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100927. /* read type */
  100928. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100929. return false; /* read_callback_ sets the state for us */
  100930. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100931. /* read MIME type */
  100932. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100933. return false; /* read_callback_ sets the state for us */
  100934. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100935. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100936. return false;
  100937. }
  100938. if(x > 0) {
  100939. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100940. return false; /* read_callback_ sets the state for us */
  100941. }
  100942. obj->mime_type[x] = '\0';
  100943. /* read description */
  100944. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100945. return false; /* read_callback_ sets the state for us */
  100946. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100947. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100948. return false;
  100949. }
  100950. if(x > 0) {
  100951. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100952. return false; /* read_callback_ sets the state for us */
  100953. }
  100954. obj->description[x] = '\0';
  100955. /* read width */
  100956. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100957. return false; /* read_callback_ sets the state for us */
  100958. /* read height */
  100959. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100960. return false; /* read_callback_ sets the state for us */
  100961. /* read depth */
  100962. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100963. return false; /* read_callback_ sets the state for us */
  100964. /* read colors */
  100965. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100966. return false; /* read_callback_ sets the state for us */
  100967. /* read data */
  100968. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100969. return false; /* read_callback_ sets the state for us */
  100970. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100971. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100972. return false;
  100973. }
  100974. if(obj->data_length > 0) {
  100975. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100976. return false; /* read_callback_ sets the state for us */
  100977. }
  100978. return true;
  100979. }
  100980. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100981. {
  100982. FLAC__uint32 x;
  100983. unsigned i, skip;
  100984. /* skip the version and flags bytes */
  100985. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100986. return false; /* read_callback_ sets the state for us */
  100987. /* get the size (in bytes) to skip */
  100988. skip = 0;
  100989. for(i = 0; i < 4; i++) {
  100990. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100991. return false; /* read_callback_ sets the state for us */
  100992. skip <<= 7;
  100993. skip |= (x & 0x7f);
  100994. }
  100995. /* skip the rest of the tag */
  100996. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100997. return false; /* read_callback_ sets the state for us */
  100998. return true;
  100999. }
  101000. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  101001. {
  101002. FLAC__uint32 x;
  101003. FLAC__bool first = true;
  101004. /* If we know the total number of samples in the stream, stop if we've read that many. */
  101005. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  101006. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  101007. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  101008. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101009. return true;
  101010. }
  101011. }
  101012. /* make sure we're byte aligned */
  101013. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101014. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101015. return false; /* read_callback_ sets the state for us */
  101016. }
  101017. while(1) {
  101018. if(decoder->private_->cached) {
  101019. x = (FLAC__uint32)decoder->private_->lookahead;
  101020. decoder->private_->cached = false;
  101021. }
  101022. else {
  101023. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101024. return false; /* read_callback_ sets the state for us */
  101025. }
  101026. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101027. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  101028. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101029. return false; /* read_callback_ sets the state for us */
  101030. /* 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 */
  101031. /* else we have to check if the second byte is the end of a sync code */
  101032. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101033. decoder->private_->lookahead = (FLAC__byte)x;
  101034. decoder->private_->cached = true;
  101035. }
  101036. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  101037. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  101038. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  101039. return true;
  101040. }
  101041. }
  101042. if(first) {
  101043. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101044. first = false;
  101045. }
  101046. }
  101047. return true;
  101048. }
  101049. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  101050. {
  101051. unsigned channel;
  101052. unsigned i;
  101053. FLAC__int32 mid, side;
  101054. unsigned frame_crc; /* the one we calculate from the input stream */
  101055. FLAC__uint32 x;
  101056. *got_a_frame = false;
  101057. /* init the CRC */
  101058. frame_crc = 0;
  101059. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  101060. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  101061. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  101062. if(!read_frame_header_(decoder))
  101063. return false;
  101064. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  101065. return true;
  101066. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  101067. return false;
  101068. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101069. /*
  101070. * first figure the correct bits-per-sample of the subframe
  101071. */
  101072. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  101073. switch(decoder->private_->frame.header.channel_assignment) {
  101074. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101075. /* no adjustment needed */
  101076. break;
  101077. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101078. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101079. if(channel == 1)
  101080. bps++;
  101081. break;
  101082. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101083. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101084. if(channel == 0)
  101085. bps++;
  101086. break;
  101087. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101088. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101089. if(channel == 1)
  101090. bps++;
  101091. break;
  101092. default:
  101093. FLAC__ASSERT(0);
  101094. }
  101095. /*
  101096. * now read it
  101097. */
  101098. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  101099. return false;
  101100. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101101. return true;
  101102. }
  101103. if(!read_zero_padding_(decoder))
  101104. return false;
  101105. 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) */
  101106. return true;
  101107. /*
  101108. * Read the frame CRC-16 from the footer and check
  101109. */
  101110. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  101111. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  101112. return false; /* read_callback_ sets the state for us */
  101113. if(frame_crc == x) {
  101114. if(do_full_decode) {
  101115. /* Undo any special channel coding */
  101116. switch(decoder->private_->frame.header.channel_assignment) {
  101117. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101118. /* do nothing */
  101119. break;
  101120. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101121. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101122. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101123. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  101124. break;
  101125. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101126. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101127. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101128. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  101129. break;
  101130. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101131. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101132. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101133. #if 1
  101134. mid = decoder->private_->output[0][i];
  101135. side = decoder->private_->output[1][i];
  101136. mid <<= 1;
  101137. mid |= (side & 1); /* i.e. if 'side' is odd... */
  101138. decoder->private_->output[0][i] = (mid + side) >> 1;
  101139. decoder->private_->output[1][i] = (mid - side) >> 1;
  101140. #else
  101141. /* OPT: without 'side' temp variable */
  101142. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  101143. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  101144. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  101145. #endif
  101146. }
  101147. break;
  101148. default:
  101149. FLAC__ASSERT(0);
  101150. break;
  101151. }
  101152. }
  101153. }
  101154. else {
  101155. /* Bad frame, emit error and zero the output signal */
  101156. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  101157. if(do_full_decode) {
  101158. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101159. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101160. }
  101161. }
  101162. }
  101163. *got_a_frame = true;
  101164. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  101165. if(decoder->private_->next_fixed_block_size)
  101166. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  101167. /* put the latest values into the public section of the decoder instance */
  101168. decoder->protected_->channels = decoder->private_->frame.header.channels;
  101169. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  101170. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  101171. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  101172. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  101173. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101174. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101175. /* write it */
  101176. if(do_full_decode) {
  101177. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101178. return false;
  101179. }
  101180. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101181. return true;
  101182. }
  101183. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101184. {
  101185. FLAC__uint32 x;
  101186. FLAC__uint64 xx;
  101187. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101188. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101189. unsigned raw_header_len;
  101190. FLAC__bool is_unparseable = false;
  101191. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101192. /* init the raw header with the saved bits from synchronization */
  101193. raw_header[0] = decoder->private_->header_warmup[0];
  101194. raw_header[1] = decoder->private_->header_warmup[1];
  101195. raw_header_len = 2;
  101196. /* check to make sure that reserved bit is 0 */
  101197. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101198. is_unparseable = true;
  101199. /*
  101200. * Note that along the way as we read the header, we look for a sync
  101201. * code inside. If we find one it would indicate that our original
  101202. * sync was bad since there cannot be a sync code in a valid header.
  101203. *
  101204. * Three kinds of things can go wrong when reading the frame header:
  101205. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101206. * If we don't find a sync code, it can end up looking like we read
  101207. * a valid but unparseable header, until getting to the frame header
  101208. * CRC. Even then we could get a false positive on the CRC.
  101209. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101210. * future encoder).
  101211. * 3) We may be on a damaged frame which appears valid but unparseable.
  101212. *
  101213. * For all these reasons, we try and read a complete frame header as
  101214. * long as it seems valid, even if unparseable, up until the frame
  101215. * header CRC.
  101216. */
  101217. /*
  101218. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101219. */
  101220. for(i = 0; i < 2; i++) {
  101221. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101222. return false; /* read_callback_ sets the state for us */
  101223. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101224. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101225. decoder->private_->lookahead = (FLAC__byte)x;
  101226. decoder->private_->cached = true;
  101227. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101228. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101229. return true;
  101230. }
  101231. raw_header[raw_header_len++] = (FLAC__byte)x;
  101232. }
  101233. switch(x = raw_header[2] >> 4) {
  101234. case 0:
  101235. is_unparseable = true;
  101236. break;
  101237. case 1:
  101238. decoder->private_->frame.header.blocksize = 192;
  101239. break;
  101240. case 2:
  101241. case 3:
  101242. case 4:
  101243. case 5:
  101244. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101245. break;
  101246. case 6:
  101247. case 7:
  101248. blocksize_hint = x;
  101249. break;
  101250. case 8:
  101251. case 9:
  101252. case 10:
  101253. case 11:
  101254. case 12:
  101255. case 13:
  101256. case 14:
  101257. case 15:
  101258. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101259. break;
  101260. default:
  101261. FLAC__ASSERT(0);
  101262. break;
  101263. }
  101264. switch(x = raw_header[2] & 0x0f) {
  101265. case 0:
  101266. if(decoder->private_->has_stream_info)
  101267. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101268. else
  101269. is_unparseable = true;
  101270. break;
  101271. case 1:
  101272. decoder->private_->frame.header.sample_rate = 88200;
  101273. break;
  101274. case 2:
  101275. decoder->private_->frame.header.sample_rate = 176400;
  101276. break;
  101277. case 3:
  101278. decoder->private_->frame.header.sample_rate = 192000;
  101279. break;
  101280. case 4:
  101281. decoder->private_->frame.header.sample_rate = 8000;
  101282. break;
  101283. case 5:
  101284. decoder->private_->frame.header.sample_rate = 16000;
  101285. break;
  101286. case 6:
  101287. decoder->private_->frame.header.sample_rate = 22050;
  101288. break;
  101289. case 7:
  101290. decoder->private_->frame.header.sample_rate = 24000;
  101291. break;
  101292. case 8:
  101293. decoder->private_->frame.header.sample_rate = 32000;
  101294. break;
  101295. case 9:
  101296. decoder->private_->frame.header.sample_rate = 44100;
  101297. break;
  101298. case 10:
  101299. decoder->private_->frame.header.sample_rate = 48000;
  101300. break;
  101301. case 11:
  101302. decoder->private_->frame.header.sample_rate = 96000;
  101303. break;
  101304. case 12:
  101305. case 13:
  101306. case 14:
  101307. sample_rate_hint = x;
  101308. break;
  101309. case 15:
  101310. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101311. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101312. return true;
  101313. default:
  101314. FLAC__ASSERT(0);
  101315. }
  101316. x = (unsigned)(raw_header[3] >> 4);
  101317. if(x & 8) {
  101318. decoder->private_->frame.header.channels = 2;
  101319. switch(x & 7) {
  101320. case 0:
  101321. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101322. break;
  101323. case 1:
  101324. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101325. break;
  101326. case 2:
  101327. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101328. break;
  101329. default:
  101330. is_unparseable = true;
  101331. break;
  101332. }
  101333. }
  101334. else {
  101335. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101336. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101337. }
  101338. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101339. case 0:
  101340. if(decoder->private_->has_stream_info)
  101341. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101342. else
  101343. is_unparseable = true;
  101344. break;
  101345. case 1:
  101346. decoder->private_->frame.header.bits_per_sample = 8;
  101347. break;
  101348. case 2:
  101349. decoder->private_->frame.header.bits_per_sample = 12;
  101350. break;
  101351. case 4:
  101352. decoder->private_->frame.header.bits_per_sample = 16;
  101353. break;
  101354. case 5:
  101355. decoder->private_->frame.header.bits_per_sample = 20;
  101356. break;
  101357. case 6:
  101358. decoder->private_->frame.header.bits_per_sample = 24;
  101359. break;
  101360. case 3:
  101361. case 7:
  101362. is_unparseable = true;
  101363. break;
  101364. default:
  101365. FLAC__ASSERT(0);
  101366. break;
  101367. }
  101368. /* check to make sure that reserved bit is 0 */
  101369. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101370. is_unparseable = true;
  101371. /* read the frame's starting sample number (or frame number as the case may be) */
  101372. if(
  101373. raw_header[1] & 0x01 ||
  101374. /*@@@ 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 */
  101375. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101376. ) { /* variable blocksize */
  101377. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101378. return false; /* read_callback_ sets the state for us */
  101379. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101380. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101381. decoder->private_->cached = true;
  101382. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101383. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101384. return true;
  101385. }
  101386. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101387. decoder->private_->frame.header.number.sample_number = xx;
  101388. }
  101389. else { /* fixed blocksize */
  101390. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101391. return false; /* read_callback_ sets the state for us */
  101392. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101393. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101394. decoder->private_->cached = true;
  101395. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101396. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101397. return true;
  101398. }
  101399. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101400. decoder->private_->frame.header.number.frame_number = x;
  101401. }
  101402. if(blocksize_hint) {
  101403. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101404. return false; /* read_callback_ sets the state for us */
  101405. raw_header[raw_header_len++] = (FLAC__byte)x;
  101406. if(blocksize_hint == 7) {
  101407. FLAC__uint32 _x;
  101408. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101409. return false; /* read_callback_ sets the state for us */
  101410. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101411. x = (x << 8) | _x;
  101412. }
  101413. decoder->private_->frame.header.blocksize = x+1;
  101414. }
  101415. if(sample_rate_hint) {
  101416. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101417. return false; /* read_callback_ sets the state for us */
  101418. raw_header[raw_header_len++] = (FLAC__byte)x;
  101419. if(sample_rate_hint != 12) {
  101420. FLAC__uint32 _x;
  101421. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101422. return false; /* read_callback_ sets the state for us */
  101423. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101424. x = (x << 8) | _x;
  101425. }
  101426. if(sample_rate_hint == 12)
  101427. decoder->private_->frame.header.sample_rate = x*1000;
  101428. else if(sample_rate_hint == 13)
  101429. decoder->private_->frame.header.sample_rate = x;
  101430. else
  101431. decoder->private_->frame.header.sample_rate = x*10;
  101432. }
  101433. /* read the CRC-8 byte */
  101434. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101435. return false; /* read_callback_ sets the state for us */
  101436. crc8 = (FLAC__byte)x;
  101437. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101438. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101439. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101440. return true;
  101441. }
  101442. /* calculate the sample number from the frame number if needed */
  101443. decoder->private_->next_fixed_block_size = 0;
  101444. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101445. x = decoder->private_->frame.header.number.frame_number;
  101446. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101447. if(decoder->private_->fixed_block_size)
  101448. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101449. else if(decoder->private_->has_stream_info) {
  101450. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101451. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101452. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101453. }
  101454. else
  101455. is_unparseable = true;
  101456. }
  101457. else if(x == 0) {
  101458. decoder->private_->frame.header.number.sample_number = 0;
  101459. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101460. }
  101461. else {
  101462. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101463. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101464. }
  101465. }
  101466. if(is_unparseable) {
  101467. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101468. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101469. return true;
  101470. }
  101471. return true;
  101472. }
  101473. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101474. {
  101475. FLAC__uint32 x;
  101476. FLAC__bool wasted_bits;
  101477. unsigned i;
  101478. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101479. return false; /* read_callback_ sets the state for us */
  101480. wasted_bits = (x & 1);
  101481. x &= 0xfe;
  101482. if(wasted_bits) {
  101483. unsigned u;
  101484. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101485. return false; /* read_callback_ sets the state for us */
  101486. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101487. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101488. }
  101489. else
  101490. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101491. /*
  101492. * Lots of magic numbers here
  101493. */
  101494. if(x & 0x80) {
  101495. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101496. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101497. return true;
  101498. }
  101499. else if(x == 0) {
  101500. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101501. return false;
  101502. }
  101503. else if(x == 2) {
  101504. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101505. return false;
  101506. }
  101507. else if(x < 16) {
  101508. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101509. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101510. return true;
  101511. }
  101512. else if(x <= 24) {
  101513. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101514. return false;
  101515. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101516. return true;
  101517. }
  101518. else if(x < 64) {
  101519. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101520. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101521. return true;
  101522. }
  101523. else {
  101524. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101525. return false;
  101526. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101527. return true;
  101528. }
  101529. if(wasted_bits && do_full_decode) {
  101530. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101531. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101532. decoder->private_->output[channel][i] <<= x;
  101533. }
  101534. return true;
  101535. }
  101536. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101537. {
  101538. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101539. FLAC__int32 x;
  101540. unsigned i;
  101541. FLAC__int32 *output = decoder->private_->output[channel];
  101542. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101543. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101544. return false; /* read_callback_ sets the state for us */
  101545. subframe->value = x;
  101546. /* decode the subframe */
  101547. if(do_full_decode) {
  101548. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101549. output[i] = x;
  101550. }
  101551. return true;
  101552. }
  101553. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101554. {
  101555. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101556. FLAC__int32 i32;
  101557. FLAC__uint32 u32;
  101558. unsigned u;
  101559. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101560. subframe->residual = decoder->private_->residual[channel];
  101561. subframe->order = order;
  101562. /* read warm-up samples */
  101563. for(u = 0; u < order; u++) {
  101564. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101565. return false; /* read_callback_ sets the state for us */
  101566. subframe->warmup[u] = i32;
  101567. }
  101568. /* read entropy coding method info */
  101569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101570. return false; /* read_callback_ sets the state for us */
  101571. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101572. switch(subframe->entropy_coding_method.type) {
  101573. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101574. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101575. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101576. return false; /* read_callback_ sets the state for us */
  101577. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101578. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101579. break;
  101580. default:
  101581. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101582. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101583. return true;
  101584. }
  101585. /* read residual */
  101586. switch(subframe->entropy_coding_method.type) {
  101587. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101588. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101589. 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))
  101590. return false;
  101591. break;
  101592. default:
  101593. FLAC__ASSERT(0);
  101594. }
  101595. /* decode the subframe */
  101596. if(do_full_decode) {
  101597. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101598. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101599. }
  101600. return true;
  101601. }
  101602. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101603. {
  101604. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101605. FLAC__int32 i32;
  101606. FLAC__uint32 u32;
  101607. unsigned u;
  101608. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101609. subframe->residual = decoder->private_->residual[channel];
  101610. subframe->order = order;
  101611. /* read warm-up samples */
  101612. for(u = 0; u < order; u++) {
  101613. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101614. return false; /* read_callback_ sets the state for us */
  101615. subframe->warmup[u] = i32;
  101616. }
  101617. /* read qlp coeff precision */
  101618. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101619. return false; /* read_callback_ sets the state for us */
  101620. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101621. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101622. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101623. return true;
  101624. }
  101625. subframe->qlp_coeff_precision = u32+1;
  101626. /* read qlp shift */
  101627. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101628. return false; /* read_callback_ sets the state for us */
  101629. subframe->quantization_level = i32;
  101630. /* read quantized lp coefficiencts */
  101631. for(u = 0; u < order; u++) {
  101632. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101633. return false; /* read_callback_ sets the state for us */
  101634. subframe->qlp_coeff[u] = i32;
  101635. }
  101636. /* read entropy coding method info */
  101637. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101638. return false; /* read_callback_ sets the state for us */
  101639. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101640. switch(subframe->entropy_coding_method.type) {
  101641. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101642. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101643. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101644. return false; /* read_callback_ sets the state for us */
  101645. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101646. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101647. break;
  101648. default:
  101649. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101650. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101651. return true;
  101652. }
  101653. /* read residual */
  101654. switch(subframe->entropy_coding_method.type) {
  101655. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101656. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101657. 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))
  101658. return false;
  101659. break;
  101660. default:
  101661. FLAC__ASSERT(0);
  101662. }
  101663. /* decode the subframe */
  101664. if(do_full_decode) {
  101665. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101666. /*@@@@@@ technically not pessimistic enough, should be more like
  101667. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101668. */
  101669. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101670. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101671. if(order <= 8)
  101672. 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);
  101673. else
  101674. 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);
  101675. }
  101676. else
  101677. 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);
  101678. else
  101679. 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);
  101680. }
  101681. return true;
  101682. }
  101683. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101684. {
  101685. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101686. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101687. unsigned i;
  101688. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101689. subframe->data = residual;
  101690. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101691. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101692. return false; /* read_callback_ sets the state for us */
  101693. residual[i] = x;
  101694. }
  101695. /* decode the subframe */
  101696. if(do_full_decode)
  101697. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101698. return true;
  101699. }
  101700. 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)
  101701. {
  101702. FLAC__uint32 rice_parameter;
  101703. int i;
  101704. unsigned partition, sample, u;
  101705. const unsigned partitions = 1u << partition_order;
  101706. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101707. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101708. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101709. /* sanity checks */
  101710. if(partition_order == 0) {
  101711. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101712. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101713. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101714. return true;
  101715. }
  101716. }
  101717. else {
  101718. if(partition_samples < predictor_order) {
  101719. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101720. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101721. return true;
  101722. }
  101723. }
  101724. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101725. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101726. return false;
  101727. }
  101728. sample = 0;
  101729. for(partition = 0; partition < partitions; partition++) {
  101730. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101731. return false; /* read_callback_ sets the state for us */
  101732. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101733. if(rice_parameter < pesc) {
  101734. partitioned_rice_contents->raw_bits[partition] = 0;
  101735. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101736. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101737. return false; /* read_callback_ sets the state for us */
  101738. sample += u;
  101739. }
  101740. else {
  101741. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101742. return false; /* read_callback_ sets the state for us */
  101743. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101744. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101745. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101746. return false; /* read_callback_ sets the state for us */
  101747. residual[sample] = i;
  101748. }
  101749. }
  101750. }
  101751. return true;
  101752. }
  101753. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101754. {
  101755. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101756. FLAC__uint32 zero = 0;
  101757. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101758. return false; /* read_callback_ sets the state for us */
  101759. if(zero != 0) {
  101760. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101761. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101762. }
  101763. }
  101764. return true;
  101765. }
  101766. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101767. {
  101768. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101769. if(
  101770. #if FLAC__HAS_OGG
  101771. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101772. !decoder->private_->is_ogg &&
  101773. #endif
  101774. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101775. ) {
  101776. *bytes = 0;
  101777. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101778. return false;
  101779. }
  101780. else if(*bytes > 0) {
  101781. /* While seeking, it is possible for our seek to land in the
  101782. * middle of audio data that looks exactly like a frame header
  101783. * from a future version of an encoder. When that happens, our
  101784. * error callback will get an
  101785. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101786. * unparseable_frame_count. But there is a remote possibility
  101787. * that it is properly synced at such a "future-codec frame",
  101788. * so to make sure, we wait to see many "unparseable" errors in
  101789. * a row before bailing out.
  101790. */
  101791. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101792. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101793. return false;
  101794. }
  101795. else {
  101796. const FLAC__StreamDecoderReadStatus status =
  101797. #if FLAC__HAS_OGG
  101798. decoder->private_->is_ogg?
  101799. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101800. #endif
  101801. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101802. ;
  101803. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101804. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101805. return false;
  101806. }
  101807. else if(*bytes == 0) {
  101808. if(
  101809. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101810. (
  101811. #if FLAC__HAS_OGG
  101812. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101813. !decoder->private_->is_ogg &&
  101814. #endif
  101815. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101816. )
  101817. ) {
  101818. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101819. return false;
  101820. }
  101821. else
  101822. return true;
  101823. }
  101824. else
  101825. return true;
  101826. }
  101827. }
  101828. else {
  101829. /* abort to avoid a deadlock */
  101830. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101831. return false;
  101832. }
  101833. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101834. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101835. * and at the same time hit the end of the stream (for example, seeking
  101836. * to a point that is after the beginning of the last Ogg page). There
  101837. * is no way to report an Ogg sync loss through the callbacks (see note
  101838. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101839. * So to keep the decoder from stopping at this point we gate the call
  101840. * to the eof_callback and let the Ogg decoder aspect set the
  101841. * end-of-stream state when it is needed.
  101842. */
  101843. }
  101844. #if FLAC__HAS_OGG
  101845. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101846. {
  101847. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101848. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101849. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101850. /* we don't really have a way to handle lost sync via read
  101851. * callback so we'll let it pass and let the underlying
  101852. * FLAC decoder catch the error
  101853. */
  101854. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101855. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101856. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101857. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101858. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101859. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101860. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101861. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101862. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101863. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101864. default:
  101865. FLAC__ASSERT(0);
  101866. /* double protection */
  101867. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101868. }
  101869. }
  101870. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101871. {
  101872. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101873. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101874. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101875. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101876. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101877. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101878. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101879. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101880. default:
  101881. /* double protection: */
  101882. FLAC__ASSERT(0);
  101883. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101884. }
  101885. }
  101886. #endif
  101887. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101888. {
  101889. if(decoder->private_->is_seeking) {
  101890. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101891. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101892. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101893. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101894. #if FLAC__HAS_OGG
  101895. decoder->private_->got_a_frame = true;
  101896. #endif
  101897. decoder->private_->last_frame = *frame; /* save the frame */
  101898. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101899. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101900. /* kick out of seek mode */
  101901. decoder->private_->is_seeking = false;
  101902. /* shift out the samples before target_sample */
  101903. if(delta > 0) {
  101904. unsigned channel;
  101905. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101906. for(channel = 0; channel < frame->header.channels; channel++)
  101907. newbuffer[channel] = buffer[channel] + delta;
  101908. decoder->private_->last_frame.header.blocksize -= delta;
  101909. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101910. /* write the relevant samples */
  101911. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101912. }
  101913. else {
  101914. /* write the relevant samples */
  101915. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101916. }
  101917. }
  101918. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101919. }
  101920. /*
  101921. * If we never got STREAMINFO, turn off MD5 checking to save
  101922. * cycles since we don't have a sum to compare to anyway
  101923. */
  101924. if(!decoder->private_->has_stream_info)
  101925. decoder->private_->do_md5_checking = false;
  101926. if(decoder->private_->do_md5_checking) {
  101927. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101928. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101929. }
  101930. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101931. }
  101932. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101933. {
  101934. if(!decoder->private_->is_seeking)
  101935. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101936. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101937. decoder->private_->unparseable_frame_count++;
  101938. }
  101939. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101940. {
  101941. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101942. FLAC__int64 pos = -1;
  101943. int i;
  101944. unsigned approx_bytes_per_frame;
  101945. FLAC__bool first_seek = true;
  101946. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101947. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101948. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101949. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101950. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101951. /* take these from the current frame in case they've changed mid-stream */
  101952. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101953. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101954. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101955. /* use values from stream info if we didn't decode a frame */
  101956. if(channels == 0)
  101957. channels = decoder->private_->stream_info.data.stream_info.channels;
  101958. if(bps == 0)
  101959. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101960. /* we are just guessing here */
  101961. if(max_framesize > 0)
  101962. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101963. /*
  101964. * Check if it's a known fixed-blocksize stream. Note that though
  101965. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101966. * never get a STREAMINFO block when decoding so the value of
  101967. * min_blocksize might be zero.
  101968. */
  101969. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101970. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101971. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101972. }
  101973. else
  101974. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101975. /*
  101976. * First, we set an upper and lower bound on where in the
  101977. * stream we will search. For now we assume the worst case
  101978. * scenario, which is our best guess at the beginning of
  101979. * the first frame and end of the stream.
  101980. */
  101981. lower_bound = first_frame_offset;
  101982. lower_bound_sample = 0;
  101983. upper_bound = stream_length;
  101984. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101985. /*
  101986. * Now we refine the bounds if we have a seektable with
  101987. * suitable points. Note that according to the spec they
  101988. * must be ordered by ascending sample number.
  101989. *
  101990. * Note: to protect against invalid seek tables we will ignore points
  101991. * that have frame_samples==0 or sample_number>=total_samples
  101992. */
  101993. if(seek_table) {
  101994. FLAC__uint64 new_lower_bound = lower_bound;
  101995. FLAC__uint64 new_upper_bound = upper_bound;
  101996. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101997. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101998. /* find the closest seek point <= target_sample, if it exists */
  101999. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  102000. if(
  102001. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  102002. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  102003. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  102004. seek_table->points[i].sample_number <= target_sample
  102005. )
  102006. break;
  102007. }
  102008. if(i >= 0) { /* i.e. we found a suitable seek point... */
  102009. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  102010. new_lower_bound_sample = seek_table->points[i].sample_number;
  102011. }
  102012. /* find the closest seek point > target_sample, if it exists */
  102013. for(i = 0; i < (int)seek_table->num_points; i++) {
  102014. if(
  102015. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  102016. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  102017. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  102018. seek_table->points[i].sample_number > target_sample
  102019. )
  102020. break;
  102021. }
  102022. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  102023. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  102024. new_upper_bound_sample = seek_table->points[i].sample_number;
  102025. }
  102026. /* final protection against unsorted seek tables; keep original values if bogus */
  102027. if(new_upper_bound >= new_lower_bound) {
  102028. lower_bound = new_lower_bound;
  102029. upper_bound = new_upper_bound;
  102030. lower_bound_sample = new_lower_bound_sample;
  102031. upper_bound_sample = new_upper_bound_sample;
  102032. }
  102033. }
  102034. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  102035. /* there are 2 insidious ways that the following equality occurs, which
  102036. * we need to fix:
  102037. * 1) total_samples is 0 (unknown) and target_sample is 0
  102038. * 2) total_samples is 0 (unknown) and target_sample happens to be
  102039. * exactly equal to the last seek point in the seek table; this
  102040. * means there is no seek point above it, and upper_bound_samples
  102041. * remains equal to the estimate (of target_samples) we made above
  102042. * in either case it does not hurt to move upper_bound_sample up by 1
  102043. */
  102044. if(upper_bound_sample == lower_bound_sample)
  102045. upper_bound_sample++;
  102046. decoder->private_->target_sample = target_sample;
  102047. while(1) {
  102048. /* check if the bounds are still ok */
  102049. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  102050. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102051. return false;
  102052. }
  102053. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102054. #if defined _MSC_VER || defined __MINGW32__
  102055. /* with VC++ you have to spoon feed it the casting */
  102056. 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;
  102057. #else
  102058. 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;
  102059. #endif
  102060. #else
  102061. /* a little less accurate: */
  102062. if(upper_bound - lower_bound < 0xffffffff)
  102063. 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;
  102064. else /* @@@ WATCHOUT, ~2TB limit */
  102065. 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;
  102066. #endif
  102067. if(pos >= (FLAC__int64)upper_bound)
  102068. pos = (FLAC__int64)upper_bound - 1;
  102069. if(pos < (FLAC__int64)lower_bound)
  102070. pos = (FLAC__int64)lower_bound;
  102071. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102072. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102073. return false;
  102074. }
  102075. if(!FLAC__stream_decoder_flush(decoder)) {
  102076. /* above call sets the state for us */
  102077. return false;
  102078. }
  102079. /* Now we need to get a frame. First we need to reset our
  102080. * unparseable_frame_count; if we get too many unparseable
  102081. * frames in a row, the read callback will return
  102082. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  102083. * FLAC__stream_decoder_process_single() to return false.
  102084. */
  102085. decoder->private_->unparseable_frame_count = 0;
  102086. if(!FLAC__stream_decoder_process_single(decoder)) {
  102087. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102088. return false;
  102089. }
  102090. /* our write callback will change the state when it gets to the target frame */
  102091. /* 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 */
  102092. #if 0
  102093. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  102094. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  102095. break;
  102096. #endif
  102097. if(!decoder->private_->is_seeking)
  102098. break;
  102099. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102100. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102101. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  102102. if (pos == (FLAC__int64)lower_bound) {
  102103. /* can't move back any more than the first frame, something is fatally wrong */
  102104. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102105. return false;
  102106. }
  102107. /* our last move backwards wasn't big enough, try again */
  102108. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  102109. continue;
  102110. }
  102111. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  102112. first_seek = false;
  102113. /* make sure we are not seeking in corrupted stream */
  102114. if (this_frame_sample < lower_bound_sample) {
  102115. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102116. return false;
  102117. }
  102118. /* we need to narrow the search */
  102119. if(target_sample < this_frame_sample) {
  102120. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102121. /*@@@@@@ what will decode position be if at end of stream? */
  102122. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  102123. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102124. return false;
  102125. }
  102126. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  102127. }
  102128. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  102129. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102130. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  102131. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102132. return false;
  102133. }
  102134. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  102135. }
  102136. }
  102137. return true;
  102138. }
  102139. #if FLAC__HAS_OGG
  102140. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  102141. {
  102142. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  102143. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  102144. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  102145. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  102146. FLAC__bool did_a_seek;
  102147. unsigned iteration = 0;
  102148. /* In the first iterations, we will calculate the target byte position
  102149. * by the distance from the target sample to left_sample and
  102150. * right_sample (let's call it "proportional search"). After that, we
  102151. * will switch to binary search.
  102152. */
  102153. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  102154. /* We will switch to a linear search once our current sample is less
  102155. * than this number of samples ahead of the target sample
  102156. */
  102157. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  102158. /* If the total number of samples is unknown, use a large value, and
  102159. * force binary search immediately.
  102160. */
  102161. if(right_sample == 0) {
  102162. right_sample = (FLAC__uint64)(-1);
  102163. BINARY_SEARCH_AFTER_ITERATION = 0;
  102164. }
  102165. decoder->private_->target_sample = target_sample;
  102166. for( ; ; iteration++) {
  102167. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  102168. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  102169. pos = (right_pos + left_pos) / 2;
  102170. }
  102171. else {
  102172. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102173. #if defined _MSC_VER || defined __MINGW32__
  102174. /* with MSVC you have to spoon feed it the casting */
  102175. 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));
  102176. #else
  102177. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102178. #endif
  102179. #else
  102180. /* a little less accurate: */
  102181. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102182. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102183. else /* @@@ WATCHOUT, ~2TB limit */
  102184. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102185. #endif
  102186. /* @@@ TODO: might want to limit pos to some distance
  102187. * before EOF, to make sure we land before the last frame,
  102188. * thereby getting a this_frame_sample and so having a better
  102189. * estimate.
  102190. */
  102191. }
  102192. /* physical seek */
  102193. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102194. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102195. return false;
  102196. }
  102197. if(!FLAC__stream_decoder_flush(decoder)) {
  102198. /* above call sets the state for us */
  102199. return false;
  102200. }
  102201. did_a_seek = true;
  102202. }
  102203. else
  102204. did_a_seek = false;
  102205. decoder->private_->got_a_frame = false;
  102206. if(!FLAC__stream_decoder_process_single(decoder)) {
  102207. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102208. return false;
  102209. }
  102210. if(!decoder->private_->got_a_frame) {
  102211. if(did_a_seek) {
  102212. /* this can happen if we seek to a point after the last frame; we drop
  102213. * to binary search right away in this case to avoid any wasted
  102214. * iterations of proportional search.
  102215. */
  102216. right_pos = pos;
  102217. BINARY_SEARCH_AFTER_ITERATION = 0;
  102218. }
  102219. else {
  102220. /* this can probably only happen if total_samples is unknown and the
  102221. * target_sample is past the end of the stream
  102222. */
  102223. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102224. return false;
  102225. }
  102226. }
  102227. /* our write callback will change the state when it gets to the target frame */
  102228. else if(!decoder->private_->is_seeking) {
  102229. break;
  102230. }
  102231. else {
  102232. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102233. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102234. if (did_a_seek) {
  102235. if (this_frame_sample <= target_sample) {
  102236. /* The 'equal' case should not happen, since
  102237. * FLAC__stream_decoder_process_single()
  102238. * should recognize that it has hit the
  102239. * target sample and we would exit through
  102240. * the 'break' above.
  102241. */
  102242. FLAC__ASSERT(this_frame_sample != target_sample);
  102243. left_sample = this_frame_sample;
  102244. /* sanity check to avoid infinite loop */
  102245. if (left_pos == pos) {
  102246. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102247. return false;
  102248. }
  102249. left_pos = pos;
  102250. }
  102251. else if(this_frame_sample > target_sample) {
  102252. right_sample = this_frame_sample;
  102253. /* sanity check to avoid infinite loop */
  102254. if (right_pos == pos) {
  102255. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102256. return false;
  102257. }
  102258. right_pos = pos;
  102259. }
  102260. }
  102261. }
  102262. }
  102263. return true;
  102264. }
  102265. #endif
  102266. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102267. {
  102268. (void)client_data;
  102269. if(*bytes > 0) {
  102270. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102271. if(ferror(decoder->private_->file))
  102272. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102273. else if(*bytes == 0)
  102274. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102275. else
  102276. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102277. }
  102278. else
  102279. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102280. }
  102281. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102282. {
  102283. (void)client_data;
  102284. if(decoder->private_->file == stdin)
  102285. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102286. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102287. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102288. else
  102289. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102290. }
  102291. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102292. {
  102293. off_t pos;
  102294. (void)client_data;
  102295. if(decoder->private_->file == stdin)
  102296. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102297. else if((pos = ftello(decoder->private_->file)) < 0)
  102298. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102299. else {
  102300. *absolute_byte_offset = (FLAC__uint64)pos;
  102301. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102302. }
  102303. }
  102304. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102305. {
  102306. struct stat filestats;
  102307. (void)client_data;
  102308. if(decoder->private_->file == stdin)
  102309. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102310. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102311. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102312. else {
  102313. *stream_length = (FLAC__uint64)filestats.st_size;
  102314. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102315. }
  102316. }
  102317. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102318. {
  102319. (void)client_data;
  102320. return feof(decoder->private_->file)? true : false;
  102321. }
  102322. #endif
  102323. /*** End of inlined file: stream_decoder.c ***/
  102324. /*** Start of inlined file: stream_encoder.c ***/
  102325. /*** Start of inlined file: juce_FlacHeader.h ***/
  102326. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102327. // tasks..
  102328. #define VERSION "1.2.1"
  102329. #define FLAC__NO_DLL 1
  102330. #if JUCE_MSVC
  102331. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102332. #endif
  102333. #if JUCE_MAC
  102334. #define FLAC__SYS_DARWIN 1
  102335. #endif
  102336. /*** End of inlined file: juce_FlacHeader.h ***/
  102337. #if JUCE_USE_FLAC
  102338. #if HAVE_CONFIG_H
  102339. # include <config.h>
  102340. #endif
  102341. #if defined _MSC_VER || defined __MINGW32__
  102342. #include <io.h> /* for _setmode() */
  102343. #include <fcntl.h> /* for _O_BINARY */
  102344. #endif
  102345. #if defined __CYGWIN__ || defined __EMX__
  102346. #include <io.h> /* for setmode(), O_BINARY */
  102347. #include <fcntl.h> /* for _O_BINARY */
  102348. #endif
  102349. #include <limits.h>
  102350. #include <stdio.h>
  102351. #include <stdlib.h> /* for malloc() */
  102352. #include <string.h> /* for memcpy() */
  102353. #include <sys/types.h> /* for off_t */
  102354. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102355. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102356. #define fseeko fseek
  102357. #define ftello ftell
  102358. #endif
  102359. #endif
  102360. /*** Start of inlined file: stream_encoder.h ***/
  102361. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102362. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102363. #if FLAC__HAS_OGG
  102364. #include "private/ogg_encoder_aspect.h"
  102365. #endif
  102366. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102367. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102368. typedef enum {
  102369. FLAC__APODIZATION_BARTLETT,
  102370. FLAC__APODIZATION_BARTLETT_HANN,
  102371. FLAC__APODIZATION_BLACKMAN,
  102372. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102373. FLAC__APODIZATION_CONNES,
  102374. FLAC__APODIZATION_FLATTOP,
  102375. FLAC__APODIZATION_GAUSS,
  102376. FLAC__APODIZATION_HAMMING,
  102377. FLAC__APODIZATION_HANN,
  102378. FLAC__APODIZATION_KAISER_BESSEL,
  102379. FLAC__APODIZATION_NUTTALL,
  102380. FLAC__APODIZATION_RECTANGLE,
  102381. FLAC__APODIZATION_TRIANGLE,
  102382. FLAC__APODIZATION_TUKEY,
  102383. FLAC__APODIZATION_WELCH
  102384. } FLAC__ApodizationFunction;
  102385. typedef struct {
  102386. FLAC__ApodizationFunction type;
  102387. union {
  102388. struct {
  102389. FLAC__real stddev;
  102390. } gauss;
  102391. struct {
  102392. FLAC__real p;
  102393. } tukey;
  102394. } parameters;
  102395. } FLAC__ApodizationSpecification;
  102396. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102397. typedef struct FLAC__StreamEncoderProtected {
  102398. FLAC__StreamEncoderState state;
  102399. FLAC__bool verify;
  102400. FLAC__bool streamable_subset;
  102401. FLAC__bool do_md5;
  102402. FLAC__bool do_mid_side_stereo;
  102403. FLAC__bool loose_mid_side_stereo;
  102404. unsigned channels;
  102405. unsigned bits_per_sample;
  102406. unsigned sample_rate;
  102407. unsigned blocksize;
  102408. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102409. unsigned num_apodizations;
  102410. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102411. #endif
  102412. unsigned max_lpc_order;
  102413. unsigned qlp_coeff_precision;
  102414. FLAC__bool do_qlp_coeff_prec_search;
  102415. FLAC__bool do_exhaustive_model_search;
  102416. FLAC__bool do_escape_coding;
  102417. unsigned min_residual_partition_order;
  102418. unsigned max_residual_partition_order;
  102419. unsigned rice_parameter_search_dist;
  102420. FLAC__uint64 total_samples_estimate;
  102421. FLAC__StreamMetadata **metadata;
  102422. unsigned num_metadata_blocks;
  102423. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102424. #if FLAC__HAS_OGG
  102425. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102426. #endif
  102427. } FLAC__StreamEncoderProtected;
  102428. #endif
  102429. /*** End of inlined file: stream_encoder.h ***/
  102430. #if FLAC__HAS_OGG
  102431. #include "include/private/ogg_helper.h"
  102432. #include "include/private/ogg_mapping.h"
  102433. #endif
  102434. /*** Start of inlined file: stream_encoder_framing.h ***/
  102435. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102436. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102437. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102438. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102439. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102440. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102441. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102442. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102443. #endif
  102444. /*** End of inlined file: stream_encoder_framing.h ***/
  102445. /*** Start of inlined file: window.h ***/
  102446. #ifndef FLAC__PRIVATE__WINDOW_H
  102447. #define FLAC__PRIVATE__WINDOW_H
  102448. #ifdef HAVE_CONFIG_H
  102449. #include <config.h>
  102450. #endif
  102451. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102452. /*
  102453. * FLAC__window_*()
  102454. * --------------------------------------------------------------------
  102455. * Calculates window coefficients according to different apodization
  102456. * functions.
  102457. *
  102458. * OUT window[0,L-1]
  102459. * IN L (number of points in window)
  102460. */
  102461. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102462. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102463. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102464. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102465. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102466. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102467. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102468. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102469. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102470. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102471. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102472. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102473. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102474. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102475. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102476. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102477. #endif
  102478. /*** End of inlined file: window.h ***/
  102479. #ifndef FLaC__INLINE
  102480. #define FLaC__INLINE
  102481. #endif
  102482. #ifdef min
  102483. #undef min
  102484. #endif
  102485. #define min(x,y) ((x)<(y)?(x):(y))
  102486. #ifdef max
  102487. #undef max
  102488. #endif
  102489. #define max(x,y) ((x)>(y)?(x):(y))
  102490. /* Exact Rice codeword length calculation is off by default. The simple
  102491. * (and fast) estimation (of how many bits a residual value will be
  102492. * encoded with) in this encoder is very good, almost always yielding
  102493. * compression within 0.1% of exact calculation.
  102494. */
  102495. #undef EXACT_RICE_BITS_CALCULATION
  102496. /* Rice parameter searching is off by default. The simple (and fast)
  102497. * parameter estimation in this encoder is very good, almost always
  102498. * yielding compression within 0.1% of the optimal parameters.
  102499. */
  102500. #undef ENABLE_RICE_PARAMETER_SEARCH
  102501. typedef struct {
  102502. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102503. unsigned size; /* of each data[] in samples */
  102504. unsigned tail;
  102505. } verify_input_fifo;
  102506. typedef struct {
  102507. const FLAC__byte *data;
  102508. unsigned capacity;
  102509. unsigned bytes;
  102510. } verify_output;
  102511. typedef enum {
  102512. ENCODER_IN_MAGIC = 0,
  102513. ENCODER_IN_METADATA = 1,
  102514. ENCODER_IN_AUDIO = 2
  102515. } EncoderStateHint;
  102516. static struct CompressionLevels {
  102517. FLAC__bool do_mid_side_stereo;
  102518. FLAC__bool loose_mid_side_stereo;
  102519. unsigned max_lpc_order;
  102520. unsigned qlp_coeff_precision;
  102521. FLAC__bool do_qlp_coeff_prec_search;
  102522. FLAC__bool do_escape_coding;
  102523. FLAC__bool do_exhaustive_model_search;
  102524. unsigned min_residual_partition_order;
  102525. unsigned max_residual_partition_order;
  102526. unsigned rice_parameter_search_dist;
  102527. } compression_levels_[] = {
  102528. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102529. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102530. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102531. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102532. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102533. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102534. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102535. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102536. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102537. };
  102538. /***********************************************************************
  102539. *
  102540. * Private class method prototypes
  102541. *
  102542. ***********************************************************************/
  102543. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102544. static void free_(FLAC__StreamEncoder *encoder);
  102545. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102546. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102547. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102548. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102549. #if FLAC__HAS_OGG
  102550. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102551. #endif
  102552. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102553. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102554. static FLAC__bool process_subframe_(
  102555. FLAC__StreamEncoder *encoder,
  102556. unsigned min_partition_order,
  102557. unsigned max_partition_order,
  102558. const FLAC__FrameHeader *frame_header,
  102559. unsigned subframe_bps,
  102560. const FLAC__int32 integer_signal[],
  102561. FLAC__Subframe *subframe[2],
  102562. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102563. FLAC__int32 *residual[2],
  102564. unsigned *best_subframe,
  102565. unsigned *best_bits
  102566. );
  102567. static FLAC__bool add_subframe_(
  102568. FLAC__StreamEncoder *encoder,
  102569. unsigned blocksize,
  102570. unsigned subframe_bps,
  102571. const FLAC__Subframe *subframe,
  102572. FLAC__BitWriter *frame
  102573. );
  102574. static unsigned evaluate_constant_subframe_(
  102575. FLAC__StreamEncoder *encoder,
  102576. const FLAC__int32 signal,
  102577. unsigned blocksize,
  102578. unsigned subframe_bps,
  102579. FLAC__Subframe *subframe
  102580. );
  102581. static unsigned evaluate_fixed_subframe_(
  102582. FLAC__StreamEncoder *encoder,
  102583. const FLAC__int32 signal[],
  102584. FLAC__int32 residual[],
  102585. FLAC__uint64 abs_residual_partition_sums[],
  102586. unsigned raw_bits_per_partition[],
  102587. unsigned blocksize,
  102588. unsigned subframe_bps,
  102589. unsigned order,
  102590. unsigned rice_parameter,
  102591. unsigned rice_parameter_limit,
  102592. unsigned min_partition_order,
  102593. unsigned max_partition_order,
  102594. FLAC__bool do_escape_coding,
  102595. unsigned rice_parameter_search_dist,
  102596. FLAC__Subframe *subframe,
  102597. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102598. );
  102599. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102600. static unsigned evaluate_lpc_subframe_(
  102601. FLAC__StreamEncoder *encoder,
  102602. const FLAC__int32 signal[],
  102603. FLAC__int32 residual[],
  102604. FLAC__uint64 abs_residual_partition_sums[],
  102605. unsigned raw_bits_per_partition[],
  102606. const FLAC__real lp_coeff[],
  102607. unsigned blocksize,
  102608. unsigned subframe_bps,
  102609. unsigned order,
  102610. unsigned qlp_coeff_precision,
  102611. unsigned rice_parameter,
  102612. unsigned rice_parameter_limit,
  102613. unsigned min_partition_order,
  102614. unsigned max_partition_order,
  102615. FLAC__bool do_escape_coding,
  102616. unsigned rice_parameter_search_dist,
  102617. FLAC__Subframe *subframe,
  102618. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102619. );
  102620. #endif
  102621. static unsigned evaluate_verbatim_subframe_(
  102622. FLAC__StreamEncoder *encoder,
  102623. const FLAC__int32 signal[],
  102624. unsigned blocksize,
  102625. unsigned subframe_bps,
  102626. FLAC__Subframe *subframe
  102627. );
  102628. static unsigned find_best_partition_order_(
  102629. struct FLAC__StreamEncoderPrivate *private_,
  102630. const FLAC__int32 residual[],
  102631. FLAC__uint64 abs_residual_partition_sums[],
  102632. unsigned raw_bits_per_partition[],
  102633. unsigned residual_samples,
  102634. unsigned predictor_order,
  102635. unsigned rice_parameter,
  102636. unsigned rice_parameter_limit,
  102637. unsigned min_partition_order,
  102638. unsigned max_partition_order,
  102639. unsigned bps,
  102640. FLAC__bool do_escape_coding,
  102641. unsigned rice_parameter_search_dist,
  102642. FLAC__EntropyCodingMethod *best_ecm
  102643. );
  102644. static void precompute_partition_info_sums_(
  102645. const FLAC__int32 residual[],
  102646. FLAC__uint64 abs_residual_partition_sums[],
  102647. unsigned residual_samples,
  102648. unsigned predictor_order,
  102649. unsigned min_partition_order,
  102650. unsigned max_partition_order,
  102651. unsigned bps
  102652. );
  102653. static void precompute_partition_info_escapes_(
  102654. const FLAC__int32 residual[],
  102655. unsigned raw_bits_per_partition[],
  102656. unsigned residual_samples,
  102657. unsigned predictor_order,
  102658. unsigned min_partition_order,
  102659. unsigned max_partition_order
  102660. );
  102661. static FLAC__bool set_partitioned_rice_(
  102662. #ifdef EXACT_RICE_BITS_CALCULATION
  102663. const FLAC__int32 residual[],
  102664. #endif
  102665. const FLAC__uint64 abs_residual_partition_sums[],
  102666. const unsigned raw_bits_per_partition[],
  102667. const unsigned residual_samples,
  102668. const unsigned predictor_order,
  102669. const unsigned suggested_rice_parameter,
  102670. const unsigned rice_parameter_limit,
  102671. const unsigned rice_parameter_search_dist,
  102672. const unsigned partition_order,
  102673. const FLAC__bool search_for_escapes,
  102674. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102675. unsigned *bits
  102676. );
  102677. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102678. /* verify-related routines: */
  102679. static void append_to_verify_fifo_(
  102680. verify_input_fifo *fifo,
  102681. const FLAC__int32 * const input[],
  102682. unsigned input_offset,
  102683. unsigned channels,
  102684. unsigned wide_samples
  102685. );
  102686. static void append_to_verify_fifo_interleaved_(
  102687. verify_input_fifo *fifo,
  102688. const FLAC__int32 input[],
  102689. unsigned input_offset,
  102690. unsigned channels,
  102691. unsigned wide_samples
  102692. );
  102693. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102694. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102695. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102696. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102697. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102698. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102699. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102700. 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);
  102701. static FILE *get_binary_stdout_(void);
  102702. /***********************************************************************
  102703. *
  102704. * Private class data
  102705. *
  102706. ***********************************************************************/
  102707. typedef struct FLAC__StreamEncoderPrivate {
  102708. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102709. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102710. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102711. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102712. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102713. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102714. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102715. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102716. #endif
  102717. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102718. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102719. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102720. FLAC__int32 *residual_workspace_mid_side[2][2];
  102721. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102722. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102723. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102724. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102725. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102726. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102727. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102728. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102729. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102730. unsigned best_subframe_mid_side[2];
  102731. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102732. unsigned best_subframe_bits_mid_side[2];
  102733. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102734. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102735. FLAC__BitWriter *frame; /* the current frame being worked on */
  102736. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102737. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102738. FLAC__ChannelAssignment last_channel_assignment;
  102739. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102740. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102741. unsigned current_sample_number;
  102742. unsigned current_frame_number;
  102743. FLAC__MD5Context md5context;
  102744. FLAC__CPUInfo cpuinfo;
  102745. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102746. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102747. #else
  102748. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102749. #endif
  102750. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102751. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102752. 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[]);
  102753. 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[]);
  102754. 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[]);
  102755. #endif
  102756. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102757. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102758. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102759. FLAC__bool disable_constant_subframes;
  102760. FLAC__bool disable_fixed_subframes;
  102761. FLAC__bool disable_verbatim_subframes;
  102762. #if FLAC__HAS_OGG
  102763. FLAC__bool is_ogg;
  102764. #endif
  102765. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102766. FLAC__StreamEncoderSeekCallback seek_callback;
  102767. FLAC__StreamEncoderTellCallback tell_callback;
  102768. FLAC__StreamEncoderWriteCallback write_callback;
  102769. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102770. FLAC__StreamEncoderProgressCallback progress_callback;
  102771. void *client_data;
  102772. unsigned first_seekpoint_to_check;
  102773. FILE *file; /* only used when encoding to a file */
  102774. FLAC__uint64 bytes_written;
  102775. FLAC__uint64 samples_written;
  102776. unsigned frames_written;
  102777. unsigned total_frames_estimate;
  102778. /* unaligned (original) pointers to allocated data */
  102779. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102780. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102781. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102782. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102783. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102784. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102785. FLAC__real *windowed_signal_unaligned;
  102786. #endif
  102787. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102788. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102789. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102790. unsigned *raw_bits_per_partition_unaligned;
  102791. /*
  102792. * These fields have been moved here from private function local
  102793. * declarations merely to save stack space during encoding.
  102794. */
  102795. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102796. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102797. #endif
  102798. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102799. /*
  102800. * The data for the verify section
  102801. */
  102802. struct {
  102803. FLAC__StreamDecoder *decoder;
  102804. EncoderStateHint state_hint;
  102805. FLAC__bool needs_magic_hack;
  102806. verify_input_fifo input_fifo;
  102807. verify_output output;
  102808. struct {
  102809. FLAC__uint64 absolute_sample;
  102810. unsigned frame_number;
  102811. unsigned channel;
  102812. unsigned sample;
  102813. FLAC__int32 expected;
  102814. FLAC__int32 got;
  102815. } error_stats;
  102816. } verify;
  102817. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102818. } FLAC__StreamEncoderPrivate;
  102819. /***********************************************************************
  102820. *
  102821. * Public static class data
  102822. *
  102823. ***********************************************************************/
  102824. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102825. "FLAC__STREAM_ENCODER_OK",
  102826. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102827. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102828. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102829. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102830. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102831. "FLAC__STREAM_ENCODER_IO_ERROR",
  102832. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102833. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102834. };
  102835. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102836. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102837. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102838. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102839. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102840. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102841. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102842. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102843. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102844. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102845. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102846. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102847. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102848. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102849. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102850. };
  102851. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102852. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102853. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102854. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102855. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102856. };
  102857. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102858. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102859. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102860. };
  102861. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102862. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102863. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102864. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102865. };
  102866. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102867. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102868. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102869. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102870. };
  102871. /* Number of samples that will be overread to watch for end of stream. By
  102872. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102873. * always try to read blocksize+1 samples before encoding a block, so that
  102874. * even if the stream has a total sample count that is an integral multiple
  102875. * of the blocksize, we will still notice when we are encoding the last
  102876. * block. This is needed, for example, to correctly set the end-of-stream
  102877. * marker in Ogg FLAC.
  102878. *
  102879. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102880. * not really any reason to change it.
  102881. */
  102882. static const unsigned OVERREAD_ = 1;
  102883. /***********************************************************************
  102884. *
  102885. * Class constructor/destructor
  102886. *
  102887. */
  102888. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102889. {
  102890. FLAC__StreamEncoder *encoder;
  102891. unsigned i;
  102892. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102893. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102894. if(encoder == 0) {
  102895. return 0;
  102896. }
  102897. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102898. if(encoder->protected_ == 0) {
  102899. free(encoder);
  102900. return 0;
  102901. }
  102902. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102903. if(encoder->private_ == 0) {
  102904. free(encoder->protected_);
  102905. free(encoder);
  102906. return 0;
  102907. }
  102908. encoder->private_->frame = FLAC__bitwriter_new();
  102909. if(encoder->private_->frame == 0) {
  102910. free(encoder->private_);
  102911. free(encoder->protected_);
  102912. free(encoder);
  102913. return 0;
  102914. }
  102915. encoder->private_->file = 0;
  102916. set_defaults_enc(encoder);
  102917. encoder->private_->is_being_deleted = false;
  102918. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102919. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102920. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102921. }
  102922. for(i = 0; i < 2; i++) {
  102923. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102924. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102925. }
  102926. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102927. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102928. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102929. }
  102930. for(i = 0; i < 2; i++) {
  102931. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102932. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102933. }
  102934. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102935. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102936. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102937. }
  102938. for(i = 0; i < 2; i++) {
  102939. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102940. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102941. }
  102942. for(i = 0; i < 2; i++)
  102943. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102944. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102945. return encoder;
  102946. }
  102947. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102948. {
  102949. unsigned i;
  102950. FLAC__ASSERT(0 != encoder);
  102951. FLAC__ASSERT(0 != encoder->protected_);
  102952. FLAC__ASSERT(0 != encoder->private_);
  102953. FLAC__ASSERT(0 != encoder->private_->frame);
  102954. encoder->private_->is_being_deleted = true;
  102955. (void)FLAC__stream_encoder_finish(encoder);
  102956. if(0 != encoder->private_->verify.decoder)
  102957. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102958. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102959. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102960. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102961. }
  102962. for(i = 0; i < 2; i++) {
  102963. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102964. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102965. }
  102966. for(i = 0; i < 2; i++)
  102967. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102968. FLAC__bitwriter_delete(encoder->private_->frame);
  102969. free(encoder->private_);
  102970. free(encoder->protected_);
  102971. free(encoder);
  102972. }
  102973. /***********************************************************************
  102974. *
  102975. * Public class methods
  102976. *
  102977. ***********************************************************************/
  102978. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102979. FLAC__StreamEncoder *encoder,
  102980. FLAC__StreamEncoderReadCallback read_callback,
  102981. FLAC__StreamEncoderWriteCallback write_callback,
  102982. FLAC__StreamEncoderSeekCallback seek_callback,
  102983. FLAC__StreamEncoderTellCallback tell_callback,
  102984. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102985. void *client_data,
  102986. FLAC__bool is_ogg
  102987. )
  102988. {
  102989. unsigned i;
  102990. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102991. FLAC__ASSERT(0 != encoder);
  102992. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102993. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102994. #if !FLAC__HAS_OGG
  102995. if(is_ogg)
  102996. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102997. #endif
  102998. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102999. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  103000. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  103001. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  103002. if(encoder->protected_->channels != 2) {
  103003. encoder->protected_->do_mid_side_stereo = false;
  103004. encoder->protected_->loose_mid_side_stereo = false;
  103005. }
  103006. else if(!encoder->protected_->do_mid_side_stereo)
  103007. encoder->protected_->loose_mid_side_stereo = false;
  103008. if(encoder->protected_->bits_per_sample >= 32)
  103009. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  103010. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  103011. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  103012. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  103013. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  103014. if(encoder->protected_->blocksize == 0) {
  103015. if(encoder->protected_->max_lpc_order == 0)
  103016. encoder->protected_->blocksize = 1152;
  103017. else
  103018. encoder->protected_->blocksize = 4096;
  103019. }
  103020. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  103021. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  103022. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  103023. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  103024. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  103025. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  103026. if(encoder->protected_->qlp_coeff_precision == 0) {
  103027. if(encoder->protected_->bits_per_sample < 16) {
  103028. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  103029. /* @@@ until then we'll make a guess */
  103030. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  103031. }
  103032. else if(encoder->protected_->bits_per_sample == 16) {
  103033. if(encoder->protected_->blocksize <= 192)
  103034. encoder->protected_->qlp_coeff_precision = 7;
  103035. else if(encoder->protected_->blocksize <= 384)
  103036. encoder->protected_->qlp_coeff_precision = 8;
  103037. else if(encoder->protected_->blocksize <= 576)
  103038. encoder->protected_->qlp_coeff_precision = 9;
  103039. else if(encoder->protected_->blocksize <= 1152)
  103040. encoder->protected_->qlp_coeff_precision = 10;
  103041. else if(encoder->protected_->blocksize <= 2304)
  103042. encoder->protected_->qlp_coeff_precision = 11;
  103043. else if(encoder->protected_->blocksize <= 4608)
  103044. encoder->protected_->qlp_coeff_precision = 12;
  103045. else
  103046. encoder->protected_->qlp_coeff_precision = 13;
  103047. }
  103048. else {
  103049. if(encoder->protected_->blocksize <= 384)
  103050. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  103051. else if(encoder->protected_->blocksize <= 1152)
  103052. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  103053. else
  103054. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  103055. }
  103056. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  103057. }
  103058. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  103059. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  103060. if(encoder->protected_->streamable_subset) {
  103061. if(
  103062. encoder->protected_->blocksize != 192 &&
  103063. encoder->protected_->blocksize != 576 &&
  103064. encoder->protected_->blocksize != 1152 &&
  103065. encoder->protected_->blocksize != 2304 &&
  103066. encoder->protected_->blocksize != 4608 &&
  103067. encoder->protected_->blocksize != 256 &&
  103068. encoder->protected_->blocksize != 512 &&
  103069. encoder->protected_->blocksize != 1024 &&
  103070. encoder->protected_->blocksize != 2048 &&
  103071. encoder->protected_->blocksize != 4096 &&
  103072. encoder->protected_->blocksize != 8192 &&
  103073. encoder->protected_->blocksize != 16384
  103074. )
  103075. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103076. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  103077. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103078. if(
  103079. encoder->protected_->bits_per_sample != 8 &&
  103080. encoder->protected_->bits_per_sample != 12 &&
  103081. encoder->protected_->bits_per_sample != 16 &&
  103082. encoder->protected_->bits_per_sample != 20 &&
  103083. encoder->protected_->bits_per_sample != 24
  103084. )
  103085. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103086. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  103087. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103088. if(
  103089. encoder->protected_->sample_rate <= 48000 &&
  103090. (
  103091. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  103092. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  103093. )
  103094. ) {
  103095. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103096. }
  103097. }
  103098. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103099. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  103100. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  103101. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  103102. #if FLAC__HAS_OGG
  103103. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  103104. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  103105. unsigned i;
  103106. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  103107. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103108. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  103109. for( ; i > 0; i--)
  103110. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  103111. encoder->protected_->metadata[0] = vc;
  103112. break;
  103113. }
  103114. }
  103115. }
  103116. #endif
  103117. /* keep track of any SEEKTABLE block */
  103118. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  103119. unsigned i;
  103120. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103121. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103122. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  103123. break; /* take only the first one */
  103124. }
  103125. }
  103126. }
  103127. /* validate metadata */
  103128. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  103129. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103130. metadata_has_seektable = false;
  103131. metadata_has_vorbis_comment = false;
  103132. metadata_picture_has_type1 = false;
  103133. metadata_picture_has_type2 = false;
  103134. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103135. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  103136. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  103137. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103138. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103139. if(metadata_has_seektable) /* only one is allowed */
  103140. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103141. metadata_has_seektable = true;
  103142. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  103143. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103144. }
  103145. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103146. if(metadata_has_vorbis_comment) /* only one is allowed */
  103147. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103148. metadata_has_vorbis_comment = true;
  103149. }
  103150. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  103151. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  103152. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103153. }
  103154. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  103155. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  103156. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103157. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  103158. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  103159. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103160. metadata_picture_has_type1 = true;
  103161. /* standard icon must be 32x32 pixel PNG */
  103162. if(
  103163. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  103164. (
  103165. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  103166. m->data.picture.width != 32 ||
  103167. m->data.picture.height != 32
  103168. )
  103169. )
  103170. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103171. }
  103172. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  103173. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103174. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103175. metadata_picture_has_type2 = true;
  103176. }
  103177. }
  103178. }
  103179. encoder->private_->input_capacity = 0;
  103180. for(i = 0; i < encoder->protected_->channels; i++) {
  103181. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103182. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103183. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103184. #endif
  103185. }
  103186. for(i = 0; i < 2; i++) {
  103187. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103188. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103189. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103190. #endif
  103191. }
  103192. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103193. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103194. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103195. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103196. #endif
  103197. for(i = 0; i < encoder->protected_->channels; i++) {
  103198. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103199. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103200. encoder->private_->best_subframe[i] = 0;
  103201. }
  103202. for(i = 0; i < 2; i++) {
  103203. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103204. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103205. encoder->private_->best_subframe_mid_side[i] = 0;
  103206. }
  103207. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103208. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103209. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103210. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103211. #else
  103212. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103213. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103214. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103215. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103216. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103217. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103218. 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);
  103219. #endif
  103220. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103221. encoder->private_->loose_mid_side_stereo_frames = 1;
  103222. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103223. encoder->private_->current_sample_number = 0;
  103224. encoder->private_->current_frame_number = 0;
  103225. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103226. 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? */
  103227. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103228. /*
  103229. * get the CPU info and set the function pointers
  103230. */
  103231. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103232. /* first default to the non-asm routines */
  103233. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103234. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103235. #endif
  103236. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103237. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103238. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103239. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103240. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103241. #endif
  103242. /* now override with asm where appropriate */
  103243. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103244. # ifndef FLAC__NO_ASM
  103245. if(encoder->private_->cpuinfo.use_asm) {
  103246. # ifdef FLAC__CPU_IA32
  103247. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103248. # ifdef FLAC__HAS_NASM
  103249. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103250. if(encoder->protected_->max_lpc_order < 4)
  103251. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103252. else if(encoder->protected_->max_lpc_order < 8)
  103253. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103254. else if(encoder->protected_->max_lpc_order < 12)
  103255. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103256. else
  103257. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103258. }
  103259. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103260. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103261. else
  103262. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103263. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103264. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103265. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103266. }
  103267. else {
  103268. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103269. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103270. }
  103271. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103272. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103273. # endif /* FLAC__HAS_NASM */
  103274. # endif /* FLAC__CPU_IA32 */
  103275. }
  103276. # endif /* !FLAC__NO_ASM */
  103277. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103278. /* finally override based on wide-ness if necessary */
  103279. if(encoder->private_->use_wide_by_block) {
  103280. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103281. }
  103282. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103283. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103284. #if FLAC__HAS_OGG
  103285. encoder->private_->is_ogg = is_ogg;
  103286. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103287. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103288. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103289. }
  103290. #endif
  103291. encoder->private_->read_callback = read_callback;
  103292. encoder->private_->write_callback = write_callback;
  103293. encoder->private_->seek_callback = seek_callback;
  103294. encoder->private_->tell_callback = tell_callback;
  103295. encoder->private_->metadata_callback = metadata_callback;
  103296. encoder->private_->client_data = client_data;
  103297. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103298. /* the above function sets the state for us in case of an error */
  103299. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103300. }
  103301. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103302. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103303. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103304. }
  103305. /*
  103306. * Set up the verify stuff if necessary
  103307. */
  103308. if(encoder->protected_->verify) {
  103309. /*
  103310. * First, set up the fifo which will hold the
  103311. * original signal to compare against
  103312. */
  103313. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103314. for(i = 0; i < encoder->protected_->channels; i++) {
  103315. 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))) {
  103316. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103317. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103318. }
  103319. }
  103320. encoder->private_->verify.input_fifo.tail = 0;
  103321. /*
  103322. * Now set up a stream decoder for verification
  103323. */
  103324. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103325. if(0 == encoder->private_->verify.decoder) {
  103326. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103327. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103328. }
  103329. 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) {
  103330. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103331. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103332. }
  103333. }
  103334. encoder->private_->verify.error_stats.absolute_sample = 0;
  103335. encoder->private_->verify.error_stats.frame_number = 0;
  103336. encoder->private_->verify.error_stats.channel = 0;
  103337. encoder->private_->verify.error_stats.sample = 0;
  103338. encoder->private_->verify.error_stats.expected = 0;
  103339. encoder->private_->verify.error_stats.got = 0;
  103340. /*
  103341. * These must be done before we write any metadata, because that
  103342. * calls the write_callback, which uses these values.
  103343. */
  103344. encoder->private_->first_seekpoint_to_check = 0;
  103345. encoder->private_->samples_written = 0;
  103346. encoder->protected_->streaminfo_offset = 0;
  103347. encoder->protected_->seektable_offset = 0;
  103348. encoder->protected_->audio_offset = 0;
  103349. /*
  103350. * write the stream header
  103351. */
  103352. if(encoder->protected_->verify)
  103353. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103354. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103355. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103356. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103357. }
  103358. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103359. /* the above function sets the state for us in case of an error */
  103360. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103361. }
  103362. /*
  103363. * write the STREAMINFO metadata block
  103364. */
  103365. if(encoder->protected_->verify)
  103366. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103367. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103368. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103369. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103370. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103371. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103372. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103373. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103374. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103375. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103376. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103377. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103378. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103379. if(encoder->protected_->do_md5)
  103380. FLAC__MD5Init(&encoder->private_->md5context);
  103381. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103382. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103383. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103384. }
  103385. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103386. /* the above function sets the state for us in case of an error */
  103387. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103388. }
  103389. /*
  103390. * Now that the STREAMINFO block is written, we can init this to an
  103391. * absurdly-high value...
  103392. */
  103393. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103394. /* ... and clear this to 0 */
  103395. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103396. /*
  103397. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103398. * if not, we will write an empty one (FLAC__add_metadata_block()
  103399. * automatically supplies the vendor string).
  103400. *
  103401. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103402. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103403. * true it will have already insured that the metadata list is properly
  103404. * ordered.)
  103405. */
  103406. if(!metadata_has_vorbis_comment) {
  103407. FLAC__StreamMetadata vorbis_comment;
  103408. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103409. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103410. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103411. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103412. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103413. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103414. vorbis_comment.data.vorbis_comment.comments = 0;
  103415. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103416. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103417. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103418. }
  103419. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103420. /* the above function sets the state for us in case of an error */
  103421. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103422. }
  103423. }
  103424. /*
  103425. * write the user's metadata blocks
  103426. */
  103427. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103428. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103429. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103430. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103431. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103432. }
  103433. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103434. /* the above function sets the state for us in case of an error */
  103435. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103436. }
  103437. }
  103438. /* now that all the metadata is written, we save the stream offset */
  103439. 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 */
  103440. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103441. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103442. }
  103443. if(encoder->protected_->verify)
  103444. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103445. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103446. }
  103447. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103448. FLAC__StreamEncoder *encoder,
  103449. FLAC__StreamEncoderWriteCallback write_callback,
  103450. FLAC__StreamEncoderSeekCallback seek_callback,
  103451. FLAC__StreamEncoderTellCallback tell_callback,
  103452. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103453. void *client_data
  103454. )
  103455. {
  103456. return init_stream_internal_enc(
  103457. encoder,
  103458. /*read_callback=*/0,
  103459. write_callback,
  103460. seek_callback,
  103461. tell_callback,
  103462. metadata_callback,
  103463. client_data,
  103464. /*is_ogg=*/false
  103465. );
  103466. }
  103467. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103468. FLAC__StreamEncoder *encoder,
  103469. FLAC__StreamEncoderReadCallback read_callback,
  103470. FLAC__StreamEncoderWriteCallback write_callback,
  103471. FLAC__StreamEncoderSeekCallback seek_callback,
  103472. FLAC__StreamEncoderTellCallback tell_callback,
  103473. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103474. void *client_data
  103475. )
  103476. {
  103477. return init_stream_internal_enc(
  103478. encoder,
  103479. read_callback,
  103480. write_callback,
  103481. seek_callback,
  103482. tell_callback,
  103483. metadata_callback,
  103484. client_data,
  103485. /*is_ogg=*/true
  103486. );
  103487. }
  103488. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103489. FLAC__StreamEncoder *encoder,
  103490. FILE *file,
  103491. FLAC__StreamEncoderProgressCallback progress_callback,
  103492. void *client_data,
  103493. FLAC__bool is_ogg
  103494. )
  103495. {
  103496. FLAC__StreamEncoderInitStatus init_status;
  103497. FLAC__ASSERT(0 != encoder);
  103498. FLAC__ASSERT(0 != file);
  103499. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103500. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103501. /* double protection */
  103502. if(file == 0) {
  103503. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103504. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103505. }
  103506. /*
  103507. * To make sure that our file does not go unclosed after an error, we
  103508. * must assign the FILE pointer before any further error can occur in
  103509. * this routine.
  103510. */
  103511. if(file == stdout)
  103512. file = get_binary_stdout_(); /* just to be safe */
  103513. encoder->private_->file = file;
  103514. encoder->private_->progress_callback = progress_callback;
  103515. encoder->private_->bytes_written = 0;
  103516. encoder->private_->samples_written = 0;
  103517. encoder->private_->frames_written = 0;
  103518. init_status = init_stream_internal_enc(
  103519. encoder,
  103520. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103521. file_write_callback_,
  103522. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103523. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103524. /*metadata_callback=*/0,
  103525. client_data,
  103526. is_ogg
  103527. );
  103528. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103529. /* the above function sets the state for us in case of an error */
  103530. return init_status;
  103531. }
  103532. {
  103533. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103534. FLAC__ASSERT(blocksize != 0);
  103535. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103536. }
  103537. return init_status;
  103538. }
  103539. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103540. FLAC__StreamEncoder *encoder,
  103541. FILE *file,
  103542. FLAC__StreamEncoderProgressCallback progress_callback,
  103543. void *client_data
  103544. )
  103545. {
  103546. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103547. }
  103548. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103549. FLAC__StreamEncoder *encoder,
  103550. FILE *file,
  103551. FLAC__StreamEncoderProgressCallback progress_callback,
  103552. void *client_data
  103553. )
  103554. {
  103555. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103556. }
  103557. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103558. FLAC__StreamEncoder *encoder,
  103559. const char *filename,
  103560. FLAC__StreamEncoderProgressCallback progress_callback,
  103561. void *client_data,
  103562. FLAC__bool is_ogg
  103563. )
  103564. {
  103565. FILE *file;
  103566. FLAC__ASSERT(0 != encoder);
  103567. /*
  103568. * To make sure that our file does not go unclosed after an error, we
  103569. * have to do the same entrance checks here that are later performed
  103570. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103571. */
  103572. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103573. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103574. file = filename? fopen(filename, "w+b") : stdout;
  103575. if(file == 0) {
  103576. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103577. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103578. }
  103579. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103580. }
  103581. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103582. FLAC__StreamEncoder *encoder,
  103583. const char *filename,
  103584. FLAC__StreamEncoderProgressCallback progress_callback,
  103585. void *client_data
  103586. )
  103587. {
  103588. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103589. }
  103590. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103591. FLAC__StreamEncoder *encoder,
  103592. const char *filename,
  103593. FLAC__StreamEncoderProgressCallback progress_callback,
  103594. void *client_data
  103595. )
  103596. {
  103597. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103598. }
  103599. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103600. {
  103601. FLAC__bool error = false;
  103602. FLAC__ASSERT(0 != encoder);
  103603. FLAC__ASSERT(0 != encoder->private_);
  103604. FLAC__ASSERT(0 != encoder->protected_);
  103605. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103606. return true;
  103607. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103608. if(encoder->private_->current_sample_number != 0) {
  103609. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103610. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103611. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103612. error = true;
  103613. }
  103614. }
  103615. if(encoder->protected_->do_md5)
  103616. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103617. if(!encoder->private_->is_being_deleted) {
  103618. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103619. if(encoder->private_->seek_callback) {
  103620. #if FLAC__HAS_OGG
  103621. if(encoder->private_->is_ogg)
  103622. update_ogg_metadata_(encoder);
  103623. else
  103624. #endif
  103625. update_metadata_(encoder);
  103626. /* check if an error occurred while updating metadata */
  103627. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103628. error = true;
  103629. }
  103630. if(encoder->private_->metadata_callback)
  103631. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103632. }
  103633. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103634. if(!error)
  103635. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103636. error = true;
  103637. }
  103638. }
  103639. if(0 != encoder->private_->file) {
  103640. if(encoder->private_->file != stdout)
  103641. fclose(encoder->private_->file);
  103642. encoder->private_->file = 0;
  103643. }
  103644. #if FLAC__HAS_OGG
  103645. if(encoder->private_->is_ogg)
  103646. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103647. #endif
  103648. free_(encoder);
  103649. set_defaults_enc(encoder);
  103650. if(!error)
  103651. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103652. return !error;
  103653. }
  103654. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long 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. #if FLAC__HAS_OGG
  103662. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103663. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103664. return true;
  103665. #else
  103666. (void)value;
  103667. return false;
  103668. #endif
  103669. }
  103670. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103671. {
  103672. FLAC__ASSERT(0 != encoder);
  103673. FLAC__ASSERT(0 != encoder->private_);
  103674. FLAC__ASSERT(0 != encoder->protected_);
  103675. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103676. return false;
  103677. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103678. encoder->protected_->verify = value;
  103679. #endif
  103680. return true;
  103681. }
  103682. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103683. {
  103684. FLAC__ASSERT(0 != encoder);
  103685. FLAC__ASSERT(0 != encoder->private_);
  103686. FLAC__ASSERT(0 != encoder->protected_);
  103687. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103688. return false;
  103689. encoder->protected_->streamable_subset = value;
  103690. return true;
  103691. }
  103692. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103693. {
  103694. FLAC__ASSERT(0 != encoder);
  103695. FLAC__ASSERT(0 != encoder->private_);
  103696. FLAC__ASSERT(0 != encoder->protected_);
  103697. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103698. return false;
  103699. encoder->protected_->do_md5 = value;
  103700. return true;
  103701. }
  103702. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103703. {
  103704. FLAC__ASSERT(0 != encoder);
  103705. FLAC__ASSERT(0 != encoder->private_);
  103706. FLAC__ASSERT(0 != encoder->protected_);
  103707. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103708. return false;
  103709. encoder->protected_->channels = value;
  103710. return true;
  103711. }
  103712. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103713. {
  103714. FLAC__ASSERT(0 != encoder);
  103715. FLAC__ASSERT(0 != encoder->private_);
  103716. FLAC__ASSERT(0 != encoder->protected_);
  103717. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103718. return false;
  103719. encoder->protected_->bits_per_sample = value;
  103720. return true;
  103721. }
  103722. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103723. {
  103724. FLAC__ASSERT(0 != encoder);
  103725. FLAC__ASSERT(0 != encoder->private_);
  103726. FLAC__ASSERT(0 != encoder->protected_);
  103727. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103728. return false;
  103729. encoder->protected_->sample_rate = value;
  103730. return true;
  103731. }
  103732. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103733. {
  103734. FLAC__bool ok = true;
  103735. FLAC__ASSERT(0 != encoder);
  103736. FLAC__ASSERT(0 != encoder->private_);
  103737. FLAC__ASSERT(0 != encoder->protected_);
  103738. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103739. return false;
  103740. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103741. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103742. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103743. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103744. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103745. #if 0
  103746. /* was: */
  103747. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103748. /* but it's too hard to specify the string in a locale-specific way */
  103749. #else
  103750. encoder->protected_->num_apodizations = 1;
  103751. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103752. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103753. #endif
  103754. #endif
  103755. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103756. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103757. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103758. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103759. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103760. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103761. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103762. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103763. return ok;
  103764. }
  103765. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103766. {
  103767. FLAC__ASSERT(0 != encoder);
  103768. FLAC__ASSERT(0 != encoder->private_);
  103769. FLAC__ASSERT(0 != encoder->protected_);
  103770. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103771. return false;
  103772. encoder->protected_->blocksize = value;
  103773. return true;
  103774. }
  103775. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103776. {
  103777. FLAC__ASSERT(0 != encoder);
  103778. FLAC__ASSERT(0 != encoder->private_);
  103779. FLAC__ASSERT(0 != encoder->protected_);
  103780. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103781. return false;
  103782. encoder->protected_->do_mid_side_stereo = value;
  103783. return true;
  103784. }
  103785. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103786. {
  103787. FLAC__ASSERT(0 != encoder);
  103788. FLAC__ASSERT(0 != encoder->private_);
  103789. FLAC__ASSERT(0 != encoder->protected_);
  103790. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103791. return false;
  103792. encoder->protected_->loose_mid_side_stereo = value;
  103793. return true;
  103794. }
  103795. /*@@@@add to tests*/
  103796. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103797. {
  103798. FLAC__ASSERT(0 != encoder);
  103799. FLAC__ASSERT(0 != encoder->private_);
  103800. FLAC__ASSERT(0 != encoder->protected_);
  103801. FLAC__ASSERT(0 != specification);
  103802. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103803. return false;
  103804. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103805. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103806. #else
  103807. encoder->protected_->num_apodizations = 0;
  103808. while(1) {
  103809. const char *s = strchr(specification, ';');
  103810. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103811. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103812. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103813. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103814. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103815. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103816. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103817. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103818. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103819. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103820. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103821. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103822. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103823. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103824. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103825. if (stddev > 0.0 && stddev <= 0.5) {
  103826. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103827. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103828. }
  103829. }
  103830. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103831. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103832. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103833. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103834. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103835. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103836. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103837. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103838. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103839. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103840. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103841. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103842. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103843. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103844. if (p >= 0.0 && p <= 1.0) {
  103845. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103846. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103847. }
  103848. }
  103849. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103850. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103851. if (encoder->protected_->num_apodizations == 32)
  103852. break;
  103853. if (s)
  103854. specification = s+1;
  103855. else
  103856. break;
  103857. }
  103858. if(encoder->protected_->num_apodizations == 0) {
  103859. encoder->protected_->num_apodizations = 1;
  103860. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103861. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103862. }
  103863. #endif
  103864. return true;
  103865. }
  103866. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103867. {
  103868. FLAC__ASSERT(0 != encoder);
  103869. FLAC__ASSERT(0 != encoder->private_);
  103870. FLAC__ASSERT(0 != encoder->protected_);
  103871. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103872. return false;
  103873. encoder->protected_->max_lpc_order = value;
  103874. return true;
  103875. }
  103876. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103877. {
  103878. FLAC__ASSERT(0 != encoder);
  103879. FLAC__ASSERT(0 != encoder->private_);
  103880. FLAC__ASSERT(0 != encoder->protected_);
  103881. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103882. return false;
  103883. encoder->protected_->qlp_coeff_precision = value;
  103884. return true;
  103885. }
  103886. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103887. {
  103888. FLAC__ASSERT(0 != encoder);
  103889. FLAC__ASSERT(0 != encoder->private_);
  103890. FLAC__ASSERT(0 != encoder->protected_);
  103891. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103892. return false;
  103893. encoder->protected_->do_qlp_coeff_prec_search = value;
  103894. return true;
  103895. }
  103896. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103897. {
  103898. FLAC__ASSERT(0 != encoder);
  103899. FLAC__ASSERT(0 != encoder->private_);
  103900. FLAC__ASSERT(0 != encoder->protected_);
  103901. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103902. return false;
  103903. #if 0
  103904. /*@@@ deprecated: */
  103905. encoder->protected_->do_escape_coding = value;
  103906. #else
  103907. (void)value;
  103908. #endif
  103909. return true;
  103910. }
  103911. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103912. {
  103913. FLAC__ASSERT(0 != encoder);
  103914. FLAC__ASSERT(0 != encoder->private_);
  103915. FLAC__ASSERT(0 != encoder->protected_);
  103916. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103917. return false;
  103918. encoder->protected_->do_exhaustive_model_search = value;
  103919. return true;
  103920. }
  103921. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103922. {
  103923. FLAC__ASSERT(0 != encoder);
  103924. FLAC__ASSERT(0 != encoder->private_);
  103925. FLAC__ASSERT(0 != encoder->protected_);
  103926. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103927. return false;
  103928. encoder->protected_->min_residual_partition_order = value;
  103929. return true;
  103930. }
  103931. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103932. {
  103933. FLAC__ASSERT(0 != encoder);
  103934. FLAC__ASSERT(0 != encoder->private_);
  103935. FLAC__ASSERT(0 != encoder->protected_);
  103936. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103937. return false;
  103938. encoder->protected_->max_residual_partition_order = value;
  103939. return true;
  103940. }
  103941. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103942. {
  103943. FLAC__ASSERT(0 != encoder);
  103944. FLAC__ASSERT(0 != encoder->private_);
  103945. FLAC__ASSERT(0 != encoder->protected_);
  103946. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103947. return false;
  103948. #if 0
  103949. /*@@@ deprecated: */
  103950. encoder->protected_->rice_parameter_search_dist = value;
  103951. #else
  103952. (void)value;
  103953. #endif
  103954. return true;
  103955. }
  103956. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103957. {
  103958. FLAC__ASSERT(0 != encoder);
  103959. FLAC__ASSERT(0 != encoder->private_);
  103960. FLAC__ASSERT(0 != encoder->protected_);
  103961. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103962. return false;
  103963. encoder->protected_->total_samples_estimate = value;
  103964. return true;
  103965. }
  103966. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103967. {
  103968. FLAC__ASSERT(0 != encoder);
  103969. FLAC__ASSERT(0 != encoder->private_);
  103970. FLAC__ASSERT(0 != encoder->protected_);
  103971. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103972. return false;
  103973. if(0 == metadata)
  103974. num_blocks = 0;
  103975. if(0 == num_blocks)
  103976. metadata = 0;
  103977. /* realloc() does not do exactly what we want so... */
  103978. if(encoder->protected_->metadata) {
  103979. free(encoder->protected_->metadata);
  103980. encoder->protected_->metadata = 0;
  103981. encoder->protected_->num_metadata_blocks = 0;
  103982. }
  103983. if(num_blocks) {
  103984. FLAC__StreamMetadata **m;
  103985. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103986. return false;
  103987. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103988. encoder->protected_->metadata = m;
  103989. encoder->protected_->num_metadata_blocks = num_blocks;
  103990. }
  103991. #if FLAC__HAS_OGG
  103992. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103993. return false;
  103994. #endif
  103995. return true;
  103996. }
  103997. /*
  103998. * These three functions are not static, but not publically exposed in
  103999. * include/FLAC/ either. They are used by the test suite.
  104000. */
  104001. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  104002. {
  104003. FLAC__ASSERT(0 != encoder);
  104004. FLAC__ASSERT(0 != encoder->private_);
  104005. FLAC__ASSERT(0 != encoder->protected_);
  104006. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  104007. return false;
  104008. encoder->private_->disable_constant_subframes = value;
  104009. return true;
  104010. }
  104011. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  104012. {
  104013. FLAC__ASSERT(0 != encoder);
  104014. FLAC__ASSERT(0 != encoder->private_);
  104015. FLAC__ASSERT(0 != encoder->protected_);
  104016. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  104017. return false;
  104018. encoder->private_->disable_fixed_subframes = value;
  104019. return true;
  104020. }
  104021. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  104022. {
  104023. FLAC__ASSERT(0 != encoder);
  104024. FLAC__ASSERT(0 != encoder->private_);
  104025. FLAC__ASSERT(0 != encoder->protected_);
  104026. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  104027. return false;
  104028. encoder->private_->disable_verbatim_subframes = value;
  104029. return true;
  104030. }
  104031. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  104032. {
  104033. FLAC__ASSERT(0 != encoder);
  104034. FLAC__ASSERT(0 != encoder->private_);
  104035. FLAC__ASSERT(0 != encoder->protected_);
  104036. return encoder->protected_->state;
  104037. }
  104038. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  104039. {
  104040. FLAC__ASSERT(0 != encoder);
  104041. FLAC__ASSERT(0 != encoder->private_);
  104042. FLAC__ASSERT(0 != encoder->protected_);
  104043. if(encoder->protected_->verify)
  104044. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  104045. else
  104046. return FLAC__STREAM_DECODER_UNINITIALIZED;
  104047. }
  104048. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  104049. {
  104050. FLAC__ASSERT(0 != encoder);
  104051. FLAC__ASSERT(0 != encoder->private_);
  104052. FLAC__ASSERT(0 != encoder->protected_);
  104053. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  104054. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  104055. else
  104056. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  104057. }
  104058. 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)
  104059. {
  104060. FLAC__ASSERT(0 != encoder);
  104061. FLAC__ASSERT(0 != encoder->private_);
  104062. FLAC__ASSERT(0 != encoder->protected_);
  104063. if(0 != absolute_sample)
  104064. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  104065. if(0 != frame_number)
  104066. *frame_number = encoder->private_->verify.error_stats.frame_number;
  104067. if(0 != channel)
  104068. *channel = encoder->private_->verify.error_stats.channel;
  104069. if(0 != sample)
  104070. *sample = encoder->private_->verify.error_stats.sample;
  104071. if(0 != expected)
  104072. *expected = encoder->private_->verify.error_stats.expected;
  104073. if(0 != got)
  104074. *got = encoder->private_->verify.error_stats.got;
  104075. }
  104076. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  104077. {
  104078. FLAC__ASSERT(0 != encoder);
  104079. FLAC__ASSERT(0 != encoder->private_);
  104080. FLAC__ASSERT(0 != encoder->protected_);
  104081. return encoder->protected_->verify;
  104082. }
  104083. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  104084. {
  104085. FLAC__ASSERT(0 != encoder);
  104086. FLAC__ASSERT(0 != encoder->private_);
  104087. FLAC__ASSERT(0 != encoder->protected_);
  104088. return encoder->protected_->streamable_subset;
  104089. }
  104090. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  104091. {
  104092. FLAC__ASSERT(0 != encoder);
  104093. FLAC__ASSERT(0 != encoder->private_);
  104094. FLAC__ASSERT(0 != encoder->protected_);
  104095. return encoder->protected_->do_md5;
  104096. }
  104097. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  104098. {
  104099. FLAC__ASSERT(0 != encoder);
  104100. FLAC__ASSERT(0 != encoder->private_);
  104101. FLAC__ASSERT(0 != encoder->protected_);
  104102. return encoder->protected_->channels;
  104103. }
  104104. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  104105. {
  104106. FLAC__ASSERT(0 != encoder);
  104107. FLAC__ASSERT(0 != encoder->private_);
  104108. FLAC__ASSERT(0 != encoder->protected_);
  104109. return encoder->protected_->bits_per_sample;
  104110. }
  104111. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  104112. {
  104113. FLAC__ASSERT(0 != encoder);
  104114. FLAC__ASSERT(0 != encoder->private_);
  104115. FLAC__ASSERT(0 != encoder->protected_);
  104116. return encoder->protected_->sample_rate;
  104117. }
  104118. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  104119. {
  104120. FLAC__ASSERT(0 != encoder);
  104121. FLAC__ASSERT(0 != encoder->private_);
  104122. FLAC__ASSERT(0 != encoder->protected_);
  104123. return encoder->protected_->blocksize;
  104124. }
  104125. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104126. {
  104127. FLAC__ASSERT(0 != encoder);
  104128. FLAC__ASSERT(0 != encoder->private_);
  104129. FLAC__ASSERT(0 != encoder->protected_);
  104130. return encoder->protected_->do_mid_side_stereo;
  104131. }
  104132. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104133. {
  104134. FLAC__ASSERT(0 != encoder);
  104135. FLAC__ASSERT(0 != encoder->private_);
  104136. FLAC__ASSERT(0 != encoder->protected_);
  104137. return encoder->protected_->loose_mid_side_stereo;
  104138. }
  104139. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  104140. {
  104141. FLAC__ASSERT(0 != encoder);
  104142. FLAC__ASSERT(0 != encoder->private_);
  104143. FLAC__ASSERT(0 != encoder->protected_);
  104144. return encoder->protected_->max_lpc_order;
  104145. }
  104146. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  104147. {
  104148. FLAC__ASSERT(0 != encoder);
  104149. FLAC__ASSERT(0 != encoder->private_);
  104150. FLAC__ASSERT(0 != encoder->protected_);
  104151. return encoder->protected_->qlp_coeff_precision;
  104152. }
  104153. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  104154. {
  104155. FLAC__ASSERT(0 != encoder);
  104156. FLAC__ASSERT(0 != encoder->private_);
  104157. FLAC__ASSERT(0 != encoder->protected_);
  104158. return encoder->protected_->do_qlp_coeff_prec_search;
  104159. }
  104160. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  104161. {
  104162. FLAC__ASSERT(0 != encoder);
  104163. FLAC__ASSERT(0 != encoder->private_);
  104164. FLAC__ASSERT(0 != encoder->protected_);
  104165. return encoder->protected_->do_escape_coding;
  104166. }
  104167. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  104168. {
  104169. FLAC__ASSERT(0 != encoder);
  104170. FLAC__ASSERT(0 != encoder->private_);
  104171. FLAC__ASSERT(0 != encoder->protected_);
  104172. return encoder->protected_->do_exhaustive_model_search;
  104173. }
  104174. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104175. {
  104176. FLAC__ASSERT(0 != encoder);
  104177. FLAC__ASSERT(0 != encoder->private_);
  104178. FLAC__ASSERT(0 != encoder->protected_);
  104179. return encoder->protected_->min_residual_partition_order;
  104180. }
  104181. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104182. {
  104183. FLAC__ASSERT(0 != encoder);
  104184. FLAC__ASSERT(0 != encoder->private_);
  104185. FLAC__ASSERT(0 != encoder->protected_);
  104186. return encoder->protected_->max_residual_partition_order;
  104187. }
  104188. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104189. {
  104190. FLAC__ASSERT(0 != encoder);
  104191. FLAC__ASSERT(0 != encoder->private_);
  104192. FLAC__ASSERT(0 != encoder->protected_);
  104193. return encoder->protected_->rice_parameter_search_dist;
  104194. }
  104195. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104196. {
  104197. FLAC__ASSERT(0 != encoder);
  104198. FLAC__ASSERT(0 != encoder->private_);
  104199. FLAC__ASSERT(0 != encoder->protected_);
  104200. return encoder->protected_->total_samples_estimate;
  104201. }
  104202. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104203. {
  104204. unsigned i, j = 0, channel;
  104205. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104206. FLAC__ASSERT(0 != encoder);
  104207. FLAC__ASSERT(0 != encoder->private_);
  104208. FLAC__ASSERT(0 != encoder->protected_);
  104209. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104210. do {
  104211. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104212. if(encoder->protected_->verify)
  104213. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104214. for(channel = 0; channel < channels; channel++)
  104215. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104216. if(encoder->protected_->do_mid_side_stereo) {
  104217. FLAC__ASSERT(channels == 2);
  104218. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104219. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104220. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104221. 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' ! */
  104222. }
  104223. }
  104224. else
  104225. j += n;
  104226. encoder->private_->current_sample_number += n;
  104227. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104228. if(encoder->private_->current_sample_number > blocksize) {
  104229. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104230. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104231. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104232. return false;
  104233. /* move unprocessed overread samples to beginnings of arrays */
  104234. for(channel = 0; channel < channels; channel++)
  104235. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104236. if(encoder->protected_->do_mid_side_stereo) {
  104237. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104238. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104239. }
  104240. encoder->private_->current_sample_number = 1;
  104241. }
  104242. } while(j < samples);
  104243. return true;
  104244. }
  104245. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104246. {
  104247. unsigned i, j, k, channel;
  104248. FLAC__int32 x, mid, side;
  104249. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104250. FLAC__ASSERT(0 != encoder);
  104251. FLAC__ASSERT(0 != encoder->private_);
  104252. FLAC__ASSERT(0 != encoder->protected_);
  104253. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104254. j = k = 0;
  104255. /*
  104256. * we have several flavors of the same basic loop, optimized for
  104257. * different conditions:
  104258. */
  104259. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104260. /*
  104261. * stereo coding: unroll channel loop
  104262. */
  104263. do {
  104264. if(encoder->protected_->verify)
  104265. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104266. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104267. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104268. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104269. x = buffer[k++];
  104270. encoder->private_->integer_signal[1][i] = x;
  104271. mid += x;
  104272. side -= x;
  104273. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104274. encoder->private_->integer_signal_mid_side[1][i] = side;
  104275. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104276. }
  104277. encoder->private_->current_sample_number = i;
  104278. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104279. if(i > blocksize) {
  104280. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104281. return false;
  104282. /* move unprocessed overread samples to beginnings of arrays */
  104283. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104284. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104285. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104286. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104287. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104288. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104289. encoder->private_->current_sample_number = 1;
  104290. }
  104291. } while(j < samples);
  104292. }
  104293. else {
  104294. /*
  104295. * independent channel coding: buffer each channel in inner loop
  104296. */
  104297. do {
  104298. if(encoder->protected_->verify)
  104299. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104300. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104301. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104302. for(channel = 0; channel < channels; channel++)
  104303. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104304. }
  104305. encoder->private_->current_sample_number = i;
  104306. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104307. if(i > blocksize) {
  104308. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104309. return false;
  104310. /* move unprocessed overread samples to beginnings of arrays */
  104311. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104312. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104313. for(channel = 0; channel < channels; channel++)
  104314. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104315. encoder->private_->current_sample_number = 1;
  104316. }
  104317. } while(j < samples);
  104318. }
  104319. return true;
  104320. }
  104321. /***********************************************************************
  104322. *
  104323. * Private class methods
  104324. *
  104325. ***********************************************************************/
  104326. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104327. {
  104328. FLAC__ASSERT(0 != encoder);
  104329. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104330. encoder->protected_->verify = true;
  104331. #else
  104332. encoder->protected_->verify = false;
  104333. #endif
  104334. encoder->protected_->streamable_subset = true;
  104335. encoder->protected_->do_md5 = true;
  104336. encoder->protected_->do_mid_side_stereo = false;
  104337. encoder->protected_->loose_mid_side_stereo = false;
  104338. encoder->protected_->channels = 2;
  104339. encoder->protected_->bits_per_sample = 16;
  104340. encoder->protected_->sample_rate = 44100;
  104341. encoder->protected_->blocksize = 0;
  104342. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104343. encoder->protected_->num_apodizations = 1;
  104344. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104345. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104346. #endif
  104347. encoder->protected_->max_lpc_order = 0;
  104348. encoder->protected_->qlp_coeff_precision = 0;
  104349. encoder->protected_->do_qlp_coeff_prec_search = false;
  104350. encoder->protected_->do_exhaustive_model_search = false;
  104351. encoder->protected_->do_escape_coding = false;
  104352. encoder->protected_->min_residual_partition_order = 0;
  104353. encoder->protected_->max_residual_partition_order = 0;
  104354. encoder->protected_->rice_parameter_search_dist = 0;
  104355. encoder->protected_->total_samples_estimate = 0;
  104356. encoder->protected_->metadata = 0;
  104357. encoder->protected_->num_metadata_blocks = 0;
  104358. encoder->private_->seek_table = 0;
  104359. encoder->private_->disable_constant_subframes = false;
  104360. encoder->private_->disable_fixed_subframes = false;
  104361. encoder->private_->disable_verbatim_subframes = false;
  104362. #if FLAC__HAS_OGG
  104363. encoder->private_->is_ogg = false;
  104364. #endif
  104365. encoder->private_->read_callback = 0;
  104366. encoder->private_->write_callback = 0;
  104367. encoder->private_->seek_callback = 0;
  104368. encoder->private_->tell_callback = 0;
  104369. encoder->private_->metadata_callback = 0;
  104370. encoder->private_->progress_callback = 0;
  104371. encoder->private_->client_data = 0;
  104372. #if FLAC__HAS_OGG
  104373. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104374. #endif
  104375. }
  104376. void free_(FLAC__StreamEncoder *encoder)
  104377. {
  104378. unsigned i, channel;
  104379. FLAC__ASSERT(0 != encoder);
  104380. if(encoder->protected_->metadata) {
  104381. free(encoder->protected_->metadata);
  104382. encoder->protected_->metadata = 0;
  104383. encoder->protected_->num_metadata_blocks = 0;
  104384. }
  104385. for(i = 0; i < encoder->protected_->channels; i++) {
  104386. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104387. free(encoder->private_->integer_signal_unaligned[i]);
  104388. encoder->private_->integer_signal_unaligned[i] = 0;
  104389. }
  104390. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104391. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104392. free(encoder->private_->real_signal_unaligned[i]);
  104393. encoder->private_->real_signal_unaligned[i] = 0;
  104394. }
  104395. #endif
  104396. }
  104397. for(i = 0; i < 2; i++) {
  104398. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104399. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104400. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104401. }
  104402. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104403. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104404. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104405. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104406. }
  104407. #endif
  104408. }
  104409. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104410. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104411. if(0 != encoder->private_->window_unaligned[i]) {
  104412. free(encoder->private_->window_unaligned[i]);
  104413. encoder->private_->window_unaligned[i] = 0;
  104414. }
  104415. }
  104416. if(0 != encoder->private_->windowed_signal_unaligned) {
  104417. free(encoder->private_->windowed_signal_unaligned);
  104418. encoder->private_->windowed_signal_unaligned = 0;
  104419. }
  104420. #endif
  104421. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104422. for(i = 0; i < 2; i++) {
  104423. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104424. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104425. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104426. }
  104427. }
  104428. }
  104429. for(channel = 0; channel < 2; channel++) {
  104430. for(i = 0; i < 2; i++) {
  104431. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104432. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104433. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104434. }
  104435. }
  104436. }
  104437. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104438. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104439. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104440. }
  104441. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104442. free(encoder->private_->raw_bits_per_partition_unaligned);
  104443. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104444. }
  104445. if(encoder->protected_->verify) {
  104446. for(i = 0; i < encoder->protected_->channels; i++) {
  104447. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104448. free(encoder->private_->verify.input_fifo.data[i]);
  104449. encoder->private_->verify.input_fifo.data[i] = 0;
  104450. }
  104451. }
  104452. }
  104453. FLAC__bitwriter_free(encoder->private_->frame);
  104454. }
  104455. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104456. {
  104457. FLAC__bool ok;
  104458. unsigned i, channel;
  104459. FLAC__ASSERT(new_blocksize > 0);
  104460. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104461. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104462. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104463. if(new_blocksize <= encoder->private_->input_capacity)
  104464. return true;
  104465. ok = true;
  104466. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104467. * requires that the input arrays (in our case the integer signals)
  104468. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104469. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104470. */
  104471. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104472. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104473. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104474. encoder->private_->integer_signal[i] += 4;
  104475. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104476. #if 0 /* @@@ currently unused */
  104477. if(encoder->protected_->max_lpc_order > 0)
  104478. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104479. #endif
  104480. #endif
  104481. }
  104482. for(i = 0; ok && i < 2; i++) {
  104483. 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]);
  104484. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104485. encoder->private_->integer_signal_mid_side[i] += 4;
  104486. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104487. #if 0 /* @@@ currently unused */
  104488. if(encoder->protected_->max_lpc_order > 0)
  104489. 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]);
  104490. #endif
  104491. #endif
  104492. }
  104493. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104494. if(ok && encoder->protected_->max_lpc_order > 0) {
  104495. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104496. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104497. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104498. }
  104499. #endif
  104500. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104501. for(i = 0; ok && i < 2; i++) {
  104502. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104503. }
  104504. }
  104505. for(channel = 0; ok && channel < 2; channel++) {
  104506. for(i = 0; ok && i < 2; i++) {
  104507. 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]);
  104508. }
  104509. }
  104510. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104511. /*@@@ 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) */
  104512. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104513. if(encoder->protected_->do_escape_coding)
  104514. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104515. /* now adjust the windows if the blocksize has changed */
  104516. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104517. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104518. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104519. switch(encoder->protected_->apodizations[i].type) {
  104520. case FLAC__APODIZATION_BARTLETT:
  104521. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104522. break;
  104523. case FLAC__APODIZATION_BARTLETT_HANN:
  104524. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104525. break;
  104526. case FLAC__APODIZATION_BLACKMAN:
  104527. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104528. break;
  104529. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104530. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104531. break;
  104532. case FLAC__APODIZATION_CONNES:
  104533. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104534. break;
  104535. case FLAC__APODIZATION_FLATTOP:
  104536. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104537. break;
  104538. case FLAC__APODIZATION_GAUSS:
  104539. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104540. break;
  104541. case FLAC__APODIZATION_HAMMING:
  104542. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104543. break;
  104544. case FLAC__APODIZATION_HANN:
  104545. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104546. break;
  104547. case FLAC__APODIZATION_KAISER_BESSEL:
  104548. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104549. break;
  104550. case FLAC__APODIZATION_NUTTALL:
  104551. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104552. break;
  104553. case FLAC__APODIZATION_RECTANGLE:
  104554. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104555. break;
  104556. case FLAC__APODIZATION_TRIANGLE:
  104557. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104558. break;
  104559. case FLAC__APODIZATION_TUKEY:
  104560. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104561. break;
  104562. case FLAC__APODIZATION_WELCH:
  104563. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104564. break;
  104565. default:
  104566. FLAC__ASSERT(0);
  104567. /* double protection */
  104568. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104569. break;
  104570. }
  104571. }
  104572. }
  104573. #endif
  104574. if(ok)
  104575. encoder->private_->input_capacity = new_blocksize;
  104576. else
  104577. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104578. return ok;
  104579. }
  104580. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104581. {
  104582. const FLAC__byte *buffer;
  104583. size_t bytes;
  104584. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104585. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104586. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104587. return false;
  104588. }
  104589. if(encoder->protected_->verify) {
  104590. encoder->private_->verify.output.data = buffer;
  104591. encoder->private_->verify.output.bytes = bytes;
  104592. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104593. encoder->private_->verify.needs_magic_hack = true;
  104594. }
  104595. else {
  104596. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104597. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104598. FLAC__bitwriter_clear(encoder->private_->frame);
  104599. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104600. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104601. return false;
  104602. }
  104603. }
  104604. }
  104605. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104606. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104607. FLAC__bitwriter_clear(encoder->private_->frame);
  104608. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104609. return false;
  104610. }
  104611. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104612. FLAC__bitwriter_clear(encoder->private_->frame);
  104613. if(samples > 0) {
  104614. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104615. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104616. }
  104617. return true;
  104618. }
  104619. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104620. {
  104621. FLAC__StreamEncoderWriteStatus status;
  104622. FLAC__uint64 output_position = 0;
  104623. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104624. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104625. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104626. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104627. }
  104628. /*
  104629. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104630. */
  104631. if(samples == 0) {
  104632. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104633. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104634. encoder->protected_->streaminfo_offset = output_position;
  104635. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104636. encoder->protected_->seektable_offset = output_position;
  104637. }
  104638. /*
  104639. * Mark the current seek point if hit (if audio_offset == 0 that
  104640. * means we're still writing metadata and haven't hit the first
  104641. * frame yet)
  104642. */
  104643. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104644. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104645. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104646. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104647. FLAC__uint64 test_sample;
  104648. unsigned i;
  104649. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104650. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104651. if(test_sample > frame_last_sample) {
  104652. break;
  104653. }
  104654. else if(test_sample >= frame_first_sample) {
  104655. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104656. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104657. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104658. encoder->private_->first_seekpoint_to_check++;
  104659. /* DO NOT: "break;" and here's why:
  104660. * The seektable template may contain more than one target
  104661. * sample for any given frame; we will keep looping, generating
  104662. * duplicate seekpoints for them, and we'll clean it up later,
  104663. * just before writing the seektable back to the metadata.
  104664. */
  104665. }
  104666. else {
  104667. encoder->private_->first_seekpoint_to_check++;
  104668. }
  104669. }
  104670. }
  104671. #if FLAC__HAS_OGG
  104672. if(encoder->private_->is_ogg) {
  104673. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104674. &encoder->protected_->ogg_encoder_aspect,
  104675. buffer,
  104676. bytes,
  104677. samples,
  104678. encoder->private_->current_frame_number,
  104679. is_last_block,
  104680. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104681. encoder,
  104682. encoder->private_->client_data
  104683. );
  104684. }
  104685. else
  104686. #endif
  104687. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104688. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104689. encoder->private_->bytes_written += bytes;
  104690. encoder->private_->samples_written += samples;
  104691. /* we keep a high watermark on the number of frames written because
  104692. * when the encoder goes back to write metadata, 'current_frame'
  104693. * will drop back to 0.
  104694. */
  104695. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104696. }
  104697. else
  104698. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104699. return status;
  104700. }
  104701. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104702. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104703. {
  104704. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104705. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104706. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104707. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104708. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104709. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104710. FLAC__StreamEncoderSeekStatus seek_status;
  104711. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104712. /* All this is based on intimate knowledge of the stream header
  104713. * layout, but a change to the header format that would break this
  104714. * would also break all streams encoded in the previous format.
  104715. */
  104716. /*
  104717. * Write MD5 signature
  104718. */
  104719. {
  104720. const unsigned md5_offset =
  104721. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104722. (
  104723. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104724. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104725. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104726. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104727. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104728. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104729. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104730. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104731. ) / 8;
  104732. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104733. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104734. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104735. return;
  104736. }
  104737. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104738. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104739. return;
  104740. }
  104741. }
  104742. /*
  104743. * Write total samples
  104744. */
  104745. {
  104746. const unsigned total_samples_byte_offset =
  104747. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104748. (
  104749. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104750. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104751. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104752. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104753. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104754. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104755. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104756. - 4
  104757. ) / 8;
  104758. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104759. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104760. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104761. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104762. b[4] = (FLAC__byte)(samples & 0xFF);
  104763. 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) {
  104764. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104765. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104766. return;
  104767. }
  104768. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104769. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104770. return;
  104771. }
  104772. }
  104773. /*
  104774. * Write min/max framesize
  104775. */
  104776. {
  104777. const unsigned min_framesize_offset =
  104778. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104779. (
  104780. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104781. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104782. ) / 8;
  104783. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104784. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104785. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104786. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104787. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104788. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104789. 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) {
  104790. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104791. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104792. return;
  104793. }
  104794. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104795. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104796. return;
  104797. }
  104798. }
  104799. /*
  104800. * Write seektable
  104801. */
  104802. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104803. unsigned i;
  104804. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104805. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104806. 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) {
  104807. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104808. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104809. return;
  104810. }
  104811. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104812. FLAC__uint64 xx;
  104813. unsigned x;
  104814. xx = encoder->private_->seek_table->points[i].sample_number;
  104815. b[7] = (FLAC__byte)xx; xx >>= 8;
  104816. b[6] = (FLAC__byte)xx; xx >>= 8;
  104817. b[5] = (FLAC__byte)xx; xx >>= 8;
  104818. b[4] = (FLAC__byte)xx; xx >>= 8;
  104819. b[3] = (FLAC__byte)xx; xx >>= 8;
  104820. b[2] = (FLAC__byte)xx; xx >>= 8;
  104821. b[1] = (FLAC__byte)xx; xx >>= 8;
  104822. b[0] = (FLAC__byte)xx; xx >>= 8;
  104823. xx = encoder->private_->seek_table->points[i].stream_offset;
  104824. b[15] = (FLAC__byte)xx; xx >>= 8;
  104825. b[14] = (FLAC__byte)xx; xx >>= 8;
  104826. b[13] = (FLAC__byte)xx; xx >>= 8;
  104827. b[12] = (FLAC__byte)xx; xx >>= 8;
  104828. b[11] = (FLAC__byte)xx; xx >>= 8;
  104829. b[10] = (FLAC__byte)xx; xx >>= 8;
  104830. b[9] = (FLAC__byte)xx; xx >>= 8;
  104831. b[8] = (FLAC__byte)xx; xx >>= 8;
  104832. x = encoder->private_->seek_table->points[i].frame_samples;
  104833. b[17] = (FLAC__byte)x; x >>= 8;
  104834. b[16] = (FLAC__byte)x; x >>= 8;
  104835. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104836. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104837. return;
  104838. }
  104839. }
  104840. }
  104841. }
  104842. #if FLAC__HAS_OGG
  104843. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104844. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104845. {
  104846. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104847. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104848. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104849. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104850. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104851. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104852. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104853. FLAC__STREAM_SYNC_LENGTH
  104854. ;
  104855. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104856. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104857. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104858. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104859. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104860. ogg_page page;
  104861. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104862. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104863. /* Pre-check that client supports seeking, since we don't want the
  104864. * ogg_helper code to ever have to deal with this condition.
  104865. */
  104866. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104867. return;
  104868. /* All this is based on intimate knowledge of the stream header
  104869. * layout, but a change to the header format that would break this
  104870. * would also break all streams encoded in the previous format.
  104871. */
  104872. /**
  104873. ** Write STREAMINFO stats
  104874. **/
  104875. simple_ogg_page__init(&page);
  104876. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104877. simple_ogg_page__clear(&page);
  104878. return; /* state already set */
  104879. }
  104880. /*
  104881. * Write MD5 signature
  104882. */
  104883. {
  104884. const unsigned md5_offset =
  104885. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104886. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104887. (
  104888. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104889. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104890. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104891. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104892. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104893. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104894. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104895. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104896. ) / 8;
  104897. if(md5_offset + 16 > (unsigned)page.body_len) {
  104898. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104899. simple_ogg_page__clear(&page);
  104900. return;
  104901. }
  104902. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104903. }
  104904. /*
  104905. * Write total samples
  104906. */
  104907. {
  104908. const unsigned total_samples_byte_offset =
  104909. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104910. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104911. (
  104912. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104913. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104914. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104915. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104916. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104917. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104918. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104919. - 4
  104920. ) / 8;
  104921. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104922. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104923. simple_ogg_page__clear(&page);
  104924. return;
  104925. }
  104926. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104927. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104928. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104929. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104930. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104931. b[4] = (FLAC__byte)(samples & 0xFF);
  104932. memcpy(page.body + total_samples_byte_offset, b, 5);
  104933. }
  104934. /*
  104935. * Write min/max framesize
  104936. */
  104937. {
  104938. const unsigned min_framesize_offset =
  104939. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104940. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104941. (
  104942. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104943. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104944. ) / 8;
  104945. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104946. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104947. simple_ogg_page__clear(&page);
  104948. return;
  104949. }
  104950. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104951. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104952. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104953. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104954. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104955. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104956. memcpy(page.body + min_framesize_offset, b, 6);
  104957. }
  104958. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104959. simple_ogg_page__clear(&page);
  104960. return; /* state already set */
  104961. }
  104962. simple_ogg_page__clear(&page);
  104963. /*
  104964. * Write seektable
  104965. */
  104966. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104967. unsigned i;
  104968. FLAC__byte *p;
  104969. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104970. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104971. simple_ogg_page__init(&page);
  104972. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104973. simple_ogg_page__clear(&page);
  104974. return; /* state already set */
  104975. }
  104976. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104977. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104978. simple_ogg_page__clear(&page);
  104979. return;
  104980. }
  104981. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104982. FLAC__uint64 xx;
  104983. unsigned x;
  104984. xx = encoder->private_->seek_table->points[i].sample_number;
  104985. b[7] = (FLAC__byte)xx; xx >>= 8;
  104986. b[6] = (FLAC__byte)xx; xx >>= 8;
  104987. b[5] = (FLAC__byte)xx; xx >>= 8;
  104988. b[4] = (FLAC__byte)xx; xx >>= 8;
  104989. b[3] = (FLAC__byte)xx; xx >>= 8;
  104990. b[2] = (FLAC__byte)xx; xx >>= 8;
  104991. b[1] = (FLAC__byte)xx; xx >>= 8;
  104992. b[0] = (FLAC__byte)xx; xx >>= 8;
  104993. xx = encoder->private_->seek_table->points[i].stream_offset;
  104994. b[15] = (FLAC__byte)xx; xx >>= 8;
  104995. b[14] = (FLAC__byte)xx; xx >>= 8;
  104996. b[13] = (FLAC__byte)xx; xx >>= 8;
  104997. b[12] = (FLAC__byte)xx; xx >>= 8;
  104998. b[11] = (FLAC__byte)xx; xx >>= 8;
  104999. b[10] = (FLAC__byte)xx; xx >>= 8;
  105000. b[9] = (FLAC__byte)xx; xx >>= 8;
  105001. b[8] = (FLAC__byte)xx; xx >>= 8;
  105002. x = encoder->private_->seek_table->points[i].frame_samples;
  105003. b[17] = (FLAC__byte)x; x >>= 8;
  105004. b[16] = (FLAC__byte)x; x >>= 8;
  105005. memcpy(p, b, 18);
  105006. }
  105007. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  105008. simple_ogg_page__clear(&page);
  105009. return; /* state already set */
  105010. }
  105011. simple_ogg_page__clear(&page);
  105012. }
  105013. }
  105014. #endif
  105015. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  105016. {
  105017. FLAC__uint16 crc;
  105018. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  105019. /*
  105020. * Accumulate raw signal to the MD5 signature
  105021. */
  105022. 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)) {
  105023. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  105024. return false;
  105025. }
  105026. /*
  105027. * Process the frame header and subframes into the frame bitbuffer
  105028. */
  105029. if(!process_subframes_(encoder, is_fractional_block)) {
  105030. /* the above function sets the state for us in case of an error */
  105031. return false;
  105032. }
  105033. /*
  105034. * Zero-pad the frame to a byte_boundary
  105035. */
  105036. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  105037. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  105038. return false;
  105039. }
  105040. /*
  105041. * CRC-16 the whole thing
  105042. */
  105043. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  105044. if(
  105045. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  105046. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  105047. ) {
  105048. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  105049. return false;
  105050. }
  105051. /*
  105052. * Write it
  105053. */
  105054. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  105055. /* the above function sets the state for us in case of an error */
  105056. return false;
  105057. }
  105058. /*
  105059. * Get ready for the next frame
  105060. */
  105061. encoder->private_->current_sample_number = 0;
  105062. encoder->private_->current_frame_number++;
  105063. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  105064. return true;
  105065. }
  105066. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  105067. {
  105068. FLAC__FrameHeader frame_header;
  105069. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  105070. FLAC__bool do_independent, do_mid_side;
  105071. /*
  105072. * Calculate the min,max Rice partition orders
  105073. */
  105074. if(is_fractional_block) {
  105075. max_partition_order = 0;
  105076. }
  105077. else {
  105078. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  105079. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  105080. }
  105081. min_partition_order = min(min_partition_order, max_partition_order);
  105082. /*
  105083. * Setup the frame
  105084. */
  105085. frame_header.blocksize = encoder->protected_->blocksize;
  105086. frame_header.sample_rate = encoder->protected_->sample_rate;
  105087. frame_header.channels = encoder->protected_->channels;
  105088. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  105089. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  105090. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  105091. frame_header.number.frame_number = encoder->private_->current_frame_number;
  105092. /*
  105093. * Figure out what channel assignments to try
  105094. */
  105095. if(encoder->protected_->do_mid_side_stereo) {
  105096. if(encoder->protected_->loose_mid_side_stereo) {
  105097. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  105098. do_independent = true;
  105099. do_mid_side = true;
  105100. }
  105101. else {
  105102. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  105103. do_mid_side = !do_independent;
  105104. }
  105105. }
  105106. else {
  105107. do_independent = true;
  105108. do_mid_side = true;
  105109. }
  105110. }
  105111. else {
  105112. do_independent = true;
  105113. do_mid_side = false;
  105114. }
  105115. FLAC__ASSERT(do_independent || do_mid_side);
  105116. /*
  105117. * Check for wasted bits; set effective bps for each subframe
  105118. */
  105119. if(do_independent) {
  105120. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105121. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  105122. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  105123. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  105124. }
  105125. }
  105126. if(do_mid_side) {
  105127. FLAC__ASSERT(encoder->protected_->channels == 2);
  105128. for(channel = 0; channel < 2; channel++) {
  105129. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  105130. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  105131. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  105132. }
  105133. }
  105134. /*
  105135. * First do a normal encoding pass of each independent channel
  105136. */
  105137. if(do_independent) {
  105138. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105139. if(!
  105140. process_subframe_(
  105141. encoder,
  105142. min_partition_order,
  105143. max_partition_order,
  105144. &frame_header,
  105145. encoder->private_->subframe_bps[channel],
  105146. encoder->private_->integer_signal[channel],
  105147. encoder->private_->subframe_workspace_ptr[channel],
  105148. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  105149. encoder->private_->residual_workspace[channel],
  105150. encoder->private_->best_subframe+channel,
  105151. encoder->private_->best_subframe_bits+channel
  105152. )
  105153. )
  105154. return false;
  105155. }
  105156. }
  105157. /*
  105158. * Now do mid and side channels if requested
  105159. */
  105160. if(do_mid_side) {
  105161. FLAC__ASSERT(encoder->protected_->channels == 2);
  105162. for(channel = 0; channel < 2; channel++) {
  105163. if(!
  105164. process_subframe_(
  105165. encoder,
  105166. min_partition_order,
  105167. max_partition_order,
  105168. &frame_header,
  105169. encoder->private_->subframe_bps_mid_side[channel],
  105170. encoder->private_->integer_signal_mid_side[channel],
  105171. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  105172. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  105173. encoder->private_->residual_workspace_mid_side[channel],
  105174. encoder->private_->best_subframe_mid_side+channel,
  105175. encoder->private_->best_subframe_bits_mid_side+channel
  105176. )
  105177. )
  105178. return false;
  105179. }
  105180. }
  105181. /*
  105182. * Compose the frame bitbuffer
  105183. */
  105184. if(do_mid_side) {
  105185. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105186. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105187. FLAC__ChannelAssignment channel_assignment;
  105188. FLAC__ASSERT(encoder->protected_->channels == 2);
  105189. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105190. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105191. }
  105192. else {
  105193. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105194. unsigned min_bits;
  105195. int ca;
  105196. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105197. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105198. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105199. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105200. FLAC__ASSERT(do_independent && do_mid_side);
  105201. /* We have to figure out which channel assignent results in the smallest frame */
  105202. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105203. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105204. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105205. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105206. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105207. min_bits = bits[channel_assignment];
  105208. for(ca = 1; ca <= 3; ca++) {
  105209. if(bits[ca] < min_bits) {
  105210. min_bits = bits[ca];
  105211. channel_assignment = (FLAC__ChannelAssignment)ca;
  105212. }
  105213. }
  105214. }
  105215. frame_header.channel_assignment = channel_assignment;
  105216. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105217. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105218. return false;
  105219. }
  105220. switch(channel_assignment) {
  105221. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105222. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105223. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105224. break;
  105225. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105226. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105227. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105228. break;
  105229. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105230. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105231. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105232. break;
  105233. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105234. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105235. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105236. break;
  105237. default:
  105238. FLAC__ASSERT(0);
  105239. }
  105240. switch(channel_assignment) {
  105241. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105242. left_bps = encoder->private_->subframe_bps [0];
  105243. right_bps = encoder->private_->subframe_bps [1];
  105244. break;
  105245. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105246. left_bps = encoder->private_->subframe_bps [0];
  105247. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105248. break;
  105249. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105250. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105251. right_bps = encoder->private_->subframe_bps [1];
  105252. break;
  105253. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105254. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105255. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105256. break;
  105257. default:
  105258. FLAC__ASSERT(0);
  105259. }
  105260. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105261. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105262. return false;
  105263. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105264. return false;
  105265. }
  105266. else {
  105267. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105268. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105269. return false;
  105270. }
  105271. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105272. 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)) {
  105273. /* the above function sets the state for us in case of an error */
  105274. return false;
  105275. }
  105276. }
  105277. }
  105278. if(encoder->protected_->loose_mid_side_stereo) {
  105279. encoder->private_->loose_mid_side_stereo_frame_count++;
  105280. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105281. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105282. }
  105283. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105284. return true;
  105285. }
  105286. FLAC__bool process_subframe_(
  105287. FLAC__StreamEncoder *encoder,
  105288. unsigned min_partition_order,
  105289. unsigned max_partition_order,
  105290. const FLAC__FrameHeader *frame_header,
  105291. unsigned subframe_bps,
  105292. const FLAC__int32 integer_signal[],
  105293. FLAC__Subframe *subframe[2],
  105294. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105295. FLAC__int32 *residual[2],
  105296. unsigned *best_subframe,
  105297. unsigned *best_bits
  105298. )
  105299. {
  105300. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105301. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105302. #else
  105303. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105304. #endif
  105305. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105306. FLAC__double lpc_residual_bits_per_sample;
  105307. 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 */
  105308. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105309. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105310. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105311. #endif
  105312. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105313. unsigned rice_parameter;
  105314. unsigned _candidate_bits, _best_bits;
  105315. unsigned _best_subframe;
  105316. /* only use RICE2 partitions if stream bps > 16 */
  105317. 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;
  105318. FLAC__ASSERT(frame_header->blocksize > 0);
  105319. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105320. _best_subframe = 0;
  105321. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105322. _best_bits = UINT_MAX;
  105323. else
  105324. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105325. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105326. unsigned signal_is_constant = false;
  105327. 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);
  105328. /* check for constant subframe */
  105329. if(
  105330. !encoder->private_->disable_constant_subframes &&
  105331. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105332. fixed_residual_bits_per_sample[1] == 0.0
  105333. #else
  105334. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105335. #endif
  105336. ) {
  105337. /* the above means it's possible all samples are the same value; now double-check it: */
  105338. unsigned i;
  105339. signal_is_constant = true;
  105340. for(i = 1; i < frame_header->blocksize; i++) {
  105341. if(integer_signal[0] != integer_signal[i]) {
  105342. signal_is_constant = false;
  105343. break;
  105344. }
  105345. }
  105346. }
  105347. if(signal_is_constant) {
  105348. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105349. if(_candidate_bits < _best_bits) {
  105350. _best_subframe = !_best_subframe;
  105351. _best_bits = _candidate_bits;
  105352. }
  105353. }
  105354. else {
  105355. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105356. /* encode fixed */
  105357. if(encoder->protected_->do_exhaustive_model_search) {
  105358. min_fixed_order = 0;
  105359. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105360. }
  105361. else {
  105362. min_fixed_order = max_fixed_order = guess_fixed_order;
  105363. }
  105364. if(max_fixed_order >= frame_header->blocksize)
  105365. max_fixed_order = frame_header->blocksize - 1;
  105366. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105367. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105368. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105369. continue; /* don't even try */
  105370. 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 */
  105371. #else
  105372. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105373. continue; /* don't even try */
  105374. 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 */
  105375. #endif
  105376. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105377. if(rice_parameter >= rice_parameter_limit) {
  105378. #ifdef DEBUG_VERBOSE
  105379. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105380. #endif
  105381. rice_parameter = rice_parameter_limit - 1;
  105382. }
  105383. _candidate_bits =
  105384. evaluate_fixed_subframe_(
  105385. encoder,
  105386. integer_signal,
  105387. residual[!_best_subframe],
  105388. encoder->private_->abs_residual_partition_sums,
  105389. encoder->private_->raw_bits_per_partition,
  105390. frame_header->blocksize,
  105391. subframe_bps,
  105392. fixed_order,
  105393. rice_parameter,
  105394. rice_parameter_limit,
  105395. min_partition_order,
  105396. max_partition_order,
  105397. encoder->protected_->do_escape_coding,
  105398. encoder->protected_->rice_parameter_search_dist,
  105399. subframe[!_best_subframe],
  105400. partitioned_rice_contents[!_best_subframe]
  105401. );
  105402. if(_candidate_bits < _best_bits) {
  105403. _best_subframe = !_best_subframe;
  105404. _best_bits = _candidate_bits;
  105405. }
  105406. }
  105407. }
  105408. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105409. /* encode lpc */
  105410. if(encoder->protected_->max_lpc_order > 0) {
  105411. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105412. max_lpc_order = frame_header->blocksize-1;
  105413. else
  105414. max_lpc_order = encoder->protected_->max_lpc_order;
  105415. if(max_lpc_order > 0) {
  105416. unsigned a;
  105417. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105418. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105419. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105420. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105421. if(autoc[0] != 0.0) {
  105422. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105423. if(encoder->protected_->do_exhaustive_model_search) {
  105424. min_lpc_order = 1;
  105425. }
  105426. else {
  105427. const unsigned guess_lpc_order =
  105428. FLAC__lpc_compute_best_order(
  105429. lpc_error,
  105430. max_lpc_order,
  105431. frame_header->blocksize,
  105432. subframe_bps + (
  105433. encoder->protected_->do_qlp_coeff_prec_search?
  105434. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105435. encoder->protected_->qlp_coeff_precision
  105436. )
  105437. );
  105438. min_lpc_order = max_lpc_order = guess_lpc_order;
  105439. }
  105440. if(max_lpc_order >= frame_header->blocksize)
  105441. max_lpc_order = frame_header->blocksize - 1;
  105442. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105443. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105444. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105445. continue; /* don't even try */
  105446. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105447. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105448. if(rice_parameter >= rice_parameter_limit) {
  105449. #ifdef DEBUG_VERBOSE
  105450. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105451. #endif
  105452. rice_parameter = rice_parameter_limit - 1;
  105453. }
  105454. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105455. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105456. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105457. if(subframe_bps <= 17) {
  105458. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105459. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105460. }
  105461. else
  105462. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105463. }
  105464. else {
  105465. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105466. }
  105467. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105468. _candidate_bits =
  105469. evaluate_lpc_subframe_(
  105470. encoder,
  105471. integer_signal,
  105472. residual[!_best_subframe],
  105473. encoder->private_->abs_residual_partition_sums,
  105474. encoder->private_->raw_bits_per_partition,
  105475. encoder->private_->lp_coeff[lpc_order-1],
  105476. frame_header->blocksize,
  105477. subframe_bps,
  105478. lpc_order,
  105479. qlp_coeff_precision,
  105480. rice_parameter,
  105481. rice_parameter_limit,
  105482. min_partition_order,
  105483. max_partition_order,
  105484. encoder->protected_->do_escape_coding,
  105485. encoder->protected_->rice_parameter_search_dist,
  105486. subframe[!_best_subframe],
  105487. partitioned_rice_contents[!_best_subframe]
  105488. );
  105489. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105490. if(_candidate_bits < _best_bits) {
  105491. _best_subframe = !_best_subframe;
  105492. _best_bits = _candidate_bits;
  105493. }
  105494. }
  105495. }
  105496. }
  105497. }
  105498. }
  105499. }
  105500. }
  105501. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105502. }
  105503. }
  105504. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105505. if(_best_bits == UINT_MAX) {
  105506. FLAC__ASSERT(_best_subframe == 0);
  105507. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105508. }
  105509. *best_subframe = _best_subframe;
  105510. *best_bits = _best_bits;
  105511. return true;
  105512. }
  105513. FLAC__bool add_subframe_(
  105514. FLAC__StreamEncoder *encoder,
  105515. unsigned blocksize,
  105516. unsigned subframe_bps,
  105517. const FLAC__Subframe *subframe,
  105518. FLAC__BitWriter *frame
  105519. )
  105520. {
  105521. switch(subframe->type) {
  105522. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105523. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105524. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105525. return false;
  105526. }
  105527. break;
  105528. case FLAC__SUBFRAME_TYPE_FIXED:
  105529. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105530. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105531. return false;
  105532. }
  105533. break;
  105534. case FLAC__SUBFRAME_TYPE_LPC:
  105535. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105536. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105537. return false;
  105538. }
  105539. break;
  105540. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105541. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105542. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105543. return false;
  105544. }
  105545. break;
  105546. default:
  105547. FLAC__ASSERT(0);
  105548. }
  105549. return true;
  105550. }
  105551. #define SPOTCHECK_ESTIMATE 0
  105552. #if SPOTCHECK_ESTIMATE
  105553. static void spotcheck_subframe_estimate_(
  105554. FLAC__StreamEncoder *encoder,
  105555. unsigned blocksize,
  105556. unsigned subframe_bps,
  105557. const FLAC__Subframe *subframe,
  105558. unsigned estimate
  105559. )
  105560. {
  105561. FLAC__bool ret;
  105562. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105563. if(frame == 0) {
  105564. fprintf(stderr, "EST: can't allocate frame\n");
  105565. return;
  105566. }
  105567. if(!FLAC__bitwriter_init(frame)) {
  105568. fprintf(stderr, "EST: can't init frame\n");
  105569. return;
  105570. }
  105571. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105572. FLAC__ASSERT(ret);
  105573. {
  105574. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105575. if(estimate != actual)
  105576. 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);
  105577. }
  105578. FLAC__bitwriter_delete(frame);
  105579. }
  105580. #endif
  105581. unsigned evaluate_constant_subframe_(
  105582. FLAC__StreamEncoder *encoder,
  105583. const FLAC__int32 signal,
  105584. unsigned blocksize,
  105585. unsigned subframe_bps,
  105586. FLAC__Subframe *subframe
  105587. )
  105588. {
  105589. unsigned estimate;
  105590. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105591. subframe->data.constant.value = signal;
  105592. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105593. #if SPOTCHECK_ESTIMATE
  105594. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105595. #else
  105596. (void)encoder, (void)blocksize;
  105597. #endif
  105598. return estimate;
  105599. }
  105600. unsigned evaluate_fixed_subframe_(
  105601. FLAC__StreamEncoder *encoder,
  105602. const FLAC__int32 signal[],
  105603. FLAC__int32 residual[],
  105604. FLAC__uint64 abs_residual_partition_sums[],
  105605. unsigned raw_bits_per_partition[],
  105606. unsigned blocksize,
  105607. unsigned subframe_bps,
  105608. unsigned order,
  105609. unsigned rice_parameter,
  105610. unsigned rice_parameter_limit,
  105611. unsigned min_partition_order,
  105612. unsigned max_partition_order,
  105613. FLAC__bool do_escape_coding,
  105614. unsigned rice_parameter_search_dist,
  105615. FLAC__Subframe *subframe,
  105616. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105617. )
  105618. {
  105619. unsigned i, residual_bits, estimate;
  105620. const unsigned residual_samples = blocksize - order;
  105621. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105622. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105623. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105624. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105625. subframe->data.fixed.residual = residual;
  105626. residual_bits =
  105627. find_best_partition_order_(
  105628. encoder->private_,
  105629. residual,
  105630. abs_residual_partition_sums,
  105631. raw_bits_per_partition,
  105632. residual_samples,
  105633. order,
  105634. rice_parameter,
  105635. rice_parameter_limit,
  105636. min_partition_order,
  105637. max_partition_order,
  105638. subframe_bps,
  105639. do_escape_coding,
  105640. rice_parameter_search_dist,
  105641. &subframe->data.fixed.entropy_coding_method
  105642. );
  105643. subframe->data.fixed.order = order;
  105644. for(i = 0; i < order; i++)
  105645. subframe->data.fixed.warmup[i] = signal[i];
  105646. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105647. #if SPOTCHECK_ESTIMATE
  105648. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105649. #endif
  105650. return estimate;
  105651. }
  105652. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105653. unsigned evaluate_lpc_subframe_(
  105654. FLAC__StreamEncoder *encoder,
  105655. const FLAC__int32 signal[],
  105656. FLAC__int32 residual[],
  105657. FLAC__uint64 abs_residual_partition_sums[],
  105658. unsigned raw_bits_per_partition[],
  105659. const FLAC__real lp_coeff[],
  105660. unsigned blocksize,
  105661. unsigned subframe_bps,
  105662. unsigned order,
  105663. unsigned qlp_coeff_precision,
  105664. unsigned rice_parameter,
  105665. unsigned rice_parameter_limit,
  105666. unsigned min_partition_order,
  105667. unsigned max_partition_order,
  105668. FLAC__bool do_escape_coding,
  105669. unsigned rice_parameter_search_dist,
  105670. FLAC__Subframe *subframe,
  105671. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105672. )
  105673. {
  105674. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105675. unsigned i, residual_bits, estimate;
  105676. int quantization, ret;
  105677. const unsigned residual_samples = blocksize - order;
  105678. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105679. if(subframe_bps <= 16) {
  105680. FLAC__ASSERT(order > 0);
  105681. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105682. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105683. }
  105684. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105685. if(ret != 0)
  105686. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105687. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105688. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105689. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105690. else
  105691. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105692. else
  105693. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105694. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105695. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105696. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105697. subframe->data.lpc.residual = residual;
  105698. residual_bits =
  105699. find_best_partition_order_(
  105700. encoder->private_,
  105701. residual,
  105702. abs_residual_partition_sums,
  105703. raw_bits_per_partition,
  105704. residual_samples,
  105705. order,
  105706. rice_parameter,
  105707. rice_parameter_limit,
  105708. min_partition_order,
  105709. max_partition_order,
  105710. subframe_bps,
  105711. do_escape_coding,
  105712. rice_parameter_search_dist,
  105713. &subframe->data.lpc.entropy_coding_method
  105714. );
  105715. subframe->data.lpc.order = order;
  105716. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105717. subframe->data.lpc.quantization_level = quantization;
  105718. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105719. for(i = 0; i < order; i++)
  105720. subframe->data.lpc.warmup[i] = signal[i];
  105721. 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;
  105722. #if SPOTCHECK_ESTIMATE
  105723. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105724. #endif
  105725. return estimate;
  105726. }
  105727. #endif
  105728. unsigned evaluate_verbatim_subframe_(
  105729. FLAC__StreamEncoder *encoder,
  105730. const FLAC__int32 signal[],
  105731. unsigned blocksize,
  105732. unsigned subframe_bps,
  105733. FLAC__Subframe *subframe
  105734. )
  105735. {
  105736. unsigned estimate;
  105737. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105738. subframe->data.verbatim.data = signal;
  105739. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105740. #if SPOTCHECK_ESTIMATE
  105741. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105742. #else
  105743. (void)encoder;
  105744. #endif
  105745. return estimate;
  105746. }
  105747. unsigned find_best_partition_order_(
  105748. FLAC__StreamEncoderPrivate *private_,
  105749. const FLAC__int32 residual[],
  105750. FLAC__uint64 abs_residual_partition_sums[],
  105751. unsigned raw_bits_per_partition[],
  105752. unsigned residual_samples,
  105753. unsigned predictor_order,
  105754. unsigned rice_parameter,
  105755. unsigned rice_parameter_limit,
  105756. unsigned min_partition_order,
  105757. unsigned max_partition_order,
  105758. unsigned bps,
  105759. FLAC__bool do_escape_coding,
  105760. unsigned rice_parameter_search_dist,
  105761. FLAC__EntropyCodingMethod *best_ecm
  105762. )
  105763. {
  105764. unsigned residual_bits, best_residual_bits = 0;
  105765. unsigned best_parameters_index = 0;
  105766. unsigned best_partition_order = 0;
  105767. const unsigned blocksize = residual_samples + predictor_order;
  105768. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105769. min_partition_order = min(min_partition_order, max_partition_order);
  105770. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105771. if(do_escape_coding)
  105772. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105773. {
  105774. int partition_order;
  105775. unsigned sum;
  105776. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105777. if(!
  105778. set_partitioned_rice_(
  105779. #ifdef EXACT_RICE_BITS_CALCULATION
  105780. residual,
  105781. #endif
  105782. abs_residual_partition_sums+sum,
  105783. raw_bits_per_partition+sum,
  105784. residual_samples,
  105785. predictor_order,
  105786. rice_parameter,
  105787. rice_parameter_limit,
  105788. rice_parameter_search_dist,
  105789. (unsigned)partition_order,
  105790. do_escape_coding,
  105791. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105792. &residual_bits
  105793. )
  105794. )
  105795. {
  105796. FLAC__ASSERT(best_residual_bits != 0);
  105797. break;
  105798. }
  105799. sum += 1u << partition_order;
  105800. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105801. best_residual_bits = residual_bits;
  105802. best_parameters_index = !best_parameters_index;
  105803. best_partition_order = partition_order;
  105804. }
  105805. }
  105806. }
  105807. best_ecm->data.partitioned_rice.order = best_partition_order;
  105808. {
  105809. /*
  105810. * We are allowed to de-const the pointer based on our special
  105811. * knowledge; it is const to the outside world.
  105812. */
  105813. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105814. unsigned partition;
  105815. /* save best parameters and raw_bits */
  105816. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105817. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105818. if(do_escape_coding)
  105819. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105820. /*
  105821. * Now need to check if the type should be changed to
  105822. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105823. * size of the rice parameters.
  105824. */
  105825. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105826. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105827. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105828. break;
  105829. }
  105830. }
  105831. }
  105832. return best_residual_bits;
  105833. }
  105834. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105835. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105836. const FLAC__int32 residual[],
  105837. FLAC__uint64 abs_residual_partition_sums[],
  105838. unsigned blocksize,
  105839. unsigned predictor_order,
  105840. unsigned min_partition_order,
  105841. unsigned max_partition_order
  105842. );
  105843. #endif
  105844. void precompute_partition_info_sums_(
  105845. const FLAC__int32 residual[],
  105846. FLAC__uint64 abs_residual_partition_sums[],
  105847. unsigned residual_samples,
  105848. unsigned predictor_order,
  105849. unsigned min_partition_order,
  105850. unsigned max_partition_order,
  105851. unsigned bps
  105852. )
  105853. {
  105854. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105855. unsigned partitions = 1u << max_partition_order;
  105856. FLAC__ASSERT(default_partition_samples > predictor_order);
  105857. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105858. /* slightly pessimistic but still catches all common cases */
  105859. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105860. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105861. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105862. return;
  105863. }
  105864. #endif
  105865. /* first do max_partition_order */
  105866. {
  105867. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105868. /* slightly pessimistic but still catches all common cases */
  105869. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105870. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105871. FLAC__uint32 abs_residual_partition_sum;
  105872. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105873. end += default_partition_samples;
  105874. abs_residual_partition_sum = 0;
  105875. for( ; residual_sample < end; residual_sample++)
  105876. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105877. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105878. }
  105879. }
  105880. else { /* have to pessimistically use 64 bits for accumulator */
  105881. FLAC__uint64 abs_residual_partition_sum;
  105882. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105883. end += default_partition_samples;
  105884. abs_residual_partition_sum = 0;
  105885. for( ; residual_sample < end; residual_sample++)
  105886. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105887. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105888. }
  105889. }
  105890. }
  105891. /* now merge partitions for lower orders */
  105892. {
  105893. unsigned from_partition = 0, to_partition = partitions;
  105894. int partition_order;
  105895. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105896. unsigned i;
  105897. partitions >>= 1;
  105898. for(i = 0; i < partitions; i++) {
  105899. abs_residual_partition_sums[to_partition++] =
  105900. abs_residual_partition_sums[from_partition ] +
  105901. abs_residual_partition_sums[from_partition+1];
  105902. from_partition += 2;
  105903. }
  105904. }
  105905. }
  105906. }
  105907. void precompute_partition_info_escapes_(
  105908. const FLAC__int32 residual[],
  105909. unsigned raw_bits_per_partition[],
  105910. unsigned residual_samples,
  105911. unsigned predictor_order,
  105912. unsigned min_partition_order,
  105913. unsigned max_partition_order
  105914. )
  105915. {
  105916. int partition_order;
  105917. unsigned from_partition, to_partition = 0;
  105918. const unsigned blocksize = residual_samples + predictor_order;
  105919. /* first do max_partition_order */
  105920. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105921. FLAC__int32 r;
  105922. FLAC__uint32 rmax;
  105923. unsigned partition, partition_sample, partition_samples, residual_sample;
  105924. const unsigned partitions = 1u << partition_order;
  105925. const unsigned default_partition_samples = blocksize >> partition_order;
  105926. FLAC__ASSERT(default_partition_samples > predictor_order);
  105927. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105928. partition_samples = default_partition_samples;
  105929. if(partition == 0)
  105930. partition_samples -= predictor_order;
  105931. rmax = 0;
  105932. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105933. r = residual[residual_sample++];
  105934. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105935. if(r < 0)
  105936. rmax |= ~r;
  105937. else
  105938. rmax |= r;
  105939. }
  105940. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105941. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105942. }
  105943. to_partition = partitions;
  105944. break; /*@@@ yuck, should remove the 'for' loop instead */
  105945. }
  105946. /* now merge partitions for lower orders */
  105947. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105948. unsigned m;
  105949. unsigned i;
  105950. const unsigned partitions = 1u << partition_order;
  105951. for(i = 0; i < partitions; i++) {
  105952. m = raw_bits_per_partition[from_partition];
  105953. from_partition++;
  105954. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105955. from_partition++;
  105956. to_partition++;
  105957. }
  105958. }
  105959. }
  105960. #ifdef EXACT_RICE_BITS_CALCULATION
  105961. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105962. const unsigned rice_parameter,
  105963. const unsigned partition_samples,
  105964. const FLAC__int32 *residual
  105965. )
  105966. {
  105967. unsigned i, partition_bits =
  105968. 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 */
  105969. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105970. ;
  105971. for(i = 0; i < partition_samples; i++)
  105972. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105973. return partition_bits;
  105974. }
  105975. #else
  105976. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105977. const unsigned rice_parameter,
  105978. const unsigned partition_samples,
  105979. const FLAC__uint64 abs_residual_partition_sum
  105980. )
  105981. {
  105982. return
  105983. 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 */
  105984. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105985. (
  105986. rice_parameter?
  105987. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105988. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105989. )
  105990. - (partition_samples >> 1)
  105991. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105992. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105993. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105994. * So the subtraction term tries to guess how many extra bits were contributed.
  105995. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105996. */
  105997. ;
  105998. }
  105999. #endif
  106000. FLAC__bool set_partitioned_rice_(
  106001. #ifdef EXACT_RICE_BITS_CALCULATION
  106002. const FLAC__int32 residual[],
  106003. #endif
  106004. const FLAC__uint64 abs_residual_partition_sums[],
  106005. const unsigned raw_bits_per_partition[],
  106006. const unsigned residual_samples,
  106007. const unsigned predictor_order,
  106008. const unsigned suggested_rice_parameter,
  106009. const unsigned rice_parameter_limit,
  106010. const unsigned rice_parameter_search_dist,
  106011. const unsigned partition_order,
  106012. const FLAC__bool search_for_escapes,
  106013. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  106014. unsigned *bits
  106015. )
  106016. {
  106017. unsigned rice_parameter, partition_bits;
  106018. unsigned best_partition_bits, best_rice_parameter = 0;
  106019. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  106020. unsigned *parameters, *raw_bits;
  106021. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106022. unsigned min_rice_parameter, max_rice_parameter;
  106023. #else
  106024. (void)rice_parameter_search_dist;
  106025. #endif
  106026. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  106027. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  106028. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  106029. parameters = partitioned_rice_contents->parameters;
  106030. raw_bits = partitioned_rice_contents->raw_bits;
  106031. if(partition_order == 0) {
  106032. best_partition_bits = (unsigned)(-1);
  106033. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106034. if(rice_parameter_search_dist) {
  106035. if(suggested_rice_parameter < rice_parameter_search_dist)
  106036. min_rice_parameter = 0;
  106037. else
  106038. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  106039. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  106040. if(max_rice_parameter >= rice_parameter_limit) {
  106041. #ifdef DEBUG_VERBOSE
  106042. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  106043. #endif
  106044. max_rice_parameter = rice_parameter_limit - 1;
  106045. }
  106046. }
  106047. else
  106048. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  106049. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106050. #else
  106051. rice_parameter = suggested_rice_parameter;
  106052. #endif
  106053. #ifdef EXACT_RICE_BITS_CALCULATION
  106054. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  106055. #else
  106056. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  106057. #endif
  106058. if(partition_bits < best_partition_bits) {
  106059. best_rice_parameter = rice_parameter;
  106060. best_partition_bits = partition_bits;
  106061. }
  106062. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106063. }
  106064. #endif
  106065. if(search_for_escapes) {
  106066. 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;
  106067. if(partition_bits <= best_partition_bits) {
  106068. raw_bits[0] = raw_bits_per_partition[0];
  106069. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106070. best_partition_bits = partition_bits;
  106071. }
  106072. else
  106073. raw_bits[0] = 0;
  106074. }
  106075. parameters[0] = best_rice_parameter;
  106076. bits_ += best_partition_bits;
  106077. }
  106078. else {
  106079. unsigned partition, residual_sample;
  106080. unsigned partition_samples;
  106081. FLAC__uint64 mean, k;
  106082. const unsigned partitions = 1u << partition_order;
  106083. for(partition = residual_sample = 0; partition < partitions; partition++) {
  106084. partition_samples = (residual_samples+predictor_order) >> partition_order;
  106085. if(partition == 0) {
  106086. if(partition_samples <= predictor_order)
  106087. return false;
  106088. else
  106089. partition_samples -= predictor_order;
  106090. }
  106091. mean = abs_residual_partition_sums[partition];
  106092. /* we are basically calculating the size in bits of the
  106093. * average residual magnitude in the partition:
  106094. * rice_parameter = floor(log2(mean/partition_samples))
  106095. * 'mean' is not a good name for the variable, it is
  106096. * actually the sum of magnitudes of all residual values
  106097. * in the partition, so the actual mean is
  106098. * mean/partition_samples
  106099. */
  106100. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  106101. ;
  106102. if(rice_parameter >= rice_parameter_limit) {
  106103. #ifdef DEBUG_VERBOSE
  106104. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  106105. #endif
  106106. rice_parameter = rice_parameter_limit - 1;
  106107. }
  106108. best_partition_bits = (unsigned)(-1);
  106109. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106110. if(rice_parameter_search_dist) {
  106111. if(rice_parameter < rice_parameter_search_dist)
  106112. min_rice_parameter = 0;
  106113. else
  106114. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  106115. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  106116. if(max_rice_parameter >= rice_parameter_limit) {
  106117. #ifdef DEBUG_VERBOSE
  106118. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  106119. #endif
  106120. max_rice_parameter = rice_parameter_limit - 1;
  106121. }
  106122. }
  106123. else
  106124. min_rice_parameter = max_rice_parameter = rice_parameter;
  106125. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106126. #endif
  106127. #ifdef EXACT_RICE_BITS_CALCULATION
  106128. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  106129. #else
  106130. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  106131. #endif
  106132. if(partition_bits < best_partition_bits) {
  106133. best_rice_parameter = rice_parameter;
  106134. best_partition_bits = partition_bits;
  106135. }
  106136. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106137. }
  106138. #endif
  106139. if(search_for_escapes) {
  106140. 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;
  106141. if(partition_bits <= best_partition_bits) {
  106142. raw_bits[partition] = raw_bits_per_partition[partition];
  106143. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106144. best_partition_bits = partition_bits;
  106145. }
  106146. else
  106147. raw_bits[partition] = 0;
  106148. }
  106149. parameters[partition] = best_rice_parameter;
  106150. bits_ += best_partition_bits;
  106151. residual_sample += partition_samples;
  106152. }
  106153. }
  106154. *bits = bits_;
  106155. return true;
  106156. }
  106157. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  106158. {
  106159. unsigned i, shift;
  106160. FLAC__int32 x = 0;
  106161. for(i = 0; i < samples && !(x&1); i++)
  106162. x |= signal[i];
  106163. if(x == 0) {
  106164. shift = 0;
  106165. }
  106166. else {
  106167. for(shift = 0; !(x&1); shift++)
  106168. x >>= 1;
  106169. }
  106170. if(shift > 0) {
  106171. for(i = 0; i < samples; i++)
  106172. signal[i] >>= shift;
  106173. }
  106174. return shift;
  106175. }
  106176. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106177. {
  106178. unsigned channel;
  106179. for(channel = 0; channel < channels; channel++)
  106180. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106181. fifo->tail += wide_samples;
  106182. FLAC__ASSERT(fifo->tail <= fifo->size);
  106183. }
  106184. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106185. {
  106186. unsigned channel;
  106187. unsigned sample, wide_sample;
  106188. unsigned tail = fifo->tail;
  106189. sample = input_offset * channels;
  106190. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106191. for(channel = 0; channel < channels; channel++)
  106192. fifo->data[channel][tail] = input[sample++];
  106193. tail++;
  106194. }
  106195. fifo->tail = tail;
  106196. FLAC__ASSERT(fifo->tail <= fifo->size);
  106197. }
  106198. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106199. {
  106200. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106201. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106202. (void)decoder;
  106203. if(encoder->private_->verify.needs_magic_hack) {
  106204. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106205. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106206. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106207. encoder->private_->verify.needs_magic_hack = false;
  106208. }
  106209. else {
  106210. if(encoded_bytes == 0) {
  106211. /*
  106212. * If we get here, a FIFO underflow has occurred,
  106213. * which means there is a bug somewhere.
  106214. */
  106215. FLAC__ASSERT(0);
  106216. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106217. }
  106218. else if(encoded_bytes < *bytes)
  106219. *bytes = encoded_bytes;
  106220. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106221. encoder->private_->verify.output.data += *bytes;
  106222. encoder->private_->verify.output.bytes -= *bytes;
  106223. }
  106224. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106225. }
  106226. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106227. {
  106228. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106229. unsigned channel;
  106230. const unsigned channels = frame->header.channels;
  106231. const unsigned blocksize = frame->header.blocksize;
  106232. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106233. (void)decoder;
  106234. for(channel = 0; channel < channels; channel++) {
  106235. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106236. unsigned i, sample = 0;
  106237. FLAC__int32 expect = 0, got = 0;
  106238. for(i = 0; i < blocksize; i++) {
  106239. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106240. sample = i;
  106241. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106242. got = (FLAC__int32)buffer[channel][i];
  106243. break;
  106244. }
  106245. }
  106246. FLAC__ASSERT(i < blocksize);
  106247. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106248. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106249. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106250. encoder->private_->verify.error_stats.channel = channel;
  106251. encoder->private_->verify.error_stats.sample = sample;
  106252. encoder->private_->verify.error_stats.expected = expect;
  106253. encoder->private_->verify.error_stats.got = got;
  106254. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106255. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106256. }
  106257. }
  106258. /* dequeue the frame from the fifo */
  106259. encoder->private_->verify.input_fifo.tail -= blocksize;
  106260. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106261. for(channel = 0; channel < channels; channel++)
  106262. 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]));
  106263. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106264. }
  106265. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106266. {
  106267. (void)decoder, (void)metadata, (void)client_data;
  106268. }
  106269. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106270. {
  106271. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106272. (void)decoder, (void)status;
  106273. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106274. }
  106275. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106276. {
  106277. (void)client_data;
  106278. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106279. if (*bytes == 0) {
  106280. if (feof(encoder->private_->file))
  106281. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106282. else if (ferror(encoder->private_->file))
  106283. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106284. }
  106285. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106286. }
  106287. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106288. {
  106289. (void)client_data;
  106290. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106291. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106292. else
  106293. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106294. }
  106295. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106296. {
  106297. off_t offset;
  106298. (void)client_data;
  106299. offset = ftello(encoder->private_->file);
  106300. if(offset < 0) {
  106301. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106302. }
  106303. else {
  106304. *absolute_byte_offset = (FLAC__uint64)offset;
  106305. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106306. }
  106307. }
  106308. #ifdef FLAC__VALGRIND_TESTING
  106309. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106310. {
  106311. size_t ret = fwrite(ptr, size, nmemb, stream);
  106312. if(!ferror(stream))
  106313. fflush(stream);
  106314. return ret;
  106315. }
  106316. #else
  106317. #define local__fwrite fwrite
  106318. #endif
  106319. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106320. {
  106321. (void)client_data, (void)current_frame;
  106322. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106323. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106324. #if FLAC__HAS_OGG
  106325. /* We would like to be able to use 'samples > 0' in the
  106326. * clause here but currently because of the nature of our
  106327. * Ogg writing implementation, 'samples' is always 0 (see
  106328. * ogg_encoder_aspect.c). The downside is extra progress
  106329. * callbacks.
  106330. */
  106331. encoder->private_->is_ogg? true :
  106332. #endif
  106333. samples > 0
  106334. );
  106335. if(call_it) {
  106336. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106337. * because at this point in the callback chain, the stats
  106338. * have not been updated. Only after we return and control
  106339. * gets back to write_frame_() are the stats updated
  106340. */
  106341. 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);
  106342. }
  106343. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106344. }
  106345. else
  106346. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106347. }
  106348. /*
  106349. * This will forcibly set stdout to binary mode (for OSes that require it)
  106350. */
  106351. FILE *get_binary_stdout_(void)
  106352. {
  106353. /* if something breaks here it is probably due to the presence or
  106354. * absence of an underscore before the identifiers 'setmode',
  106355. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106356. */
  106357. #if defined _MSC_VER || defined __MINGW32__
  106358. _setmode(_fileno(stdout), _O_BINARY);
  106359. #elif defined __CYGWIN__
  106360. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106361. setmode(_fileno(stdout), _O_BINARY);
  106362. #elif defined __EMX__
  106363. setmode(fileno(stdout), O_BINARY);
  106364. #endif
  106365. return stdout;
  106366. }
  106367. #endif
  106368. /*** End of inlined file: stream_encoder.c ***/
  106369. /*** Start of inlined file: stream_encoder_framing.c ***/
  106370. /*** Start of inlined file: juce_FlacHeader.h ***/
  106371. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106372. // tasks..
  106373. #define VERSION "1.2.1"
  106374. #define FLAC__NO_DLL 1
  106375. #if JUCE_MSVC
  106376. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106377. #endif
  106378. #if JUCE_MAC
  106379. #define FLAC__SYS_DARWIN 1
  106380. #endif
  106381. /*** End of inlined file: juce_FlacHeader.h ***/
  106382. #if JUCE_USE_FLAC
  106383. #if HAVE_CONFIG_H
  106384. # include <config.h>
  106385. #endif
  106386. #include <stdio.h>
  106387. #include <string.h> /* for strlen() */
  106388. #ifdef max
  106389. #undef max
  106390. #endif
  106391. #define max(x,y) ((x)>(y)?(x):(y))
  106392. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106393. 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);
  106394. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106395. {
  106396. unsigned i, j;
  106397. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106398. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106399. return false;
  106400. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106401. return false;
  106402. /*
  106403. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106404. */
  106405. i = metadata->length;
  106406. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106407. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106408. i -= metadata->data.vorbis_comment.vendor_string.length;
  106409. i += vendor_string_length;
  106410. }
  106411. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106412. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106413. return false;
  106414. switch(metadata->type) {
  106415. case FLAC__METADATA_TYPE_STREAMINFO:
  106416. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106417. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106418. return false;
  106419. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106420. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106421. return false;
  106422. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106423. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106424. return false;
  106425. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106426. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106427. return false;
  106428. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106429. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106430. return false;
  106431. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106432. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106433. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106434. return false;
  106435. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106436. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106437. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106438. return false;
  106439. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106440. return false;
  106441. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106442. return false;
  106443. break;
  106444. case FLAC__METADATA_TYPE_PADDING:
  106445. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106446. return false;
  106447. break;
  106448. case FLAC__METADATA_TYPE_APPLICATION:
  106449. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106450. return false;
  106451. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106452. return false;
  106453. break;
  106454. case FLAC__METADATA_TYPE_SEEKTABLE:
  106455. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106456. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106457. return false;
  106458. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106459. return false;
  106460. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106461. return false;
  106462. }
  106463. break;
  106464. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106465. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106466. return false;
  106467. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106468. return false;
  106469. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106470. return false;
  106471. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106472. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106473. return false;
  106474. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106475. return false;
  106476. }
  106477. break;
  106478. case FLAC__METADATA_TYPE_CUESHEET:
  106479. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106480. 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))
  106481. return false;
  106482. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106483. return false;
  106484. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106485. return false;
  106486. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106487. return false;
  106488. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106489. return false;
  106490. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106491. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106492. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106493. return false;
  106494. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106495. return false;
  106496. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106497. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106498. return false;
  106499. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106500. return false;
  106501. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106502. return false;
  106503. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106504. return false;
  106505. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106506. return false;
  106507. for(j = 0; j < track->num_indices; j++) {
  106508. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106509. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106510. return false;
  106511. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106512. return false;
  106513. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106514. return false;
  106515. }
  106516. }
  106517. break;
  106518. case FLAC__METADATA_TYPE_PICTURE:
  106519. {
  106520. size_t len;
  106521. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106522. return false;
  106523. len = strlen(metadata->data.picture.mime_type);
  106524. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106525. return false;
  106526. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106527. return false;
  106528. len = strlen((const char *)metadata->data.picture.description);
  106529. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106530. return false;
  106531. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106532. return false;
  106533. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106534. return false;
  106535. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106536. return false;
  106537. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106538. return false;
  106539. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106540. return false;
  106541. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106542. return false;
  106543. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106544. return false;
  106545. }
  106546. break;
  106547. default:
  106548. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106549. return false;
  106550. break;
  106551. }
  106552. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106553. return true;
  106554. }
  106555. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106556. {
  106557. unsigned u, blocksize_hint, sample_rate_hint;
  106558. FLAC__byte crc;
  106559. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106560. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106561. return false;
  106562. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106563. return false;
  106564. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106565. return false;
  106566. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106567. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106568. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106569. blocksize_hint = 0;
  106570. switch(header->blocksize) {
  106571. case 192: u = 1; break;
  106572. case 576: u = 2; break;
  106573. case 1152: u = 3; break;
  106574. case 2304: u = 4; break;
  106575. case 4608: u = 5; break;
  106576. case 256: u = 8; break;
  106577. case 512: u = 9; break;
  106578. case 1024: u = 10; break;
  106579. case 2048: u = 11; break;
  106580. case 4096: u = 12; break;
  106581. case 8192: u = 13; break;
  106582. case 16384: u = 14; break;
  106583. case 32768: u = 15; break;
  106584. default:
  106585. if(header->blocksize <= 0x100)
  106586. blocksize_hint = u = 6;
  106587. else
  106588. blocksize_hint = u = 7;
  106589. break;
  106590. }
  106591. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106592. return false;
  106593. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106594. sample_rate_hint = 0;
  106595. switch(header->sample_rate) {
  106596. case 88200: u = 1; break;
  106597. case 176400: u = 2; break;
  106598. case 192000: u = 3; break;
  106599. case 8000: u = 4; break;
  106600. case 16000: u = 5; break;
  106601. case 22050: u = 6; break;
  106602. case 24000: u = 7; break;
  106603. case 32000: u = 8; break;
  106604. case 44100: u = 9; break;
  106605. case 48000: u = 10; break;
  106606. case 96000: u = 11; break;
  106607. default:
  106608. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106609. sample_rate_hint = u = 12;
  106610. else if(header->sample_rate % 10 == 0)
  106611. sample_rate_hint = u = 14;
  106612. else if(header->sample_rate <= 0xffff)
  106613. sample_rate_hint = u = 13;
  106614. else
  106615. u = 0;
  106616. break;
  106617. }
  106618. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106619. return false;
  106620. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106621. switch(header->channel_assignment) {
  106622. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106623. u = header->channels - 1;
  106624. break;
  106625. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106626. FLAC__ASSERT(header->channels == 2);
  106627. u = 8;
  106628. break;
  106629. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106630. FLAC__ASSERT(header->channels == 2);
  106631. u = 9;
  106632. break;
  106633. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106634. FLAC__ASSERT(header->channels == 2);
  106635. u = 10;
  106636. break;
  106637. default:
  106638. FLAC__ASSERT(0);
  106639. }
  106640. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106641. return false;
  106642. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106643. switch(header->bits_per_sample) {
  106644. case 8 : u = 1; break;
  106645. case 12: u = 2; break;
  106646. case 16: u = 4; break;
  106647. case 20: u = 5; break;
  106648. case 24: u = 6; break;
  106649. default: u = 0; break;
  106650. }
  106651. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106652. return false;
  106653. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106654. return false;
  106655. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106656. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106657. return false;
  106658. }
  106659. else {
  106660. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106661. return false;
  106662. }
  106663. if(blocksize_hint)
  106664. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106665. return false;
  106666. switch(sample_rate_hint) {
  106667. case 12:
  106668. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106669. return false;
  106670. break;
  106671. case 13:
  106672. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106673. return false;
  106674. break;
  106675. case 14:
  106676. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106677. return false;
  106678. break;
  106679. }
  106680. /* write the CRC */
  106681. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106682. return false;
  106683. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106684. return false;
  106685. return true;
  106686. }
  106687. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106688. {
  106689. FLAC__bool ok;
  106690. ok =
  106691. 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) &&
  106692. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106693. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106694. ;
  106695. return ok;
  106696. }
  106697. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106698. {
  106699. unsigned i;
  106700. 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))
  106701. return false;
  106702. if(wasted_bits)
  106703. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106704. return false;
  106705. for(i = 0; i < subframe->order; i++)
  106706. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106707. return false;
  106708. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106709. return false;
  106710. switch(subframe->entropy_coding_method.type) {
  106711. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106712. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106713. if(!add_residual_partitioned_rice_(
  106714. bw,
  106715. subframe->residual,
  106716. residual_samples,
  106717. subframe->order,
  106718. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106719. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106720. subframe->entropy_coding_method.data.partitioned_rice.order,
  106721. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106722. ))
  106723. return false;
  106724. break;
  106725. default:
  106726. FLAC__ASSERT(0);
  106727. }
  106728. return true;
  106729. }
  106730. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106731. {
  106732. unsigned i;
  106733. 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))
  106734. return false;
  106735. if(wasted_bits)
  106736. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106737. return false;
  106738. for(i = 0; i < subframe->order; i++)
  106739. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106740. return false;
  106741. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106742. return false;
  106743. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106744. return false;
  106745. for(i = 0; i < subframe->order; i++)
  106746. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106747. return false;
  106748. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106749. return false;
  106750. switch(subframe->entropy_coding_method.type) {
  106751. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106752. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106753. if(!add_residual_partitioned_rice_(
  106754. bw,
  106755. subframe->residual,
  106756. residual_samples,
  106757. subframe->order,
  106758. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106759. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106760. subframe->entropy_coding_method.data.partitioned_rice.order,
  106761. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106762. ))
  106763. return false;
  106764. break;
  106765. default:
  106766. FLAC__ASSERT(0);
  106767. }
  106768. return true;
  106769. }
  106770. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106771. {
  106772. unsigned i;
  106773. const FLAC__int32 *signal = subframe->data;
  106774. 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))
  106775. return false;
  106776. if(wasted_bits)
  106777. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106778. return false;
  106779. for(i = 0; i < samples; i++)
  106780. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106781. return false;
  106782. return true;
  106783. }
  106784. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106785. {
  106786. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106787. return false;
  106788. switch(method->type) {
  106789. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106790. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106791. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106792. return false;
  106793. break;
  106794. default:
  106795. FLAC__ASSERT(0);
  106796. }
  106797. return true;
  106798. }
  106799. 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)
  106800. {
  106801. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106802. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106803. if(partition_order == 0) {
  106804. unsigned i;
  106805. if(raw_bits[0] == 0) {
  106806. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106807. return false;
  106808. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106809. return false;
  106810. }
  106811. else {
  106812. FLAC__ASSERT(rice_parameters[0] == 0);
  106813. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106814. return false;
  106815. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106816. return false;
  106817. for(i = 0; i < residual_samples; i++) {
  106818. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106819. return false;
  106820. }
  106821. }
  106822. return true;
  106823. }
  106824. else {
  106825. unsigned i, j, k = 0, k_last = 0;
  106826. unsigned partition_samples;
  106827. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106828. for(i = 0; i < (1u<<partition_order); i++) {
  106829. partition_samples = default_partition_samples;
  106830. if(i == 0)
  106831. partition_samples -= predictor_order;
  106832. k += partition_samples;
  106833. if(raw_bits[i] == 0) {
  106834. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106835. return false;
  106836. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106837. return false;
  106838. }
  106839. else {
  106840. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106841. return false;
  106842. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106843. return false;
  106844. for(j = k_last; j < k; j++) {
  106845. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106846. return false;
  106847. }
  106848. }
  106849. k_last = k;
  106850. }
  106851. return true;
  106852. }
  106853. }
  106854. #endif
  106855. /*** End of inlined file: stream_encoder_framing.c ***/
  106856. /*** Start of inlined file: window_flac.c ***/
  106857. /*** Start of inlined file: juce_FlacHeader.h ***/
  106858. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106859. // tasks..
  106860. #define VERSION "1.2.1"
  106861. #define FLAC__NO_DLL 1
  106862. #if JUCE_MSVC
  106863. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106864. #endif
  106865. #if JUCE_MAC
  106866. #define FLAC__SYS_DARWIN 1
  106867. #endif
  106868. /*** End of inlined file: juce_FlacHeader.h ***/
  106869. #if JUCE_USE_FLAC
  106870. #if HAVE_CONFIG_H
  106871. # include <config.h>
  106872. #endif
  106873. #include <math.h>
  106874. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106875. #ifndef M_PI
  106876. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106877. #define M_PI 3.14159265358979323846
  106878. #endif
  106879. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106880. {
  106881. const FLAC__int32 N = L - 1;
  106882. FLAC__int32 n;
  106883. if (L & 1) {
  106884. for (n = 0; n <= N/2; n++)
  106885. window[n] = 2.0f * n / (float)N;
  106886. for (; n <= N; n++)
  106887. window[n] = 2.0f - 2.0f * n / (float)N;
  106888. }
  106889. else {
  106890. for (n = 0; n <= L/2-1; n++)
  106891. window[n] = 2.0f * n / (float)N;
  106892. for (; n <= N; n++)
  106893. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106894. }
  106895. }
  106896. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106897. {
  106898. const FLAC__int32 N = L - 1;
  106899. FLAC__int32 n;
  106900. for (n = 0; n < L; n++)
  106901. 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)));
  106902. }
  106903. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106904. {
  106905. const FLAC__int32 N = L - 1;
  106906. FLAC__int32 n;
  106907. for (n = 0; n < L; n++)
  106908. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106909. }
  106910. /* 4-term -92dB side-lobe */
  106911. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106912. {
  106913. const FLAC__int32 N = L - 1;
  106914. FLAC__int32 n;
  106915. for (n = 0; n <= N; n++)
  106916. 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));
  106917. }
  106918. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106919. {
  106920. const FLAC__int32 N = L - 1;
  106921. const double N2 = (double)N / 2.;
  106922. FLAC__int32 n;
  106923. for (n = 0; n <= N; n++) {
  106924. double k = ((double)n - N2) / N2;
  106925. k = 1.0f - k * k;
  106926. window[n] = (FLAC__real)(k * k);
  106927. }
  106928. }
  106929. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106930. {
  106931. const FLAC__int32 N = L - 1;
  106932. FLAC__int32 n;
  106933. for (n = 0; n < L; n++)
  106934. 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));
  106935. }
  106936. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106937. {
  106938. const FLAC__int32 N = L - 1;
  106939. const double N2 = (double)N / 2.;
  106940. FLAC__int32 n;
  106941. for (n = 0; n <= N; n++) {
  106942. const double k = ((double)n - N2) / (stddev * N2);
  106943. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106944. }
  106945. }
  106946. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106947. {
  106948. const FLAC__int32 N = L - 1;
  106949. FLAC__int32 n;
  106950. for (n = 0; n < L; n++)
  106951. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106952. }
  106953. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106954. {
  106955. const FLAC__int32 N = L - 1;
  106956. FLAC__int32 n;
  106957. for (n = 0; n < L; n++)
  106958. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106959. }
  106960. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106961. {
  106962. const FLAC__int32 N = L - 1;
  106963. FLAC__int32 n;
  106964. for (n = 0; n < L; n++)
  106965. 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));
  106966. }
  106967. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106968. {
  106969. const FLAC__int32 N = L - 1;
  106970. FLAC__int32 n;
  106971. for (n = 0; n < L; n++)
  106972. 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));
  106973. }
  106974. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106975. {
  106976. FLAC__int32 n;
  106977. for (n = 0; n < L; n++)
  106978. window[n] = 1.0f;
  106979. }
  106980. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106981. {
  106982. FLAC__int32 n;
  106983. if (L & 1) {
  106984. for (n = 1; n <= L+1/2; n++)
  106985. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106986. for (; n <= L; n++)
  106987. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106988. }
  106989. else {
  106990. for (n = 1; n <= L/2; n++)
  106991. window[n-1] = 2.0f * n / (float)L;
  106992. for (; n <= L; n++)
  106993. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106994. }
  106995. }
  106996. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106997. {
  106998. if (p <= 0.0)
  106999. FLAC__window_rectangle(window, L);
  107000. else if (p >= 1.0)
  107001. FLAC__window_hann(window, L);
  107002. else {
  107003. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  107004. FLAC__int32 n;
  107005. /* start with rectangle... */
  107006. FLAC__window_rectangle(window, L);
  107007. /* ...replace ends with hann */
  107008. if (Np > 0) {
  107009. for (n = 0; n <= Np; n++) {
  107010. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  107011. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  107012. }
  107013. }
  107014. }
  107015. }
  107016. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  107017. {
  107018. const FLAC__int32 N = L - 1;
  107019. const double N2 = (double)N / 2.;
  107020. FLAC__int32 n;
  107021. for (n = 0; n <= N; n++) {
  107022. const double k = ((double)n - N2) / N2;
  107023. window[n] = (FLAC__real)(1.0f - k * k);
  107024. }
  107025. }
  107026. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  107027. #endif
  107028. /*** End of inlined file: window_flac.c ***/
  107029. #else
  107030. #include <FLAC/all.h>
  107031. #endif
  107032. }
  107033. #undef max
  107034. #undef min
  107035. BEGIN_JUCE_NAMESPACE
  107036. static const char* const flacFormatName = "FLAC file";
  107037. static const char* const flacExtensions[] = { ".flac", 0 };
  107038. class FlacReader : public AudioFormatReader
  107039. {
  107040. public:
  107041. FlacReader (InputStream* const in)
  107042. : AudioFormatReader (in, TRANS (flacFormatName)),
  107043. reservoir (2, 0),
  107044. reservoirStart (0),
  107045. samplesInReservoir (0),
  107046. scanningForLength (false)
  107047. {
  107048. using namespace FlacNamespace;
  107049. lengthInSamples = 0;
  107050. decoder = FLAC__stream_decoder_new();
  107051. ok = FLAC__stream_decoder_init_stream (decoder,
  107052. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  107053. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  107054. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  107055. if (ok)
  107056. {
  107057. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107058. if (lengthInSamples == 0 && sampleRate > 0)
  107059. {
  107060. // the length hasn't been stored in the metadata, so we'll need to
  107061. // work it out the length the hard way, by scanning the whole file..
  107062. scanningForLength = true;
  107063. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  107064. scanningForLength = false;
  107065. const int64 tempLength = lengthInSamples;
  107066. FLAC__stream_decoder_reset (decoder);
  107067. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107068. lengthInSamples = tempLength;
  107069. }
  107070. }
  107071. }
  107072. ~FlacReader()
  107073. {
  107074. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  107075. }
  107076. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  107077. {
  107078. sampleRate = info.sample_rate;
  107079. bitsPerSample = info.bits_per_sample;
  107080. lengthInSamples = (unsigned int) info.total_samples;
  107081. numChannels = info.channels;
  107082. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  107083. }
  107084. // returns the number of samples read
  107085. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  107086. int64 startSampleInFile, int numSamples)
  107087. {
  107088. using namespace FlacNamespace;
  107089. if (! ok)
  107090. return false;
  107091. while (numSamples > 0)
  107092. {
  107093. if (startSampleInFile >= reservoirStart
  107094. && startSampleInFile < reservoirStart + samplesInReservoir)
  107095. {
  107096. const int num = (int) jmin ((int64) numSamples,
  107097. reservoirStart + samplesInReservoir - startSampleInFile);
  107098. jassert (num > 0);
  107099. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  107100. if (destSamples[i] != 0)
  107101. memcpy (destSamples[i] + startOffsetInDestBuffer,
  107102. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  107103. sizeof (int) * num);
  107104. startOffsetInDestBuffer += num;
  107105. startSampleInFile += num;
  107106. numSamples -= num;
  107107. }
  107108. else
  107109. {
  107110. if (startSampleInFile >= (int) lengthInSamples)
  107111. {
  107112. samplesInReservoir = 0;
  107113. }
  107114. else if (startSampleInFile < reservoirStart
  107115. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  107116. {
  107117. // had some problems with flac crashing if the read pos is aligned more
  107118. // accurately than this. Probably fixed in newer versions of the library, though.
  107119. reservoirStart = (int) (startSampleInFile & ~511);
  107120. samplesInReservoir = 0;
  107121. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  107122. }
  107123. else
  107124. {
  107125. reservoirStart += samplesInReservoir;
  107126. samplesInReservoir = 0;
  107127. FLAC__stream_decoder_process_single (decoder);
  107128. }
  107129. if (samplesInReservoir == 0)
  107130. break;
  107131. }
  107132. }
  107133. if (numSamples > 0)
  107134. {
  107135. for (int i = numDestChannels; --i >= 0;)
  107136. if (destSamples[i] != 0)
  107137. zeromem (destSamples[i] + startOffsetInDestBuffer,
  107138. sizeof (int) * numSamples);
  107139. }
  107140. return true;
  107141. }
  107142. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  107143. {
  107144. if (scanningForLength)
  107145. {
  107146. lengthInSamples += numSamples;
  107147. }
  107148. else
  107149. {
  107150. if (numSamples > reservoir.getNumSamples())
  107151. reservoir.setSize (numChannels, numSamples, false, false, true);
  107152. const int bitsToShift = 32 - bitsPerSample;
  107153. for (int i = 0; i < (int) numChannels; ++i)
  107154. {
  107155. const FlacNamespace::FLAC__int32* src = buffer[i];
  107156. int n = i;
  107157. while (src == 0 && n > 0)
  107158. src = buffer [--n];
  107159. if (src != 0)
  107160. {
  107161. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  107162. for (int j = 0; j < numSamples; ++j)
  107163. dest[j] = src[j] << bitsToShift;
  107164. }
  107165. }
  107166. samplesInReservoir = numSamples;
  107167. }
  107168. }
  107169. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  107170. {
  107171. using namespace FlacNamespace;
  107172. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  107173. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107174. }
  107175. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107176. {
  107177. using namespace FlacNamespace;
  107178. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107179. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107180. }
  107181. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107182. {
  107183. using namespace FlacNamespace;
  107184. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107185. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107186. }
  107187. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107188. {
  107189. using namespace FlacNamespace;
  107190. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107191. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107192. }
  107193. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107194. {
  107195. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107196. }
  107197. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107198. const FlacNamespace::FLAC__Frame* frame,
  107199. const FlacNamespace::FLAC__int32* const buffer[],
  107200. void* client_data)
  107201. {
  107202. using namespace FlacNamespace;
  107203. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107204. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107205. }
  107206. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107207. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107208. void* client_data)
  107209. {
  107210. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107211. }
  107212. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107213. {
  107214. }
  107215. juce_UseDebuggingNewOperator
  107216. private:
  107217. FlacNamespace::FLAC__StreamDecoder* decoder;
  107218. AudioSampleBuffer reservoir;
  107219. int reservoirStart, samplesInReservoir;
  107220. bool ok, scanningForLength;
  107221. FlacReader (const FlacReader&);
  107222. FlacReader& operator= (const FlacReader&);
  107223. };
  107224. class FlacWriter : public AudioFormatWriter
  107225. {
  107226. public:
  107227. FlacWriter (OutputStream* const out,
  107228. const double sampleRate_,
  107229. const int numChannels_,
  107230. const int bitsPerSample_)
  107231. : AudioFormatWriter (out, TRANS (flacFormatName),
  107232. sampleRate_,
  107233. numChannels_,
  107234. bitsPerSample_)
  107235. {
  107236. using namespace FlacNamespace;
  107237. encoder = FLAC__stream_encoder_new();
  107238. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107239. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107240. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107241. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107242. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107243. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107244. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107245. ok = FLAC__stream_encoder_init_stream (encoder,
  107246. encodeWriteCallback, encodeSeekCallback,
  107247. encodeTellCallback, encodeMetadataCallback,
  107248. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107249. }
  107250. ~FlacWriter()
  107251. {
  107252. if (ok)
  107253. {
  107254. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107255. output->flush();
  107256. }
  107257. else
  107258. {
  107259. output = 0; // to stop the base class deleting this, as it needs to be returned
  107260. // to the caller of createWriter()
  107261. }
  107262. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107263. }
  107264. bool write (const int** samplesToWrite, int numSamples)
  107265. {
  107266. using namespace FlacNamespace;
  107267. if (! ok)
  107268. return false;
  107269. int* buf[3];
  107270. const int bitsToShift = 32 - bitsPerSample;
  107271. if (bitsToShift > 0)
  107272. {
  107273. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107274. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  107275. buf[0] = temp.getData();
  107276. buf[1] = temp.getData() + numSamples;
  107277. buf[2] = 0;
  107278. for (int i = numChannelsToWrite; --i >= 0;)
  107279. {
  107280. if (samplesToWrite[i] != 0)
  107281. {
  107282. for (int j = 0; j < numSamples; ++j)
  107283. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107284. }
  107285. }
  107286. samplesToWrite = const_cast<const int**> (buf);
  107287. }
  107288. return FLAC__stream_encoder_process (encoder,
  107289. (const FLAC__int32**) samplesToWrite,
  107290. numSamples) != 0;
  107291. }
  107292. bool writeData (const void* const data, const int size) const
  107293. {
  107294. return output->write (data, size);
  107295. }
  107296. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107297. {
  107298. using namespace FlacNamespace;
  107299. b += bytes;
  107300. for (int i = 0; i < bytes; ++i)
  107301. {
  107302. *(--b) = (FLAC__byte) (val & 0xff);
  107303. val >>= 8;
  107304. }
  107305. }
  107306. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107307. {
  107308. using namespace FlacNamespace;
  107309. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107310. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107311. const unsigned int channelsMinus1 = info.channels - 1;
  107312. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107313. packUint32 (info.min_blocksize, buffer, 2);
  107314. packUint32 (info.max_blocksize, buffer + 2, 2);
  107315. packUint32 (info.min_framesize, buffer + 4, 3);
  107316. packUint32 (info.max_framesize, buffer + 7, 3);
  107317. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107318. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107319. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107320. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107321. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107322. memcpy (buffer + 18, info.md5sum, 16);
  107323. const bool seekOk = output->setPosition (4);
  107324. (void) seekOk;
  107325. // if this fails, you've given it an output stream that can't seek! It needs
  107326. // to be able to seek back to write the header
  107327. jassert (seekOk);
  107328. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107329. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107330. }
  107331. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107332. const FlacNamespace::FLAC__byte buffer[],
  107333. size_t bytes,
  107334. unsigned int /*samples*/,
  107335. unsigned int /*current_frame*/,
  107336. void* client_data)
  107337. {
  107338. using namespace FlacNamespace;
  107339. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107340. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107341. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107342. }
  107343. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107344. {
  107345. using namespace FlacNamespace;
  107346. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107347. }
  107348. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107349. {
  107350. using namespace FlacNamespace;
  107351. if (client_data == 0)
  107352. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107353. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107354. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107355. }
  107356. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107357. {
  107358. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107359. }
  107360. juce_UseDebuggingNewOperator
  107361. bool ok;
  107362. private:
  107363. FlacNamespace::FLAC__StreamEncoder* encoder;
  107364. FlacWriter (const FlacWriter&);
  107365. FlacWriter& operator= (const FlacWriter&);
  107366. };
  107367. FlacAudioFormat::FlacAudioFormat()
  107368. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107369. {
  107370. }
  107371. FlacAudioFormat::~FlacAudioFormat()
  107372. {
  107373. }
  107374. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107375. {
  107376. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107377. return Array <int> (rates);
  107378. }
  107379. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107380. {
  107381. const int depths[] = { 16, 24, 0 };
  107382. return Array <int> (depths);
  107383. }
  107384. bool FlacAudioFormat::canDoStereo()
  107385. {
  107386. return true;
  107387. }
  107388. bool FlacAudioFormat::canDoMono()
  107389. {
  107390. return true;
  107391. }
  107392. bool FlacAudioFormat::isCompressed()
  107393. {
  107394. return true;
  107395. }
  107396. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107397. const bool deleteStreamIfOpeningFails)
  107398. {
  107399. ScopedPointer<FlacReader> r (new FlacReader (in));
  107400. if (r->sampleRate != 0)
  107401. return r.release();
  107402. if (! deleteStreamIfOpeningFails)
  107403. r->input = 0;
  107404. return 0;
  107405. }
  107406. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107407. double sampleRate,
  107408. unsigned int numberOfChannels,
  107409. int bitsPerSample,
  107410. const StringPairArray& /*metadataValues*/,
  107411. int /*qualityOptionIndex*/)
  107412. {
  107413. if (getPossibleBitDepths().contains (bitsPerSample))
  107414. {
  107415. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  107416. if (w->ok)
  107417. return w.release();
  107418. }
  107419. return 0;
  107420. }
  107421. END_JUCE_NAMESPACE
  107422. #endif
  107423. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107424. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107425. #if JUCE_USE_OGGVORBIS
  107426. #if JUCE_MAC
  107427. #define __MACOSX__ 1
  107428. #endif
  107429. namespace OggVorbisNamespace
  107430. {
  107431. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107432. /*** Start of inlined file: vorbisenc.h ***/
  107433. #ifndef _OV_ENC_H_
  107434. #define _OV_ENC_H_
  107435. #ifdef __cplusplus
  107436. extern "C"
  107437. {
  107438. #endif /* __cplusplus */
  107439. /*** Start of inlined file: codec.h ***/
  107440. #ifndef _vorbis_codec_h_
  107441. #define _vorbis_codec_h_
  107442. #ifdef __cplusplus
  107443. extern "C"
  107444. {
  107445. #endif /* __cplusplus */
  107446. /*** Start of inlined file: ogg.h ***/
  107447. #ifndef _OGG_H
  107448. #define _OGG_H
  107449. #ifdef __cplusplus
  107450. extern "C" {
  107451. #endif
  107452. /*** Start of inlined file: os_types.h ***/
  107453. #ifndef _OS_TYPES_H
  107454. #define _OS_TYPES_H
  107455. /* make it easy on the folks that want to compile the libs with a
  107456. different malloc than stdlib */
  107457. #define _ogg_malloc malloc
  107458. #define _ogg_calloc calloc
  107459. #define _ogg_realloc realloc
  107460. #define _ogg_free free
  107461. #if defined(_WIN32)
  107462. # if defined(__CYGWIN__)
  107463. # include <_G_config.h>
  107464. typedef _G_int64_t ogg_int64_t;
  107465. typedef _G_int32_t ogg_int32_t;
  107466. typedef _G_uint32_t ogg_uint32_t;
  107467. typedef _G_int16_t ogg_int16_t;
  107468. typedef _G_uint16_t ogg_uint16_t;
  107469. # elif defined(__MINGW32__)
  107470. typedef short ogg_int16_t;
  107471. typedef unsigned short ogg_uint16_t;
  107472. typedef int ogg_int32_t;
  107473. typedef unsigned int ogg_uint32_t;
  107474. typedef long long ogg_int64_t;
  107475. typedef unsigned long long ogg_uint64_t;
  107476. # elif defined(__MWERKS__)
  107477. typedef long long ogg_int64_t;
  107478. typedef int ogg_int32_t;
  107479. typedef unsigned int ogg_uint32_t;
  107480. typedef short ogg_int16_t;
  107481. typedef unsigned short ogg_uint16_t;
  107482. # else
  107483. /* MSVC/Borland */
  107484. typedef __int64 ogg_int64_t;
  107485. typedef __int32 ogg_int32_t;
  107486. typedef unsigned __int32 ogg_uint32_t;
  107487. typedef __int16 ogg_int16_t;
  107488. typedef unsigned __int16 ogg_uint16_t;
  107489. # endif
  107490. #elif defined(__MACOS__)
  107491. # include <sys/types.h>
  107492. typedef SInt16 ogg_int16_t;
  107493. typedef UInt16 ogg_uint16_t;
  107494. typedef SInt32 ogg_int32_t;
  107495. typedef UInt32 ogg_uint32_t;
  107496. typedef SInt64 ogg_int64_t;
  107497. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107498. # include <sys/types.h>
  107499. typedef int16_t ogg_int16_t;
  107500. typedef u_int16_t ogg_uint16_t;
  107501. typedef int32_t ogg_int32_t;
  107502. typedef u_int32_t ogg_uint32_t;
  107503. typedef int64_t ogg_int64_t;
  107504. #elif defined(__BEOS__)
  107505. /* Be */
  107506. # include <inttypes.h>
  107507. typedef int16_t ogg_int16_t;
  107508. typedef u_int16_t ogg_uint16_t;
  107509. typedef int32_t ogg_int32_t;
  107510. typedef u_int32_t ogg_uint32_t;
  107511. typedef int64_t ogg_int64_t;
  107512. #elif defined (__EMX__)
  107513. /* OS/2 GCC */
  107514. typedef short ogg_int16_t;
  107515. typedef unsigned short ogg_uint16_t;
  107516. typedef int ogg_int32_t;
  107517. typedef unsigned int ogg_uint32_t;
  107518. typedef long long ogg_int64_t;
  107519. #elif defined (DJGPP)
  107520. /* DJGPP */
  107521. typedef short ogg_int16_t;
  107522. typedef int ogg_int32_t;
  107523. typedef unsigned int ogg_uint32_t;
  107524. typedef long long ogg_int64_t;
  107525. #elif defined(R5900)
  107526. /* PS2 EE */
  107527. typedef long ogg_int64_t;
  107528. typedef int ogg_int32_t;
  107529. typedef unsigned ogg_uint32_t;
  107530. typedef short ogg_int16_t;
  107531. #elif defined(__SYMBIAN32__)
  107532. /* Symbian GCC */
  107533. typedef signed short ogg_int16_t;
  107534. typedef unsigned short ogg_uint16_t;
  107535. typedef signed int ogg_int32_t;
  107536. typedef unsigned int ogg_uint32_t;
  107537. typedef long long int ogg_int64_t;
  107538. #else
  107539. # include <sys/types.h>
  107540. /*** Start of inlined file: config_types.h ***/
  107541. #ifndef __CONFIG_TYPES_H__
  107542. #define __CONFIG_TYPES_H__
  107543. typedef int16_t ogg_int16_t;
  107544. typedef unsigned short ogg_uint16_t;
  107545. typedef int32_t ogg_int32_t;
  107546. typedef unsigned int ogg_uint32_t;
  107547. typedef int64_t ogg_int64_t;
  107548. #endif
  107549. /*** End of inlined file: config_types.h ***/
  107550. #endif
  107551. #endif /* _OS_TYPES_H */
  107552. /*** End of inlined file: os_types.h ***/
  107553. typedef struct {
  107554. long endbyte;
  107555. int endbit;
  107556. unsigned char *buffer;
  107557. unsigned char *ptr;
  107558. long storage;
  107559. } oggpack_buffer;
  107560. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107561. typedef struct {
  107562. unsigned char *header;
  107563. long header_len;
  107564. unsigned char *body;
  107565. long body_len;
  107566. } ogg_page;
  107567. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107568. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107569. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107570. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107571. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107572. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107573. }
  107574. /* ogg_stream_state contains the current encode/decode state of a logical
  107575. Ogg bitstream **********************************************************/
  107576. typedef struct {
  107577. unsigned char *body_data; /* bytes from packet bodies */
  107578. long body_storage; /* storage elements allocated */
  107579. long body_fill; /* elements stored; fill mark */
  107580. long body_returned; /* elements of fill returned */
  107581. int *lacing_vals; /* The values that will go to the segment table */
  107582. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107583. this way, but it is simple coupled to the
  107584. lacing fifo */
  107585. long lacing_storage;
  107586. long lacing_fill;
  107587. long lacing_packet;
  107588. long lacing_returned;
  107589. unsigned char header[282]; /* working space for header encode */
  107590. int header_fill;
  107591. int e_o_s; /* set when we have buffered the last packet in the
  107592. logical bitstream */
  107593. int b_o_s; /* set after we've written the initial page
  107594. of a logical bitstream */
  107595. long serialno;
  107596. long pageno;
  107597. ogg_int64_t packetno; /* sequence number for decode; the framing
  107598. knows where there's a hole in the data,
  107599. but we need coupling so that the codec
  107600. (which is in a seperate abstraction
  107601. layer) also knows about the gap */
  107602. ogg_int64_t granulepos;
  107603. } ogg_stream_state;
  107604. /* ogg_packet is used to encapsulate the data and metadata belonging
  107605. to a single raw Ogg/Vorbis packet *************************************/
  107606. typedef struct {
  107607. unsigned char *packet;
  107608. long bytes;
  107609. long b_o_s;
  107610. long e_o_s;
  107611. ogg_int64_t granulepos;
  107612. ogg_int64_t packetno; /* sequence number for decode; the framing
  107613. knows where there's a hole in the data,
  107614. but we need coupling so that the codec
  107615. (which is in a seperate abstraction
  107616. layer) also knows about the gap */
  107617. } ogg_packet;
  107618. typedef struct {
  107619. unsigned char *data;
  107620. int storage;
  107621. int fill;
  107622. int returned;
  107623. int unsynced;
  107624. int headerbytes;
  107625. int bodybytes;
  107626. } ogg_sync_state;
  107627. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107628. extern void oggpack_writeinit(oggpack_buffer *b);
  107629. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107630. extern void oggpack_writealign(oggpack_buffer *b);
  107631. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107632. extern void oggpack_reset(oggpack_buffer *b);
  107633. extern void oggpack_writeclear(oggpack_buffer *b);
  107634. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107635. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107636. extern long oggpack_look(oggpack_buffer *b,int bits);
  107637. extern long oggpack_look1(oggpack_buffer *b);
  107638. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107639. extern void oggpack_adv1(oggpack_buffer *b);
  107640. extern long oggpack_read(oggpack_buffer *b,int bits);
  107641. extern long oggpack_read1(oggpack_buffer *b);
  107642. extern long oggpack_bytes(oggpack_buffer *b);
  107643. extern long oggpack_bits(oggpack_buffer *b);
  107644. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107645. extern void oggpackB_writeinit(oggpack_buffer *b);
  107646. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107647. extern void oggpackB_writealign(oggpack_buffer *b);
  107648. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107649. extern void oggpackB_reset(oggpack_buffer *b);
  107650. extern void oggpackB_writeclear(oggpack_buffer *b);
  107651. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107652. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107653. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107654. extern long oggpackB_look1(oggpack_buffer *b);
  107655. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107656. extern void oggpackB_adv1(oggpack_buffer *b);
  107657. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107658. extern long oggpackB_read1(oggpack_buffer *b);
  107659. extern long oggpackB_bytes(oggpack_buffer *b);
  107660. extern long oggpackB_bits(oggpack_buffer *b);
  107661. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107662. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107663. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107664. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107665. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107666. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107667. extern int ogg_sync_init(ogg_sync_state *oy);
  107668. extern int ogg_sync_clear(ogg_sync_state *oy);
  107669. extern int ogg_sync_reset(ogg_sync_state *oy);
  107670. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107671. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107672. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107673. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107674. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107675. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107676. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107677. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107678. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107679. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107680. extern int ogg_stream_clear(ogg_stream_state *os);
  107681. extern int ogg_stream_reset(ogg_stream_state *os);
  107682. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107683. extern int ogg_stream_destroy(ogg_stream_state *os);
  107684. extern int ogg_stream_eos(ogg_stream_state *os);
  107685. extern void ogg_page_checksum_set(ogg_page *og);
  107686. extern int ogg_page_version(ogg_page *og);
  107687. extern int ogg_page_continued(ogg_page *og);
  107688. extern int ogg_page_bos(ogg_page *og);
  107689. extern int ogg_page_eos(ogg_page *og);
  107690. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107691. extern int ogg_page_serialno(ogg_page *og);
  107692. extern long ogg_page_pageno(ogg_page *og);
  107693. extern int ogg_page_packets(ogg_page *og);
  107694. extern void ogg_packet_clear(ogg_packet *op);
  107695. #ifdef __cplusplus
  107696. }
  107697. #endif
  107698. #endif /* _OGG_H */
  107699. /*** End of inlined file: ogg.h ***/
  107700. typedef struct vorbis_info{
  107701. int version;
  107702. int channels;
  107703. long rate;
  107704. /* The below bitrate declarations are *hints*.
  107705. Combinations of the three values carry the following implications:
  107706. all three set to the same value:
  107707. implies a fixed rate bitstream
  107708. only nominal set:
  107709. implies a VBR stream that averages the nominal bitrate. No hard
  107710. upper/lower limit
  107711. upper and or lower set:
  107712. implies a VBR bitstream that obeys the bitrate limits. nominal
  107713. may also be set to give a nominal rate.
  107714. none set:
  107715. the coder does not care to speculate.
  107716. */
  107717. long bitrate_upper;
  107718. long bitrate_nominal;
  107719. long bitrate_lower;
  107720. long bitrate_window;
  107721. void *codec_setup;
  107722. } vorbis_info;
  107723. /* vorbis_dsp_state buffers the current vorbis audio
  107724. analysis/synthesis state. The DSP state belongs to a specific
  107725. logical bitstream ****************************************************/
  107726. typedef struct vorbis_dsp_state{
  107727. int analysisp;
  107728. vorbis_info *vi;
  107729. float **pcm;
  107730. float **pcmret;
  107731. int pcm_storage;
  107732. int pcm_current;
  107733. int pcm_returned;
  107734. int preextrapolate;
  107735. int eofflag;
  107736. long lW;
  107737. long W;
  107738. long nW;
  107739. long centerW;
  107740. ogg_int64_t granulepos;
  107741. ogg_int64_t sequence;
  107742. ogg_int64_t glue_bits;
  107743. ogg_int64_t time_bits;
  107744. ogg_int64_t floor_bits;
  107745. ogg_int64_t res_bits;
  107746. void *backend_state;
  107747. } vorbis_dsp_state;
  107748. typedef struct vorbis_block{
  107749. /* necessary stream state for linking to the framing abstraction */
  107750. float **pcm; /* this is a pointer into local storage */
  107751. oggpack_buffer opb;
  107752. long lW;
  107753. long W;
  107754. long nW;
  107755. int pcmend;
  107756. int mode;
  107757. int eofflag;
  107758. ogg_int64_t granulepos;
  107759. ogg_int64_t sequence;
  107760. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107761. /* local storage to avoid remallocing; it's up to the mapping to
  107762. structure it */
  107763. void *localstore;
  107764. long localtop;
  107765. long localalloc;
  107766. long totaluse;
  107767. struct alloc_chain *reap;
  107768. /* bitmetrics for the frame */
  107769. long glue_bits;
  107770. long time_bits;
  107771. long floor_bits;
  107772. long res_bits;
  107773. void *internal;
  107774. } vorbis_block;
  107775. /* vorbis_block is a single block of data to be processed as part of
  107776. the analysis/synthesis stream; it belongs to a specific logical
  107777. bitstream, but is independant from other vorbis_blocks belonging to
  107778. that logical bitstream. *************************************************/
  107779. struct alloc_chain{
  107780. void *ptr;
  107781. struct alloc_chain *next;
  107782. };
  107783. /* vorbis_info contains all the setup information specific to the
  107784. specific compression/decompression mode in progress (eg,
  107785. psychoacoustic settings, channel setup, options, codebook
  107786. etc). vorbis_info and substructures are in backends.h.
  107787. *********************************************************************/
  107788. /* the comments are not part of vorbis_info so that vorbis_info can be
  107789. static storage */
  107790. typedef struct vorbis_comment{
  107791. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107792. whatever vendor is set to in encode */
  107793. char **user_comments;
  107794. int *comment_lengths;
  107795. int comments;
  107796. char *vendor;
  107797. } vorbis_comment;
  107798. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107799. and produce a packet (see docs/analysis.txt). The packet is then
  107800. coded into a framed OggSquish bitstream by the second layer (see
  107801. docs/framing.txt). Decode is the reverse process; we sync/frame
  107802. the bitstream and extract individual packets, then decode the
  107803. packet back into PCM audio.
  107804. The extra framing/packetizing is used in streaming formats, such as
  107805. files. Over the net (such as with UDP), the framing and
  107806. packetization aren't necessary as they're provided by the transport
  107807. and the streaming layer is not used */
  107808. /* Vorbis PRIMITIVES: general ***************************************/
  107809. extern void vorbis_info_init(vorbis_info *vi);
  107810. extern void vorbis_info_clear(vorbis_info *vi);
  107811. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107812. extern void vorbis_comment_init(vorbis_comment *vc);
  107813. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107814. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107815. const char *tag, char *contents);
  107816. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107817. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107818. extern void vorbis_comment_clear(vorbis_comment *vc);
  107819. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107820. extern int vorbis_block_clear(vorbis_block *vb);
  107821. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107822. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107823. ogg_int64_t granulepos);
  107824. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107825. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107826. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107827. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107828. vorbis_comment *vc,
  107829. ogg_packet *op,
  107830. ogg_packet *op_comm,
  107831. ogg_packet *op_code);
  107832. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107833. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107834. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107835. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107836. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107837. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107838. ogg_packet *op);
  107839. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107840. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107841. ogg_packet *op);
  107842. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107843. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107844. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107845. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107846. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107847. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107848. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107849. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107850. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107851. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107852. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107853. /* Vorbis ERRORS and return codes ***********************************/
  107854. #define OV_FALSE -1
  107855. #define OV_EOF -2
  107856. #define OV_HOLE -3
  107857. #define OV_EREAD -128
  107858. #define OV_EFAULT -129
  107859. #define OV_EIMPL -130
  107860. #define OV_EINVAL -131
  107861. #define OV_ENOTVORBIS -132
  107862. #define OV_EBADHEADER -133
  107863. #define OV_EVERSION -134
  107864. #define OV_ENOTAUDIO -135
  107865. #define OV_EBADPACKET -136
  107866. #define OV_EBADLINK -137
  107867. #define OV_ENOSEEK -138
  107868. #ifdef __cplusplus
  107869. }
  107870. #endif /* __cplusplus */
  107871. #endif
  107872. /*** End of inlined file: codec.h ***/
  107873. extern int vorbis_encode_init(vorbis_info *vi,
  107874. long channels,
  107875. long rate,
  107876. long max_bitrate,
  107877. long nominal_bitrate,
  107878. long min_bitrate);
  107879. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107880. long channels,
  107881. long rate,
  107882. long max_bitrate,
  107883. long nominal_bitrate,
  107884. long min_bitrate);
  107885. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107886. long channels,
  107887. long rate,
  107888. float quality /* quality level from 0. (lo) to 1. (hi) */
  107889. );
  107890. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107891. long channels,
  107892. long rate,
  107893. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107894. );
  107895. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107896. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107897. /* deprecated rate management supported only for compatability */
  107898. #define OV_ECTL_RATEMANAGE_GET 0x10
  107899. #define OV_ECTL_RATEMANAGE_SET 0x11
  107900. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107901. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107902. struct ovectl_ratemanage_arg {
  107903. int management_active;
  107904. long bitrate_hard_min;
  107905. long bitrate_hard_max;
  107906. double bitrate_hard_window;
  107907. long bitrate_av_lo;
  107908. long bitrate_av_hi;
  107909. double bitrate_av_window;
  107910. double bitrate_av_window_center;
  107911. };
  107912. /* new rate setup */
  107913. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107914. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107915. struct ovectl_ratemanage2_arg {
  107916. int management_active;
  107917. long bitrate_limit_min_kbps;
  107918. long bitrate_limit_max_kbps;
  107919. long bitrate_limit_reservoir_bits;
  107920. double bitrate_limit_reservoir_bias;
  107921. long bitrate_average_kbps;
  107922. double bitrate_average_damping;
  107923. };
  107924. #define OV_ECTL_LOWPASS_GET 0x20
  107925. #define OV_ECTL_LOWPASS_SET 0x21
  107926. #define OV_ECTL_IBLOCK_GET 0x30
  107927. #define OV_ECTL_IBLOCK_SET 0x31
  107928. #ifdef __cplusplus
  107929. }
  107930. #endif /* __cplusplus */
  107931. #endif
  107932. /*** End of inlined file: vorbisenc.h ***/
  107933. /*** Start of inlined file: vorbisfile.h ***/
  107934. #ifndef _OV_FILE_H_
  107935. #define _OV_FILE_H_
  107936. #ifdef __cplusplus
  107937. extern "C"
  107938. {
  107939. #endif /* __cplusplus */
  107940. #include <stdio.h>
  107941. /* The function prototypes for the callbacks are basically the same as for
  107942. * the stdio functions fread, fseek, fclose, ftell.
  107943. * The one difference is that the FILE * arguments have been replaced with
  107944. * a void * - this is to be used as a pointer to whatever internal data these
  107945. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107946. *
  107947. * If you use other functions, check the docs for these functions and return
  107948. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107949. * unseekable
  107950. */
  107951. typedef struct {
  107952. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107953. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107954. int (*close_func) (void *datasource);
  107955. long (*tell_func) (void *datasource);
  107956. } ov_callbacks;
  107957. #define NOTOPEN 0
  107958. #define PARTOPEN 1
  107959. #define OPENED 2
  107960. #define STREAMSET 3
  107961. #define INITSET 4
  107962. typedef struct OggVorbis_File {
  107963. void *datasource; /* Pointer to a FILE *, etc. */
  107964. int seekable;
  107965. ogg_int64_t offset;
  107966. ogg_int64_t end;
  107967. ogg_sync_state oy;
  107968. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107969. stream appears */
  107970. int links;
  107971. ogg_int64_t *offsets;
  107972. ogg_int64_t *dataoffsets;
  107973. long *serialnos;
  107974. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107975. compatability; x2 size, stores both
  107976. beginning and end values */
  107977. vorbis_info *vi;
  107978. vorbis_comment *vc;
  107979. /* Decoding working state local storage */
  107980. ogg_int64_t pcm_offset;
  107981. int ready_state;
  107982. long current_serialno;
  107983. int current_link;
  107984. double bittrack;
  107985. double samptrack;
  107986. ogg_stream_state os; /* take physical pages, weld into a logical
  107987. stream of packets */
  107988. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107989. vorbis_block vb; /* local working space for packet->PCM decode */
  107990. ov_callbacks callbacks;
  107991. } OggVorbis_File;
  107992. extern int ov_clear(OggVorbis_File *vf);
  107993. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107994. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107995. char *initial, long ibytes, ov_callbacks callbacks);
  107996. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107997. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107998. char *initial, long ibytes, ov_callbacks callbacks);
  107999. extern int ov_test_open(OggVorbis_File *vf);
  108000. extern long ov_bitrate(OggVorbis_File *vf,int i);
  108001. extern long ov_bitrate_instant(OggVorbis_File *vf);
  108002. extern long ov_streams(OggVorbis_File *vf);
  108003. extern long ov_seekable(OggVorbis_File *vf);
  108004. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  108005. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  108006. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  108007. extern double ov_time_total(OggVorbis_File *vf,int i);
  108008. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  108009. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  108010. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  108011. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  108012. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  108013. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  108014. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  108015. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  108016. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  108017. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  108018. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  108019. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  108020. extern double ov_time_tell(OggVorbis_File *vf);
  108021. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  108022. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  108023. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  108024. int *bitstream);
  108025. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  108026. int bigendianp,int word,int sgned,int *bitstream);
  108027. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  108028. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  108029. extern int ov_halfrate_p(OggVorbis_File *vf);
  108030. #ifdef __cplusplus
  108031. }
  108032. #endif /* __cplusplus */
  108033. #endif
  108034. /*** End of inlined file: vorbisfile.h ***/
  108035. /*** Start of inlined file: bitwise.c ***/
  108036. /* We're 'LSb' endian; if we write a word but read individual bits,
  108037. then we'll read the lsb first */
  108038. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108039. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108040. // tasks..
  108041. #if JUCE_MSVC
  108042. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108043. #endif
  108044. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108045. #if JUCE_USE_OGGVORBIS
  108046. #include <string.h>
  108047. #include <stdlib.h>
  108048. #define BUFFER_INCREMENT 256
  108049. static const unsigned long mask[]=
  108050. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  108051. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  108052. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  108053. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  108054. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  108055. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  108056. 0x3fffffff,0x7fffffff,0xffffffff };
  108057. static const unsigned int mask8B[]=
  108058. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  108059. void oggpack_writeinit(oggpack_buffer *b){
  108060. memset(b,0,sizeof(*b));
  108061. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  108062. b->buffer[0]='\0';
  108063. b->storage=BUFFER_INCREMENT;
  108064. }
  108065. void oggpackB_writeinit(oggpack_buffer *b){
  108066. oggpack_writeinit(b);
  108067. }
  108068. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  108069. long bytes=bits>>3;
  108070. bits-=bytes*8;
  108071. b->ptr=b->buffer+bytes;
  108072. b->endbit=bits;
  108073. b->endbyte=bytes;
  108074. *b->ptr&=mask[bits];
  108075. }
  108076. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  108077. long bytes=bits>>3;
  108078. bits-=bytes*8;
  108079. b->ptr=b->buffer+bytes;
  108080. b->endbit=bits;
  108081. b->endbyte=bytes;
  108082. *b->ptr&=mask8B[bits];
  108083. }
  108084. /* Takes only up to 32 bits. */
  108085. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  108086. if(b->endbyte+4>=b->storage){
  108087. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108088. b->storage+=BUFFER_INCREMENT;
  108089. b->ptr=b->buffer+b->endbyte;
  108090. }
  108091. value&=mask[bits];
  108092. bits+=b->endbit;
  108093. b->ptr[0]|=value<<b->endbit;
  108094. if(bits>=8){
  108095. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  108096. if(bits>=16){
  108097. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  108098. if(bits>=24){
  108099. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  108100. if(bits>=32){
  108101. if(b->endbit)
  108102. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  108103. else
  108104. b->ptr[4]=0;
  108105. }
  108106. }
  108107. }
  108108. }
  108109. b->endbyte+=bits/8;
  108110. b->ptr+=bits/8;
  108111. b->endbit=bits&7;
  108112. }
  108113. /* Takes only up to 32 bits. */
  108114. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  108115. if(b->endbyte+4>=b->storage){
  108116. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108117. b->storage+=BUFFER_INCREMENT;
  108118. b->ptr=b->buffer+b->endbyte;
  108119. }
  108120. value=(value&mask[bits])<<(32-bits);
  108121. bits+=b->endbit;
  108122. b->ptr[0]|=value>>(24+b->endbit);
  108123. if(bits>=8){
  108124. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  108125. if(bits>=16){
  108126. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  108127. if(bits>=24){
  108128. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  108129. if(bits>=32){
  108130. if(b->endbit)
  108131. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  108132. else
  108133. b->ptr[4]=0;
  108134. }
  108135. }
  108136. }
  108137. }
  108138. b->endbyte+=bits/8;
  108139. b->ptr+=bits/8;
  108140. b->endbit=bits&7;
  108141. }
  108142. void oggpack_writealign(oggpack_buffer *b){
  108143. int bits=8-b->endbit;
  108144. if(bits<8)
  108145. oggpack_write(b,0,bits);
  108146. }
  108147. void oggpackB_writealign(oggpack_buffer *b){
  108148. int bits=8-b->endbit;
  108149. if(bits<8)
  108150. oggpackB_write(b,0,bits);
  108151. }
  108152. static void oggpack_writecopy_helper(oggpack_buffer *b,
  108153. void *source,
  108154. long bits,
  108155. void (*w)(oggpack_buffer *,
  108156. unsigned long,
  108157. int),
  108158. int msb){
  108159. unsigned char *ptr=(unsigned char *)source;
  108160. long bytes=bits/8;
  108161. bits-=bytes*8;
  108162. if(b->endbit){
  108163. int i;
  108164. /* unaligned copy. Do it the hard way. */
  108165. for(i=0;i<bytes;i++)
  108166. w(b,(unsigned long)(ptr[i]),8);
  108167. }else{
  108168. /* aligned block copy */
  108169. if(b->endbyte+bytes+1>=b->storage){
  108170. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  108171. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  108172. b->ptr=b->buffer+b->endbyte;
  108173. }
  108174. memmove(b->ptr,source,bytes);
  108175. b->ptr+=bytes;
  108176. b->endbyte+=bytes;
  108177. *b->ptr=0;
  108178. }
  108179. if(bits){
  108180. if(msb)
  108181. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  108182. else
  108183. w(b,(unsigned long)(ptr[bytes]),bits);
  108184. }
  108185. }
  108186. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108187. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108188. }
  108189. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108190. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108191. }
  108192. void oggpack_reset(oggpack_buffer *b){
  108193. b->ptr=b->buffer;
  108194. b->buffer[0]=0;
  108195. b->endbit=b->endbyte=0;
  108196. }
  108197. void oggpackB_reset(oggpack_buffer *b){
  108198. oggpack_reset(b);
  108199. }
  108200. void oggpack_writeclear(oggpack_buffer *b){
  108201. _ogg_free(b->buffer);
  108202. memset(b,0,sizeof(*b));
  108203. }
  108204. void oggpackB_writeclear(oggpack_buffer *b){
  108205. oggpack_writeclear(b);
  108206. }
  108207. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108208. memset(b,0,sizeof(*b));
  108209. b->buffer=b->ptr=buf;
  108210. b->storage=bytes;
  108211. }
  108212. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108213. oggpack_readinit(b,buf,bytes);
  108214. }
  108215. /* Read in bits without advancing the bitptr; bits <= 32 */
  108216. long oggpack_look(oggpack_buffer *b,int bits){
  108217. unsigned long ret;
  108218. unsigned long m=mask[bits];
  108219. bits+=b->endbit;
  108220. if(b->endbyte+4>=b->storage){
  108221. /* not the main path */
  108222. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108223. }
  108224. ret=b->ptr[0]>>b->endbit;
  108225. if(bits>8){
  108226. ret|=b->ptr[1]<<(8-b->endbit);
  108227. if(bits>16){
  108228. ret|=b->ptr[2]<<(16-b->endbit);
  108229. if(bits>24){
  108230. ret|=b->ptr[3]<<(24-b->endbit);
  108231. if(bits>32 && b->endbit)
  108232. ret|=b->ptr[4]<<(32-b->endbit);
  108233. }
  108234. }
  108235. }
  108236. return(m&ret);
  108237. }
  108238. /* Read in bits without advancing the bitptr; bits <= 32 */
  108239. long oggpackB_look(oggpack_buffer *b,int bits){
  108240. unsigned long ret;
  108241. int m=32-bits;
  108242. bits+=b->endbit;
  108243. if(b->endbyte+4>=b->storage){
  108244. /* not the main path */
  108245. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108246. }
  108247. ret=b->ptr[0]<<(24+b->endbit);
  108248. if(bits>8){
  108249. ret|=b->ptr[1]<<(16+b->endbit);
  108250. if(bits>16){
  108251. ret|=b->ptr[2]<<(8+b->endbit);
  108252. if(bits>24){
  108253. ret|=b->ptr[3]<<(b->endbit);
  108254. if(bits>32 && b->endbit)
  108255. ret|=b->ptr[4]>>(8-b->endbit);
  108256. }
  108257. }
  108258. }
  108259. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108260. }
  108261. long oggpack_look1(oggpack_buffer *b){
  108262. if(b->endbyte>=b->storage)return(-1);
  108263. return((b->ptr[0]>>b->endbit)&1);
  108264. }
  108265. long oggpackB_look1(oggpack_buffer *b){
  108266. if(b->endbyte>=b->storage)return(-1);
  108267. return((b->ptr[0]>>(7-b->endbit))&1);
  108268. }
  108269. void oggpack_adv(oggpack_buffer *b,int bits){
  108270. bits+=b->endbit;
  108271. b->ptr+=bits/8;
  108272. b->endbyte+=bits/8;
  108273. b->endbit=bits&7;
  108274. }
  108275. void oggpackB_adv(oggpack_buffer *b,int bits){
  108276. oggpack_adv(b,bits);
  108277. }
  108278. void oggpack_adv1(oggpack_buffer *b){
  108279. if(++(b->endbit)>7){
  108280. b->endbit=0;
  108281. b->ptr++;
  108282. b->endbyte++;
  108283. }
  108284. }
  108285. void oggpackB_adv1(oggpack_buffer *b){
  108286. oggpack_adv1(b);
  108287. }
  108288. /* bits <= 32 */
  108289. long oggpack_read(oggpack_buffer *b,int bits){
  108290. long ret;
  108291. unsigned long m=mask[bits];
  108292. bits+=b->endbit;
  108293. if(b->endbyte+4>=b->storage){
  108294. /* not the main path */
  108295. ret=-1L;
  108296. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108297. }
  108298. ret=b->ptr[0]>>b->endbit;
  108299. if(bits>8){
  108300. ret|=b->ptr[1]<<(8-b->endbit);
  108301. if(bits>16){
  108302. ret|=b->ptr[2]<<(16-b->endbit);
  108303. if(bits>24){
  108304. ret|=b->ptr[3]<<(24-b->endbit);
  108305. if(bits>32 && b->endbit){
  108306. ret|=b->ptr[4]<<(32-b->endbit);
  108307. }
  108308. }
  108309. }
  108310. }
  108311. ret&=m;
  108312. overflow:
  108313. b->ptr+=bits/8;
  108314. b->endbyte+=bits/8;
  108315. b->endbit=bits&7;
  108316. return(ret);
  108317. }
  108318. /* bits <= 32 */
  108319. long oggpackB_read(oggpack_buffer *b,int bits){
  108320. long ret;
  108321. long m=32-bits;
  108322. bits+=b->endbit;
  108323. if(b->endbyte+4>=b->storage){
  108324. /* not the main path */
  108325. ret=-1L;
  108326. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108327. }
  108328. ret=b->ptr[0]<<(24+b->endbit);
  108329. if(bits>8){
  108330. ret|=b->ptr[1]<<(16+b->endbit);
  108331. if(bits>16){
  108332. ret|=b->ptr[2]<<(8+b->endbit);
  108333. if(bits>24){
  108334. ret|=b->ptr[3]<<(b->endbit);
  108335. if(bits>32 && b->endbit)
  108336. ret|=b->ptr[4]>>(8-b->endbit);
  108337. }
  108338. }
  108339. }
  108340. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108341. overflow:
  108342. b->ptr+=bits/8;
  108343. b->endbyte+=bits/8;
  108344. b->endbit=bits&7;
  108345. return(ret);
  108346. }
  108347. long oggpack_read1(oggpack_buffer *b){
  108348. long ret;
  108349. if(b->endbyte>=b->storage){
  108350. /* not the main path */
  108351. ret=-1L;
  108352. goto overflow;
  108353. }
  108354. ret=(b->ptr[0]>>b->endbit)&1;
  108355. overflow:
  108356. b->endbit++;
  108357. if(b->endbit>7){
  108358. b->endbit=0;
  108359. b->ptr++;
  108360. b->endbyte++;
  108361. }
  108362. return(ret);
  108363. }
  108364. long oggpackB_read1(oggpack_buffer *b){
  108365. long ret;
  108366. if(b->endbyte>=b->storage){
  108367. /* not the main path */
  108368. ret=-1L;
  108369. goto overflow;
  108370. }
  108371. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108372. overflow:
  108373. b->endbit++;
  108374. if(b->endbit>7){
  108375. b->endbit=0;
  108376. b->ptr++;
  108377. b->endbyte++;
  108378. }
  108379. return(ret);
  108380. }
  108381. long oggpack_bytes(oggpack_buffer *b){
  108382. return(b->endbyte+(b->endbit+7)/8);
  108383. }
  108384. long oggpack_bits(oggpack_buffer *b){
  108385. return(b->endbyte*8+b->endbit);
  108386. }
  108387. long oggpackB_bytes(oggpack_buffer *b){
  108388. return oggpack_bytes(b);
  108389. }
  108390. long oggpackB_bits(oggpack_buffer *b){
  108391. return oggpack_bits(b);
  108392. }
  108393. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108394. return(b->buffer);
  108395. }
  108396. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108397. return oggpack_get_buffer(b);
  108398. }
  108399. /* Self test of the bitwise routines; everything else is based on
  108400. them, so they damned well better be solid. */
  108401. #ifdef _V_SELFTEST
  108402. #include <stdio.h>
  108403. static int ilog(unsigned int v){
  108404. int ret=0;
  108405. while(v){
  108406. ret++;
  108407. v>>=1;
  108408. }
  108409. return(ret);
  108410. }
  108411. oggpack_buffer o;
  108412. oggpack_buffer r;
  108413. void report(char *in){
  108414. fprintf(stderr,"%s",in);
  108415. exit(1);
  108416. }
  108417. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108418. long bytes,i;
  108419. unsigned char *buffer;
  108420. oggpack_reset(&o);
  108421. for(i=0;i<vals;i++)
  108422. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108423. buffer=oggpack_get_buffer(&o);
  108424. bytes=oggpack_bytes(&o);
  108425. if(bytes!=compsize)report("wrong number of bytes!\n");
  108426. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108427. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108428. report("wrote incorrect value!\n");
  108429. }
  108430. oggpack_readinit(&r,buffer,bytes);
  108431. for(i=0;i<vals;i++){
  108432. int tbit=bits?bits:ilog(b[i]);
  108433. if(oggpack_look(&r,tbit)==-1)
  108434. report("out of data!\n");
  108435. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108436. report("looked at incorrect value!\n");
  108437. if(tbit==1)
  108438. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108439. report("looked at single bit incorrect value!\n");
  108440. if(tbit==1){
  108441. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108442. report("read incorrect single bit value!\n");
  108443. }else{
  108444. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108445. report("read incorrect value!\n");
  108446. }
  108447. }
  108448. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108449. }
  108450. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108451. long bytes,i;
  108452. unsigned char *buffer;
  108453. oggpackB_reset(&o);
  108454. for(i=0;i<vals;i++)
  108455. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108456. buffer=oggpackB_get_buffer(&o);
  108457. bytes=oggpackB_bytes(&o);
  108458. if(bytes!=compsize)report("wrong number of bytes!\n");
  108459. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108460. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108461. report("wrote incorrect value!\n");
  108462. }
  108463. oggpackB_readinit(&r,buffer,bytes);
  108464. for(i=0;i<vals;i++){
  108465. int tbit=bits?bits:ilog(b[i]);
  108466. if(oggpackB_look(&r,tbit)==-1)
  108467. report("out of data!\n");
  108468. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108469. report("looked at incorrect value!\n");
  108470. if(tbit==1)
  108471. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108472. report("looked at single bit incorrect value!\n");
  108473. if(tbit==1){
  108474. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108475. report("read incorrect single bit value!\n");
  108476. }else{
  108477. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108478. report("read incorrect value!\n");
  108479. }
  108480. }
  108481. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108482. }
  108483. int main(void){
  108484. unsigned char *buffer;
  108485. long bytes,i;
  108486. static unsigned long testbuffer1[]=
  108487. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108488. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108489. int test1size=43;
  108490. static unsigned long testbuffer2[]=
  108491. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108492. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108493. 85525151,0,12321,1,349528352};
  108494. int test2size=21;
  108495. static unsigned long testbuffer3[]=
  108496. {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,
  108497. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108498. int test3size=56;
  108499. static unsigned long large[]=
  108500. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108501. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108502. 85525151,0,12321,1,2146528352};
  108503. int onesize=33;
  108504. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108505. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108506. 223,4};
  108507. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108508. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108509. 245,251,128};
  108510. int twosize=6;
  108511. static int two[6]={61,255,255,251,231,29};
  108512. static int twoB[6]={247,63,255,253,249,120};
  108513. int threesize=54;
  108514. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108515. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108516. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108517. 100,52,4,14,18,86,77,1};
  108518. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108519. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108520. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108521. 200,20,254,4,58,106,176,144,0};
  108522. int foursize=38;
  108523. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108524. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108525. 28,2,133,0,1};
  108526. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108527. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108528. 129,10,4,32};
  108529. int fivesize=45;
  108530. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108531. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108532. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108533. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108534. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108535. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108536. int sixsize=7;
  108537. static int six[7]={17,177,170,242,169,19,148};
  108538. static int sixB[7]={136,141,85,79,149,200,41};
  108539. /* Test read/write together */
  108540. /* Later we test against pregenerated bitstreams */
  108541. oggpack_writeinit(&o);
  108542. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108543. cliptest(testbuffer1,test1size,0,one,onesize);
  108544. fprintf(stderr,"ok.");
  108545. fprintf(stderr,"\nNull bit call (LSb): ");
  108546. cliptest(testbuffer3,test3size,0,two,twosize);
  108547. fprintf(stderr,"ok.");
  108548. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108549. cliptest(testbuffer2,test2size,0,three,threesize);
  108550. fprintf(stderr,"ok.");
  108551. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108552. oggpack_reset(&o);
  108553. for(i=0;i<test2size;i++)
  108554. oggpack_write(&o,large[i],32);
  108555. buffer=oggpack_get_buffer(&o);
  108556. bytes=oggpack_bytes(&o);
  108557. oggpack_readinit(&r,buffer,bytes);
  108558. for(i=0;i<test2size;i++){
  108559. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108560. if(oggpack_look(&r,32)!=large[i]){
  108561. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108562. oggpack_look(&r,32),large[i]);
  108563. report("read incorrect value!\n");
  108564. }
  108565. oggpack_adv(&r,32);
  108566. }
  108567. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108568. fprintf(stderr,"ok.");
  108569. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108570. cliptest(testbuffer1,test1size,7,four,foursize);
  108571. fprintf(stderr,"ok.");
  108572. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108573. cliptest(testbuffer2,test2size,17,five,fivesize);
  108574. fprintf(stderr,"ok.");
  108575. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108576. cliptest(testbuffer3,test3size,1,six,sixsize);
  108577. fprintf(stderr,"ok.");
  108578. fprintf(stderr,"\nTesting read past end (LSb): ");
  108579. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108580. for(i=0;i<64;i++){
  108581. if(oggpack_read(&r,1)!=0){
  108582. fprintf(stderr,"failed; got -1 prematurely.\n");
  108583. exit(1);
  108584. }
  108585. }
  108586. if(oggpack_look(&r,1)!=-1 ||
  108587. oggpack_read(&r,1)!=-1){
  108588. fprintf(stderr,"failed; read past end without -1.\n");
  108589. exit(1);
  108590. }
  108591. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108592. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108593. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108594. exit(1);
  108595. }
  108596. if(oggpack_look(&r,18)!=0 ||
  108597. oggpack_look(&r,18)!=0){
  108598. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108599. exit(1);
  108600. }
  108601. if(oggpack_look(&r,19)!=-1 ||
  108602. oggpack_look(&r,19)!=-1){
  108603. fprintf(stderr,"failed; read past end without -1.\n");
  108604. exit(1);
  108605. }
  108606. if(oggpack_look(&r,32)!=-1 ||
  108607. oggpack_look(&r,32)!=-1){
  108608. fprintf(stderr,"failed; read past end without -1.\n");
  108609. exit(1);
  108610. }
  108611. oggpack_writeclear(&o);
  108612. fprintf(stderr,"ok.\n");
  108613. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108614. /* Test read/write together */
  108615. /* Later we test against pregenerated bitstreams */
  108616. oggpackB_writeinit(&o);
  108617. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108618. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108619. fprintf(stderr,"ok.");
  108620. fprintf(stderr,"\nNull bit call (MSb): ");
  108621. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108622. fprintf(stderr,"ok.");
  108623. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108624. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108625. fprintf(stderr,"ok.");
  108626. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108627. oggpackB_reset(&o);
  108628. for(i=0;i<test2size;i++)
  108629. oggpackB_write(&o,large[i],32);
  108630. buffer=oggpackB_get_buffer(&o);
  108631. bytes=oggpackB_bytes(&o);
  108632. oggpackB_readinit(&r,buffer,bytes);
  108633. for(i=0;i<test2size;i++){
  108634. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108635. if(oggpackB_look(&r,32)!=large[i]){
  108636. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108637. oggpackB_look(&r,32),large[i]);
  108638. report("read incorrect value!\n");
  108639. }
  108640. oggpackB_adv(&r,32);
  108641. }
  108642. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108643. fprintf(stderr,"ok.");
  108644. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108645. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108646. fprintf(stderr,"ok.");
  108647. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108648. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108649. fprintf(stderr,"ok.");
  108650. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108651. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108652. fprintf(stderr,"ok.");
  108653. fprintf(stderr,"\nTesting read past end (MSb): ");
  108654. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108655. for(i=0;i<64;i++){
  108656. if(oggpackB_read(&r,1)!=0){
  108657. fprintf(stderr,"failed; got -1 prematurely.\n");
  108658. exit(1);
  108659. }
  108660. }
  108661. if(oggpackB_look(&r,1)!=-1 ||
  108662. oggpackB_read(&r,1)!=-1){
  108663. fprintf(stderr,"failed; read past end without -1.\n");
  108664. exit(1);
  108665. }
  108666. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108667. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108668. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108669. exit(1);
  108670. }
  108671. if(oggpackB_look(&r,18)!=0 ||
  108672. oggpackB_look(&r,18)!=0){
  108673. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108674. exit(1);
  108675. }
  108676. if(oggpackB_look(&r,19)!=-1 ||
  108677. oggpackB_look(&r,19)!=-1){
  108678. fprintf(stderr,"failed; read past end without -1.\n");
  108679. exit(1);
  108680. }
  108681. if(oggpackB_look(&r,32)!=-1 ||
  108682. oggpackB_look(&r,32)!=-1){
  108683. fprintf(stderr,"failed; read past end without -1.\n");
  108684. exit(1);
  108685. }
  108686. oggpackB_writeclear(&o);
  108687. fprintf(stderr,"ok.\n\n");
  108688. return(0);
  108689. }
  108690. #endif /* _V_SELFTEST */
  108691. #undef BUFFER_INCREMENT
  108692. #endif
  108693. /*** End of inlined file: bitwise.c ***/
  108694. /*** Start of inlined file: framing.c ***/
  108695. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108696. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108697. // tasks..
  108698. #if JUCE_MSVC
  108699. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108700. #endif
  108701. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108702. #if JUCE_USE_OGGVORBIS
  108703. #include <stdlib.h>
  108704. #include <string.h>
  108705. /* A complete description of Ogg framing exists in docs/framing.html */
  108706. int ogg_page_version(ogg_page *og){
  108707. return((int)(og->header[4]));
  108708. }
  108709. int ogg_page_continued(ogg_page *og){
  108710. return((int)(og->header[5]&0x01));
  108711. }
  108712. int ogg_page_bos(ogg_page *og){
  108713. return((int)(og->header[5]&0x02));
  108714. }
  108715. int ogg_page_eos(ogg_page *og){
  108716. return((int)(og->header[5]&0x04));
  108717. }
  108718. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108719. unsigned char *page=og->header;
  108720. ogg_int64_t granulepos=page[13]&(0xff);
  108721. granulepos= (granulepos<<8)|(page[12]&0xff);
  108722. granulepos= (granulepos<<8)|(page[11]&0xff);
  108723. granulepos= (granulepos<<8)|(page[10]&0xff);
  108724. granulepos= (granulepos<<8)|(page[9]&0xff);
  108725. granulepos= (granulepos<<8)|(page[8]&0xff);
  108726. granulepos= (granulepos<<8)|(page[7]&0xff);
  108727. granulepos= (granulepos<<8)|(page[6]&0xff);
  108728. return(granulepos);
  108729. }
  108730. int ogg_page_serialno(ogg_page *og){
  108731. return(og->header[14] |
  108732. (og->header[15]<<8) |
  108733. (og->header[16]<<16) |
  108734. (og->header[17]<<24));
  108735. }
  108736. long ogg_page_pageno(ogg_page *og){
  108737. return(og->header[18] |
  108738. (og->header[19]<<8) |
  108739. (og->header[20]<<16) |
  108740. (og->header[21]<<24));
  108741. }
  108742. /* returns the number of packets that are completed on this page (if
  108743. the leading packet is begun on a previous page, but ends on this
  108744. page, it's counted */
  108745. /* NOTE:
  108746. If a page consists of a packet begun on a previous page, and a new
  108747. packet begun (but not completed) on this page, the return will be:
  108748. ogg_page_packets(page) ==1,
  108749. ogg_page_continued(page) !=0
  108750. If a page happens to be a single packet that was begun on a
  108751. previous page, and spans to the next page (in the case of a three or
  108752. more page packet), the return will be:
  108753. ogg_page_packets(page) ==0,
  108754. ogg_page_continued(page) !=0
  108755. */
  108756. int ogg_page_packets(ogg_page *og){
  108757. int i,n=og->header[26],count=0;
  108758. for(i=0;i<n;i++)
  108759. if(og->header[27+i]<255)count++;
  108760. return(count);
  108761. }
  108762. #if 0
  108763. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108764. use the static init below) */
  108765. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108766. int i;
  108767. unsigned long r;
  108768. r = index << 24;
  108769. for (i=0; i<8; i++)
  108770. if (r & 0x80000000UL)
  108771. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108772. polynomial, although we use an
  108773. unreflected alg and an init/final
  108774. of 0, not 0xffffffff */
  108775. else
  108776. r<<=1;
  108777. return (r & 0xffffffffUL);
  108778. }
  108779. #endif
  108780. static const ogg_uint32_t crc_lookup[256]={
  108781. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108782. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108783. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108784. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108785. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108786. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108787. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108788. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108789. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108790. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108791. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108792. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108793. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108794. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108795. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108796. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108797. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108798. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108799. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108800. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108801. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108802. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108803. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108804. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108805. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108806. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108807. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108808. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108809. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108810. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108811. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108812. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108813. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108814. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108815. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108816. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108817. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108818. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108819. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108820. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108821. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108822. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108823. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108824. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108825. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108826. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108827. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108828. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108829. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108830. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108831. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108832. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108833. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108834. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108835. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108836. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108837. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108838. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108839. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108840. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108841. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108842. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108843. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108844. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108845. /* init the encode/decode logical stream state */
  108846. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108847. if(os){
  108848. memset(os,0,sizeof(*os));
  108849. os->body_storage=16*1024;
  108850. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108851. os->lacing_storage=1024;
  108852. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108853. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108854. os->serialno=serialno;
  108855. return(0);
  108856. }
  108857. return(-1);
  108858. }
  108859. /* _clear does not free os, only the non-flat storage within */
  108860. int ogg_stream_clear(ogg_stream_state *os){
  108861. if(os){
  108862. if(os->body_data)_ogg_free(os->body_data);
  108863. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108864. if(os->granule_vals)_ogg_free(os->granule_vals);
  108865. memset(os,0,sizeof(*os));
  108866. }
  108867. return(0);
  108868. }
  108869. int ogg_stream_destroy(ogg_stream_state *os){
  108870. if(os){
  108871. ogg_stream_clear(os);
  108872. _ogg_free(os);
  108873. }
  108874. return(0);
  108875. }
  108876. /* Helpers for ogg_stream_encode; this keeps the structure and
  108877. what's happening fairly clear */
  108878. static void _os_body_expand(ogg_stream_state *os,int needed){
  108879. if(os->body_storage<=os->body_fill+needed){
  108880. os->body_storage+=(needed+1024);
  108881. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108882. }
  108883. }
  108884. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108885. if(os->lacing_storage<=os->lacing_fill+needed){
  108886. os->lacing_storage+=(needed+32);
  108887. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108888. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108889. }
  108890. }
  108891. /* checksum the page */
  108892. /* Direct table CRC; note that this will be faster in the future if we
  108893. perform the checksum silmultaneously with other copies */
  108894. void ogg_page_checksum_set(ogg_page *og){
  108895. if(og){
  108896. ogg_uint32_t crc_reg=0;
  108897. int i;
  108898. /* safety; needed for API behavior, but not framing code */
  108899. og->header[22]=0;
  108900. og->header[23]=0;
  108901. og->header[24]=0;
  108902. og->header[25]=0;
  108903. for(i=0;i<og->header_len;i++)
  108904. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108905. for(i=0;i<og->body_len;i++)
  108906. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108907. og->header[22]=(unsigned char)(crc_reg&0xff);
  108908. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108909. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108910. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108911. }
  108912. }
  108913. /* submit data to the internal buffer of the framing engine */
  108914. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108915. int lacing_vals=op->bytes/255+1,i;
  108916. if(os->body_returned){
  108917. /* advance packet data according to the body_returned pointer. We
  108918. had to keep it around to return a pointer into the buffer last
  108919. call */
  108920. os->body_fill-=os->body_returned;
  108921. if(os->body_fill)
  108922. memmove(os->body_data,os->body_data+os->body_returned,
  108923. os->body_fill);
  108924. os->body_returned=0;
  108925. }
  108926. /* make sure we have the buffer storage */
  108927. _os_body_expand(os,op->bytes);
  108928. _os_lacing_expand(os,lacing_vals);
  108929. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108930. the liability of overly clean abstraction for the time being. It
  108931. will actually be fairly easy to eliminate the extra copy in the
  108932. future */
  108933. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108934. os->body_fill+=op->bytes;
  108935. /* Store lacing vals for this packet */
  108936. for(i=0;i<lacing_vals-1;i++){
  108937. os->lacing_vals[os->lacing_fill+i]=255;
  108938. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108939. }
  108940. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108941. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108942. /* flag the first segment as the beginning of the packet */
  108943. os->lacing_vals[os->lacing_fill]|= 0x100;
  108944. os->lacing_fill+=lacing_vals;
  108945. /* for the sake of completeness */
  108946. os->packetno++;
  108947. if(op->e_o_s)os->e_o_s=1;
  108948. return(0);
  108949. }
  108950. /* This will flush remaining packets into a page (returning nonzero),
  108951. even if there is not enough data to trigger a flush normally
  108952. (undersized page). If there are no packets or partial packets to
  108953. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108954. try to flush a normal sized page like ogg_stream_pageout; a call to
  108955. ogg_stream_flush does not guarantee that all packets have flushed.
  108956. Only a return value of 0 from ogg_stream_flush indicates all packet
  108957. data is flushed into pages.
  108958. since ogg_stream_flush will flush the last page in a stream even if
  108959. it's undersized, you almost certainly want to use ogg_stream_pageout
  108960. (and *not* ogg_stream_flush) unless you specifically need to flush
  108961. an page regardless of size in the middle of a stream. */
  108962. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108963. int i;
  108964. int vals=0;
  108965. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108966. int bytes=0;
  108967. long acc=0;
  108968. ogg_int64_t granule_pos=-1;
  108969. if(maxvals==0)return(0);
  108970. /* construct a page */
  108971. /* decide how many segments to include */
  108972. /* If this is the initial header case, the first page must only include
  108973. the initial header packet */
  108974. if(os->b_o_s==0){ /* 'initial header page' case */
  108975. granule_pos=0;
  108976. for(vals=0;vals<maxvals;vals++){
  108977. if((os->lacing_vals[vals]&0x0ff)<255){
  108978. vals++;
  108979. break;
  108980. }
  108981. }
  108982. }else{
  108983. for(vals=0;vals<maxvals;vals++){
  108984. if(acc>4096)break;
  108985. acc+=os->lacing_vals[vals]&0x0ff;
  108986. if((os->lacing_vals[vals]&0xff)<255)
  108987. granule_pos=os->granule_vals[vals];
  108988. }
  108989. }
  108990. /* construct the header in temp storage */
  108991. memcpy(os->header,"OggS",4);
  108992. /* stream structure version */
  108993. os->header[4]=0x00;
  108994. /* continued packet flag? */
  108995. os->header[5]=0x00;
  108996. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108997. /* first page flag? */
  108998. if(os->b_o_s==0)os->header[5]|=0x02;
  108999. /* last page flag? */
  109000. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  109001. os->b_o_s=1;
  109002. /* 64 bits of PCM position */
  109003. for(i=6;i<14;i++){
  109004. os->header[i]=(unsigned char)(granule_pos&0xff);
  109005. granule_pos>>=8;
  109006. }
  109007. /* 32 bits of stream serial number */
  109008. {
  109009. long serialno=os->serialno;
  109010. for(i=14;i<18;i++){
  109011. os->header[i]=(unsigned char)(serialno&0xff);
  109012. serialno>>=8;
  109013. }
  109014. }
  109015. /* 32 bits of page counter (we have both counter and page header
  109016. because this val can roll over) */
  109017. if(os->pageno==-1)os->pageno=0; /* because someone called
  109018. stream_reset; this would be a
  109019. strange thing to do in an
  109020. encode stream, but it has
  109021. plausible uses */
  109022. {
  109023. long pageno=os->pageno++;
  109024. for(i=18;i<22;i++){
  109025. os->header[i]=(unsigned char)(pageno&0xff);
  109026. pageno>>=8;
  109027. }
  109028. }
  109029. /* zero for computation; filled in later */
  109030. os->header[22]=0;
  109031. os->header[23]=0;
  109032. os->header[24]=0;
  109033. os->header[25]=0;
  109034. /* segment table */
  109035. os->header[26]=(unsigned char)(vals&0xff);
  109036. for(i=0;i<vals;i++)
  109037. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  109038. /* set pointers in the ogg_page struct */
  109039. og->header=os->header;
  109040. og->header_len=os->header_fill=vals+27;
  109041. og->body=os->body_data+os->body_returned;
  109042. og->body_len=bytes;
  109043. /* advance the lacing data and set the body_returned pointer */
  109044. os->lacing_fill-=vals;
  109045. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  109046. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  109047. os->body_returned+=bytes;
  109048. /* calculate the checksum */
  109049. ogg_page_checksum_set(og);
  109050. /* done */
  109051. return(1);
  109052. }
  109053. /* This constructs pages from buffered packet segments. The pointers
  109054. returned are to static buffers; do not free. The returned buffers are
  109055. good only until the next call (using the same ogg_stream_state) */
  109056. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  109057. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  109058. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  109059. os->lacing_fill>=255 || /* 'segment table full' case */
  109060. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  109061. return(ogg_stream_flush(os,og));
  109062. }
  109063. /* not enough data to construct a page and not end of stream */
  109064. return(0);
  109065. }
  109066. int ogg_stream_eos(ogg_stream_state *os){
  109067. return os->e_o_s;
  109068. }
  109069. /* DECODING PRIMITIVES: packet streaming layer **********************/
  109070. /* This has two layers to place more of the multi-serialno and paging
  109071. control in the application's hands. First, we expose a data buffer
  109072. using ogg_sync_buffer(). The app either copies into the
  109073. buffer, or passes it directly to read(), etc. We then call
  109074. ogg_sync_wrote() to tell how many bytes we just added.
  109075. Pages are returned (pointers into the buffer in ogg_sync_state)
  109076. by ogg_sync_pageout(). The page is then submitted to
  109077. ogg_stream_pagein() along with the appropriate
  109078. ogg_stream_state* (ie, matching serialno). We then get raw
  109079. packets out calling ogg_stream_packetout() with a
  109080. ogg_stream_state. */
  109081. /* initialize the struct to a known state */
  109082. int ogg_sync_init(ogg_sync_state *oy){
  109083. if(oy){
  109084. memset(oy,0,sizeof(*oy));
  109085. }
  109086. return(0);
  109087. }
  109088. /* clear non-flat storage within */
  109089. int ogg_sync_clear(ogg_sync_state *oy){
  109090. if(oy){
  109091. if(oy->data)_ogg_free(oy->data);
  109092. ogg_sync_init(oy);
  109093. }
  109094. return(0);
  109095. }
  109096. int ogg_sync_destroy(ogg_sync_state *oy){
  109097. if(oy){
  109098. ogg_sync_clear(oy);
  109099. _ogg_free(oy);
  109100. }
  109101. return(0);
  109102. }
  109103. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  109104. /* first, clear out any space that has been previously returned */
  109105. if(oy->returned){
  109106. oy->fill-=oy->returned;
  109107. if(oy->fill>0)
  109108. memmove(oy->data,oy->data+oy->returned,oy->fill);
  109109. oy->returned=0;
  109110. }
  109111. if(size>oy->storage-oy->fill){
  109112. /* We need to extend the internal buffer */
  109113. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  109114. if(oy->data)
  109115. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  109116. else
  109117. oy->data=(unsigned char*) _ogg_malloc(newsize);
  109118. oy->storage=newsize;
  109119. }
  109120. /* expose a segment at least as large as requested at the fill mark */
  109121. return((char *)oy->data+oy->fill);
  109122. }
  109123. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  109124. if(oy->fill+bytes>oy->storage)return(-1);
  109125. oy->fill+=bytes;
  109126. return(0);
  109127. }
  109128. /* sync the stream. This is meant to be useful for finding page
  109129. boundaries.
  109130. return values for this:
  109131. -n) skipped n bytes
  109132. 0) page not ready; more data (no bytes skipped)
  109133. n) page synced at current location; page length n bytes
  109134. */
  109135. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  109136. unsigned char *page=oy->data+oy->returned;
  109137. unsigned char *next;
  109138. long bytes=oy->fill-oy->returned;
  109139. if(oy->headerbytes==0){
  109140. int headerbytes,i;
  109141. if(bytes<27)return(0); /* not enough for a header */
  109142. /* verify capture pattern */
  109143. if(memcmp(page,"OggS",4))goto sync_fail;
  109144. headerbytes=page[26]+27;
  109145. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  109146. /* count up body length in the segment table */
  109147. for(i=0;i<page[26];i++)
  109148. oy->bodybytes+=page[27+i];
  109149. oy->headerbytes=headerbytes;
  109150. }
  109151. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  109152. /* The whole test page is buffered. Verify the checksum */
  109153. {
  109154. /* Grab the checksum bytes, set the header field to zero */
  109155. char chksum[4];
  109156. ogg_page log;
  109157. memcpy(chksum,page+22,4);
  109158. memset(page+22,0,4);
  109159. /* set up a temp page struct and recompute the checksum */
  109160. log.header=page;
  109161. log.header_len=oy->headerbytes;
  109162. log.body=page+oy->headerbytes;
  109163. log.body_len=oy->bodybytes;
  109164. ogg_page_checksum_set(&log);
  109165. /* Compare */
  109166. if(memcmp(chksum,page+22,4)){
  109167. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  109168. at all) */
  109169. /* replace the computed checksum with the one actually read in */
  109170. memcpy(page+22,chksum,4);
  109171. /* Bad checksum. Lose sync */
  109172. goto sync_fail;
  109173. }
  109174. }
  109175. /* yes, have a whole page all ready to go */
  109176. {
  109177. unsigned char *page=oy->data+oy->returned;
  109178. long bytes;
  109179. if(og){
  109180. og->header=page;
  109181. og->header_len=oy->headerbytes;
  109182. og->body=page+oy->headerbytes;
  109183. og->body_len=oy->bodybytes;
  109184. }
  109185. oy->unsynced=0;
  109186. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109187. oy->headerbytes=0;
  109188. oy->bodybytes=0;
  109189. return(bytes);
  109190. }
  109191. sync_fail:
  109192. oy->headerbytes=0;
  109193. oy->bodybytes=0;
  109194. /* search for possible capture */
  109195. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109196. if(!next)
  109197. next=oy->data+oy->fill;
  109198. oy->returned=next-oy->data;
  109199. return(-(next-page));
  109200. }
  109201. /* sync the stream and get a page. Keep trying until we find a page.
  109202. Supress 'sync errors' after reporting the first.
  109203. return values:
  109204. -1) recapture (hole in data)
  109205. 0) need more data
  109206. 1) page returned
  109207. Returns pointers into buffered data; invalidated by next call to
  109208. _stream, _clear, _init, or _buffer */
  109209. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109210. /* all we need to do is verify a page at the head of the stream
  109211. buffer. If it doesn't verify, we look for the next potential
  109212. frame */
  109213. for(;;){
  109214. long ret=ogg_sync_pageseek(oy,og);
  109215. if(ret>0){
  109216. /* have a page */
  109217. return(1);
  109218. }
  109219. if(ret==0){
  109220. /* need more data */
  109221. return(0);
  109222. }
  109223. /* head did not start a synced page... skipped some bytes */
  109224. if(!oy->unsynced){
  109225. oy->unsynced=1;
  109226. return(-1);
  109227. }
  109228. /* loop. keep looking */
  109229. }
  109230. }
  109231. /* add the incoming page to the stream state; we decompose the page
  109232. into packet segments here as well. */
  109233. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109234. unsigned char *header=og->header;
  109235. unsigned char *body=og->body;
  109236. long bodysize=og->body_len;
  109237. int segptr=0;
  109238. int version=ogg_page_version(og);
  109239. int continued=ogg_page_continued(og);
  109240. int bos=ogg_page_bos(og);
  109241. int eos=ogg_page_eos(og);
  109242. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109243. int serialno=ogg_page_serialno(og);
  109244. long pageno=ogg_page_pageno(og);
  109245. int segments=header[26];
  109246. /* clean up 'returned data' */
  109247. {
  109248. long lr=os->lacing_returned;
  109249. long br=os->body_returned;
  109250. /* body data */
  109251. if(br){
  109252. os->body_fill-=br;
  109253. if(os->body_fill)
  109254. memmove(os->body_data,os->body_data+br,os->body_fill);
  109255. os->body_returned=0;
  109256. }
  109257. if(lr){
  109258. /* segment table */
  109259. if(os->lacing_fill-lr){
  109260. memmove(os->lacing_vals,os->lacing_vals+lr,
  109261. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109262. memmove(os->granule_vals,os->granule_vals+lr,
  109263. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109264. }
  109265. os->lacing_fill-=lr;
  109266. os->lacing_packet-=lr;
  109267. os->lacing_returned=0;
  109268. }
  109269. }
  109270. /* check the serial number */
  109271. if(serialno!=os->serialno)return(-1);
  109272. if(version>0)return(-1);
  109273. _os_lacing_expand(os,segments+1);
  109274. /* are we in sequence? */
  109275. if(pageno!=os->pageno){
  109276. int i;
  109277. /* unroll previous partial packet (if any) */
  109278. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109279. os->body_fill-=os->lacing_vals[i]&0xff;
  109280. os->lacing_fill=os->lacing_packet;
  109281. /* make a note of dropped data in segment table */
  109282. if(os->pageno!=-1){
  109283. os->lacing_vals[os->lacing_fill++]=0x400;
  109284. os->lacing_packet++;
  109285. }
  109286. }
  109287. /* are we a 'continued packet' page? If so, we may need to skip
  109288. some segments */
  109289. if(continued){
  109290. if(os->lacing_fill<1 ||
  109291. os->lacing_vals[os->lacing_fill-1]==0x400){
  109292. bos=0;
  109293. for(;segptr<segments;segptr++){
  109294. int val=header[27+segptr];
  109295. body+=val;
  109296. bodysize-=val;
  109297. if(val<255){
  109298. segptr++;
  109299. break;
  109300. }
  109301. }
  109302. }
  109303. }
  109304. if(bodysize){
  109305. _os_body_expand(os,bodysize);
  109306. memcpy(os->body_data+os->body_fill,body,bodysize);
  109307. os->body_fill+=bodysize;
  109308. }
  109309. {
  109310. int saved=-1;
  109311. while(segptr<segments){
  109312. int val=header[27+segptr];
  109313. os->lacing_vals[os->lacing_fill]=val;
  109314. os->granule_vals[os->lacing_fill]=-1;
  109315. if(bos){
  109316. os->lacing_vals[os->lacing_fill]|=0x100;
  109317. bos=0;
  109318. }
  109319. if(val<255)saved=os->lacing_fill;
  109320. os->lacing_fill++;
  109321. segptr++;
  109322. if(val<255)os->lacing_packet=os->lacing_fill;
  109323. }
  109324. /* set the granulepos on the last granuleval of the last full packet */
  109325. if(saved!=-1){
  109326. os->granule_vals[saved]=granulepos;
  109327. }
  109328. }
  109329. if(eos){
  109330. os->e_o_s=1;
  109331. if(os->lacing_fill>0)
  109332. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109333. }
  109334. os->pageno=pageno+1;
  109335. return(0);
  109336. }
  109337. /* clear things to an initial state. Good to call, eg, before seeking */
  109338. int ogg_sync_reset(ogg_sync_state *oy){
  109339. oy->fill=0;
  109340. oy->returned=0;
  109341. oy->unsynced=0;
  109342. oy->headerbytes=0;
  109343. oy->bodybytes=0;
  109344. return(0);
  109345. }
  109346. int ogg_stream_reset(ogg_stream_state *os){
  109347. os->body_fill=0;
  109348. os->body_returned=0;
  109349. os->lacing_fill=0;
  109350. os->lacing_packet=0;
  109351. os->lacing_returned=0;
  109352. os->header_fill=0;
  109353. os->e_o_s=0;
  109354. os->b_o_s=0;
  109355. os->pageno=-1;
  109356. os->packetno=0;
  109357. os->granulepos=0;
  109358. return(0);
  109359. }
  109360. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109361. ogg_stream_reset(os);
  109362. os->serialno=serialno;
  109363. return(0);
  109364. }
  109365. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109366. /* The last part of decode. We have the stream broken into packet
  109367. segments. Now we need to group them into packets (or return the
  109368. out of sync markers) */
  109369. int ptr=os->lacing_returned;
  109370. if(os->lacing_packet<=ptr)return(0);
  109371. if(os->lacing_vals[ptr]&0x400){
  109372. /* we need to tell the codec there's a gap; it might need to
  109373. handle previous packet dependencies. */
  109374. os->lacing_returned++;
  109375. os->packetno++;
  109376. return(-1);
  109377. }
  109378. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109379. to ask if there's a whole packet
  109380. waiting */
  109381. /* Gather the whole packet. We'll have no holes or a partial packet */
  109382. {
  109383. int size=os->lacing_vals[ptr]&0xff;
  109384. int bytes=size;
  109385. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109386. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109387. while(size==255){
  109388. int val=os->lacing_vals[++ptr];
  109389. size=val&0xff;
  109390. if(val&0x200)eos=0x200;
  109391. bytes+=size;
  109392. }
  109393. if(op){
  109394. op->e_o_s=eos;
  109395. op->b_o_s=bos;
  109396. op->packet=os->body_data+os->body_returned;
  109397. op->packetno=os->packetno;
  109398. op->granulepos=os->granule_vals[ptr];
  109399. op->bytes=bytes;
  109400. }
  109401. if(adv){
  109402. os->body_returned+=bytes;
  109403. os->lacing_returned=ptr+1;
  109404. os->packetno++;
  109405. }
  109406. }
  109407. return(1);
  109408. }
  109409. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109410. return _packetout(os,op,1);
  109411. }
  109412. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109413. return _packetout(os,op,0);
  109414. }
  109415. void ogg_packet_clear(ogg_packet *op) {
  109416. _ogg_free(op->packet);
  109417. memset(op, 0, sizeof(*op));
  109418. }
  109419. #ifdef _V_SELFTEST
  109420. #include <stdio.h>
  109421. ogg_stream_state os_en, os_de;
  109422. ogg_sync_state oy;
  109423. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109424. long j;
  109425. static int sequence=0;
  109426. static int lastno=0;
  109427. if(op->bytes!=len){
  109428. fprintf(stderr,"incorrect packet length!\n");
  109429. exit(1);
  109430. }
  109431. if(op->granulepos!=pos){
  109432. fprintf(stderr,"incorrect packet position!\n");
  109433. exit(1);
  109434. }
  109435. /* packet number just follows sequence/gap; adjust the input number
  109436. for that */
  109437. if(no==0){
  109438. sequence=0;
  109439. }else{
  109440. sequence++;
  109441. if(no>lastno+1)
  109442. sequence++;
  109443. }
  109444. lastno=no;
  109445. if(op->packetno!=sequence){
  109446. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109447. (long)(op->packetno),sequence);
  109448. exit(1);
  109449. }
  109450. /* Test data */
  109451. for(j=0;j<op->bytes;j++)
  109452. if(op->packet[j]!=((j+no)&0xff)){
  109453. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109454. j,op->packet[j],(j+no)&0xff);
  109455. exit(1);
  109456. }
  109457. }
  109458. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109459. long j;
  109460. /* Test data */
  109461. for(j=0;j<og->body_len;j++)
  109462. if(og->body[j]!=data[j]){
  109463. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109464. j,data[j],og->body[j]);
  109465. exit(1);
  109466. }
  109467. /* Test header */
  109468. for(j=0;j<og->header_len;j++){
  109469. if(og->header[j]!=header[j]){
  109470. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109471. for(j=0;j<header[26]+27;j++)
  109472. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109473. fprintf(stderr,"\n");
  109474. exit(1);
  109475. }
  109476. }
  109477. if(og->header_len!=header[26]+27){
  109478. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109479. og->header_len,header[26]+27);
  109480. exit(1);
  109481. }
  109482. }
  109483. void print_header(ogg_page *og){
  109484. int j;
  109485. fprintf(stderr,"\nHEADER:\n");
  109486. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109487. og->header[0],og->header[1],og->header[2],og->header[3],
  109488. (int)og->header[4],(int)og->header[5]);
  109489. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109490. (og->header[9]<<24)|(og->header[8]<<16)|
  109491. (og->header[7]<<8)|og->header[6],
  109492. (og->header[17]<<24)|(og->header[16]<<16)|
  109493. (og->header[15]<<8)|og->header[14],
  109494. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109495. (og->header[19]<<8)|og->header[18]);
  109496. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109497. (int)og->header[22],(int)og->header[23],
  109498. (int)og->header[24],(int)og->header[25],
  109499. (int)og->header[26]);
  109500. for(j=27;j<og->header_len;j++)
  109501. fprintf(stderr,"%d ",(int)og->header[j]);
  109502. fprintf(stderr,")\n\n");
  109503. }
  109504. void copy_page(ogg_page *og){
  109505. unsigned char *temp=_ogg_malloc(og->header_len);
  109506. memcpy(temp,og->header,og->header_len);
  109507. og->header=temp;
  109508. temp=_ogg_malloc(og->body_len);
  109509. memcpy(temp,og->body,og->body_len);
  109510. og->body=temp;
  109511. }
  109512. void free_page(ogg_page *og){
  109513. _ogg_free (og->header);
  109514. _ogg_free (og->body);
  109515. }
  109516. void error(void){
  109517. fprintf(stderr,"error!\n");
  109518. exit(1);
  109519. }
  109520. /* 17 only */
  109521. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109522. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109523. 0x01,0x02,0x03,0x04,0,0,0,0,
  109524. 0x15,0xed,0xec,0x91,
  109525. 1,
  109526. 17};
  109527. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109528. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109529. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109530. 0x01,0x02,0x03,0x04,0,0,0,0,
  109531. 0x59,0x10,0x6c,0x2c,
  109532. 1,
  109533. 17};
  109534. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109535. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109536. 0x01,0x02,0x03,0x04,1,0,0,0,
  109537. 0x89,0x33,0x85,0xce,
  109538. 13,
  109539. 254,255,0,255,1,255,245,255,255,0,
  109540. 255,255,90};
  109541. /* nil packets; beginning,middle,end */
  109542. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109543. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109544. 0x01,0x02,0x03,0x04,0,0,0,0,
  109545. 0xff,0x7b,0x23,0x17,
  109546. 1,
  109547. 0};
  109548. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109549. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109550. 0x01,0x02,0x03,0x04,1,0,0,0,
  109551. 0x5c,0x3f,0x66,0xcb,
  109552. 17,
  109553. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109554. 255,255,90,0};
  109555. /* large initial packet */
  109556. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109557. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109558. 0x01,0x02,0x03,0x04,0,0,0,0,
  109559. 0x01,0x27,0x31,0xaa,
  109560. 18,
  109561. 255,255,255,255,255,255,255,255,
  109562. 255,255,255,255,255,255,255,255,255,10};
  109563. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109564. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109565. 0x01,0x02,0x03,0x04,1,0,0,0,
  109566. 0x7f,0x4e,0x8a,0xd2,
  109567. 4,
  109568. 255,4,255,0};
  109569. /* continuing packet test */
  109570. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109571. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109572. 0x01,0x02,0x03,0x04,0,0,0,0,
  109573. 0xff,0x7b,0x23,0x17,
  109574. 1,
  109575. 0};
  109576. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109577. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109578. 0x01,0x02,0x03,0x04,1,0,0,0,
  109579. 0x54,0x05,0x51,0xc8,
  109580. 17,
  109581. 255,255,255,255,255,255,255,255,
  109582. 255,255,255,255,255,255,255,255,255};
  109583. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109584. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109585. 0x01,0x02,0x03,0x04,2,0,0,0,
  109586. 0xc8,0xc3,0xcb,0xed,
  109587. 5,
  109588. 10,255,4,255,0};
  109589. /* page with the 255 segment limit */
  109590. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109591. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109592. 0x01,0x02,0x03,0x04,0,0,0,0,
  109593. 0xff,0x7b,0x23,0x17,
  109594. 1,
  109595. 0};
  109596. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109597. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109598. 0x01,0x02,0x03,0x04,1,0,0,0,
  109599. 0xed,0x2a,0x2e,0xa7,
  109600. 255,
  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,10,
  109621. 10,10,10,10,10,10,10,10,
  109622. 10,10,10,10,10,10,10,10,
  109623. 10,10,10,10,10,10,10,10,
  109624. 10,10,10,10,10,10,10,10,
  109625. 10,10,10,10,10,10,10,10,
  109626. 10,10,10,10,10,10,10,10,
  109627. 10,10,10,10,10,10,10,10,
  109628. 10,10,10,10,10,10,10,10,
  109629. 10,10,10,10,10,10,10,10,
  109630. 10,10,10,10,10,10,10,10,
  109631. 10,10,10,10,10,10,10,10,
  109632. 10,10,10,10,10,10,10};
  109633. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109634. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109635. 0x01,0x02,0x03,0x04,2,0,0,0,
  109636. 0x6c,0x3b,0x82,0x3d,
  109637. 1,
  109638. 50};
  109639. /* packet that overspans over an entire page */
  109640. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109641. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109642. 0x01,0x02,0x03,0x04,0,0,0,0,
  109643. 0xff,0x7b,0x23,0x17,
  109644. 1,
  109645. 0};
  109646. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109647. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109648. 0x01,0x02,0x03,0x04,1,0,0,0,
  109649. 0x3c,0xd9,0x4d,0x3f,
  109650. 17,
  109651. 100,255,255,255,255,255,255,255,255,
  109652. 255,255,255,255,255,255,255,255};
  109653. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109654. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109655. 0x01,0x02,0x03,0x04,2,0,0,0,
  109656. 0x01,0xd2,0xe5,0xe5,
  109657. 17,
  109658. 255,255,255,255,255,255,255,255,
  109659. 255,255,255,255,255,255,255,255,255};
  109660. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109661. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109662. 0x01,0x02,0x03,0x04,3,0,0,0,
  109663. 0xef,0xdd,0x88,0xde,
  109664. 7,
  109665. 255,255,75,255,4,255,0};
  109666. /* packet that overspans over an entire page */
  109667. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109668. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109669. 0x01,0x02,0x03,0x04,0,0,0,0,
  109670. 0xff,0x7b,0x23,0x17,
  109671. 1,
  109672. 0};
  109673. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109674. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109675. 0x01,0x02,0x03,0x04,1,0,0,0,
  109676. 0x3c,0xd9,0x4d,0x3f,
  109677. 17,
  109678. 100,255,255,255,255,255,255,255,255,
  109679. 255,255,255,255,255,255,255,255};
  109680. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109681. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109682. 0x01,0x02,0x03,0x04,2,0,0,0,
  109683. 0xd4,0xe0,0x60,0xe5,
  109684. 1,0};
  109685. void test_pack(const int *pl, const int **headers, int byteskip,
  109686. int pageskip, int packetskip){
  109687. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109688. long inptr=0;
  109689. long outptr=0;
  109690. long deptr=0;
  109691. long depacket=0;
  109692. long granule_pos=7,pageno=0;
  109693. int i,j,packets,pageout=pageskip;
  109694. int eosflag=0;
  109695. int bosflag=0;
  109696. int byteskipcount=0;
  109697. ogg_stream_reset(&os_en);
  109698. ogg_stream_reset(&os_de);
  109699. ogg_sync_reset(&oy);
  109700. for(packets=0;packets<packetskip;packets++)
  109701. depacket+=pl[packets];
  109702. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109703. for(i=0;i<packets;i++){
  109704. /* construct a test packet */
  109705. ogg_packet op;
  109706. int len=pl[i];
  109707. op.packet=data+inptr;
  109708. op.bytes=len;
  109709. op.e_o_s=(pl[i+1]<0?1:0);
  109710. op.granulepos=granule_pos;
  109711. granule_pos+=1024;
  109712. for(j=0;j<len;j++)data[inptr++]=i+j;
  109713. /* submit the test packet */
  109714. ogg_stream_packetin(&os_en,&op);
  109715. /* retrieve any finished pages */
  109716. {
  109717. ogg_page og;
  109718. while(ogg_stream_pageout(&os_en,&og)){
  109719. /* We have a page. Check it carefully */
  109720. fprintf(stderr,"%ld, ",pageno);
  109721. if(headers[pageno]==NULL){
  109722. fprintf(stderr,"coded too many pages!\n");
  109723. exit(1);
  109724. }
  109725. check_page(data+outptr,headers[pageno],&og);
  109726. outptr+=og.body_len;
  109727. pageno++;
  109728. if(pageskip){
  109729. bosflag=1;
  109730. pageskip--;
  109731. deptr+=og.body_len;
  109732. }
  109733. /* have a complete page; submit it to sync/decode */
  109734. {
  109735. ogg_page og_de;
  109736. ogg_packet op_de,op_de2;
  109737. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109738. char *next=buf;
  109739. byteskipcount+=og.header_len;
  109740. if(byteskipcount>byteskip){
  109741. memcpy(next,og.header,byteskipcount-byteskip);
  109742. next+=byteskipcount-byteskip;
  109743. byteskipcount=byteskip;
  109744. }
  109745. byteskipcount+=og.body_len;
  109746. if(byteskipcount>byteskip){
  109747. memcpy(next,og.body,byteskipcount-byteskip);
  109748. next+=byteskipcount-byteskip;
  109749. byteskipcount=byteskip;
  109750. }
  109751. ogg_sync_wrote(&oy,next-buf);
  109752. while(1){
  109753. int ret=ogg_sync_pageout(&oy,&og_de);
  109754. if(ret==0)break;
  109755. if(ret<0)continue;
  109756. /* got a page. Happy happy. Verify that it's good. */
  109757. fprintf(stderr,"(%ld), ",pageout);
  109758. check_page(data+deptr,headers[pageout],&og_de);
  109759. deptr+=og_de.body_len;
  109760. pageout++;
  109761. /* submit it to deconstitution */
  109762. ogg_stream_pagein(&os_de,&og_de);
  109763. /* packets out? */
  109764. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109765. ogg_stream_packetpeek(&os_de,NULL);
  109766. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109767. /* verify peek and out match */
  109768. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109769. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109770. depacket);
  109771. exit(1);
  109772. }
  109773. /* verify the packet! */
  109774. /* check data */
  109775. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109776. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109777. depacket);
  109778. exit(1);
  109779. }
  109780. /* check bos flag */
  109781. if(bosflag==0 && op_de.b_o_s==0){
  109782. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109783. exit(1);
  109784. }
  109785. if(bosflag && op_de.b_o_s){
  109786. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109787. exit(1);
  109788. }
  109789. bosflag=1;
  109790. depacket+=op_de.bytes;
  109791. /* check eos flag */
  109792. if(eosflag){
  109793. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109794. exit(1);
  109795. }
  109796. if(op_de.e_o_s)eosflag=1;
  109797. /* check granulepos flag */
  109798. if(op_de.granulepos!=-1){
  109799. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109800. }
  109801. }
  109802. }
  109803. }
  109804. }
  109805. }
  109806. }
  109807. _ogg_free(data);
  109808. if(headers[pageno]!=NULL){
  109809. fprintf(stderr,"did not write last page!\n");
  109810. exit(1);
  109811. }
  109812. if(headers[pageout]!=NULL){
  109813. fprintf(stderr,"did not decode last page!\n");
  109814. exit(1);
  109815. }
  109816. if(inptr!=outptr){
  109817. fprintf(stderr,"encoded page data incomplete!\n");
  109818. exit(1);
  109819. }
  109820. if(inptr!=deptr){
  109821. fprintf(stderr,"decoded page data incomplete!\n");
  109822. exit(1);
  109823. }
  109824. if(inptr!=depacket){
  109825. fprintf(stderr,"decoded packet data incomplete!\n");
  109826. exit(1);
  109827. }
  109828. if(!eosflag){
  109829. fprintf(stderr,"Never got a packet with EOS set!\n");
  109830. exit(1);
  109831. }
  109832. fprintf(stderr,"ok.\n");
  109833. }
  109834. int main(void){
  109835. ogg_stream_init(&os_en,0x04030201);
  109836. ogg_stream_init(&os_de,0x04030201);
  109837. ogg_sync_init(&oy);
  109838. /* Exercise each code path in the framing code. Also verify that
  109839. the checksums are working. */
  109840. {
  109841. /* 17 only */
  109842. const int packets[]={17, -1};
  109843. const int *headret[]={head1_0,NULL};
  109844. fprintf(stderr,"testing single page encoding... ");
  109845. test_pack(packets,headret,0,0,0);
  109846. }
  109847. {
  109848. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109849. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109850. const int *headret[]={head1_1,head2_1,NULL};
  109851. fprintf(stderr,"testing basic page encoding... ");
  109852. test_pack(packets,headret,0,0,0);
  109853. }
  109854. {
  109855. /* nil packets; beginning,middle,end */
  109856. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109857. const int *headret[]={head1_2,head2_2,NULL};
  109858. fprintf(stderr,"testing basic nil packets... ");
  109859. test_pack(packets,headret,0,0,0);
  109860. }
  109861. {
  109862. /* large initial packet */
  109863. const int packets[]={4345,259,255,-1};
  109864. const int *headret[]={head1_3,head2_3,NULL};
  109865. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109866. test_pack(packets,headret,0,0,0);
  109867. }
  109868. {
  109869. /* continuing packet test */
  109870. const int packets[]={0,4345,259,255,-1};
  109871. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109872. fprintf(stderr,"testing single packet page span... ");
  109873. test_pack(packets,headret,0,0,0);
  109874. }
  109875. /* page with the 255 segment limit */
  109876. {
  109877. const int packets[]={0,10,10,10,10,10,10,10,10,
  109878. 10,10,10,10,10,10,10,10,
  109879. 10,10,10,10,10,10,10,10,
  109880. 10,10,10,10,10,10,10,10,
  109881. 10,10,10,10,10,10,10,10,
  109882. 10,10,10,10,10,10,10,10,
  109883. 10,10,10,10,10,10,10,10,
  109884. 10,10,10,10,10,10,10,10,
  109885. 10,10,10,10,10,10,10,10,
  109886. 10,10,10,10,10,10,10,10,
  109887. 10,10,10,10,10,10,10,10,
  109888. 10,10,10,10,10,10,10,10,
  109889. 10,10,10,10,10,10,10,10,
  109890. 10,10,10,10,10,10,10,10,
  109891. 10,10,10,10,10,10,10,10,
  109892. 10,10,10,10,10,10,10,10,
  109893. 10,10,10,10,10,10,10,10,
  109894. 10,10,10,10,10,10,10,10,
  109895. 10,10,10,10,10,10,10,10,
  109896. 10,10,10,10,10,10,10,10,
  109897. 10,10,10,10,10,10,10,10,
  109898. 10,10,10,10,10,10,10,10,
  109899. 10,10,10,10,10,10,10,10,
  109900. 10,10,10,10,10,10,10,10,
  109901. 10,10,10,10,10,10,10,10,
  109902. 10,10,10,10,10,10,10,10,
  109903. 10,10,10,10,10,10,10,10,
  109904. 10,10,10,10,10,10,10,10,
  109905. 10,10,10,10,10,10,10,10,
  109906. 10,10,10,10,10,10,10,10,
  109907. 10,10,10,10,10,10,10,10,
  109908. 10,10,10,10,10,10,10,50,-1};
  109909. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109910. fprintf(stderr,"testing max packet segments... ");
  109911. test_pack(packets,headret,0,0,0);
  109912. }
  109913. {
  109914. /* packet that overspans over an entire page */
  109915. const int packets[]={0,100,9000,259,255,-1};
  109916. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109917. fprintf(stderr,"testing very large packets... ");
  109918. test_pack(packets,headret,0,0,0);
  109919. }
  109920. {
  109921. /* test for the libogg 1.1.1 resync in large continuation bug
  109922. found by Josh Coalson) */
  109923. const int packets[]={0,100,9000,259,255,-1};
  109924. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109925. fprintf(stderr,"testing continuation resync in very large packets... ");
  109926. test_pack(packets,headret,100,2,3);
  109927. }
  109928. {
  109929. /* term only page. why not? */
  109930. const int packets[]={0,100,4080,-1};
  109931. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109932. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109933. test_pack(packets,headret,0,0,0);
  109934. }
  109935. {
  109936. /* build a bunch of pages for testing */
  109937. unsigned char *data=_ogg_malloc(1024*1024);
  109938. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109939. int inptr=0,i,j;
  109940. ogg_page og[5];
  109941. ogg_stream_reset(&os_en);
  109942. for(i=0;pl[i]!=-1;i++){
  109943. ogg_packet op;
  109944. int len=pl[i];
  109945. op.packet=data+inptr;
  109946. op.bytes=len;
  109947. op.e_o_s=(pl[i+1]<0?1:0);
  109948. op.granulepos=(i+1)*1000;
  109949. for(j=0;j<len;j++)data[inptr++]=i+j;
  109950. ogg_stream_packetin(&os_en,&op);
  109951. }
  109952. _ogg_free(data);
  109953. /* retrieve finished pages */
  109954. for(i=0;i<5;i++){
  109955. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109956. fprintf(stderr,"Too few pages output building sync tests!\n");
  109957. exit(1);
  109958. }
  109959. copy_page(&og[i]);
  109960. }
  109961. /* Test lost pages on pagein/packetout: no rollback */
  109962. {
  109963. ogg_page temp;
  109964. ogg_packet test;
  109965. fprintf(stderr,"Testing loss of pages... ");
  109966. ogg_sync_reset(&oy);
  109967. ogg_stream_reset(&os_de);
  109968. for(i=0;i<5;i++){
  109969. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109970. og[i].header_len);
  109971. ogg_sync_wrote(&oy,og[i].header_len);
  109972. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109973. ogg_sync_wrote(&oy,og[i].body_len);
  109974. }
  109975. ogg_sync_pageout(&oy,&temp);
  109976. ogg_stream_pagein(&os_de,&temp);
  109977. ogg_sync_pageout(&oy,&temp);
  109978. ogg_stream_pagein(&os_de,&temp);
  109979. ogg_sync_pageout(&oy,&temp);
  109980. /* skip */
  109981. ogg_sync_pageout(&oy,&temp);
  109982. ogg_stream_pagein(&os_de,&temp);
  109983. /* do we get the expected results/packets? */
  109984. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109985. checkpacket(&test,0,0,0);
  109986. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109987. checkpacket(&test,100,1,-1);
  109988. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109989. checkpacket(&test,4079,2,3000);
  109990. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109991. fprintf(stderr,"Error: loss of page did not return error\n");
  109992. exit(1);
  109993. }
  109994. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109995. checkpacket(&test,76,5,-1);
  109996. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109997. checkpacket(&test,34,6,-1);
  109998. fprintf(stderr,"ok.\n");
  109999. }
  110000. /* Test lost pages on pagein/packetout: rollback with continuation */
  110001. {
  110002. ogg_page temp;
  110003. ogg_packet test;
  110004. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  110005. ogg_sync_reset(&oy);
  110006. ogg_stream_reset(&os_de);
  110007. for(i=0;i<5;i++){
  110008. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  110009. og[i].header_len);
  110010. ogg_sync_wrote(&oy,og[i].header_len);
  110011. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  110012. ogg_sync_wrote(&oy,og[i].body_len);
  110013. }
  110014. ogg_sync_pageout(&oy,&temp);
  110015. ogg_stream_pagein(&os_de,&temp);
  110016. ogg_sync_pageout(&oy,&temp);
  110017. ogg_stream_pagein(&os_de,&temp);
  110018. ogg_sync_pageout(&oy,&temp);
  110019. ogg_stream_pagein(&os_de,&temp);
  110020. ogg_sync_pageout(&oy,&temp);
  110021. /* skip */
  110022. ogg_sync_pageout(&oy,&temp);
  110023. ogg_stream_pagein(&os_de,&temp);
  110024. /* do we get the expected results/packets? */
  110025. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  110026. checkpacket(&test,0,0,0);
  110027. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  110028. checkpacket(&test,100,1,-1);
  110029. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  110030. checkpacket(&test,4079,2,3000);
  110031. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  110032. checkpacket(&test,2956,3,4000);
  110033. if(ogg_stream_packetout(&os_de,&test)!=-1){
  110034. fprintf(stderr,"Error: loss of page did not return error\n");
  110035. exit(1);
  110036. }
  110037. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  110038. checkpacket(&test,300,13,14000);
  110039. fprintf(stderr,"ok.\n");
  110040. }
  110041. /* the rest only test sync */
  110042. {
  110043. ogg_page og_de;
  110044. /* Test fractional page inputs: incomplete capture */
  110045. fprintf(stderr,"Testing sync on partial inputs... ");
  110046. ogg_sync_reset(&oy);
  110047. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110048. 3);
  110049. ogg_sync_wrote(&oy,3);
  110050. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110051. /* Test fractional page inputs: incomplete fixed header */
  110052. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  110053. 20);
  110054. ogg_sync_wrote(&oy,20);
  110055. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110056. /* Test fractional page inputs: incomplete header */
  110057. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  110058. 5);
  110059. ogg_sync_wrote(&oy,5);
  110060. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110061. /* Test fractional page inputs: incomplete body */
  110062. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  110063. og[1].header_len-28);
  110064. ogg_sync_wrote(&oy,og[1].header_len-28);
  110065. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110066. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  110067. ogg_sync_wrote(&oy,1000);
  110068. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110069. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  110070. og[1].body_len-1000);
  110071. ogg_sync_wrote(&oy,og[1].body_len-1000);
  110072. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110073. fprintf(stderr,"ok.\n");
  110074. }
  110075. /* Test fractional page inputs: page + incomplete capture */
  110076. {
  110077. ogg_page og_de;
  110078. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  110079. ogg_sync_reset(&oy);
  110080. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110081. og[1].header_len);
  110082. ogg_sync_wrote(&oy,og[1].header_len);
  110083. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110084. og[1].body_len);
  110085. ogg_sync_wrote(&oy,og[1].body_len);
  110086. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110087. 20);
  110088. ogg_sync_wrote(&oy,20);
  110089. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110090. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110091. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  110092. og[1].header_len-20);
  110093. ogg_sync_wrote(&oy,og[1].header_len-20);
  110094. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110095. og[1].body_len);
  110096. ogg_sync_wrote(&oy,og[1].body_len);
  110097. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110098. fprintf(stderr,"ok.\n");
  110099. }
  110100. /* Test recapture: garbage + page */
  110101. {
  110102. ogg_page og_de;
  110103. fprintf(stderr,"Testing search for capture... ");
  110104. ogg_sync_reset(&oy);
  110105. /* 'garbage' */
  110106. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110107. og[1].body_len);
  110108. ogg_sync_wrote(&oy,og[1].body_len);
  110109. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110110. og[1].header_len);
  110111. ogg_sync_wrote(&oy,og[1].header_len);
  110112. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110113. og[1].body_len);
  110114. ogg_sync_wrote(&oy,og[1].body_len);
  110115. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110116. 20);
  110117. ogg_sync_wrote(&oy,20);
  110118. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110119. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110120. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110121. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  110122. og[2].header_len-20);
  110123. ogg_sync_wrote(&oy,og[2].header_len-20);
  110124. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110125. og[2].body_len);
  110126. ogg_sync_wrote(&oy,og[2].body_len);
  110127. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110128. fprintf(stderr,"ok.\n");
  110129. }
  110130. /* Test recapture: page + garbage + page */
  110131. {
  110132. ogg_page og_de;
  110133. fprintf(stderr,"Testing recapture... ");
  110134. ogg_sync_reset(&oy);
  110135. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110136. og[1].header_len);
  110137. ogg_sync_wrote(&oy,og[1].header_len);
  110138. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110139. og[1].body_len);
  110140. ogg_sync_wrote(&oy,og[1].body_len);
  110141. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110142. og[2].header_len);
  110143. ogg_sync_wrote(&oy,og[2].header_len);
  110144. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110145. og[2].header_len);
  110146. ogg_sync_wrote(&oy,og[2].header_len);
  110147. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110148. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110149. og[2].body_len-5);
  110150. ogg_sync_wrote(&oy,og[2].body_len-5);
  110151. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  110152. og[3].header_len);
  110153. ogg_sync_wrote(&oy,og[3].header_len);
  110154. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  110155. og[3].body_len);
  110156. ogg_sync_wrote(&oy,og[3].body_len);
  110157. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110158. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110159. fprintf(stderr,"ok.\n");
  110160. }
  110161. /* Free page data that was previously copied */
  110162. {
  110163. for(i=0;i<5;i++){
  110164. free_page(&og[i]);
  110165. }
  110166. }
  110167. }
  110168. return(0);
  110169. }
  110170. #endif
  110171. #endif
  110172. /*** End of inlined file: framing.c ***/
  110173. /*** Start of inlined file: analysis.c ***/
  110174. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110175. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110176. // tasks..
  110177. #if JUCE_MSVC
  110178. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110179. #endif
  110180. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110181. #if JUCE_USE_OGGVORBIS
  110182. #include <stdio.h>
  110183. #include <string.h>
  110184. #include <math.h>
  110185. /*** Start of inlined file: codec_internal.h ***/
  110186. #ifndef _V_CODECI_H_
  110187. #define _V_CODECI_H_
  110188. /*** Start of inlined file: envelope.h ***/
  110189. #ifndef _V_ENVELOPE_
  110190. #define _V_ENVELOPE_
  110191. /*** Start of inlined file: mdct.h ***/
  110192. #ifndef _OGG_mdct_H_
  110193. #define _OGG_mdct_H_
  110194. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110195. #ifdef MDCT_INTEGERIZED
  110196. #define DATA_TYPE int
  110197. #define REG_TYPE register int
  110198. #define TRIGBITS 14
  110199. #define cPI3_8 6270
  110200. #define cPI2_8 11585
  110201. #define cPI1_8 15137
  110202. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110203. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110204. #define HALVE(x) ((x)>>1)
  110205. #else
  110206. #define DATA_TYPE float
  110207. #define REG_TYPE float
  110208. #define cPI3_8 .38268343236508977175F
  110209. #define cPI2_8 .70710678118654752441F
  110210. #define cPI1_8 .92387953251128675613F
  110211. #define FLOAT_CONV(x) (x)
  110212. #define MULT_NORM(x) (x)
  110213. #define HALVE(x) ((x)*.5f)
  110214. #endif
  110215. typedef struct {
  110216. int n;
  110217. int log2n;
  110218. DATA_TYPE *trig;
  110219. int *bitrev;
  110220. DATA_TYPE scale;
  110221. } mdct_lookup;
  110222. extern void mdct_init(mdct_lookup *lookup,int n);
  110223. extern void mdct_clear(mdct_lookup *l);
  110224. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110225. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110226. #endif
  110227. /*** End of inlined file: mdct.h ***/
  110228. #define VE_PRE 16
  110229. #define VE_WIN 4
  110230. #define VE_POST 2
  110231. #define VE_AMP (VE_PRE+VE_POST-1)
  110232. #define VE_BANDS 7
  110233. #define VE_NEARDC 15
  110234. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110235. #define VE_MAXSTRETCH 12 /* one-third full block */
  110236. typedef struct {
  110237. float ampbuf[VE_AMP];
  110238. int ampptr;
  110239. float nearDC[VE_NEARDC];
  110240. float nearDC_acc;
  110241. float nearDC_partialacc;
  110242. int nearptr;
  110243. } envelope_filter_state;
  110244. typedef struct {
  110245. int begin;
  110246. int end;
  110247. float *window;
  110248. float total;
  110249. } envelope_band;
  110250. typedef struct {
  110251. int ch;
  110252. int winlength;
  110253. int searchstep;
  110254. float minenergy;
  110255. mdct_lookup mdct;
  110256. float *mdct_win;
  110257. envelope_band band[VE_BANDS];
  110258. envelope_filter_state *filter;
  110259. int stretch;
  110260. int *mark;
  110261. long storage;
  110262. long current;
  110263. long curmark;
  110264. long cursor;
  110265. } envelope_lookup;
  110266. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110267. extern void _ve_envelope_clear(envelope_lookup *e);
  110268. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110269. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110270. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110271. #endif
  110272. /*** End of inlined file: envelope.h ***/
  110273. /*** Start of inlined file: codebook.h ***/
  110274. #ifndef _V_CODEBOOK_H_
  110275. #define _V_CODEBOOK_H_
  110276. /* This structure encapsulates huffman and VQ style encoding books; it
  110277. doesn't do anything specific to either.
  110278. valuelist/quantlist are nonNULL (and q_* significant) only if
  110279. there's entry->value mapping to be done.
  110280. If encode-side mapping must be done (and thus the entry needs to be
  110281. hunted), the auxiliary encode pointer will point to a decision
  110282. tree. This is true of both VQ and huffman, but is mostly useful
  110283. with VQ.
  110284. */
  110285. typedef struct static_codebook{
  110286. long dim; /* codebook dimensions (elements per vector) */
  110287. long entries; /* codebook entries */
  110288. long *lengthlist; /* codeword lengths in bits */
  110289. /* mapping ***************************************************************/
  110290. int maptype; /* 0=none
  110291. 1=implicitly populated values from map column
  110292. 2=listed arbitrary values */
  110293. /* The below does a linear, single monotonic sequence mapping. */
  110294. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110295. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110296. int q_quant; /* bits: 0 < quant <= 16 */
  110297. int q_sequencep; /* bitflag */
  110298. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110299. map == 2: list of dim*entries quantized entry vals
  110300. */
  110301. /* encode helpers ********************************************************/
  110302. struct encode_aux_nearestmatch *nearest_tree;
  110303. struct encode_aux_threshmatch *thresh_tree;
  110304. struct encode_aux_pigeonhole *pigeon_tree;
  110305. int allocedp;
  110306. } static_codebook;
  110307. /* this structures an arbitrary trained book to quickly find the
  110308. nearest cell match */
  110309. typedef struct encode_aux_nearestmatch{
  110310. /* pre-calculated partitioning tree */
  110311. long *ptr0;
  110312. long *ptr1;
  110313. long *p; /* decision points (each is an entry) */
  110314. long *q; /* decision points (each is an entry) */
  110315. long aux; /* number of tree entries */
  110316. long alloc;
  110317. } encode_aux_nearestmatch;
  110318. /* assumes a maptype of 1; encode side only, so that's OK */
  110319. typedef struct encode_aux_threshmatch{
  110320. float *quantthresh;
  110321. long *quantmap;
  110322. int quantvals;
  110323. int threshvals;
  110324. } encode_aux_threshmatch;
  110325. typedef struct encode_aux_pigeonhole{
  110326. float min;
  110327. float del;
  110328. int mapentries;
  110329. int quantvals;
  110330. long *pigeonmap;
  110331. long fittotal;
  110332. long *fitlist;
  110333. long *fitmap;
  110334. long *fitlength;
  110335. } encode_aux_pigeonhole;
  110336. typedef struct codebook{
  110337. long dim; /* codebook dimensions (elements per vector) */
  110338. long entries; /* codebook entries */
  110339. long used_entries; /* populated codebook entries */
  110340. const static_codebook *c;
  110341. /* for encode, the below are entry-ordered, fully populated */
  110342. /* for decode, the below are ordered by bitreversed codeword and only
  110343. used entries are populated */
  110344. float *valuelist; /* list of dim*entries actual entry values */
  110345. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110346. int *dec_index; /* only used if sparseness collapsed */
  110347. char *dec_codelengths;
  110348. ogg_uint32_t *dec_firsttable;
  110349. int dec_firsttablen;
  110350. int dec_maxlength;
  110351. } codebook;
  110352. extern void vorbis_staticbook_clear(static_codebook *b);
  110353. extern void vorbis_staticbook_destroy(static_codebook *b);
  110354. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110355. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110356. extern void vorbis_book_clear(codebook *b);
  110357. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110358. extern float *_book_logdist(const static_codebook *b,float *vals);
  110359. extern float _float32_unpack(long val);
  110360. extern long _float32_pack(float val);
  110361. extern int _best(codebook *book, float *a, int step);
  110362. extern int _ilog(unsigned int v);
  110363. extern long _book_maptype1_quantvals(const static_codebook *b);
  110364. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110365. extern long vorbis_book_codeword(codebook *book,int entry);
  110366. extern long vorbis_book_codelen(codebook *book,int entry);
  110367. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110368. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110369. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110370. extern int vorbis_book_errorv(codebook *book, float *a);
  110371. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110372. oggpack_buffer *b);
  110373. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110374. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110375. oggpack_buffer *b,int n);
  110376. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110377. oggpack_buffer *b,int n);
  110378. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110379. oggpack_buffer *b,int n);
  110380. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110381. long off,int ch,
  110382. oggpack_buffer *b,int n);
  110383. #endif
  110384. /*** End of inlined file: codebook.h ***/
  110385. #define BLOCKTYPE_IMPULSE 0
  110386. #define BLOCKTYPE_PADDING 1
  110387. #define BLOCKTYPE_TRANSITION 0
  110388. #define BLOCKTYPE_LONG 1
  110389. #define PACKETBLOBS 15
  110390. typedef struct vorbis_block_internal{
  110391. float **pcmdelay; /* this is a pointer into local storage */
  110392. float ampmax;
  110393. int blocktype;
  110394. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110395. blob [PACKETBLOBS/2] points to
  110396. the oggpack_buffer in the
  110397. main vorbis_block */
  110398. } vorbis_block_internal;
  110399. typedef void vorbis_look_floor;
  110400. typedef void vorbis_look_residue;
  110401. typedef void vorbis_look_transform;
  110402. /* mode ************************************************************/
  110403. typedef struct {
  110404. int blockflag;
  110405. int windowtype;
  110406. int transformtype;
  110407. int mapping;
  110408. } vorbis_info_mode;
  110409. typedef void vorbis_info_floor;
  110410. typedef void vorbis_info_residue;
  110411. typedef void vorbis_info_mapping;
  110412. /*** Start of inlined file: psy.h ***/
  110413. #ifndef _V_PSY_H_
  110414. #define _V_PSY_H_
  110415. /*** Start of inlined file: smallft.h ***/
  110416. #ifndef _V_SMFT_H_
  110417. #define _V_SMFT_H_
  110418. typedef struct {
  110419. int n;
  110420. float *trigcache;
  110421. int *splitcache;
  110422. } drft_lookup;
  110423. extern void drft_forward(drft_lookup *l,float *data);
  110424. extern void drft_backward(drft_lookup *l,float *data);
  110425. extern void drft_init(drft_lookup *l,int n);
  110426. extern void drft_clear(drft_lookup *l);
  110427. #endif
  110428. /*** End of inlined file: smallft.h ***/
  110429. /*** Start of inlined file: backends.h ***/
  110430. /* this is exposed up here because we need it for static modes.
  110431. Lookups for each backend aren't exposed because there's no reason
  110432. to do so */
  110433. #ifndef _vorbis_backend_h_
  110434. #define _vorbis_backend_h_
  110435. /* this would all be simpler/shorter with templates, but.... */
  110436. /* Floor backend generic *****************************************/
  110437. typedef struct{
  110438. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110439. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110440. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110441. void (*free_info) (vorbis_info_floor *);
  110442. void (*free_look) (vorbis_look_floor *);
  110443. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110444. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110445. void *buffer,float *);
  110446. } vorbis_func_floor;
  110447. typedef struct{
  110448. int order;
  110449. long rate;
  110450. long barkmap;
  110451. int ampbits;
  110452. int ampdB;
  110453. int numbooks; /* <= 16 */
  110454. int books[16];
  110455. float lessthan; /* encode-only config setting hacks for libvorbis */
  110456. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110457. } vorbis_info_floor0;
  110458. #define VIF_POSIT 63
  110459. #define VIF_CLASS 16
  110460. #define VIF_PARTS 31
  110461. typedef struct{
  110462. int partitions; /* 0 to 31 */
  110463. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110464. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110465. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110466. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110467. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110468. int mult; /* 1 2 3 or 4 */
  110469. int postlist[VIF_POSIT+2]; /* first two implicit */
  110470. /* encode side analysis parameters */
  110471. float maxover;
  110472. float maxunder;
  110473. float maxerr;
  110474. float twofitweight;
  110475. float twofitatten;
  110476. int n;
  110477. } vorbis_info_floor1;
  110478. /* Residue backend generic *****************************************/
  110479. typedef struct{
  110480. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110481. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110482. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110483. vorbis_info_residue *);
  110484. void (*free_info) (vorbis_info_residue *);
  110485. void (*free_look) (vorbis_look_residue *);
  110486. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110487. float **,int *,int);
  110488. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110489. vorbis_look_residue *,
  110490. float **,float **,int *,int,long **);
  110491. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110492. float **,int *,int);
  110493. } vorbis_func_residue;
  110494. typedef struct vorbis_info_residue0{
  110495. /* block-partitioned VQ coded straight residue */
  110496. long begin;
  110497. long end;
  110498. /* first stage (lossless partitioning) */
  110499. int grouping; /* group n vectors per partition */
  110500. int partitions; /* possible codebooks for a partition */
  110501. int groupbook; /* huffbook for partitioning */
  110502. int secondstages[64]; /* expanded out to pointers in lookup */
  110503. int booklist[256]; /* list of second stage books */
  110504. float classmetric1[64];
  110505. float classmetric2[64];
  110506. } vorbis_info_residue0;
  110507. /* Mapping backend generic *****************************************/
  110508. typedef struct{
  110509. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110510. oggpack_buffer *);
  110511. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110512. void (*free_info) (vorbis_info_mapping *);
  110513. int (*forward) (struct vorbis_block *vb);
  110514. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110515. } vorbis_func_mapping;
  110516. typedef struct vorbis_info_mapping0{
  110517. int submaps; /* <= 16 */
  110518. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110519. int floorsubmap[16]; /* [mux] submap to floors */
  110520. int residuesubmap[16]; /* [mux] submap to residue */
  110521. int coupling_steps;
  110522. int coupling_mag[256];
  110523. int coupling_ang[256];
  110524. } vorbis_info_mapping0;
  110525. #endif
  110526. /*** End of inlined file: backends.h ***/
  110527. #ifndef EHMER_MAX
  110528. #define EHMER_MAX 56
  110529. #endif
  110530. /* psychoacoustic setup ********************************************/
  110531. #define P_BANDS 17 /* 62Hz to 16kHz */
  110532. #define P_LEVELS 8 /* 30dB to 100dB */
  110533. #define P_LEVEL_0 30. /* 30 dB */
  110534. #define P_NOISECURVES 3
  110535. #define NOISE_COMPAND_LEVELS 40
  110536. typedef struct vorbis_info_psy{
  110537. int blockflag;
  110538. float ath_adjatt;
  110539. float ath_maxatt;
  110540. float tone_masteratt[P_NOISECURVES];
  110541. float tone_centerboost;
  110542. float tone_decay;
  110543. float tone_abs_limit;
  110544. float toneatt[P_BANDS];
  110545. int noisemaskp;
  110546. float noisemaxsupp;
  110547. float noisewindowlo;
  110548. float noisewindowhi;
  110549. int noisewindowlomin;
  110550. int noisewindowhimin;
  110551. int noisewindowfixed;
  110552. float noiseoff[P_NOISECURVES][P_BANDS];
  110553. float noisecompand[NOISE_COMPAND_LEVELS];
  110554. float max_curve_dB;
  110555. int normal_channel_p;
  110556. int normal_point_p;
  110557. int normal_start;
  110558. int normal_partition;
  110559. double normal_thresh;
  110560. } vorbis_info_psy;
  110561. typedef struct{
  110562. int eighth_octave_lines;
  110563. /* for block long/short tuning; encode only */
  110564. float preecho_thresh[VE_BANDS];
  110565. float postecho_thresh[VE_BANDS];
  110566. float stretch_penalty;
  110567. float preecho_minenergy;
  110568. float ampmax_att_per_sec;
  110569. /* channel coupling config */
  110570. int coupling_pkHz[PACKETBLOBS];
  110571. int coupling_pointlimit[2][PACKETBLOBS];
  110572. int coupling_prepointamp[PACKETBLOBS];
  110573. int coupling_postpointamp[PACKETBLOBS];
  110574. int sliding_lowpass[2][PACKETBLOBS];
  110575. } vorbis_info_psy_global;
  110576. typedef struct {
  110577. float ampmax;
  110578. int channels;
  110579. vorbis_info_psy_global *gi;
  110580. int coupling_pointlimit[2][P_NOISECURVES];
  110581. } vorbis_look_psy_global;
  110582. typedef struct {
  110583. int n;
  110584. struct vorbis_info_psy *vi;
  110585. float ***tonecurves;
  110586. float **noiseoffset;
  110587. float *ath;
  110588. long *octave; /* in n.ocshift format */
  110589. long *bark;
  110590. long firstoc;
  110591. long shiftoc;
  110592. int eighth_octave_lines; /* power of two, please */
  110593. int total_octave_lines;
  110594. long rate; /* cache it */
  110595. float m_val; /* Masking compensation value */
  110596. } vorbis_look_psy;
  110597. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110598. vorbis_info_psy_global *gi,int n,long rate);
  110599. extern void _vp_psy_clear(vorbis_look_psy *p);
  110600. extern void *_vi_psy_dup(void *source);
  110601. extern void _vi_psy_free(vorbis_info_psy *i);
  110602. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110603. extern void _vp_remove_floor(vorbis_look_psy *p,
  110604. float *mdct,
  110605. int *icodedflr,
  110606. float *residue,
  110607. int sliding_lowpass);
  110608. extern void _vp_noisemask(vorbis_look_psy *p,
  110609. float *logmdct,
  110610. float *logmask);
  110611. extern void _vp_tonemask(vorbis_look_psy *p,
  110612. float *logfft,
  110613. float *logmask,
  110614. float global_specmax,
  110615. float local_specmax);
  110616. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110617. float *noise,
  110618. float *tone,
  110619. int offset_select,
  110620. float *logmask,
  110621. float *mdct,
  110622. float *logmdct);
  110623. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110624. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110625. vorbis_info_psy_global *g,
  110626. vorbis_look_psy *p,
  110627. vorbis_info_mapping0 *vi,
  110628. float **mdct);
  110629. extern void _vp_couple(int blobno,
  110630. vorbis_info_psy_global *g,
  110631. vorbis_look_psy *p,
  110632. vorbis_info_mapping0 *vi,
  110633. float **res,
  110634. float **mag_memo,
  110635. int **mag_sort,
  110636. int **ifloor,
  110637. int *nonzero,
  110638. int sliding_lowpass);
  110639. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110640. float *in,float *out,int *sortedindex);
  110641. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110642. float *magnitudes,int *sortedindex);
  110643. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110644. vorbis_look_psy *p,
  110645. vorbis_info_mapping0 *vi,
  110646. float **mags);
  110647. extern void hf_reduction(vorbis_info_psy_global *g,
  110648. vorbis_look_psy *p,
  110649. vorbis_info_mapping0 *vi,
  110650. float **mdct);
  110651. #endif
  110652. /*** End of inlined file: psy.h ***/
  110653. /*** Start of inlined file: bitrate.h ***/
  110654. #ifndef _V_BITRATE_H_
  110655. #define _V_BITRATE_H_
  110656. /*** Start of inlined file: os.h ***/
  110657. #ifndef _OS_H
  110658. #define _OS_H
  110659. /********************************************************************
  110660. * *
  110661. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110662. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110663. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110664. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110665. * *
  110666. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110667. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110668. * *
  110669. ********************************************************************
  110670. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110671. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110672. ********************************************************************/
  110673. #ifdef HAVE_CONFIG_H
  110674. #include "config.h"
  110675. #endif
  110676. #include <math.h>
  110677. /*** Start of inlined file: misc.h ***/
  110678. #ifndef _V_RANDOM_H_
  110679. #define _V_RANDOM_H_
  110680. extern int analysis_noisy;
  110681. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110682. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110683. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110684. ogg_int64_t off);
  110685. #ifdef DEBUG_MALLOC
  110686. #define _VDBG_GRAPHFILE "malloc.m"
  110687. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110688. extern void _VDBG_free(void *ptr,char *file,long line);
  110689. #ifndef MISC_C
  110690. #undef _ogg_malloc
  110691. #undef _ogg_calloc
  110692. #undef _ogg_realloc
  110693. #undef _ogg_free
  110694. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110695. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110696. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110697. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110698. #endif
  110699. #endif
  110700. #endif
  110701. /*** End of inlined file: misc.h ***/
  110702. #ifndef _V_IFDEFJAIL_H_
  110703. # define _V_IFDEFJAIL_H_
  110704. # ifdef __GNUC__
  110705. # define STIN static __inline__
  110706. # elif _WIN32
  110707. # define STIN static __inline
  110708. # else
  110709. # define STIN static
  110710. # endif
  110711. #ifdef DJGPP
  110712. # define rint(x) (floor((x)+0.5f))
  110713. #endif
  110714. #ifndef M_PI
  110715. # define M_PI (3.1415926536f)
  110716. #endif
  110717. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110718. # include <malloc.h>
  110719. # define rint(x) (floor((x)+0.5f))
  110720. # define NO_FLOAT_MATH_LIB
  110721. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110722. #endif
  110723. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110724. void *_alloca(size_t size);
  110725. # define alloca _alloca
  110726. #endif
  110727. #ifndef FAST_HYPOT
  110728. # define FAST_HYPOT hypot
  110729. #endif
  110730. #endif
  110731. #ifdef HAVE_ALLOCA_H
  110732. # include <alloca.h>
  110733. #endif
  110734. #ifdef USE_MEMORY_H
  110735. # include <memory.h>
  110736. #endif
  110737. #ifndef min
  110738. # define min(x,y) ((x)>(y)?(y):(x))
  110739. #endif
  110740. #ifndef max
  110741. # define max(x,y) ((x)<(y)?(y):(x))
  110742. #endif
  110743. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110744. # define VORBIS_FPU_CONTROL
  110745. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110746. Because of encapsulation constraints (GCC can't see inside the asm
  110747. block and so we end up doing stupid things like a store/load that
  110748. is collectively a noop), we do it this way */
  110749. /* we must set up the fpu before this works!! */
  110750. typedef ogg_int16_t vorbis_fpu_control;
  110751. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110752. ogg_int16_t ret;
  110753. ogg_int16_t temp;
  110754. __asm__ __volatile__("fnstcw %0\n\t"
  110755. "movw %0,%%dx\n\t"
  110756. "orw $62463,%%dx\n\t"
  110757. "movw %%dx,%1\n\t"
  110758. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110759. *fpu=ret;
  110760. }
  110761. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110762. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110763. }
  110764. /* assumes the FPU is in round mode! */
  110765. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110766. we get extra fst/fld to
  110767. truncate precision */
  110768. int i;
  110769. __asm__("fistl %0": "=m"(i) : "t"(f));
  110770. return(i);
  110771. }
  110772. #endif
  110773. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110774. # define VORBIS_FPU_CONTROL
  110775. typedef ogg_int16_t vorbis_fpu_control;
  110776. static __inline int vorbis_ftoi(double f){
  110777. int i;
  110778. __asm{
  110779. fld f
  110780. fistp i
  110781. }
  110782. return i;
  110783. }
  110784. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110785. }
  110786. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110787. }
  110788. #endif
  110789. #ifndef VORBIS_FPU_CONTROL
  110790. typedef int vorbis_fpu_control;
  110791. static int vorbis_ftoi(double f){
  110792. return (int)(f+.5);
  110793. }
  110794. /* We don't have special code for this compiler/arch, so do it the slow way */
  110795. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110796. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110797. #endif
  110798. #endif /* _OS_H */
  110799. /*** End of inlined file: os.h ***/
  110800. /* encode side bitrate tracking */
  110801. typedef struct bitrate_manager_state {
  110802. int managed;
  110803. long avg_reservoir;
  110804. long minmax_reservoir;
  110805. long avg_bitsper;
  110806. long min_bitsper;
  110807. long max_bitsper;
  110808. long short_per_long;
  110809. double avgfloat;
  110810. vorbis_block *vb;
  110811. int choice;
  110812. } bitrate_manager_state;
  110813. typedef struct bitrate_manager_info{
  110814. long avg_rate;
  110815. long min_rate;
  110816. long max_rate;
  110817. long reservoir_bits;
  110818. double reservoir_bias;
  110819. double slew_damp;
  110820. } bitrate_manager_info;
  110821. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110822. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110823. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110824. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110825. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110826. #endif
  110827. /*** End of inlined file: bitrate.h ***/
  110828. static int ilog(unsigned int v){
  110829. int ret=0;
  110830. while(v){
  110831. ret++;
  110832. v>>=1;
  110833. }
  110834. return(ret);
  110835. }
  110836. static int ilog2(unsigned int v){
  110837. int ret=0;
  110838. if(v)--v;
  110839. while(v){
  110840. ret++;
  110841. v>>=1;
  110842. }
  110843. return(ret);
  110844. }
  110845. typedef struct private_state {
  110846. /* local lookup storage */
  110847. envelope_lookup *ve; /* envelope lookup */
  110848. int window[2];
  110849. vorbis_look_transform **transform[2]; /* block, type */
  110850. drft_lookup fft_look[2];
  110851. int modebits;
  110852. vorbis_look_floor **flr;
  110853. vorbis_look_residue **residue;
  110854. vorbis_look_psy *psy;
  110855. vorbis_look_psy_global *psy_g_look;
  110856. /* local storage, only used on the encoding side. This way the
  110857. application does not need to worry about freeing some packets'
  110858. memory and not others'; packet storage is always tracked.
  110859. Cleared next call to a _dsp_ function */
  110860. unsigned char *header;
  110861. unsigned char *header1;
  110862. unsigned char *header2;
  110863. bitrate_manager_state bms;
  110864. ogg_int64_t sample_count;
  110865. } private_state;
  110866. /* codec_setup_info contains all the setup information specific to the
  110867. specific compression/decompression mode in progress (eg,
  110868. psychoacoustic settings, channel setup, options, codebook
  110869. etc).
  110870. *********************************************************************/
  110871. /*** Start of inlined file: highlevel.h ***/
  110872. typedef struct highlevel_byblocktype {
  110873. double tone_mask_setting;
  110874. double tone_peaklimit_setting;
  110875. double noise_bias_setting;
  110876. double noise_compand_setting;
  110877. } highlevel_byblocktype;
  110878. typedef struct highlevel_encode_setup {
  110879. void *setup;
  110880. int set_in_stone;
  110881. double base_setting;
  110882. double long_setting;
  110883. double short_setting;
  110884. double impulse_noisetune;
  110885. int managed;
  110886. long bitrate_min;
  110887. long bitrate_av;
  110888. double bitrate_av_damp;
  110889. long bitrate_max;
  110890. long bitrate_reservoir;
  110891. double bitrate_reservoir_bias;
  110892. int impulse_block_p;
  110893. int noise_normalize_p;
  110894. double stereo_point_setting;
  110895. double lowpass_kHz;
  110896. double ath_floating_dB;
  110897. double ath_absolute_dB;
  110898. double amplitude_track_dBpersec;
  110899. double trigger_setting;
  110900. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110901. } highlevel_encode_setup;
  110902. /*** End of inlined file: highlevel.h ***/
  110903. typedef struct codec_setup_info {
  110904. /* Vorbis supports only short and long blocks, but allows the
  110905. encoder to choose the sizes */
  110906. long blocksizes[2];
  110907. /* modes are the primary means of supporting on-the-fly different
  110908. blocksizes, different channel mappings (LR or M/A),
  110909. different residue backends, etc. Each mode consists of a
  110910. blocksize flag and a mapping (along with the mapping setup */
  110911. int modes;
  110912. int maps;
  110913. int floors;
  110914. int residues;
  110915. int books;
  110916. int psys; /* encode only */
  110917. vorbis_info_mode *mode_param[64];
  110918. int map_type[64];
  110919. vorbis_info_mapping *map_param[64];
  110920. int floor_type[64];
  110921. vorbis_info_floor *floor_param[64];
  110922. int residue_type[64];
  110923. vorbis_info_residue *residue_param[64];
  110924. static_codebook *book_param[256];
  110925. codebook *fullbooks;
  110926. vorbis_info_psy *psy_param[4]; /* encode only */
  110927. vorbis_info_psy_global psy_g_param;
  110928. bitrate_manager_info bi;
  110929. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110930. highly redundant structure, but
  110931. improves clarity of program flow. */
  110932. int halfrate_flag; /* painless downsample for decode */
  110933. } codec_setup_info;
  110934. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110935. extern void _vp_global_free(vorbis_look_psy_global *look);
  110936. #endif
  110937. /*** End of inlined file: codec_internal.h ***/
  110938. /*** Start of inlined file: registry.h ***/
  110939. #ifndef _V_REG_H_
  110940. #define _V_REG_H_
  110941. #define VI_TRANSFORMB 1
  110942. #define VI_WINDOWB 1
  110943. #define VI_TIMEB 1
  110944. #define VI_FLOORB 2
  110945. #define VI_RESB 3
  110946. #define VI_MAPB 1
  110947. extern vorbis_func_floor *_floor_P[];
  110948. extern vorbis_func_residue *_residue_P[];
  110949. extern vorbis_func_mapping *_mapping_P[];
  110950. #endif
  110951. /*** End of inlined file: registry.h ***/
  110952. /*** Start of inlined file: scales.h ***/
  110953. #ifndef _V_SCALES_H_
  110954. #define _V_SCALES_H_
  110955. #include <math.h>
  110956. /* 20log10(x) */
  110957. #define VORBIS_IEEE_FLOAT32 1
  110958. #ifdef VORBIS_IEEE_FLOAT32
  110959. static float unitnorm(float x){
  110960. union {
  110961. ogg_uint32_t i;
  110962. float f;
  110963. } ix;
  110964. ix.f = x;
  110965. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110966. return ix.f;
  110967. }
  110968. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110969. static float todB(const float *x){
  110970. union {
  110971. ogg_uint32_t i;
  110972. float f;
  110973. } ix;
  110974. ix.f = *x;
  110975. ix.i = ix.i&0x7fffffff;
  110976. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110977. }
  110978. #define todB_nn(x) todB(x)
  110979. #else
  110980. static float unitnorm(float x){
  110981. if(x<0)return(-1.f);
  110982. return(1.f);
  110983. }
  110984. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110985. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110986. #endif
  110987. #define fromdB(x) (exp((x)*.11512925f))
  110988. /* The bark scale equations are approximations, since the original
  110989. table was somewhat hand rolled. The below are chosen to have the
  110990. best possible fit to the rolled tables, thus their somewhat odd
  110991. appearance (these are more accurate and over a longer range than
  110992. the oft-quoted bark equations found in the texts I have). The
  110993. approximations are valid from 0 - 30kHz (nyquist) or so.
  110994. all f in Hz, z in Bark */
  110995. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110996. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110997. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110998. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110999. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  111000. 0.0 */
  111001. #define toOC(n) (log(n)*1.442695f-5.965784f)
  111002. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  111003. #endif
  111004. /*** End of inlined file: scales.h ***/
  111005. int analysis_noisy=1;
  111006. /* decides between modes, dispatches to the appropriate mapping. */
  111007. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  111008. int ret,i;
  111009. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111010. vb->glue_bits=0;
  111011. vb->time_bits=0;
  111012. vb->floor_bits=0;
  111013. vb->res_bits=0;
  111014. /* first things first. Make sure encode is ready */
  111015. for(i=0;i<PACKETBLOBS;i++)
  111016. oggpack_reset(vbi->packetblob[i]);
  111017. /* we only have one mapping type (0), and we let the mapping code
  111018. itself figure out what soft mode to use. This allows easier
  111019. bitrate management */
  111020. if((ret=_mapping_P[0]->forward(vb)))
  111021. return(ret);
  111022. if(op){
  111023. if(vorbis_bitrate_managed(vb))
  111024. /* The app is using a bitmanaged mode... but not using the
  111025. bitrate management interface. */
  111026. return(OV_EINVAL);
  111027. op->packet=oggpack_get_buffer(&vb->opb);
  111028. op->bytes=oggpack_bytes(&vb->opb);
  111029. op->b_o_s=0;
  111030. op->e_o_s=vb->eofflag;
  111031. op->granulepos=vb->granulepos;
  111032. op->packetno=vb->sequence; /* for sake of completeness */
  111033. }
  111034. return(0);
  111035. }
  111036. /* there was no great place to put this.... */
  111037. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  111038. int j;
  111039. FILE *of;
  111040. char buffer[80];
  111041. /* if(i==5870){*/
  111042. sprintf(buffer,"%s_%d.m",base,i);
  111043. of=fopen(buffer,"w");
  111044. if(!of)perror("failed to open data dump file");
  111045. for(j=0;j<n;j++){
  111046. if(bark){
  111047. float b=toBARK((4000.f*j/n)+.25);
  111048. fprintf(of,"%f ",b);
  111049. }else
  111050. if(off!=0)
  111051. fprintf(of,"%f ",(double)(j+off)/8000.);
  111052. else
  111053. fprintf(of,"%f ",(double)j);
  111054. if(dB){
  111055. float val;
  111056. if(v[j]==0.)
  111057. val=-140.;
  111058. else
  111059. val=todB(v+j);
  111060. fprintf(of,"%f\n",val);
  111061. }else{
  111062. fprintf(of,"%f\n",v[j]);
  111063. }
  111064. }
  111065. fclose(of);
  111066. /* } */
  111067. }
  111068. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  111069. ogg_int64_t off){
  111070. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  111071. }
  111072. #endif
  111073. /*** End of inlined file: analysis.c ***/
  111074. /*** Start of inlined file: bitrate.c ***/
  111075. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111076. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111077. // tasks..
  111078. #if JUCE_MSVC
  111079. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111080. #endif
  111081. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111082. #if JUCE_USE_OGGVORBIS
  111083. #include <stdlib.h>
  111084. #include <string.h>
  111085. #include <math.h>
  111086. /* compute bitrate tracking setup */
  111087. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  111088. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111089. bitrate_manager_info *bi=&ci->bi;
  111090. memset(bm,0,sizeof(*bm));
  111091. if(bi && (bi->reservoir_bits>0)){
  111092. long ratesamples=vi->rate;
  111093. int halfsamples=ci->blocksizes[0]>>1;
  111094. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  111095. bm->managed=1;
  111096. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  111097. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  111098. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  111099. bm->avgfloat=PACKETBLOBS/2;
  111100. /* not a necessary fix, but one that leads to a more balanced
  111101. typical initialization */
  111102. {
  111103. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111104. bm->minmax_reservoir=desired_fill;
  111105. bm->avg_reservoir=desired_fill;
  111106. }
  111107. }
  111108. }
  111109. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  111110. memset(bm,0,sizeof(*bm));
  111111. return;
  111112. }
  111113. int vorbis_bitrate_managed(vorbis_block *vb){
  111114. vorbis_dsp_state *vd=vb->vd;
  111115. private_state *b=(private_state*)vd->backend_state;
  111116. bitrate_manager_state *bm=&b->bms;
  111117. if(bm && bm->managed)return(1);
  111118. return(0);
  111119. }
  111120. /* finish taking in the block we just processed */
  111121. int vorbis_bitrate_addblock(vorbis_block *vb){
  111122. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111123. vorbis_dsp_state *vd=vb->vd;
  111124. private_state *b=(private_state*)vd->backend_state;
  111125. bitrate_manager_state *bm=&b->bms;
  111126. vorbis_info *vi=vd->vi;
  111127. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111128. bitrate_manager_info *bi=&ci->bi;
  111129. int choice=rint(bm->avgfloat);
  111130. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111131. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  111132. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  111133. int samples=ci->blocksizes[vb->W]>>1;
  111134. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111135. if(!bm->managed){
  111136. /* not a bitrate managed stream, but for API simplicity, we'll
  111137. buffer the packet to keep the code path clean */
  111138. if(bm->vb)return(-1); /* one has been submitted without
  111139. being claimed */
  111140. bm->vb=vb;
  111141. return(0);
  111142. }
  111143. bm->vb=vb;
  111144. /* look ahead for avg floater */
  111145. if(bm->avg_bitsper>0){
  111146. double slew=0.;
  111147. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111148. double slewlimit= 15./bi->slew_damp;
  111149. /* choosing a new floater:
  111150. if we're over target, we slew down
  111151. if we're under target, we slew up
  111152. choose slew as follows: look through packetblobs of this frame
  111153. and set slew as the first in the appropriate direction that
  111154. gives us the slew we want. This may mean no slew if delta is
  111155. already favorable.
  111156. Then limit slew to slew max */
  111157. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111158. while(choice>0 && this_bits>avg_target_bits &&
  111159. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111160. choice--;
  111161. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111162. }
  111163. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111164. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  111165. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111166. choice++;
  111167. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111168. }
  111169. }
  111170. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  111171. if(slew<-slewlimit)slew=-slewlimit;
  111172. if(slew>slewlimit)slew=slewlimit;
  111173. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  111174. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111175. }
  111176. /* enforce min(if used) on the current floater (if used) */
  111177. if(bm->min_bitsper>0){
  111178. /* do we need to force the bitrate up? */
  111179. if(this_bits<min_target_bits){
  111180. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  111181. choice++;
  111182. if(choice>=PACKETBLOBS)break;
  111183. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111184. }
  111185. }
  111186. }
  111187. /* enforce max (if used) on the current floater (if used) */
  111188. if(bm->max_bitsper>0){
  111189. /* do we need to force the bitrate down? */
  111190. if(this_bits>max_target_bits){
  111191. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111192. choice--;
  111193. if(choice<0)break;
  111194. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111195. }
  111196. }
  111197. }
  111198. /* Choice of packetblobs now made based on floater, and min/max
  111199. requirements. Now boundary check extreme choices */
  111200. if(choice<0){
  111201. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111202. frame will need to be truncated */
  111203. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111204. bm->choice=choice=0;
  111205. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111206. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111207. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111208. }
  111209. }else{
  111210. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111211. if(choice>=PACKETBLOBS)
  111212. choice=PACKETBLOBS-1;
  111213. bm->choice=choice;
  111214. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111215. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111216. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111217. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111218. }
  111219. /* now we have the final packet and the final packet size. Update statistics */
  111220. /* min and max reservoir */
  111221. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111222. if(max_target_bits>0 && this_bits>max_target_bits){
  111223. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111224. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111225. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111226. }else{
  111227. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111228. if(bm->minmax_reservoir>desired_fill){
  111229. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111230. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111231. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111232. }else{
  111233. bm->minmax_reservoir=desired_fill;
  111234. }
  111235. }else{
  111236. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111237. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111238. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111239. }else{
  111240. bm->minmax_reservoir=desired_fill;
  111241. }
  111242. }
  111243. }
  111244. }
  111245. /* avg reservoir */
  111246. if(bm->avg_bitsper>0){
  111247. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111248. bm->avg_reservoir+=this_bits-avg_target_bits;
  111249. }
  111250. return(0);
  111251. }
  111252. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111253. private_state *b=(private_state*)vd->backend_state;
  111254. bitrate_manager_state *bm=&b->bms;
  111255. vorbis_block *vb=bm->vb;
  111256. int choice=PACKETBLOBS/2;
  111257. if(!vb)return 0;
  111258. if(op){
  111259. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111260. if(vorbis_bitrate_managed(vb))
  111261. choice=bm->choice;
  111262. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111263. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111264. op->b_o_s=0;
  111265. op->e_o_s=vb->eofflag;
  111266. op->granulepos=vb->granulepos;
  111267. op->packetno=vb->sequence; /* for sake of completeness */
  111268. }
  111269. bm->vb=0;
  111270. return(1);
  111271. }
  111272. #endif
  111273. /*** End of inlined file: bitrate.c ***/
  111274. /*** Start of inlined file: block.c ***/
  111275. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111276. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111277. // tasks..
  111278. #if JUCE_MSVC
  111279. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111280. #endif
  111281. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111282. #if JUCE_USE_OGGVORBIS
  111283. #include <stdio.h>
  111284. #include <stdlib.h>
  111285. #include <string.h>
  111286. /*** Start of inlined file: window.h ***/
  111287. #ifndef _V_WINDOW_
  111288. #define _V_WINDOW_
  111289. extern float *_vorbis_window_get(int n);
  111290. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111291. int lW,int W,int nW);
  111292. #endif
  111293. /*** End of inlined file: window.h ***/
  111294. /*** Start of inlined file: lpc.h ***/
  111295. #ifndef _V_LPC_H_
  111296. #define _V_LPC_H_
  111297. /* simple linear scale LPC code */
  111298. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111299. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111300. float *data,long n);
  111301. #endif
  111302. /*** End of inlined file: lpc.h ***/
  111303. /* pcm accumulator examples (not exhaustive):
  111304. <-------------- lW ---------------->
  111305. <--------------- W ---------------->
  111306. : .....|..... _______________ |
  111307. : .''' | '''_--- | |\ |
  111308. :.....''' |_____--- '''......| | \_______|
  111309. :.................|__________________|_______|__|______|
  111310. |<------ Sl ------>| > Sr < |endW
  111311. |beginSl |endSl | |endSr
  111312. |beginW |endlW |beginSr
  111313. |< lW >|
  111314. <--------------- W ---------------->
  111315. | | .. ______________ |
  111316. | | ' `/ | ---_ |
  111317. |___.'___/`. | ---_____|
  111318. |_______|__|_______|_________________|
  111319. | >|Sl|< |<------ Sr ----->|endW
  111320. | | |endSl |beginSr |endSr
  111321. |beginW | |endlW
  111322. mult[0] |beginSl mult[n]
  111323. <-------------- lW ----------------->
  111324. |<--W-->|
  111325. : .............. ___ | |
  111326. : .''' |`/ \ | |
  111327. :.....''' |/`....\|...|
  111328. :.........................|___|___|___|
  111329. |Sl |Sr |endW
  111330. | | |endSr
  111331. | |beginSr
  111332. | |endSl
  111333. |beginSl
  111334. |beginW
  111335. */
  111336. /* block abstraction setup *********************************************/
  111337. #ifndef WORD_ALIGN
  111338. #define WORD_ALIGN 8
  111339. #endif
  111340. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111341. int i;
  111342. memset(vb,0,sizeof(*vb));
  111343. vb->vd=v;
  111344. vb->localalloc=0;
  111345. vb->localstore=NULL;
  111346. if(v->analysisp){
  111347. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111348. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111349. vbi->ampmax=-9999;
  111350. for(i=0;i<PACKETBLOBS;i++){
  111351. if(i==PACKETBLOBS/2){
  111352. vbi->packetblob[i]=&vb->opb;
  111353. }else{
  111354. vbi->packetblob[i]=
  111355. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111356. }
  111357. oggpack_writeinit(vbi->packetblob[i]);
  111358. }
  111359. }
  111360. return(0);
  111361. }
  111362. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111363. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111364. if(bytes+vb->localtop>vb->localalloc){
  111365. /* can't just _ogg_realloc... there are outstanding pointers */
  111366. if(vb->localstore){
  111367. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111368. vb->totaluse+=vb->localtop;
  111369. link->next=vb->reap;
  111370. link->ptr=vb->localstore;
  111371. vb->reap=link;
  111372. }
  111373. /* highly conservative */
  111374. vb->localalloc=bytes;
  111375. vb->localstore=_ogg_malloc(vb->localalloc);
  111376. vb->localtop=0;
  111377. }
  111378. {
  111379. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111380. vb->localtop+=bytes;
  111381. return ret;
  111382. }
  111383. }
  111384. /* reap the chain, pull the ripcord */
  111385. void _vorbis_block_ripcord(vorbis_block *vb){
  111386. /* reap the chain */
  111387. struct alloc_chain *reap=vb->reap;
  111388. while(reap){
  111389. struct alloc_chain *next=reap->next;
  111390. _ogg_free(reap->ptr);
  111391. memset(reap,0,sizeof(*reap));
  111392. _ogg_free(reap);
  111393. reap=next;
  111394. }
  111395. /* consolidate storage */
  111396. if(vb->totaluse){
  111397. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111398. vb->localalloc+=vb->totaluse;
  111399. vb->totaluse=0;
  111400. }
  111401. /* pull the ripcord */
  111402. vb->localtop=0;
  111403. vb->reap=NULL;
  111404. }
  111405. int vorbis_block_clear(vorbis_block *vb){
  111406. int i;
  111407. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111408. _vorbis_block_ripcord(vb);
  111409. if(vb->localstore)_ogg_free(vb->localstore);
  111410. if(vbi){
  111411. for(i=0;i<PACKETBLOBS;i++){
  111412. oggpack_writeclear(vbi->packetblob[i]);
  111413. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111414. }
  111415. _ogg_free(vbi);
  111416. }
  111417. memset(vb,0,sizeof(*vb));
  111418. return(0);
  111419. }
  111420. /* Analysis side code, but directly related to blocking. Thus it's
  111421. here and not in analysis.c (which is for analysis transforms only).
  111422. The init is here because some of it is shared */
  111423. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111424. int i;
  111425. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111426. private_state *b=NULL;
  111427. int hs;
  111428. if(ci==NULL) return 1;
  111429. hs=ci->halfrate_flag;
  111430. memset(v,0,sizeof(*v));
  111431. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111432. v->vi=vi;
  111433. b->modebits=ilog2(ci->modes);
  111434. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111435. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111436. /* MDCT is tranform 0 */
  111437. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111438. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111439. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111440. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111441. /* Vorbis I uses only window type 0 */
  111442. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111443. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111444. if(encp){ /* encode/decode differ here */
  111445. /* analysis always needs an fft */
  111446. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111447. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111448. /* finish the codebooks */
  111449. if(!ci->fullbooks){
  111450. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111451. for(i=0;i<ci->books;i++)
  111452. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111453. }
  111454. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111455. for(i=0;i<ci->psys;i++){
  111456. _vp_psy_init(b->psy+i,
  111457. ci->psy_param[i],
  111458. &ci->psy_g_param,
  111459. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111460. vi->rate);
  111461. }
  111462. v->analysisp=1;
  111463. }else{
  111464. /* finish the codebooks */
  111465. if(!ci->fullbooks){
  111466. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111467. for(i=0;i<ci->books;i++){
  111468. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111469. /* decode codebooks are now standalone after init */
  111470. vorbis_staticbook_destroy(ci->book_param[i]);
  111471. ci->book_param[i]=NULL;
  111472. }
  111473. }
  111474. }
  111475. /* initialize the storage vectors. blocksize[1] is small for encode,
  111476. but the correct size for decode */
  111477. v->pcm_storage=ci->blocksizes[1];
  111478. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111479. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111480. {
  111481. int i;
  111482. for(i=0;i<vi->channels;i++)
  111483. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111484. }
  111485. /* all 1 (large block) or 0 (small block) */
  111486. /* explicitly set for the sake of clarity */
  111487. v->lW=0; /* previous window size */
  111488. v->W=0; /* current window size */
  111489. /* all vector indexes */
  111490. v->centerW=ci->blocksizes[1]/2;
  111491. v->pcm_current=v->centerW;
  111492. /* initialize all the backend lookups */
  111493. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111494. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111495. for(i=0;i<ci->floors;i++)
  111496. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111497. look(v,ci->floor_param[i]);
  111498. for(i=0;i<ci->residues;i++)
  111499. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111500. look(v,ci->residue_param[i]);
  111501. return 0;
  111502. }
  111503. /* arbitrary settings and spec-mandated numbers get filled in here */
  111504. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111505. private_state *b=NULL;
  111506. if(_vds_shared_init(v,vi,1))return 1;
  111507. b=(private_state*)v->backend_state;
  111508. b->psy_g_look=_vp_global_look(vi);
  111509. /* Initialize the envelope state storage */
  111510. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111511. _ve_envelope_init(b->ve,vi);
  111512. vorbis_bitrate_init(vi,&b->bms);
  111513. /* compressed audio packets start after the headers
  111514. with sequence number 3 */
  111515. v->sequence=3;
  111516. return(0);
  111517. }
  111518. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111519. int i;
  111520. if(v){
  111521. vorbis_info *vi=v->vi;
  111522. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111523. private_state *b=(private_state*)v->backend_state;
  111524. if(b){
  111525. if(b->ve){
  111526. _ve_envelope_clear(b->ve);
  111527. _ogg_free(b->ve);
  111528. }
  111529. if(b->transform[0]){
  111530. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111531. _ogg_free(b->transform[0][0]);
  111532. _ogg_free(b->transform[0]);
  111533. }
  111534. if(b->transform[1]){
  111535. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111536. _ogg_free(b->transform[1][0]);
  111537. _ogg_free(b->transform[1]);
  111538. }
  111539. if(b->flr){
  111540. for(i=0;i<ci->floors;i++)
  111541. _floor_P[ci->floor_type[i]]->
  111542. free_look(b->flr[i]);
  111543. _ogg_free(b->flr);
  111544. }
  111545. if(b->residue){
  111546. for(i=0;i<ci->residues;i++)
  111547. _residue_P[ci->residue_type[i]]->
  111548. free_look(b->residue[i]);
  111549. _ogg_free(b->residue);
  111550. }
  111551. if(b->psy){
  111552. for(i=0;i<ci->psys;i++)
  111553. _vp_psy_clear(b->psy+i);
  111554. _ogg_free(b->psy);
  111555. }
  111556. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111557. vorbis_bitrate_clear(&b->bms);
  111558. drft_clear(&b->fft_look[0]);
  111559. drft_clear(&b->fft_look[1]);
  111560. }
  111561. if(v->pcm){
  111562. for(i=0;i<vi->channels;i++)
  111563. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111564. _ogg_free(v->pcm);
  111565. if(v->pcmret)_ogg_free(v->pcmret);
  111566. }
  111567. if(b){
  111568. /* free header, header1, header2 */
  111569. if(b->header)_ogg_free(b->header);
  111570. if(b->header1)_ogg_free(b->header1);
  111571. if(b->header2)_ogg_free(b->header2);
  111572. _ogg_free(b);
  111573. }
  111574. memset(v,0,sizeof(*v));
  111575. }
  111576. }
  111577. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111578. int i;
  111579. vorbis_info *vi=v->vi;
  111580. private_state *b=(private_state*)v->backend_state;
  111581. /* free header, header1, header2 */
  111582. if(b->header)_ogg_free(b->header);b->header=NULL;
  111583. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111584. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111585. /* Do we have enough storage space for the requested buffer? If not,
  111586. expand the PCM (and envelope) storage */
  111587. if(v->pcm_current+vals>=v->pcm_storage){
  111588. v->pcm_storage=v->pcm_current+vals*2;
  111589. for(i=0;i<vi->channels;i++){
  111590. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111591. }
  111592. }
  111593. for(i=0;i<vi->channels;i++)
  111594. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111595. return(v->pcmret);
  111596. }
  111597. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111598. int i;
  111599. int order=32;
  111600. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111601. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111602. long j;
  111603. v->preextrapolate=1;
  111604. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111605. for(i=0;i<v->vi->channels;i++){
  111606. /* need to run the extrapolation in reverse! */
  111607. for(j=0;j<v->pcm_current;j++)
  111608. work[j]=v->pcm[i][v->pcm_current-j-1];
  111609. /* prime as above */
  111610. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111611. /* run the predictor filter */
  111612. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111613. order,
  111614. work+v->pcm_current-v->centerW,
  111615. v->centerW);
  111616. for(j=0;j<v->pcm_current;j++)
  111617. v->pcm[i][v->pcm_current-j-1]=work[j];
  111618. }
  111619. }
  111620. }
  111621. /* call with val<=0 to set eof */
  111622. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111623. vorbis_info *vi=v->vi;
  111624. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111625. if(vals<=0){
  111626. int order=32;
  111627. int i;
  111628. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111629. /* if it wasn't done earlier (very short sample) */
  111630. if(!v->preextrapolate)
  111631. _preextrapolate_helper(v);
  111632. /* We're encoding the end of the stream. Just make sure we have
  111633. [at least] a few full blocks of zeroes at the end. */
  111634. /* actually, we don't want zeroes; that could drop a large
  111635. amplitude off a cliff, creating spread spectrum noise that will
  111636. suck to encode. Extrapolate for the sake of cleanliness. */
  111637. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111638. v->eofflag=v->pcm_current;
  111639. v->pcm_current+=ci->blocksizes[1]*3;
  111640. for(i=0;i<vi->channels;i++){
  111641. if(v->eofflag>order*2){
  111642. /* extrapolate with LPC to fill in */
  111643. long n;
  111644. /* make a predictor filter */
  111645. n=v->eofflag;
  111646. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111647. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111648. /* run the predictor filter */
  111649. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111650. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111651. }else{
  111652. /* not enough data to extrapolate (unlikely to happen due to
  111653. guarding the overlap, but bulletproof in case that
  111654. assumtion goes away). zeroes will do. */
  111655. memset(v->pcm[i]+v->eofflag,0,
  111656. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111657. }
  111658. }
  111659. }else{
  111660. if(v->pcm_current+vals>v->pcm_storage)
  111661. return(OV_EINVAL);
  111662. v->pcm_current+=vals;
  111663. /* we may want to reverse extrapolate the beginning of a stream
  111664. too... in case we're beginning on a cliff! */
  111665. /* clumsy, but simple. It only runs once, so simple is good. */
  111666. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111667. _preextrapolate_helper(v);
  111668. }
  111669. return(0);
  111670. }
  111671. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111672. the next block on which to continue analysis */
  111673. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111674. int i;
  111675. vorbis_info *vi=v->vi;
  111676. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111677. private_state *b=(private_state*)v->backend_state;
  111678. vorbis_look_psy_global *g=b->psy_g_look;
  111679. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111680. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111681. /* check to see if we're started... */
  111682. if(!v->preextrapolate)return(0);
  111683. /* check to see if we're done... */
  111684. if(v->eofflag==-1)return(0);
  111685. /* By our invariant, we have lW, W and centerW set. Search for
  111686. the next boundary so we can determine nW (the next window size)
  111687. which lets us compute the shape of the current block's window */
  111688. /* we do an envelope search even on a single blocksize; we may still
  111689. be throwing more bits at impulses, and envelope search handles
  111690. marking impulses too. */
  111691. {
  111692. long bp=_ve_envelope_search(v);
  111693. if(bp==-1){
  111694. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111695. full long block */
  111696. v->nW=0;
  111697. }else{
  111698. if(ci->blocksizes[0]==ci->blocksizes[1])
  111699. v->nW=0;
  111700. else
  111701. v->nW=bp;
  111702. }
  111703. }
  111704. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111705. {
  111706. /* center of next block + next block maximum right side. */
  111707. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111708. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111709. although this check is
  111710. less strict that the
  111711. _ve_envelope_search,
  111712. the search is not run
  111713. if we only use one
  111714. block size */
  111715. }
  111716. /* fill in the block. Note that for a short window, lW and nW are *short*
  111717. regardless of actual settings in the stream */
  111718. _vorbis_block_ripcord(vb);
  111719. vb->lW=v->lW;
  111720. vb->W=v->W;
  111721. vb->nW=v->nW;
  111722. if(v->W){
  111723. if(!v->lW || !v->nW){
  111724. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111725. /*fprintf(stderr,"-");*/
  111726. }else{
  111727. vbi->blocktype=BLOCKTYPE_LONG;
  111728. /*fprintf(stderr,"_");*/
  111729. }
  111730. }else{
  111731. if(_ve_envelope_mark(v)){
  111732. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111733. /*fprintf(stderr,"|");*/
  111734. }else{
  111735. vbi->blocktype=BLOCKTYPE_PADDING;
  111736. /*fprintf(stderr,".");*/
  111737. }
  111738. }
  111739. vb->vd=v;
  111740. vb->sequence=v->sequence++;
  111741. vb->granulepos=v->granulepos;
  111742. vb->pcmend=ci->blocksizes[v->W];
  111743. /* copy the vectors; this uses the local storage in vb */
  111744. /* this tracks 'strongest peak' for later psychoacoustics */
  111745. /* moved to the global psy state; clean this mess up */
  111746. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111747. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111748. vbi->ampmax=g->ampmax;
  111749. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111750. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111751. for(i=0;i<vi->channels;i++){
  111752. vbi->pcmdelay[i]=
  111753. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111754. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111755. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111756. /* before we added the delay
  111757. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111758. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111759. */
  111760. }
  111761. /* handle eof detection: eof==0 means that we've not yet received EOF
  111762. eof>0 marks the last 'real' sample in pcm[]
  111763. eof<0 'no more to do'; doesn't get here */
  111764. if(v->eofflag){
  111765. if(v->centerW>=v->eofflag){
  111766. v->eofflag=-1;
  111767. vb->eofflag=1;
  111768. return(1);
  111769. }
  111770. }
  111771. /* advance storage vectors and clean up */
  111772. {
  111773. int new_centerNext=ci->blocksizes[1]/2;
  111774. int movementW=centerNext-new_centerNext;
  111775. if(movementW>0){
  111776. _ve_envelope_shift(b->ve,movementW);
  111777. v->pcm_current-=movementW;
  111778. for(i=0;i<vi->channels;i++)
  111779. memmove(v->pcm[i],v->pcm[i]+movementW,
  111780. v->pcm_current*sizeof(*v->pcm[i]));
  111781. v->lW=v->W;
  111782. v->W=v->nW;
  111783. v->centerW=new_centerNext;
  111784. if(v->eofflag){
  111785. v->eofflag-=movementW;
  111786. if(v->eofflag<=0)v->eofflag=-1;
  111787. /* do not add padding to end of stream! */
  111788. if(v->centerW>=v->eofflag){
  111789. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111790. }else{
  111791. v->granulepos+=movementW;
  111792. }
  111793. }else{
  111794. v->granulepos+=movementW;
  111795. }
  111796. }
  111797. }
  111798. /* done */
  111799. return(1);
  111800. }
  111801. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111802. vorbis_info *vi=v->vi;
  111803. codec_setup_info *ci;
  111804. int hs;
  111805. if(!v->backend_state)return -1;
  111806. if(!vi)return -1;
  111807. ci=(codec_setup_info*) vi->codec_setup;
  111808. if(!ci)return -1;
  111809. hs=ci->halfrate_flag;
  111810. v->centerW=ci->blocksizes[1]>>(hs+1);
  111811. v->pcm_current=v->centerW>>hs;
  111812. v->pcm_returned=-1;
  111813. v->granulepos=-1;
  111814. v->sequence=-1;
  111815. v->eofflag=0;
  111816. ((private_state *)(v->backend_state))->sample_count=-1;
  111817. return(0);
  111818. }
  111819. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111820. if(_vds_shared_init(v,vi,0)) return 1;
  111821. vorbis_synthesis_restart(v);
  111822. return 0;
  111823. }
  111824. /* Unlike in analysis, the window is only partially applied for each
  111825. block. The time domain envelope is not yet handled at the point of
  111826. calling (as it relies on the previous block). */
  111827. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111828. vorbis_info *vi=v->vi;
  111829. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111830. private_state *b=(private_state*)v->backend_state;
  111831. int hs=ci->halfrate_flag;
  111832. int i,j;
  111833. if(!vb)return(OV_EINVAL);
  111834. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111835. v->lW=v->W;
  111836. v->W=vb->W;
  111837. v->nW=-1;
  111838. if((v->sequence==-1)||
  111839. (v->sequence+1 != vb->sequence)){
  111840. v->granulepos=-1; /* out of sequence; lose count */
  111841. b->sample_count=-1;
  111842. }
  111843. v->sequence=vb->sequence;
  111844. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111845. was called on block */
  111846. int n=ci->blocksizes[v->W]>>(hs+1);
  111847. int n0=ci->blocksizes[0]>>(hs+1);
  111848. int n1=ci->blocksizes[1]>>(hs+1);
  111849. int thisCenter;
  111850. int prevCenter;
  111851. v->glue_bits+=vb->glue_bits;
  111852. v->time_bits+=vb->time_bits;
  111853. v->floor_bits+=vb->floor_bits;
  111854. v->res_bits+=vb->res_bits;
  111855. if(v->centerW){
  111856. thisCenter=n1;
  111857. prevCenter=0;
  111858. }else{
  111859. thisCenter=0;
  111860. prevCenter=n1;
  111861. }
  111862. /* v->pcm is now used like a two-stage double buffer. We don't want
  111863. to have to constantly shift *or* adjust memory usage. Don't
  111864. accept a new block until the old is shifted out */
  111865. for(j=0;j<vi->channels;j++){
  111866. /* the overlap/add section */
  111867. if(v->lW){
  111868. if(v->W){
  111869. /* large/large */
  111870. float *w=_vorbis_window_get(b->window[1]-hs);
  111871. float *pcm=v->pcm[j]+prevCenter;
  111872. float *p=vb->pcm[j];
  111873. for(i=0;i<n1;i++)
  111874. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111875. }else{
  111876. /* large/small */
  111877. float *w=_vorbis_window_get(b->window[0]-hs);
  111878. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111879. float *p=vb->pcm[j];
  111880. for(i=0;i<n0;i++)
  111881. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111882. }
  111883. }else{
  111884. if(v->W){
  111885. /* small/large */
  111886. float *w=_vorbis_window_get(b->window[0]-hs);
  111887. float *pcm=v->pcm[j]+prevCenter;
  111888. float *p=vb->pcm[j]+n1/2-n0/2;
  111889. for(i=0;i<n0;i++)
  111890. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111891. for(;i<n1/2+n0/2;i++)
  111892. pcm[i]=p[i];
  111893. }else{
  111894. /* small/small */
  111895. float *w=_vorbis_window_get(b->window[0]-hs);
  111896. float *pcm=v->pcm[j]+prevCenter;
  111897. float *p=vb->pcm[j];
  111898. for(i=0;i<n0;i++)
  111899. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111900. }
  111901. }
  111902. /* the copy section */
  111903. {
  111904. float *pcm=v->pcm[j]+thisCenter;
  111905. float *p=vb->pcm[j]+n;
  111906. for(i=0;i<n;i++)
  111907. pcm[i]=p[i];
  111908. }
  111909. }
  111910. if(v->centerW)
  111911. v->centerW=0;
  111912. else
  111913. v->centerW=n1;
  111914. /* deal with initial packet state; we do this using the explicit
  111915. pcm_returned==-1 flag otherwise we're sensitive to first block
  111916. being short or long */
  111917. if(v->pcm_returned==-1){
  111918. v->pcm_returned=thisCenter;
  111919. v->pcm_current=thisCenter;
  111920. }else{
  111921. v->pcm_returned=prevCenter;
  111922. v->pcm_current=prevCenter+
  111923. ((ci->blocksizes[v->lW]/4+
  111924. ci->blocksizes[v->W]/4)>>hs);
  111925. }
  111926. }
  111927. /* track the frame number... This is for convenience, but also
  111928. making sure our last packet doesn't end with added padding. If
  111929. the last packet is partial, the number of samples we'll have to
  111930. return will be past the vb->granulepos.
  111931. This is not foolproof! It will be confused if we begin
  111932. decoding at the last page after a seek or hole. In that case,
  111933. we don't have a starting point to judge where the last frame
  111934. is. For this reason, vorbisfile will always try to make sure
  111935. it reads the last two marked pages in proper sequence */
  111936. if(b->sample_count==-1){
  111937. b->sample_count=0;
  111938. }else{
  111939. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111940. }
  111941. if(v->granulepos==-1){
  111942. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111943. v->granulepos=vb->granulepos;
  111944. /* is this a short page? */
  111945. if(b->sample_count>v->granulepos){
  111946. /* corner case; if this is both the first and last audio page,
  111947. then spec says the end is cut, not beginning */
  111948. if(vb->eofflag){
  111949. /* trim the end */
  111950. /* no preceeding granulepos; assume we started at zero (we'd
  111951. have to in a short single-page stream) */
  111952. /* granulepos could be -1 due to a seek, but that would result
  111953. in a long count, not short count */
  111954. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111955. }else{
  111956. /* trim the beginning */
  111957. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111958. if(v->pcm_returned>v->pcm_current)
  111959. v->pcm_returned=v->pcm_current;
  111960. }
  111961. }
  111962. }
  111963. }else{
  111964. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111965. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111966. if(v->granulepos>vb->granulepos){
  111967. long extra=v->granulepos-vb->granulepos;
  111968. if(extra)
  111969. if(vb->eofflag){
  111970. /* partial last frame. Strip the extra samples off */
  111971. v->pcm_current-=extra>>hs;
  111972. } /* else {Shouldn't happen *unless* the bitstream is out of
  111973. spec. Either way, believe the bitstream } */
  111974. } /* else {Shouldn't happen *unless* the bitstream is out of
  111975. spec. Either way, believe the bitstream } */
  111976. v->granulepos=vb->granulepos;
  111977. }
  111978. }
  111979. /* Update, cleanup */
  111980. if(vb->eofflag)v->eofflag=1;
  111981. return(0);
  111982. }
  111983. /* pcm==NULL indicates we just want the pending samples, no more */
  111984. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111985. vorbis_info *vi=v->vi;
  111986. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111987. if(pcm){
  111988. int i;
  111989. for(i=0;i<vi->channels;i++)
  111990. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111991. *pcm=v->pcmret;
  111992. }
  111993. return(v->pcm_current-v->pcm_returned);
  111994. }
  111995. return(0);
  111996. }
  111997. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111998. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111999. v->pcm_returned+=n;
  112000. return(0);
  112001. }
  112002. /* intended for use with a specific vorbisfile feature; we want access
  112003. to the [usually synthetic/postextrapolated] buffer and lapping at
  112004. the end of a decode cycle, specifically, a half-short-block worth.
  112005. This funtion works like pcmout above, except it will also expose
  112006. this implicit buffer data not normally decoded. */
  112007. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  112008. vorbis_info *vi=v->vi;
  112009. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112010. int hs=ci->halfrate_flag;
  112011. int n=ci->blocksizes[v->W]>>(hs+1);
  112012. int n0=ci->blocksizes[0]>>(hs+1);
  112013. int n1=ci->blocksizes[1]>>(hs+1);
  112014. int i,j;
  112015. if(v->pcm_returned<0)return 0;
  112016. /* our returned data ends at pcm_returned; because the synthesis pcm
  112017. buffer is a two-fragment ring, that means our data block may be
  112018. fragmented by buffering, wrapping or a short block not filling
  112019. out a buffer. To simplify things, we unfragment if it's at all
  112020. possibly needed. Otherwise, we'd need to call lapout more than
  112021. once as well as hold additional dsp state. Opt for
  112022. simplicity. */
  112023. /* centerW was advanced by blockin; it would be the center of the
  112024. *next* block */
  112025. if(v->centerW==n1){
  112026. /* the data buffer wraps; swap the halves */
  112027. /* slow, sure, small */
  112028. for(j=0;j<vi->channels;j++){
  112029. float *p=v->pcm[j];
  112030. for(i=0;i<n1;i++){
  112031. float temp=p[i];
  112032. p[i]=p[i+n1];
  112033. p[i+n1]=temp;
  112034. }
  112035. }
  112036. v->pcm_current-=n1;
  112037. v->pcm_returned-=n1;
  112038. v->centerW=0;
  112039. }
  112040. /* solidify buffer into contiguous space */
  112041. if((v->lW^v->W)==1){
  112042. /* long/short or short/long */
  112043. for(j=0;j<vi->channels;j++){
  112044. float *s=v->pcm[j];
  112045. float *d=v->pcm[j]+(n1-n0)/2;
  112046. for(i=(n1+n0)/2-1;i>=0;--i)
  112047. d[i]=s[i];
  112048. }
  112049. v->pcm_returned+=(n1-n0)/2;
  112050. v->pcm_current+=(n1-n0)/2;
  112051. }else{
  112052. if(v->lW==0){
  112053. /* short/short */
  112054. for(j=0;j<vi->channels;j++){
  112055. float *s=v->pcm[j];
  112056. float *d=v->pcm[j]+n1-n0;
  112057. for(i=n0-1;i>=0;--i)
  112058. d[i]=s[i];
  112059. }
  112060. v->pcm_returned+=n1-n0;
  112061. v->pcm_current+=n1-n0;
  112062. }
  112063. }
  112064. if(pcm){
  112065. int i;
  112066. for(i=0;i<vi->channels;i++)
  112067. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  112068. *pcm=v->pcmret;
  112069. }
  112070. return(n1+n-v->pcm_returned);
  112071. }
  112072. float *vorbis_window(vorbis_dsp_state *v,int W){
  112073. vorbis_info *vi=v->vi;
  112074. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112075. int hs=ci->halfrate_flag;
  112076. private_state *b=(private_state*)v->backend_state;
  112077. if(b->window[W]-1<0)return NULL;
  112078. return _vorbis_window_get(b->window[W]-hs);
  112079. }
  112080. #endif
  112081. /*** End of inlined file: block.c ***/
  112082. /*** Start of inlined file: codebook.c ***/
  112083. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112084. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112085. // tasks..
  112086. #if JUCE_MSVC
  112087. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112088. #endif
  112089. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112090. #if JUCE_USE_OGGVORBIS
  112091. #include <stdlib.h>
  112092. #include <string.h>
  112093. #include <math.h>
  112094. /* packs the given codebook into the bitstream **************************/
  112095. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  112096. long i,j;
  112097. int ordered=0;
  112098. /* first the basic parameters */
  112099. oggpack_write(opb,0x564342,24);
  112100. oggpack_write(opb,c->dim,16);
  112101. oggpack_write(opb,c->entries,24);
  112102. /* pack the codewords. There are two packings; length ordered and
  112103. length random. Decide between the two now. */
  112104. for(i=1;i<c->entries;i++)
  112105. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  112106. if(i==c->entries)ordered=1;
  112107. if(ordered){
  112108. /* length ordered. We only need to say how many codewords of
  112109. each length. The actual codewords are generated
  112110. deterministically */
  112111. long count=0;
  112112. oggpack_write(opb,1,1); /* ordered */
  112113. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  112114. for(i=1;i<c->entries;i++){
  112115. long thisx=c->lengthlist[i];
  112116. long last=c->lengthlist[i-1];
  112117. if(thisx>last){
  112118. for(j=last;j<thisx;j++){
  112119. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112120. count=i;
  112121. }
  112122. }
  112123. }
  112124. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112125. }else{
  112126. /* length random. Again, we don't code the codeword itself, just
  112127. the length. This time, though, we have to encode each length */
  112128. oggpack_write(opb,0,1); /* unordered */
  112129. /* algortihmic mapping has use for 'unused entries', which we tag
  112130. here. The algorithmic mapping happens as usual, but the unused
  112131. entry has no codeword. */
  112132. for(i=0;i<c->entries;i++)
  112133. if(c->lengthlist[i]==0)break;
  112134. if(i==c->entries){
  112135. oggpack_write(opb,0,1); /* no unused entries */
  112136. for(i=0;i<c->entries;i++)
  112137. oggpack_write(opb,c->lengthlist[i]-1,5);
  112138. }else{
  112139. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  112140. for(i=0;i<c->entries;i++){
  112141. if(c->lengthlist[i]==0){
  112142. oggpack_write(opb,0,1);
  112143. }else{
  112144. oggpack_write(opb,1,1);
  112145. oggpack_write(opb,c->lengthlist[i]-1,5);
  112146. }
  112147. }
  112148. }
  112149. }
  112150. /* is the entry number the desired return value, or do we have a
  112151. mapping? If we have a mapping, what type? */
  112152. oggpack_write(opb,c->maptype,4);
  112153. switch(c->maptype){
  112154. case 0:
  112155. /* no mapping */
  112156. break;
  112157. case 1:case 2:
  112158. /* implicitly populated value mapping */
  112159. /* explicitly populated value mapping */
  112160. if(!c->quantlist){
  112161. /* no quantlist? error */
  112162. return(-1);
  112163. }
  112164. /* values that define the dequantization */
  112165. oggpack_write(opb,c->q_min,32);
  112166. oggpack_write(opb,c->q_delta,32);
  112167. oggpack_write(opb,c->q_quant-1,4);
  112168. oggpack_write(opb,c->q_sequencep,1);
  112169. {
  112170. int quantvals;
  112171. switch(c->maptype){
  112172. case 1:
  112173. /* a single column of (c->entries/c->dim) quantized values for
  112174. building a full value list algorithmically (square lattice) */
  112175. quantvals=_book_maptype1_quantvals(c);
  112176. break;
  112177. case 2:
  112178. /* every value (c->entries*c->dim total) specified explicitly */
  112179. quantvals=c->entries*c->dim;
  112180. break;
  112181. default: /* NOT_REACHABLE */
  112182. quantvals=-1;
  112183. }
  112184. /* quantized values */
  112185. for(i=0;i<quantvals;i++)
  112186. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112187. }
  112188. break;
  112189. default:
  112190. /* error case; we don't have any other map types now */
  112191. return(-1);
  112192. }
  112193. return(0);
  112194. }
  112195. /* unpacks a codebook from the packet buffer into the codebook struct,
  112196. readies the codebook auxiliary structures for decode *************/
  112197. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112198. long i,j;
  112199. memset(s,0,sizeof(*s));
  112200. s->allocedp=1;
  112201. /* make sure alignment is correct */
  112202. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112203. /* first the basic parameters */
  112204. s->dim=oggpack_read(opb,16);
  112205. s->entries=oggpack_read(opb,24);
  112206. if(s->entries==-1)goto _eofout;
  112207. /* codeword ordering.... length ordered or unordered? */
  112208. switch((int)oggpack_read(opb,1)){
  112209. case 0:
  112210. /* unordered */
  112211. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112212. /* allocated but unused entries? */
  112213. if(oggpack_read(opb,1)){
  112214. /* yes, unused entries */
  112215. for(i=0;i<s->entries;i++){
  112216. if(oggpack_read(opb,1)){
  112217. long num=oggpack_read(opb,5);
  112218. if(num==-1)goto _eofout;
  112219. s->lengthlist[i]=num+1;
  112220. }else
  112221. s->lengthlist[i]=0;
  112222. }
  112223. }else{
  112224. /* all entries used; no tagging */
  112225. for(i=0;i<s->entries;i++){
  112226. long num=oggpack_read(opb,5);
  112227. if(num==-1)goto _eofout;
  112228. s->lengthlist[i]=num+1;
  112229. }
  112230. }
  112231. break;
  112232. case 1:
  112233. /* ordered */
  112234. {
  112235. long length=oggpack_read(opb,5)+1;
  112236. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112237. for(i=0;i<s->entries;){
  112238. long num=oggpack_read(opb,_ilog(s->entries-i));
  112239. if(num==-1)goto _eofout;
  112240. for(j=0;j<num && i<s->entries;j++,i++)
  112241. s->lengthlist[i]=length;
  112242. length++;
  112243. }
  112244. }
  112245. break;
  112246. default:
  112247. /* EOF */
  112248. return(-1);
  112249. }
  112250. /* Do we have a mapping to unpack? */
  112251. switch((s->maptype=oggpack_read(opb,4))){
  112252. case 0:
  112253. /* no mapping */
  112254. break;
  112255. case 1: case 2:
  112256. /* implicitly populated value mapping */
  112257. /* explicitly populated value mapping */
  112258. s->q_min=oggpack_read(opb,32);
  112259. s->q_delta=oggpack_read(opb,32);
  112260. s->q_quant=oggpack_read(opb,4)+1;
  112261. s->q_sequencep=oggpack_read(opb,1);
  112262. {
  112263. int quantvals=0;
  112264. switch(s->maptype){
  112265. case 1:
  112266. quantvals=_book_maptype1_quantvals(s);
  112267. break;
  112268. case 2:
  112269. quantvals=s->entries*s->dim;
  112270. break;
  112271. }
  112272. /* quantized values */
  112273. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112274. for(i=0;i<quantvals;i++)
  112275. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112276. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112277. }
  112278. break;
  112279. default:
  112280. goto _errout;
  112281. }
  112282. /* all set */
  112283. return(0);
  112284. _errout:
  112285. _eofout:
  112286. vorbis_staticbook_clear(s);
  112287. return(-1);
  112288. }
  112289. /* returns the number of bits ************************************************/
  112290. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112291. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112292. return(book->c->lengthlist[a]);
  112293. }
  112294. /* One the encode side, our vector writers are each designed for a
  112295. specific purpose, and the encoder is not flexible without modification:
  112296. The LSP vector coder uses a single stage nearest-match with no
  112297. interleave, so no step and no error return. This is specced by floor0
  112298. and doesn't change.
  112299. Residue0 encoding interleaves, uses multiple stages, and each stage
  112300. peels of a specific amount of resolution from a lattice (thus we want
  112301. to match by threshold, not nearest match). Residue doesn't *have* to
  112302. be encoded that way, but to change it, one will need to add more
  112303. infrastructure on the encode side (decode side is specced and simpler) */
  112304. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112305. /* returns entry number and *modifies a* to the quantization value *****/
  112306. int vorbis_book_errorv(codebook *book,float *a){
  112307. int dim=book->dim,k;
  112308. int best=_best(book,a,1);
  112309. for(k=0;k<dim;k++)
  112310. a[k]=(book->valuelist+best*dim)[k];
  112311. return(best);
  112312. }
  112313. /* returns the number of bits and *modifies a* to the quantization value *****/
  112314. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112315. int k,dim=book->dim;
  112316. for(k=0;k<dim;k++)
  112317. a[k]=(book->valuelist+best*dim)[k];
  112318. return(vorbis_book_encode(book,best,b));
  112319. }
  112320. /* the 'eliminate the decode tree' optimization actually requires the
  112321. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112322. (and one of the first places where carefully thought out design
  112323. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112324. to an MSb bitpacker), but not actually the huge hit it appears to
  112325. be. The first-stage decode table catches most words so that
  112326. bitreverse is not in the main execution path. */
  112327. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112328. int read=book->dec_maxlength;
  112329. long lo,hi;
  112330. long lok = oggpack_look(b,book->dec_firsttablen);
  112331. if (lok >= 0) {
  112332. long entry = book->dec_firsttable[lok];
  112333. if(entry&0x80000000UL){
  112334. lo=(entry>>15)&0x7fff;
  112335. hi=book->used_entries-(entry&0x7fff);
  112336. }else{
  112337. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112338. return(entry-1);
  112339. }
  112340. }else{
  112341. lo=0;
  112342. hi=book->used_entries;
  112343. }
  112344. lok = oggpack_look(b, read);
  112345. while(lok<0 && read>1)
  112346. lok = oggpack_look(b, --read);
  112347. if(lok<0)return -1;
  112348. /* bisect search for the codeword in the ordered list */
  112349. {
  112350. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112351. while(hi-lo>1){
  112352. long p=(hi-lo)>>1;
  112353. long test=book->codelist[lo+p]>testword;
  112354. lo+=p&(test-1);
  112355. hi-=p&(-test);
  112356. }
  112357. if(book->dec_codelengths[lo]<=read){
  112358. oggpack_adv(b, book->dec_codelengths[lo]);
  112359. return(lo);
  112360. }
  112361. }
  112362. oggpack_adv(b, read);
  112363. return(-1);
  112364. }
  112365. /* Decode side is specced and easier, because we don't need to find
  112366. matches using different criteria; we simply read and map. There are
  112367. two things we need to do 'depending':
  112368. We may need to support interleave. We don't really, but it's
  112369. convenient to do it here rather than rebuild the vector later.
  112370. Cascades may be additive or multiplicitive; this is not inherent in
  112371. the codebook, but set in the code using the codebook. Like
  112372. interleaving, it's easiest to do it here.
  112373. addmul==0 -> declarative (set the value)
  112374. addmul==1 -> additive
  112375. addmul==2 -> multiplicitive */
  112376. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112377. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112378. long packed_entry=decode_packed_entry_number(book,b);
  112379. if(packed_entry>=0)
  112380. return(book->dec_index[packed_entry]);
  112381. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112382. return(packed_entry);
  112383. }
  112384. /* returns 0 on OK or -1 on eof *************************************/
  112385. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112386. int step=n/book->dim;
  112387. long *entry = (long*)alloca(sizeof(*entry)*step);
  112388. float **t = (float**)alloca(sizeof(*t)*step);
  112389. int i,j,o;
  112390. for (i = 0; i < step; i++) {
  112391. entry[i]=decode_packed_entry_number(book,b);
  112392. if(entry[i]==-1)return(-1);
  112393. t[i] = book->valuelist+entry[i]*book->dim;
  112394. }
  112395. for(i=0,o=0;i<book->dim;i++,o+=step)
  112396. for (j=0;j<step;j++)
  112397. a[o+j]+=t[j][i];
  112398. return(0);
  112399. }
  112400. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112401. int i,j,entry;
  112402. float *t;
  112403. if(book->dim>8){
  112404. for(i=0;i<n;){
  112405. entry = decode_packed_entry_number(book,b);
  112406. if(entry==-1)return(-1);
  112407. t = book->valuelist+entry*book->dim;
  112408. for (j=0;j<book->dim;)
  112409. a[i++]+=t[j++];
  112410. }
  112411. }else{
  112412. for(i=0;i<n;){
  112413. entry = decode_packed_entry_number(book,b);
  112414. if(entry==-1)return(-1);
  112415. t = book->valuelist+entry*book->dim;
  112416. j=0;
  112417. switch((int)book->dim){
  112418. case 8:
  112419. a[i++]+=t[j++];
  112420. case 7:
  112421. a[i++]+=t[j++];
  112422. case 6:
  112423. a[i++]+=t[j++];
  112424. case 5:
  112425. a[i++]+=t[j++];
  112426. case 4:
  112427. a[i++]+=t[j++];
  112428. case 3:
  112429. a[i++]+=t[j++];
  112430. case 2:
  112431. a[i++]+=t[j++];
  112432. case 1:
  112433. a[i++]+=t[j++];
  112434. case 0:
  112435. break;
  112436. }
  112437. }
  112438. }
  112439. return(0);
  112440. }
  112441. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112442. int i,j,entry;
  112443. float *t;
  112444. for(i=0;i<n;){
  112445. entry = decode_packed_entry_number(book,b);
  112446. if(entry==-1)return(-1);
  112447. t = book->valuelist+entry*book->dim;
  112448. for (j=0;j<book->dim;)
  112449. a[i++]=t[j++];
  112450. }
  112451. return(0);
  112452. }
  112453. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112454. oggpack_buffer *b,int n){
  112455. long i,j,entry;
  112456. int chptr=0;
  112457. for(i=offset/ch;i<(offset+n)/ch;){
  112458. entry = decode_packed_entry_number(book,b);
  112459. if(entry==-1)return(-1);
  112460. {
  112461. const float *t = book->valuelist+entry*book->dim;
  112462. for (j=0;j<book->dim;j++){
  112463. a[chptr++][i]+=t[j];
  112464. if(chptr==ch){
  112465. chptr=0;
  112466. i++;
  112467. }
  112468. }
  112469. }
  112470. }
  112471. return(0);
  112472. }
  112473. #ifdef _V_SELFTEST
  112474. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112475. number of vectors through (keeping track of the quantized values),
  112476. and decode using the unpacked book. quantized version of in should
  112477. exactly equal out */
  112478. #include <stdio.h>
  112479. #include "vorbis/book/lsp20_0.vqh"
  112480. #include "vorbis/book/res0a_13.vqh"
  112481. #define TESTSIZE 40
  112482. float test1[TESTSIZE]={
  112483. 0.105939f,
  112484. 0.215373f,
  112485. 0.429117f,
  112486. 0.587974f,
  112487. 0.181173f,
  112488. 0.296583f,
  112489. 0.515707f,
  112490. 0.715261f,
  112491. 0.162327f,
  112492. 0.263834f,
  112493. 0.342876f,
  112494. 0.406025f,
  112495. 0.103571f,
  112496. 0.223561f,
  112497. 0.368513f,
  112498. 0.540313f,
  112499. 0.136672f,
  112500. 0.395882f,
  112501. 0.587183f,
  112502. 0.652476f,
  112503. 0.114338f,
  112504. 0.417300f,
  112505. 0.525486f,
  112506. 0.698679f,
  112507. 0.147492f,
  112508. 0.324481f,
  112509. 0.643089f,
  112510. 0.757582f,
  112511. 0.139556f,
  112512. 0.215795f,
  112513. 0.324559f,
  112514. 0.399387f,
  112515. 0.120236f,
  112516. 0.267420f,
  112517. 0.446940f,
  112518. 0.608760f,
  112519. 0.115587f,
  112520. 0.287234f,
  112521. 0.571081f,
  112522. 0.708603f,
  112523. };
  112524. float test3[TESTSIZE]={
  112525. 0,1,-2,3,4,-5,6,7,8,9,
  112526. 8,-2,7,-1,4,6,8,3,1,-9,
  112527. 10,11,12,13,14,15,26,17,18,19,
  112528. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112529. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112530. &_vq_book_res0a_13,NULL};
  112531. float *testvec[]={test1,test3};
  112532. int main(){
  112533. oggpack_buffer write;
  112534. oggpack_buffer read;
  112535. long ptr=0,i;
  112536. oggpack_writeinit(&write);
  112537. fprintf(stderr,"Testing codebook abstraction...:\n");
  112538. while(testlist[ptr]){
  112539. codebook c;
  112540. static_codebook s;
  112541. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112542. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112543. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112544. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112545. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112546. /* pack the codebook, write the testvector */
  112547. oggpack_reset(&write);
  112548. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112549. we can write */
  112550. vorbis_staticbook_pack(testlist[ptr],&write);
  112551. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112552. for(i=0;i<TESTSIZE;i+=c.dim){
  112553. int best=_best(&c,qv+i,1);
  112554. vorbis_book_encodev(&c,best,qv+i,&write);
  112555. }
  112556. vorbis_book_clear(&c);
  112557. fprintf(stderr,"OK.\n");
  112558. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112559. /* transfer the write data to a read buffer and unpack/read */
  112560. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112561. if(vorbis_staticbook_unpack(&read,&s)){
  112562. fprintf(stderr,"Error unpacking codebook.\n");
  112563. exit(1);
  112564. }
  112565. if(vorbis_book_init_decode(&c,&s)){
  112566. fprintf(stderr,"Error initializing codebook.\n");
  112567. exit(1);
  112568. }
  112569. for(i=0;i<TESTSIZE;i+=c.dim)
  112570. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112571. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112572. exit(1);
  112573. }
  112574. for(i=0;i<TESTSIZE;i++)
  112575. if(fabs(qv[i]-iv[i])>.000001){
  112576. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112577. iv[i],qv[i],i);
  112578. exit(1);
  112579. }
  112580. fprintf(stderr,"OK\n");
  112581. ptr++;
  112582. }
  112583. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112584. exit(0);
  112585. }
  112586. #endif
  112587. #endif
  112588. /*** End of inlined file: codebook.c ***/
  112589. /*** Start of inlined file: envelope.c ***/
  112590. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112591. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112592. // tasks..
  112593. #if JUCE_MSVC
  112594. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112595. #endif
  112596. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112597. #if JUCE_USE_OGGVORBIS
  112598. #include <stdlib.h>
  112599. #include <string.h>
  112600. #include <stdio.h>
  112601. #include <math.h>
  112602. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112603. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112604. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112605. int ch=vi->channels;
  112606. int i,j;
  112607. int n=e->winlength=128;
  112608. e->searchstep=64; /* not random */
  112609. e->minenergy=gi->preecho_minenergy;
  112610. e->ch=ch;
  112611. e->storage=128;
  112612. e->cursor=ci->blocksizes[1]/2;
  112613. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112614. mdct_init(&e->mdct,n);
  112615. for(i=0;i<n;i++){
  112616. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112617. e->mdct_win[i]*=e->mdct_win[i];
  112618. }
  112619. /* magic follows */
  112620. e->band[0].begin=2; e->band[0].end=4;
  112621. e->band[1].begin=4; e->band[1].end=5;
  112622. e->band[2].begin=6; e->band[2].end=6;
  112623. e->band[3].begin=9; e->band[3].end=8;
  112624. e->band[4].begin=13; e->band[4].end=8;
  112625. e->band[5].begin=17; e->band[5].end=8;
  112626. e->band[6].begin=22; e->band[6].end=8;
  112627. for(j=0;j<VE_BANDS;j++){
  112628. n=e->band[j].end;
  112629. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112630. for(i=0;i<n;i++){
  112631. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112632. e->band[j].total+=e->band[j].window[i];
  112633. }
  112634. e->band[j].total=1./e->band[j].total;
  112635. }
  112636. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112637. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112638. }
  112639. void _ve_envelope_clear(envelope_lookup *e){
  112640. int i;
  112641. mdct_clear(&e->mdct);
  112642. for(i=0;i<VE_BANDS;i++)
  112643. _ogg_free(e->band[i].window);
  112644. _ogg_free(e->mdct_win);
  112645. _ogg_free(e->filter);
  112646. _ogg_free(e->mark);
  112647. memset(e,0,sizeof(*e));
  112648. }
  112649. /* fairly straight threshhold-by-band based until we find something
  112650. that works better and isn't patented. */
  112651. static int _ve_amp(envelope_lookup *ve,
  112652. vorbis_info_psy_global *gi,
  112653. float *data,
  112654. envelope_band *bands,
  112655. envelope_filter_state *filters,
  112656. long pos){
  112657. long n=ve->winlength;
  112658. int ret=0;
  112659. long i,j;
  112660. float decay;
  112661. /* we want to have a 'minimum bar' for energy, else we're just
  112662. basing blocks on quantization noise that outweighs the signal
  112663. itself (for low power signals) */
  112664. float minV=ve->minenergy;
  112665. float *vec=(float*) alloca(n*sizeof(*vec));
  112666. /* stretch is used to gradually lengthen the number of windows
  112667. considered prevoius-to-potential-trigger */
  112668. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112669. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112670. if(penalty<0.f)penalty=0.f;
  112671. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112672. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112673. totalshift+pos*ve->searchstep);*/
  112674. /* window and transform */
  112675. for(i=0;i<n;i++)
  112676. vec[i]=data[i]*ve->mdct_win[i];
  112677. mdct_forward(&ve->mdct,vec,vec);
  112678. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112679. /* near-DC spreading function; this has nothing to do with
  112680. psychoacoustics, just sidelobe leakage and window size */
  112681. {
  112682. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112683. int ptr=filters->nearptr;
  112684. /* the accumulation is regularly refreshed from scratch to avoid
  112685. floating point creep */
  112686. if(ptr==0){
  112687. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112688. filters->nearDC_partialacc=temp;
  112689. }else{
  112690. decay=filters->nearDC_acc+=temp;
  112691. filters->nearDC_partialacc+=temp;
  112692. }
  112693. filters->nearDC_acc-=filters->nearDC[ptr];
  112694. filters->nearDC[ptr]=temp;
  112695. decay*=(1./(VE_NEARDC+1));
  112696. filters->nearptr++;
  112697. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112698. decay=todB(&decay)*.5-15.f;
  112699. }
  112700. /* perform spreading and limiting, also smooth the spectrum. yes,
  112701. the MDCT results in all real coefficients, but it still *behaves*
  112702. like real/imaginary pairs */
  112703. for(i=0;i<n/2;i+=2){
  112704. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112705. val=todB(&val)*.5f;
  112706. if(val<decay)val=decay;
  112707. if(val<minV)val=minV;
  112708. vec[i>>1]=val;
  112709. decay-=8.;
  112710. }
  112711. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112712. /* perform preecho/postecho triggering by band */
  112713. for(j=0;j<VE_BANDS;j++){
  112714. float acc=0.;
  112715. float valmax,valmin;
  112716. /* accumulate amplitude */
  112717. for(i=0;i<bands[j].end;i++)
  112718. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112719. acc*=bands[j].total;
  112720. /* convert amplitude to delta */
  112721. {
  112722. int p,thisx=filters[j].ampptr;
  112723. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112724. p=thisx;
  112725. p--;
  112726. if(p<0)p+=VE_AMP;
  112727. postmax=max(acc,filters[j].ampbuf[p]);
  112728. postmin=min(acc,filters[j].ampbuf[p]);
  112729. for(i=0;i<stretch;i++){
  112730. p--;
  112731. if(p<0)p+=VE_AMP;
  112732. premax=max(premax,filters[j].ampbuf[p]);
  112733. premin=min(premin,filters[j].ampbuf[p]);
  112734. }
  112735. valmin=postmin-premin;
  112736. valmax=postmax-premax;
  112737. /*filters[j].markers[pos]=valmax;*/
  112738. filters[j].ampbuf[thisx]=acc;
  112739. filters[j].ampptr++;
  112740. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112741. }
  112742. /* look at min/max, decide trigger */
  112743. if(valmax>gi->preecho_thresh[j]+penalty){
  112744. ret|=1;
  112745. ret|=4;
  112746. }
  112747. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112748. }
  112749. return(ret);
  112750. }
  112751. #if 0
  112752. static int seq=0;
  112753. static ogg_int64_t totalshift=-1024;
  112754. #endif
  112755. long _ve_envelope_search(vorbis_dsp_state *v){
  112756. vorbis_info *vi=v->vi;
  112757. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112758. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112759. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112760. long i,j;
  112761. int first=ve->current/ve->searchstep;
  112762. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112763. if(first<0)first=0;
  112764. /* make sure we have enough storage to match the PCM */
  112765. if(last+VE_WIN+VE_POST>ve->storage){
  112766. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112767. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112768. }
  112769. for(j=first;j<last;j++){
  112770. int ret=0;
  112771. ve->stretch++;
  112772. if(ve->stretch>VE_MAXSTRETCH*2)
  112773. ve->stretch=VE_MAXSTRETCH*2;
  112774. for(i=0;i<ve->ch;i++){
  112775. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112776. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112777. }
  112778. ve->mark[j+VE_POST]=0;
  112779. if(ret&1){
  112780. ve->mark[j]=1;
  112781. ve->mark[j+1]=1;
  112782. }
  112783. if(ret&2){
  112784. ve->mark[j]=1;
  112785. if(j>0)ve->mark[j-1]=1;
  112786. }
  112787. if(ret&4)ve->stretch=-1;
  112788. }
  112789. ve->current=last*ve->searchstep;
  112790. {
  112791. long centerW=v->centerW;
  112792. long testW=
  112793. centerW+
  112794. ci->blocksizes[v->W]/4+
  112795. ci->blocksizes[1]/2+
  112796. ci->blocksizes[0]/4;
  112797. j=ve->cursor;
  112798. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112799. working back one window */
  112800. if(j>=testW)return(1);
  112801. ve->cursor=j;
  112802. if(ve->mark[j/ve->searchstep]){
  112803. if(j>centerW){
  112804. #if 0
  112805. if(j>ve->curmark){
  112806. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112807. int l,m;
  112808. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112809. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112810. seq,
  112811. (totalshift+ve->cursor)/44100.,
  112812. (totalshift+j)/44100.);
  112813. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112814. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112815. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112816. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112817. for(m=0;m<VE_BANDS;m++){
  112818. char buf[80];
  112819. sprintf(buf,"delL%d",m);
  112820. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112821. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112822. }
  112823. for(m=0;m<VE_BANDS;m++){
  112824. char buf[80];
  112825. sprintf(buf,"delR%d",m);
  112826. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112827. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112828. }
  112829. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112830. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112831. seq++;
  112832. }
  112833. #endif
  112834. ve->curmark=j;
  112835. if(j>=testW)return(1);
  112836. return(0);
  112837. }
  112838. }
  112839. j+=ve->searchstep;
  112840. }
  112841. }
  112842. return(-1);
  112843. }
  112844. int _ve_envelope_mark(vorbis_dsp_state *v){
  112845. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112846. vorbis_info *vi=v->vi;
  112847. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112848. long centerW=v->centerW;
  112849. long beginW=centerW-ci->blocksizes[v->W]/4;
  112850. long endW=centerW+ci->blocksizes[v->W]/4;
  112851. if(v->W){
  112852. beginW-=ci->blocksizes[v->lW]/4;
  112853. endW+=ci->blocksizes[v->nW]/4;
  112854. }else{
  112855. beginW-=ci->blocksizes[0]/4;
  112856. endW+=ci->blocksizes[0]/4;
  112857. }
  112858. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112859. {
  112860. long first=beginW/ve->searchstep;
  112861. long last=endW/ve->searchstep;
  112862. long i;
  112863. for(i=first;i<last;i++)
  112864. if(ve->mark[i])return(1);
  112865. }
  112866. return(0);
  112867. }
  112868. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112869. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112870. ahead of ve->current */
  112871. int smallshift=shift/e->searchstep;
  112872. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112873. #if 0
  112874. for(i=0;i<VE_BANDS*e->ch;i++)
  112875. memmove(e->filter[i].markers,
  112876. e->filter[i].markers+smallshift,
  112877. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112878. totalshift+=shift;
  112879. #endif
  112880. e->current-=shift;
  112881. if(e->curmark>=0)
  112882. e->curmark-=shift;
  112883. e->cursor-=shift;
  112884. }
  112885. #endif
  112886. /*** End of inlined file: envelope.c ***/
  112887. /*** Start of inlined file: floor0.c ***/
  112888. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112889. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112890. // tasks..
  112891. #if JUCE_MSVC
  112892. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112893. #endif
  112894. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112895. #if JUCE_USE_OGGVORBIS
  112896. #include <stdlib.h>
  112897. #include <string.h>
  112898. #include <math.h>
  112899. /*** Start of inlined file: lsp.h ***/
  112900. #ifndef _V_LSP_H_
  112901. #define _V_LSP_H_
  112902. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112903. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112904. float *lsp,int m,
  112905. float amp,float ampoffset);
  112906. #endif
  112907. /*** End of inlined file: lsp.h ***/
  112908. #include <stdio.h>
  112909. typedef struct {
  112910. int ln;
  112911. int m;
  112912. int **linearmap;
  112913. int n[2];
  112914. vorbis_info_floor0 *vi;
  112915. long bits;
  112916. long frames;
  112917. } vorbis_look_floor0;
  112918. /***********************************************/
  112919. static void floor0_free_info(vorbis_info_floor *i){
  112920. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112921. if(info){
  112922. memset(info,0,sizeof(*info));
  112923. _ogg_free(info);
  112924. }
  112925. }
  112926. static void floor0_free_look(vorbis_look_floor *i){
  112927. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112928. if(look){
  112929. if(look->linearmap){
  112930. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112931. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112932. _ogg_free(look->linearmap);
  112933. }
  112934. memset(look,0,sizeof(*look));
  112935. _ogg_free(look);
  112936. }
  112937. }
  112938. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112939. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112940. int j;
  112941. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112942. info->order=oggpack_read(opb,8);
  112943. info->rate=oggpack_read(opb,16);
  112944. info->barkmap=oggpack_read(opb,16);
  112945. info->ampbits=oggpack_read(opb,6);
  112946. info->ampdB=oggpack_read(opb,8);
  112947. info->numbooks=oggpack_read(opb,4)+1;
  112948. if(info->order<1)goto err_out;
  112949. if(info->rate<1)goto err_out;
  112950. if(info->barkmap<1)goto err_out;
  112951. if(info->numbooks<1)goto err_out;
  112952. for(j=0;j<info->numbooks;j++){
  112953. info->books[j]=oggpack_read(opb,8);
  112954. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112955. }
  112956. return(info);
  112957. err_out:
  112958. floor0_free_info(info);
  112959. return(NULL);
  112960. }
  112961. /* initialize Bark scale and normalization lookups. We could do this
  112962. with static tables, but Vorbis allows a number of possible
  112963. combinations, so it's best to do it computationally.
  112964. The below is authoritative in terms of defining scale mapping.
  112965. Note that the scale depends on the sampling rate as well as the
  112966. linear block and mapping sizes */
  112967. static void floor0_map_lazy_init(vorbis_block *vb,
  112968. vorbis_info_floor *infoX,
  112969. vorbis_look_floor0 *look){
  112970. if(!look->linearmap[vb->W]){
  112971. vorbis_dsp_state *vd=vb->vd;
  112972. vorbis_info *vi=vd->vi;
  112973. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112974. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112975. int W=vb->W;
  112976. int n=ci->blocksizes[W]/2,j;
  112977. /* we choose a scaling constant so that:
  112978. floor(bark(rate/2-1)*C)=mapped-1
  112979. floor(bark(rate/2)*C)=mapped */
  112980. float scale=look->ln/toBARK(info->rate/2.f);
  112981. /* the mapping from a linear scale to a smaller bark scale is
  112982. straightforward. We do *not* make sure that the linear mapping
  112983. does not skip bark-scale bins; the decoder simply skips them and
  112984. the encoder may do what it wishes in filling them. They're
  112985. necessary in some mapping combinations to keep the scale spacing
  112986. accurate */
  112987. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112988. for(j=0;j<n;j++){
  112989. int val=floor( toBARK((info->rate/2.f)/n*j)
  112990. *scale); /* bark numbers represent band edges */
  112991. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112992. look->linearmap[W][j]=val;
  112993. }
  112994. look->linearmap[W][j]=-1;
  112995. look->n[W]=n;
  112996. }
  112997. }
  112998. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112999. vorbis_info_floor *i){
  113000. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  113001. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  113002. look->m=info->order;
  113003. look->ln=info->barkmap;
  113004. look->vi=info;
  113005. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  113006. return look;
  113007. }
  113008. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  113009. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  113010. vorbis_info_floor0 *info=look->vi;
  113011. int j,k;
  113012. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  113013. if(ampraw>0){ /* also handles the -1 out of data case */
  113014. long maxval=(1<<info->ampbits)-1;
  113015. float amp=(float)ampraw/maxval*info->ampdB;
  113016. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  113017. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  113018. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  113019. codebook *b=ci->fullbooks+info->books[booknum];
  113020. float last=0.f;
  113021. /* the additional b->dim is a guard against any possible stack
  113022. smash; b->dim is provably more than we can overflow the
  113023. vector */
  113024. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  113025. for(j=0;j<look->m;j+=b->dim)
  113026. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  113027. for(j=0;j<look->m;){
  113028. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  113029. last=lsp[j-1];
  113030. }
  113031. lsp[look->m]=amp;
  113032. return(lsp);
  113033. }
  113034. }
  113035. eop:
  113036. return(NULL);
  113037. }
  113038. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  113039. void *memo,float *out){
  113040. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  113041. vorbis_info_floor0 *info=look->vi;
  113042. floor0_map_lazy_init(vb,info,look);
  113043. if(memo){
  113044. float *lsp=(float *)memo;
  113045. float amp=lsp[look->m];
  113046. /* take the coefficients back to a spectral envelope curve */
  113047. vorbis_lsp_to_curve(out,
  113048. look->linearmap[vb->W],
  113049. look->n[vb->W],
  113050. look->ln,
  113051. lsp,look->m,amp,(float)info->ampdB);
  113052. return(1);
  113053. }
  113054. memset(out,0,sizeof(*out)*look->n[vb->W]);
  113055. return(0);
  113056. }
  113057. /* export hooks */
  113058. vorbis_func_floor floor0_exportbundle={
  113059. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  113060. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  113061. };
  113062. #endif
  113063. /*** End of inlined file: floor0.c ***/
  113064. /*** Start of inlined file: floor1.c ***/
  113065. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113066. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113067. // tasks..
  113068. #if JUCE_MSVC
  113069. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113070. #endif
  113071. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113072. #if JUCE_USE_OGGVORBIS
  113073. #include <stdlib.h>
  113074. #include <string.h>
  113075. #include <math.h>
  113076. #include <stdio.h>
  113077. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  113078. typedef struct {
  113079. int sorted_index[VIF_POSIT+2];
  113080. int forward_index[VIF_POSIT+2];
  113081. int reverse_index[VIF_POSIT+2];
  113082. int hineighbor[VIF_POSIT];
  113083. int loneighbor[VIF_POSIT];
  113084. int posts;
  113085. int n;
  113086. int quant_q;
  113087. vorbis_info_floor1 *vi;
  113088. long phrasebits;
  113089. long postbits;
  113090. long frames;
  113091. } vorbis_look_floor1;
  113092. typedef struct lsfit_acc{
  113093. long x0;
  113094. long x1;
  113095. long xa;
  113096. long ya;
  113097. long x2a;
  113098. long y2a;
  113099. long xya;
  113100. long an;
  113101. } lsfit_acc;
  113102. /***********************************************/
  113103. static void floor1_free_info(vorbis_info_floor *i){
  113104. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113105. if(info){
  113106. memset(info,0,sizeof(*info));
  113107. _ogg_free(info);
  113108. }
  113109. }
  113110. static void floor1_free_look(vorbis_look_floor *i){
  113111. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  113112. if(look){
  113113. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  113114. (float)look->phrasebits/look->frames,
  113115. (float)look->postbits/look->frames,
  113116. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113117. memset(look,0,sizeof(*look));
  113118. _ogg_free(look);
  113119. }
  113120. }
  113121. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  113122. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113123. int j,k;
  113124. int count=0;
  113125. int rangebits;
  113126. int maxposit=info->postlist[1];
  113127. int maxclass=-1;
  113128. /* save out partitions */
  113129. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  113130. for(j=0;j<info->partitions;j++){
  113131. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  113132. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113133. }
  113134. /* save out partition classes */
  113135. for(j=0;j<maxclass+1;j++){
  113136. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  113137. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  113138. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  113139. for(k=0;k<(1<<info->class_subs[j]);k++)
  113140. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  113141. }
  113142. /* save out the post list */
  113143. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  113144. oggpack_write(opb,ilog2(maxposit),4);
  113145. rangebits=ilog2(maxposit);
  113146. for(j=0,k=0;j<info->partitions;j++){
  113147. count+=info->class_dim[info->partitionclass[j]];
  113148. for(;k<count;k++)
  113149. oggpack_write(opb,info->postlist[k+2],rangebits);
  113150. }
  113151. }
  113152. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  113153. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113154. int j,k,count=0,maxclass=-1,rangebits;
  113155. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  113156. /* read partitions */
  113157. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  113158. for(j=0;j<info->partitions;j++){
  113159. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  113160. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113161. }
  113162. /* read partition classes */
  113163. for(j=0;j<maxclass+1;j++){
  113164. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  113165. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  113166. if(info->class_subs[j]<0)
  113167. goto err_out;
  113168. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  113169. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  113170. goto err_out;
  113171. for(k=0;k<(1<<info->class_subs[j]);k++){
  113172. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  113173. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  113174. goto err_out;
  113175. }
  113176. }
  113177. /* read the post list */
  113178. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  113179. rangebits=oggpack_read(opb,4);
  113180. for(j=0,k=0;j<info->partitions;j++){
  113181. count+=info->class_dim[info->partitionclass[j]];
  113182. for(;k<count;k++){
  113183. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  113184. if(t<0 || t>=(1<<rangebits))
  113185. goto err_out;
  113186. }
  113187. }
  113188. info->postlist[0]=0;
  113189. info->postlist[1]=1<<rangebits;
  113190. return(info);
  113191. err_out:
  113192. floor1_free_info(info);
  113193. return(NULL);
  113194. }
  113195. static int icomp(const void *a,const void *b){
  113196. return(**(int **)a-**(int **)b);
  113197. }
  113198. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113199. vorbis_info_floor *in){
  113200. int *sortpointer[VIF_POSIT+2];
  113201. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113202. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113203. int i,j,n=0;
  113204. look->vi=info;
  113205. look->n=info->postlist[1];
  113206. /* we drop each position value in-between already decoded values,
  113207. and use linear interpolation to predict each new value past the
  113208. edges. The positions are read in the order of the position
  113209. list... we precompute the bounding positions in the lookup. Of
  113210. course, the neighbors can change (if a position is declined), but
  113211. this is an initial mapping */
  113212. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113213. n+=2;
  113214. look->posts=n;
  113215. /* also store a sorted position index */
  113216. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113217. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113218. /* points from sort order back to range number */
  113219. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113220. /* points from range order to sorted position */
  113221. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113222. /* we actually need the post values too */
  113223. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113224. /* quantize values to multiplier spec */
  113225. switch(info->mult){
  113226. case 1: /* 1024 -> 256 */
  113227. look->quant_q=256;
  113228. break;
  113229. case 2: /* 1024 -> 128 */
  113230. look->quant_q=128;
  113231. break;
  113232. case 3: /* 1024 -> 86 */
  113233. look->quant_q=86;
  113234. break;
  113235. case 4: /* 1024 -> 64 */
  113236. look->quant_q=64;
  113237. break;
  113238. }
  113239. /* discover our neighbors for decode where we don't use fit flags
  113240. (that would push the neighbors outward) */
  113241. for(i=0;i<n-2;i++){
  113242. int lo=0;
  113243. int hi=1;
  113244. int lx=0;
  113245. int hx=look->n;
  113246. int currentx=info->postlist[i+2];
  113247. for(j=0;j<i+2;j++){
  113248. int x=info->postlist[j];
  113249. if(x>lx && x<currentx){
  113250. lo=j;
  113251. lx=x;
  113252. }
  113253. if(x<hx && x>currentx){
  113254. hi=j;
  113255. hx=x;
  113256. }
  113257. }
  113258. look->loneighbor[i]=lo;
  113259. look->hineighbor[i]=hi;
  113260. }
  113261. return(look);
  113262. }
  113263. static int render_point(int x0,int x1,int y0,int y1,int x){
  113264. y0&=0x7fff; /* mask off flag */
  113265. y1&=0x7fff;
  113266. {
  113267. int dy=y1-y0;
  113268. int adx=x1-x0;
  113269. int ady=abs(dy);
  113270. int err=ady*(x-x0);
  113271. int off=err/adx;
  113272. if(dy<0)return(y0-off);
  113273. return(y0+off);
  113274. }
  113275. }
  113276. static int vorbis_dBquant(const float *x){
  113277. int i= *x*7.3142857f+1023.5f;
  113278. if(i>1023)return(1023);
  113279. if(i<0)return(0);
  113280. return i;
  113281. }
  113282. static float FLOOR1_fromdB_LOOKUP[256]={
  113283. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113284. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113285. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113286. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113287. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113288. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113289. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113290. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113291. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113292. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113293. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113294. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113295. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113296. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113297. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113298. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113299. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113300. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113301. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113302. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113303. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113304. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113305. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113306. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113307. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113308. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113309. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113310. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113311. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113312. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113313. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113314. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113315. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113316. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113317. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113318. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113319. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113320. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113321. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113322. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113323. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113324. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113325. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113326. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113327. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113328. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113329. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113330. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113331. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113332. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113333. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113334. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113335. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113336. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113337. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113338. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113339. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113340. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113341. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113342. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113343. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113344. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113345. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113346. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113347. };
  113348. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113349. int dy=y1-y0;
  113350. int adx=x1-x0;
  113351. int ady=abs(dy);
  113352. int base=dy/adx;
  113353. int sy=(dy<0?base-1:base+1);
  113354. int x=x0;
  113355. int y=y0;
  113356. int err=0;
  113357. ady-=abs(base*adx);
  113358. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113359. while(++x<x1){
  113360. err=err+ady;
  113361. if(err>=adx){
  113362. err-=adx;
  113363. y+=sy;
  113364. }else{
  113365. y+=base;
  113366. }
  113367. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113368. }
  113369. }
  113370. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113371. int dy=y1-y0;
  113372. int adx=x1-x0;
  113373. int ady=abs(dy);
  113374. int base=dy/adx;
  113375. int sy=(dy<0?base-1:base+1);
  113376. int x=x0;
  113377. int y=y0;
  113378. int err=0;
  113379. ady-=abs(base*adx);
  113380. d[x]=y;
  113381. while(++x<x1){
  113382. err=err+ady;
  113383. if(err>=adx){
  113384. err-=adx;
  113385. y+=sy;
  113386. }else{
  113387. y+=base;
  113388. }
  113389. d[x]=y;
  113390. }
  113391. }
  113392. /* the floor has already been filtered to only include relevant sections */
  113393. static int accumulate_fit(const float *flr,const float *mdct,
  113394. int x0, int x1,lsfit_acc *a,
  113395. int n,vorbis_info_floor1 *info){
  113396. long i;
  113397. 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;
  113398. memset(a,0,sizeof(*a));
  113399. a->x0=x0;
  113400. a->x1=x1;
  113401. if(x1>=n)x1=n-1;
  113402. for(i=x0;i<=x1;i++){
  113403. int quantized=vorbis_dBquant(flr+i);
  113404. if(quantized){
  113405. if(mdct[i]+info->twofitatten>=flr[i]){
  113406. xa += i;
  113407. ya += quantized;
  113408. x2a += i*i;
  113409. y2a += quantized*quantized;
  113410. xya += i*quantized;
  113411. na++;
  113412. }else{
  113413. xb += i;
  113414. yb += quantized;
  113415. x2b += i*i;
  113416. y2b += quantized*quantized;
  113417. xyb += i*quantized;
  113418. nb++;
  113419. }
  113420. }
  113421. }
  113422. xb+=xa;
  113423. yb+=ya;
  113424. x2b+=x2a;
  113425. y2b+=y2a;
  113426. xyb+=xya;
  113427. nb+=na;
  113428. /* weight toward the actually used frequencies if we meet the threshhold */
  113429. {
  113430. int weight=nb*info->twofitweight/(na+1);
  113431. a->xa=xa*weight+xb;
  113432. a->ya=ya*weight+yb;
  113433. a->x2a=x2a*weight+x2b;
  113434. a->y2a=y2a*weight+y2b;
  113435. a->xya=xya*weight+xyb;
  113436. a->an=na*weight+nb;
  113437. }
  113438. return(na);
  113439. }
  113440. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113441. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113442. long x0=a[0].x0;
  113443. long x1=a[fits-1].x1;
  113444. for(i=0;i<fits;i++){
  113445. x+=a[i].xa;
  113446. y+=a[i].ya;
  113447. x2+=a[i].x2a;
  113448. y2+=a[i].y2a;
  113449. xy+=a[i].xya;
  113450. an+=a[i].an;
  113451. }
  113452. if(*y0>=0){
  113453. x+= x0;
  113454. y+= *y0;
  113455. x2+= x0 * x0;
  113456. y2+= *y0 * *y0;
  113457. xy+= *y0 * x0;
  113458. an++;
  113459. }
  113460. if(*y1>=0){
  113461. x+= x1;
  113462. y+= *y1;
  113463. x2+= x1 * x1;
  113464. y2+= *y1 * *y1;
  113465. xy+= *y1 * x1;
  113466. an++;
  113467. }
  113468. if(an){
  113469. /* need 64 bit multiplies, which C doesn't give portably as int */
  113470. double fx=x;
  113471. double fy=y;
  113472. double fx2=x2;
  113473. double fxy=xy;
  113474. double denom=1./(an*fx2-fx*fx);
  113475. double a=(fy*fx2-fxy*fx)*denom;
  113476. double b=(an*fxy-fx*fy)*denom;
  113477. *y0=rint(a+b*x0);
  113478. *y1=rint(a+b*x1);
  113479. /* limit to our range! */
  113480. if(*y0>1023)*y0=1023;
  113481. if(*y1>1023)*y1=1023;
  113482. if(*y0<0)*y0=0;
  113483. if(*y1<0)*y1=0;
  113484. }else{
  113485. *y0=0;
  113486. *y1=0;
  113487. }
  113488. }
  113489. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113490. long y=0;
  113491. int i;
  113492. for(i=0;i<fits && y==0;i++)
  113493. y+=a[i].ya;
  113494. *y0=*y1=y;
  113495. }*/
  113496. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113497. const float *mdct,
  113498. vorbis_info_floor1 *info){
  113499. int dy=y1-y0;
  113500. int adx=x1-x0;
  113501. int ady=abs(dy);
  113502. int base=dy/adx;
  113503. int sy=(dy<0?base-1:base+1);
  113504. int x=x0;
  113505. int y=y0;
  113506. int err=0;
  113507. int val=vorbis_dBquant(mask+x);
  113508. int mse=0;
  113509. int n=0;
  113510. ady-=abs(base*adx);
  113511. mse=(y-val);
  113512. mse*=mse;
  113513. n++;
  113514. if(mdct[x]+info->twofitatten>=mask[x]){
  113515. if(y+info->maxover<val)return(1);
  113516. if(y-info->maxunder>val)return(1);
  113517. }
  113518. while(++x<x1){
  113519. err=err+ady;
  113520. if(err>=adx){
  113521. err-=adx;
  113522. y+=sy;
  113523. }else{
  113524. y+=base;
  113525. }
  113526. val=vorbis_dBquant(mask+x);
  113527. mse+=((y-val)*(y-val));
  113528. n++;
  113529. if(mdct[x]+info->twofitatten>=mask[x]){
  113530. if(val){
  113531. if(y+info->maxover<val)return(1);
  113532. if(y-info->maxunder>val)return(1);
  113533. }
  113534. }
  113535. }
  113536. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113537. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113538. if(mse/n>info->maxerr)return(1);
  113539. return(0);
  113540. }
  113541. static int post_Y(int *A,int *B,int pos){
  113542. if(A[pos]<0)
  113543. return B[pos];
  113544. if(B[pos]<0)
  113545. return A[pos];
  113546. return (A[pos]+B[pos])>>1;
  113547. }
  113548. int *floor1_fit(vorbis_block *vb,void *look_,
  113549. const float *logmdct, /* in */
  113550. const float *logmask){
  113551. long i,j;
  113552. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113553. vorbis_info_floor1 *info=look->vi;
  113554. long n=look->n;
  113555. long posts=look->posts;
  113556. long nonzero=0;
  113557. lsfit_acc fits[VIF_POSIT+1];
  113558. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113559. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113560. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113561. int hineighbor[VIF_POSIT+2];
  113562. int *output=NULL;
  113563. int memo[VIF_POSIT+2];
  113564. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113565. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113566. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113567. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113568. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113569. /* quantize the relevant floor points and collect them into line fit
  113570. structures (one per minimal division) at the same time */
  113571. if(posts==0){
  113572. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113573. }else{
  113574. for(i=0;i<posts-1;i++)
  113575. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113576. look->sorted_index[i+1],fits+i,
  113577. n,info);
  113578. }
  113579. if(nonzero){
  113580. /* start by fitting the implicit base case.... */
  113581. int y0=-200;
  113582. int y1=-200;
  113583. fit_line(fits,posts-1,&y0,&y1);
  113584. fit_valueA[0]=y0;
  113585. fit_valueB[0]=y0;
  113586. fit_valueB[1]=y1;
  113587. fit_valueA[1]=y1;
  113588. /* Non degenerate case */
  113589. /* start progressive splitting. This is a greedy, non-optimal
  113590. algorithm, but simple and close enough to the best
  113591. answer. */
  113592. for(i=2;i<posts;i++){
  113593. int sortpos=look->reverse_index[i];
  113594. int ln=loneighbor[sortpos];
  113595. int hn=hineighbor[sortpos];
  113596. /* eliminate repeat searches of a particular range with a memo */
  113597. if(memo[ln]!=hn){
  113598. /* haven't performed this error search yet */
  113599. int lsortpos=look->reverse_index[ln];
  113600. int hsortpos=look->reverse_index[hn];
  113601. memo[ln]=hn;
  113602. {
  113603. /* A note: we want to bound/minimize *local*, not global, error */
  113604. int lx=info->postlist[ln];
  113605. int hx=info->postlist[hn];
  113606. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113607. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113608. if(ly==-1 || hy==-1){
  113609. exit(1);
  113610. }
  113611. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113612. /* outside error bounds/begin search area. Split it. */
  113613. int ly0=-200;
  113614. int ly1=-200;
  113615. int hy0=-200;
  113616. int hy1=-200;
  113617. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113618. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113619. /* store new edge values */
  113620. fit_valueB[ln]=ly0;
  113621. if(ln==0)fit_valueA[ln]=ly0;
  113622. fit_valueA[i]=ly1;
  113623. fit_valueB[i]=hy0;
  113624. fit_valueA[hn]=hy1;
  113625. if(hn==1)fit_valueB[hn]=hy1;
  113626. if(ly1>=0 || hy0>=0){
  113627. /* store new neighbor values */
  113628. for(j=sortpos-1;j>=0;j--)
  113629. if(hineighbor[j]==hn)
  113630. hineighbor[j]=i;
  113631. else
  113632. break;
  113633. for(j=sortpos+1;j<posts;j++)
  113634. if(loneighbor[j]==ln)
  113635. loneighbor[j]=i;
  113636. else
  113637. break;
  113638. }
  113639. }else{
  113640. fit_valueA[i]=-200;
  113641. fit_valueB[i]=-200;
  113642. }
  113643. }
  113644. }
  113645. }
  113646. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113647. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113648. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113649. /* fill in posts marked as not using a fit; we will zero
  113650. back out to 'unused' when encoding them so long as curve
  113651. interpolation doesn't force them into use */
  113652. for(i=2;i<posts;i++){
  113653. int ln=look->loneighbor[i-2];
  113654. int hn=look->hineighbor[i-2];
  113655. int x0=info->postlist[ln];
  113656. int x1=info->postlist[hn];
  113657. int y0=output[ln];
  113658. int y1=output[hn];
  113659. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113660. int vx=post_Y(fit_valueA,fit_valueB,i);
  113661. if(vx>=0 && predicted!=vx){
  113662. output[i]=vx;
  113663. }else{
  113664. output[i]= predicted|0x8000;
  113665. }
  113666. }
  113667. }
  113668. return(output);
  113669. }
  113670. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113671. int *A,int *B,
  113672. int del){
  113673. long i;
  113674. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113675. long posts=look->posts;
  113676. int *output=NULL;
  113677. if(A && B){
  113678. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113679. for(i=0;i<posts;i++){
  113680. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113681. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113682. }
  113683. }
  113684. return(output);
  113685. }
  113686. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113687. void*look_,
  113688. int *post,int *ilogmask){
  113689. long i,j;
  113690. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113691. vorbis_info_floor1 *info=look->vi;
  113692. long posts=look->posts;
  113693. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113694. int out[VIF_POSIT+2];
  113695. static_codebook **sbooks=ci->book_param;
  113696. codebook *books=ci->fullbooks;
  113697. static long seq=0;
  113698. /* quantize values to multiplier spec */
  113699. if(post){
  113700. for(i=0;i<posts;i++){
  113701. int val=post[i]&0x7fff;
  113702. switch(info->mult){
  113703. case 1: /* 1024 -> 256 */
  113704. val>>=2;
  113705. break;
  113706. case 2: /* 1024 -> 128 */
  113707. val>>=3;
  113708. break;
  113709. case 3: /* 1024 -> 86 */
  113710. val/=12;
  113711. break;
  113712. case 4: /* 1024 -> 64 */
  113713. val>>=4;
  113714. break;
  113715. }
  113716. post[i]=val | (post[i]&0x8000);
  113717. }
  113718. out[0]=post[0];
  113719. out[1]=post[1];
  113720. /* find prediction values for each post and subtract them */
  113721. for(i=2;i<posts;i++){
  113722. int ln=look->loneighbor[i-2];
  113723. int hn=look->hineighbor[i-2];
  113724. int x0=info->postlist[ln];
  113725. int x1=info->postlist[hn];
  113726. int y0=post[ln];
  113727. int y1=post[hn];
  113728. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113729. if((post[i]&0x8000) || (predicted==post[i])){
  113730. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113731. in interpolation */
  113732. out[i]=0;
  113733. }else{
  113734. int headroom=(look->quant_q-predicted<predicted?
  113735. look->quant_q-predicted:predicted);
  113736. int val=post[i]-predicted;
  113737. /* at this point the 'deviation' value is in the range +/- max
  113738. range, but the real, unique range can always be mapped to
  113739. only [0-maxrange). So we want to wrap the deviation into
  113740. this limited range, but do it in the way that least screws
  113741. an essentially gaussian probability distribution. */
  113742. if(val<0)
  113743. if(val<-headroom)
  113744. val=headroom-val-1;
  113745. else
  113746. val=-1-(val<<1);
  113747. else
  113748. if(val>=headroom)
  113749. val= val+headroom;
  113750. else
  113751. val<<=1;
  113752. out[i]=val;
  113753. post[ln]&=0x7fff;
  113754. post[hn]&=0x7fff;
  113755. }
  113756. }
  113757. /* we have everything we need. pack it out */
  113758. /* mark nontrivial floor */
  113759. oggpack_write(opb,1,1);
  113760. /* beginning/end post */
  113761. look->frames++;
  113762. look->postbits+=ilog(look->quant_q-1)*2;
  113763. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113764. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113765. /* partition by partition */
  113766. for(i=0,j=2;i<info->partitions;i++){
  113767. int classx=info->partitionclass[i];
  113768. int cdim=info->class_dim[classx];
  113769. int csubbits=info->class_subs[classx];
  113770. int csub=1<<csubbits;
  113771. int bookas[8]={0,0,0,0,0,0,0,0};
  113772. int cval=0;
  113773. int cshift=0;
  113774. int k,l;
  113775. /* generate the partition's first stage cascade value */
  113776. if(csubbits){
  113777. int maxval[8];
  113778. for(k=0;k<csub;k++){
  113779. int booknum=info->class_subbook[classx][k];
  113780. if(booknum<0){
  113781. maxval[k]=1;
  113782. }else{
  113783. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113784. }
  113785. }
  113786. for(k=0;k<cdim;k++){
  113787. for(l=0;l<csub;l++){
  113788. int val=out[j+k];
  113789. if(val<maxval[l]){
  113790. bookas[k]=l;
  113791. break;
  113792. }
  113793. }
  113794. cval|= bookas[k]<<cshift;
  113795. cshift+=csubbits;
  113796. }
  113797. /* write it */
  113798. look->phrasebits+=
  113799. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113800. #ifdef TRAIN_FLOOR1
  113801. {
  113802. FILE *of;
  113803. char buffer[80];
  113804. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113805. vb->pcmend/2,posts-2,class);
  113806. of=fopen(buffer,"a");
  113807. fprintf(of,"%d\n",cval);
  113808. fclose(of);
  113809. }
  113810. #endif
  113811. }
  113812. /* write post values */
  113813. for(k=0;k<cdim;k++){
  113814. int book=info->class_subbook[classx][bookas[k]];
  113815. if(book>=0){
  113816. /* hack to allow training with 'bad' books */
  113817. if(out[j+k]<(books+book)->entries)
  113818. look->postbits+=vorbis_book_encode(books+book,
  113819. out[j+k],opb);
  113820. /*else
  113821. fprintf(stderr,"+!");*/
  113822. #ifdef TRAIN_FLOOR1
  113823. {
  113824. FILE *of;
  113825. char buffer[80];
  113826. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113827. vb->pcmend/2,posts-2,class,bookas[k]);
  113828. of=fopen(buffer,"a");
  113829. fprintf(of,"%d\n",out[j+k]);
  113830. fclose(of);
  113831. }
  113832. #endif
  113833. }
  113834. }
  113835. j+=cdim;
  113836. }
  113837. {
  113838. /* generate quantized floor equivalent to what we'd unpack in decode */
  113839. /* render the lines */
  113840. int hx=0;
  113841. int lx=0;
  113842. int ly=post[0]*info->mult;
  113843. for(j=1;j<look->posts;j++){
  113844. int current=look->forward_index[j];
  113845. int hy=post[current]&0x7fff;
  113846. if(hy==post[current]){
  113847. hy*=info->mult;
  113848. hx=info->postlist[current];
  113849. render_line0(lx,hx,ly,hy,ilogmask);
  113850. lx=hx;
  113851. ly=hy;
  113852. }
  113853. }
  113854. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113855. seq++;
  113856. return(1);
  113857. }
  113858. }else{
  113859. oggpack_write(opb,0,1);
  113860. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113861. seq++;
  113862. return(0);
  113863. }
  113864. }
  113865. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113866. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113867. vorbis_info_floor1 *info=look->vi;
  113868. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113869. int i,j,k;
  113870. codebook *books=ci->fullbooks;
  113871. /* unpack wrapped/predicted values from stream */
  113872. if(oggpack_read(&vb->opb,1)==1){
  113873. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113874. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113875. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113876. /* partition by partition */
  113877. for(i=0,j=2;i<info->partitions;i++){
  113878. int classx=info->partitionclass[i];
  113879. int cdim=info->class_dim[classx];
  113880. int csubbits=info->class_subs[classx];
  113881. int csub=1<<csubbits;
  113882. int cval=0;
  113883. /* decode the partition's first stage cascade value */
  113884. if(csubbits){
  113885. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113886. if(cval==-1)goto eop;
  113887. }
  113888. for(k=0;k<cdim;k++){
  113889. int book=info->class_subbook[classx][cval&(csub-1)];
  113890. cval>>=csubbits;
  113891. if(book>=0){
  113892. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113893. goto eop;
  113894. }else{
  113895. fit_value[j+k]=0;
  113896. }
  113897. }
  113898. j+=cdim;
  113899. }
  113900. /* unwrap positive values and reconsitute via linear interpolation */
  113901. for(i=2;i<look->posts;i++){
  113902. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113903. info->postlist[look->hineighbor[i-2]],
  113904. fit_value[look->loneighbor[i-2]],
  113905. fit_value[look->hineighbor[i-2]],
  113906. info->postlist[i]);
  113907. int hiroom=look->quant_q-predicted;
  113908. int loroom=predicted;
  113909. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113910. int val=fit_value[i];
  113911. if(val){
  113912. if(val>=room){
  113913. if(hiroom>loroom){
  113914. val = val-loroom;
  113915. }else{
  113916. val = -1-(val-hiroom);
  113917. }
  113918. }else{
  113919. if(val&1){
  113920. val= -((val+1)>>1);
  113921. }else{
  113922. val>>=1;
  113923. }
  113924. }
  113925. fit_value[i]=val+predicted;
  113926. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113927. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113928. }else{
  113929. fit_value[i]=predicted|0x8000;
  113930. }
  113931. }
  113932. return(fit_value);
  113933. }
  113934. eop:
  113935. return(NULL);
  113936. }
  113937. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113938. float *out){
  113939. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113940. vorbis_info_floor1 *info=look->vi;
  113941. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113942. int n=ci->blocksizes[vb->W]/2;
  113943. int j;
  113944. if(memo){
  113945. /* render the lines */
  113946. int *fit_value=(int *)memo;
  113947. int hx=0;
  113948. int lx=0;
  113949. int ly=fit_value[0]*info->mult;
  113950. for(j=1;j<look->posts;j++){
  113951. int current=look->forward_index[j];
  113952. int hy=fit_value[current]&0x7fff;
  113953. if(hy==fit_value[current]){
  113954. hy*=info->mult;
  113955. hx=info->postlist[current];
  113956. render_line(lx,hx,ly,hy,out);
  113957. lx=hx;
  113958. ly=hy;
  113959. }
  113960. }
  113961. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113962. return(1);
  113963. }
  113964. memset(out,0,sizeof(*out)*n);
  113965. return(0);
  113966. }
  113967. /* export hooks */
  113968. vorbis_func_floor floor1_exportbundle={
  113969. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113970. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113971. };
  113972. #endif
  113973. /*** End of inlined file: floor1.c ***/
  113974. /*** Start of inlined file: info.c ***/
  113975. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113976. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113977. // tasks..
  113978. #if JUCE_MSVC
  113979. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113980. #endif
  113981. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113982. #if JUCE_USE_OGGVORBIS
  113983. /* general handling of the header and the vorbis_info structure (and
  113984. substructures) */
  113985. #include <stdlib.h>
  113986. #include <string.h>
  113987. #include <ctype.h>
  113988. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113989. while(bytes--){
  113990. oggpack_write(o,*s++,8);
  113991. }
  113992. }
  113993. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113994. while(bytes--){
  113995. *buf++=oggpack_read(o,8);
  113996. }
  113997. }
  113998. void vorbis_comment_init(vorbis_comment *vc){
  113999. memset(vc,0,sizeof(*vc));
  114000. }
  114001. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  114002. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  114003. (vc->comments+2)*sizeof(*vc->user_comments));
  114004. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  114005. (vc->comments+2)*sizeof(*vc->comment_lengths));
  114006. vc->comment_lengths[vc->comments]=strlen(comment);
  114007. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  114008. strcpy(vc->user_comments[vc->comments], comment);
  114009. vc->comments++;
  114010. vc->user_comments[vc->comments]=NULL;
  114011. }
  114012. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  114013. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  114014. strcpy(comment, tag);
  114015. strcat(comment, "=");
  114016. strcat(comment, contents);
  114017. vorbis_comment_add(vc, comment);
  114018. }
  114019. /* This is more or less the same as strncasecmp - but that doesn't exist
  114020. * everywhere, and this is a fairly trivial function, so we include it */
  114021. static int tagcompare(const char *s1, const char *s2, int n){
  114022. int c=0;
  114023. while(c < n){
  114024. if(toupper(s1[c]) != toupper(s2[c]))
  114025. return !0;
  114026. c++;
  114027. }
  114028. return 0;
  114029. }
  114030. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  114031. long i;
  114032. int found = 0;
  114033. int taglen = strlen(tag)+1; /* +1 for the = we append */
  114034. char *fulltag = (char*)alloca(taglen+ 1);
  114035. strcpy(fulltag, tag);
  114036. strcat(fulltag, "=");
  114037. for(i=0;i<vc->comments;i++){
  114038. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  114039. if(count == found)
  114040. /* We return a pointer to the data, not a copy */
  114041. return vc->user_comments[i] + taglen;
  114042. else
  114043. found++;
  114044. }
  114045. }
  114046. return NULL; /* didn't find anything */
  114047. }
  114048. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  114049. int i,count=0;
  114050. int taglen = strlen(tag)+1; /* +1 for the = we append */
  114051. char *fulltag = (char*)alloca(taglen+1);
  114052. strcpy(fulltag,tag);
  114053. strcat(fulltag, "=");
  114054. for(i=0;i<vc->comments;i++){
  114055. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  114056. count++;
  114057. }
  114058. return count;
  114059. }
  114060. void vorbis_comment_clear(vorbis_comment *vc){
  114061. if(vc){
  114062. long i;
  114063. for(i=0;i<vc->comments;i++)
  114064. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  114065. if(vc->user_comments)_ogg_free(vc->user_comments);
  114066. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  114067. if(vc->vendor)_ogg_free(vc->vendor);
  114068. }
  114069. memset(vc,0,sizeof(*vc));
  114070. }
  114071. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  114072. They may be equal, but short will never ge greater than long */
  114073. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  114074. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  114075. return ci ? ci->blocksizes[zo] : -1;
  114076. }
  114077. /* used by synthesis, which has a full, alloced vi */
  114078. void vorbis_info_init(vorbis_info *vi){
  114079. memset(vi,0,sizeof(*vi));
  114080. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  114081. }
  114082. void vorbis_info_clear(vorbis_info *vi){
  114083. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114084. int i;
  114085. if(ci){
  114086. for(i=0;i<ci->modes;i++)
  114087. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  114088. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  114089. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  114090. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  114091. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  114092. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  114093. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  114094. for(i=0;i<ci->books;i++){
  114095. if(ci->book_param[i]){
  114096. /* knows if the book was not alloced */
  114097. vorbis_staticbook_destroy(ci->book_param[i]);
  114098. }
  114099. if(ci->fullbooks)
  114100. vorbis_book_clear(ci->fullbooks+i);
  114101. }
  114102. if(ci->fullbooks)
  114103. _ogg_free(ci->fullbooks);
  114104. for(i=0;i<ci->psys;i++)
  114105. _vi_psy_free(ci->psy_param[i]);
  114106. _ogg_free(ci);
  114107. }
  114108. memset(vi,0,sizeof(*vi));
  114109. }
  114110. /* Header packing/unpacking ********************************************/
  114111. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  114112. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114113. if(!ci)return(OV_EFAULT);
  114114. vi->version=oggpack_read(opb,32);
  114115. if(vi->version!=0)return(OV_EVERSION);
  114116. vi->channels=oggpack_read(opb,8);
  114117. vi->rate=oggpack_read(opb,32);
  114118. vi->bitrate_upper=oggpack_read(opb,32);
  114119. vi->bitrate_nominal=oggpack_read(opb,32);
  114120. vi->bitrate_lower=oggpack_read(opb,32);
  114121. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  114122. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  114123. if(vi->rate<1)goto err_out;
  114124. if(vi->channels<1)goto err_out;
  114125. if(ci->blocksizes[0]<8)goto err_out;
  114126. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  114127. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114128. return(0);
  114129. err_out:
  114130. vorbis_info_clear(vi);
  114131. return(OV_EBADHEADER);
  114132. }
  114133. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  114134. int i;
  114135. int vendorlen=oggpack_read(opb,32);
  114136. if(vendorlen<0)goto err_out;
  114137. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  114138. _v_readstring(opb,vc->vendor,vendorlen);
  114139. vc->comments=oggpack_read(opb,32);
  114140. if(vc->comments<0)goto err_out;
  114141. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  114142. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  114143. for(i=0;i<vc->comments;i++){
  114144. int len=oggpack_read(opb,32);
  114145. if(len<0)goto err_out;
  114146. vc->comment_lengths[i]=len;
  114147. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  114148. _v_readstring(opb,vc->user_comments[i],len);
  114149. }
  114150. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114151. return(0);
  114152. err_out:
  114153. vorbis_comment_clear(vc);
  114154. return(OV_EBADHEADER);
  114155. }
  114156. /* all of the real encoding details are here. The modes, books,
  114157. everything */
  114158. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  114159. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114160. int i;
  114161. if(!ci)return(OV_EFAULT);
  114162. /* codebooks */
  114163. ci->books=oggpack_read(opb,8)+1;
  114164. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  114165. for(i=0;i<ci->books;i++){
  114166. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  114167. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  114168. }
  114169. /* time backend settings; hooks are unused */
  114170. {
  114171. int times=oggpack_read(opb,6)+1;
  114172. for(i=0;i<times;i++){
  114173. int test=oggpack_read(opb,16);
  114174. if(test<0 || test>=VI_TIMEB)goto err_out;
  114175. }
  114176. }
  114177. /* floor backend settings */
  114178. ci->floors=oggpack_read(opb,6)+1;
  114179. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  114180. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  114181. for(i=0;i<ci->floors;i++){
  114182. ci->floor_type[i]=oggpack_read(opb,16);
  114183. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  114184. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114185. if(!ci->floor_param[i])goto err_out;
  114186. }
  114187. /* residue backend settings */
  114188. ci->residues=oggpack_read(opb,6)+1;
  114189. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114190. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114191. for(i=0;i<ci->residues;i++){
  114192. ci->residue_type[i]=oggpack_read(opb,16);
  114193. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114194. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114195. if(!ci->residue_param[i])goto err_out;
  114196. }
  114197. /* map backend settings */
  114198. ci->maps=oggpack_read(opb,6)+1;
  114199. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114200. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114201. for(i=0;i<ci->maps;i++){
  114202. ci->map_type[i]=oggpack_read(opb,16);
  114203. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114204. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114205. if(!ci->map_param[i])goto err_out;
  114206. }
  114207. /* mode settings */
  114208. ci->modes=oggpack_read(opb,6)+1;
  114209. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114210. for(i=0;i<ci->modes;i++){
  114211. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114212. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114213. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114214. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114215. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114216. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114217. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114218. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114219. }
  114220. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114221. return(0);
  114222. err_out:
  114223. vorbis_info_clear(vi);
  114224. return(OV_EBADHEADER);
  114225. }
  114226. /* The Vorbis header is in three packets; the initial small packet in
  114227. the first page that identifies basic parameters, a second packet
  114228. with bitstream comments and a third packet that holds the
  114229. codebook. */
  114230. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114231. oggpack_buffer opb;
  114232. if(op){
  114233. oggpack_readinit(&opb,op->packet,op->bytes);
  114234. /* Which of the three types of header is this? */
  114235. /* Also verify header-ness, vorbis */
  114236. {
  114237. char buffer[6];
  114238. int packtype=oggpack_read(&opb,8);
  114239. memset(buffer,0,6);
  114240. _v_readstring(&opb,buffer,6);
  114241. if(memcmp(buffer,"vorbis",6)){
  114242. /* not a vorbis header */
  114243. return(OV_ENOTVORBIS);
  114244. }
  114245. switch(packtype){
  114246. case 0x01: /* least significant *bit* is read first */
  114247. if(!op->b_o_s){
  114248. /* Not the initial packet */
  114249. return(OV_EBADHEADER);
  114250. }
  114251. if(vi->rate!=0){
  114252. /* previously initialized info header */
  114253. return(OV_EBADHEADER);
  114254. }
  114255. return(_vorbis_unpack_info(vi,&opb));
  114256. case 0x03: /* least significant *bit* is read first */
  114257. if(vi->rate==0){
  114258. /* um... we didn't get the initial header */
  114259. return(OV_EBADHEADER);
  114260. }
  114261. return(_vorbis_unpack_comment(vc,&opb));
  114262. case 0x05: /* least significant *bit* is read first */
  114263. if(vi->rate==0 || vc->vendor==NULL){
  114264. /* um... we didn;t get the initial header or comments yet */
  114265. return(OV_EBADHEADER);
  114266. }
  114267. return(_vorbis_unpack_books(vi,&opb));
  114268. default:
  114269. /* Not a valid vorbis header type */
  114270. return(OV_EBADHEADER);
  114271. break;
  114272. }
  114273. }
  114274. }
  114275. return(OV_EBADHEADER);
  114276. }
  114277. /* pack side **********************************************************/
  114278. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114279. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114280. if(!ci)return(OV_EFAULT);
  114281. /* preamble */
  114282. oggpack_write(opb,0x01,8);
  114283. _v_writestring(opb,"vorbis", 6);
  114284. /* basic information about the stream */
  114285. oggpack_write(opb,0x00,32);
  114286. oggpack_write(opb,vi->channels,8);
  114287. oggpack_write(opb,vi->rate,32);
  114288. oggpack_write(opb,vi->bitrate_upper,32);
  114289. oggpack_write(opb,vi->bitrate_nominal,32);
  114290. oggpack_write(opb,vi->bitrate_lower,32);
  114291. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114292. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114293. oggpack_write(opb,1,1);
  114294. return(0);
  114295. }
  114296. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114297. char temp[]="Xiph.Org libVorbis I 20050304";
  114298. int bytes = strlen(temp);
  114299. /* preamble */
  114300. oggpack_write(opb,0x03,8);
  114301. _v_writestring(opb,"vorbis", 6);
  114302. /* vendor */
  114303. oggpack_write(opb,bytes,32);
  114304. _v_writestring(opb,temp, bytes);
  114305. /* comments */
  114306. oggpack_write(opb,vc->comments,32);
  114307. if(vc->comments){
  114308. int i;
  114309. for(i=0;i<vc->comments;i++){
  114310. if(vc->user_comments[i]){
  114311. oggpack_write(opb,vc->comment_lengths[i],32);
  114312. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114313. }else{
  114314. oggpack_write(opb,0,32);
  114315. }
  114316. }
  114317. }
  114318. oggpack_write(opb,1,1);
  114319. return(0);
  114320. }
  114321. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114322. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114323. int i;
  114324. if(!ci)return(OV_EFAULT);
  114325. oggpack_write(opb,0x05,8);
  114326. _v_writestring(opb,"vorbis", 6);
  114327. /* books */
  114328. oggpack_write(opb,ci->books-1,8);
  114329. for(i=0;i<ci->books;i++)
  114330. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114331. /* times; hook placeholders */
  114332. oggpack_write(opb,0,6);
  114333. oggpack_write(opb,0,16);
  114334. /* floors */
  114335. oggpack_write(opb,ci->floors-1,6);
  114336. for(i=0;i<ci->floors;i++){
  114337. oggpack_write(opb,ci->floor_type[i],16);
  114338. if(_floor_P[ci->floor_type[i]]->pack)
  114339. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114340. else
  114341. goto err_out;
  114342. }
  114343. /* residues */
  114344. oggpack_write(opb,ci->residues-1,6);
  114345. for(i=0;i<ci->residues;i++){
  114346. oggpack_write(opb,ci->residue_type[i],16);
  114347. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114348. }
  114349. /* maps */
  114350. oggpack_write(opb,ci->maps-1,6);
  114351. for(i=0;i<ci->maps;i++){
  114352. oggpack_write(opb,ci->map_type[i],16);
  114353. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114354. }
  114355. /* modes */
  114356. oggpack_write(opb,ci->modes-1,6);
  114357. for(i=0;i<ci->modes;i++){
  114358. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114359. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114360. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114361. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114362. }
  114363. oggpack_write(opb,1,1);
  114364. return(0);
  114365. err_out:
  114366. return(-1);
  114367. }
  114368. int vorbis_commentheader_out(vorbis_comment *vc,
  114369. ogg_packet *op){
  114370. oggpack_buffer opb;
  114371. oggpack_writeinit(&opb);
  114372. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114373. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114374. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114375. op->bytes=oggpack_bytes(&opb);
  114376. op->b_o_s=0;
  114377. op->e_o_s=0;
  114378. op->granulepos=0;
  114379. op->packetno=1;
  114380. return 0;
  114381. }
  114382. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114383. vorbis_comment *vc,
  114384. ogg_packet *op,
  114385. ogg_packet *op_comm,
  114386. ogg_packet *op_code){
  114387. int ret=OV_EIMPL;
  114388. vorbis_info *vi=v->vi;
  114389. oggpack_buffer opb;
  114390. private_state *b=(private_state*)v->backend_state;
  114391. if(!b){
  114392. ret=OV_EFAULT;
  114393. goto err_out;
  114394. }
  114395. /* first header packet **********************************************/
  114396. oggpack_writeinit(&opb);
  114397. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114398. /* build the packet */
  114399. if(b->header)_ogg_free(b->header);
  114400. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114401. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114402. op->packet=b->header;
  114403. op->bytes=oggpack_bytes(&opb);
  114404. op->b_o_s=1;
  114405. op->e_o_s=0;
  114406. op->granulepos=0;
  114407. op->packetno=0;
  114408. /* second header packet (comments) **********************************/
  114409. oggpack_reset(&opb);
  114410. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114411. if(b->header1)_ogg_free(b->header1);
  114412. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114413. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114414. op_comm->packet=b->header1;
  114415. op_comm->bytes=oggpack_bytes(&opb);
  114416. op_comm->b_o_s=0;
  114417. op_comm->e_o_s=0;
  114418. op_comm->granulepos=0;
  114419. op_comm->packetno=1;
  114420. /* third header packet (modes/codebooks) ****************************/
  114421. oggpack_reset(&opb);
  114422. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114423. if(b->header2)_ogg_free(b->header2);
  114424. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114425. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114426. op_code->packet=b->header2;
  114427. op_code->bytes=oggpack_bytes(&opb);
  114428. op_code->b_o_s=0;
  114429. op_code->e_o_s=0;
  114430. op_code->granulepos=0;
  114431. op_code->packetno=2;
  114432. oggpack_writeclear(&opb);
  114433. return(0);
  114434. err_out:
  114435. oggpack_writeclear(&opb);
  114436. memset(op,0,sizeof(*op));
  114437. memset(op_comm,0,sizeof(*op_comm));
  114438. memset(op_code,0,sizeof(*op_code));
  114439. if(b->header)_ogg_free(b->header);
  114440. if(b->header1)_ogg_free(b->header1);
  114441. if(b->header2)_ogg_free(b->header2);
  114442. b->header=NULL;
  114443. b->header1=NULL;
  114444. b->header2=NULL;
  114445. return(ret);
  114446. }
  114447. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114448. if(granulepos>=0)
  114449. return((double)granulepos/v->vi->rate);
  114450. return(-1);
  114451. }
  114452. #endif
  114453. /*** End of inlined file: info.c ***/
  114454. /*** Start of inlined file: lpc.c ***/
  114455. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114456. are derived from code written by Jutta Degener and Carsten Bormann;
  114457. thus we include their copyright below. The entirety of this file
  114458. is freely redistributable on the condition that both of these
  114459. copyright notices are preserved without modification. */
  114460. /* Preserved Copyright: *********************************************/
  114461. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114462. Technische Universita"t Berlin
  114463. Any use of this software is permitted provided that this notice is not
  114464. removed and that neither the authors nor the Technische Universita"t
  114465. Berlin are deemed to have made any representations as to the
  114466. suitability of this software for any purpose nor are held responsible
  114467. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114468. THIS SOFTWARE.
  114469. As a matter of courtesy, the authors request to be informed about uses
  114470. this software has found, about bugs in this software, and about any
  114471. improvements that may be of general interest.
  114472. Berlin, 28.11.1994
  114473. Jutta Degener
  114474. Carsten Bormann
  114475. *********************************************************************/
  114476. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114477. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114478. // tasks..
  114479. #if JUCE_MSVC
  114480. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114481. #endif
  114482. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114483. #if JUCE_USE_OGGVORBIS
  114484. #include <stdlib.h>
  114485. #include <string.h>
  114486. #include <math.h>
  114487. /* Autocorrelation LPC coeff generation algorithm invented by
  114488. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114489. /* Input : n elements of time doamin data
  114490. Output: m lpc coefficients, excitation energy */
  114491. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114492. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114493. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114494. double error;
  114495. int i,j;
  114496. /* autocorrelation, p+1 lag coefficients */
  114497. j=m+1;
  114498. while(j--){
  114499. double d=0; /* double needed for accumulator depth */
  114500. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114501. aut[j]=d;
  114502. }
  114503. /* Generate lpc coefficients from autocorr values */
  114504. error=aut[0];
  114505. for(i=0;i<m;i++){
  114506. double r= -aut[i+1];
  114507. if(error==0){
  114508. memset(lpci,0,m*sizeof(*lpci));
  114509. return 0;
  114510. }
  114511. /* Sum up this iteration's reflection coefficient; note that in
  114512. Vorbis we don't save it. If anyone wants to recycle this code
  114513. and needs reflection coefficients, save the results of 'r' from
  114514. each iteration. */
  114515. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114516. r/=error;
  114517. /* Update LPC coefficients and total error */
  114518. lpc[i]=r;
  114519. for(j=0;j<i/2;j++){
  114520. double tmp=lpc[j];
  114521. lpc[j]+=r*lpc[i-1-j];
  114522. lpc[i-1-j]+=r*tmp;
  114523. }
  114524. if(i%2)lpc[j]+=lpc[j]*r;
  114525. error*=1.f-r*r;
  114526. }
  114527. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114528. /* we need the error value to know how big an impulse to hit the
  114529. filter with later */
  114530. return error;
  114531. }
  114532. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114533. float *data,long n){
  114534. /* in: coeff[0...m-1] LPC coefficients
  114535. prime[0...m-1] initial values (allocated size of n+m-1)
  114536. out: data[0...n-1] data samples */
  114537. long i,j,o,p;
  114538. float y;
  114539. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114540. if(!prime)
  114541. for(i=0;i<m;i++)
  114542. work[i]=0.f;
  114543. else
  114544. for(i=0;i<m;i++)
  114545. work[i]=prime[i];
  114546. for(i=0;i<n;i++){
  114547. y=0;
  114548. o=i;
  114549. p=m;
  114550. for(j=0;j<m;j++)
  114551. y-=work[o++]*coeff[--p];
  114552. data[i]=work[o]=y;
  114553. }
  114554. }
  114555. #endif
  114556. /*** End of inlined file: lpc.c ***/
  114557. /*** Start of inlined file: lsp.c ***/
  114558. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114559. an iterative root polisher (CACM algorithm 283). It *is* possible
  114560. to confuse this algorithm into not converging; that should only
  114561. happen with absurdly closely spaced roots (very sharp peaks in the
  114562. LPC f response) which in turn should be impossible in our use of
  114563. the code. If this *does* happen anyway, it's a bug in the floor
  114564. finder; find the cause of the confusion (probably a single bin
  114565. spike or accidental near-float-limit resolution problems) and
  114566. correct it. */
  114567. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114568. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114569. // tasks..
  114570. #if JUCE_MSVC
  114571. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114572. #endif
  114573. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114574. #if JUCE_USE_OGGVORBIS
  114575. #include <math.h>
  114576. #include <string.h>
  114577. #include <stdlib.h>
  114578. /*** Start of inlined file: lookup.h ***/
  114579. #ifndef _V_LOOKUP_H_
  114580. #ifdef FLOAT_LOOKUP
  114581. extern float vorbis_coslook(float a);
  114582. extern float vorbis_invsqlook(float a);
  114583. extern float vorbis_invsq2explook(int a);
  114584. extern float vorbis_fromdBlook(float a);
  114585. #endif
  114586. #ifdef INT_LOOKUP
  114587. extern long vorbis_invsqlook_i(long a,long e);
  114588. extern long vorbis_coslook_i(long a);
  114589. extern float vorbis_fromdBlook_i(long a);
  114590. #endif
  114591. #endif
  114592. /*** End of inlined file: lookup.h ***/
  114593. /* three possible LSP to f curve functions; the exact computation
  114594. (float), a lookup based float implementation, and an integer
  114595. implementation. The float lookup is likely the optimal choice on
  114596. any machine with an FPU. The integer implementation is *not* fixed
  114597. point (due to the need for a large dynamic range and thus a
  114598. seperately tracked exponent) and thus much more complex than the
  114599. relatively simple float implementations. It's mostly for future
  114600. work on a fully fixed point implementation for processors like the
  114601. ARM family. */
  114602. /* undefine both for the 'old' but more precise implementation */
  114603. #define FLOAT_LOOKUP
  114604. #undef INT_LOOKUP
  114605. #ifdef FLOAT_LOOKUP
  114606. /*** Start of inlined file: lookup.c ***/
  114607. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114608. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114609. // tasks..
  114610. #if JUCE_MSVC
  114611. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114612. #endif
  114613. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114614. #if JUCE_USE_OGGVORBIS
  114615. #include <math.h>
  114616. /*** Start of inlined file: lookup.h ***/
  114617. #ifndef _V_LOOKUP_H_
  114618. #ifdef FLOAT_LOOKUP
  114619. extern float vorbis_coslook(float a);
  114620. extern float vorbis_invsqlook(float a);
  114621. extern float vorbis_invsq2explook(int a);
  114622. extern float vorbis_fromdBlook(float a);
  114623. #endif
  114624. #ifdef INT_LOOKUP
  114625. extern long vorbis_invsqlook_i(long a,long e);
  114626. extern long vorbis_coslook_i(long a);
  114627. extern float vorbis_fromdBlook_i(long a);
  114628. #endif
  114629. #endif
  114630. /*** End of inlined file: lookup.h ***/
  114631. /*** Start of inlined file: lookup_data.h ***/
  114632. #ifndef _V_LOOKUP_DATA_H_
  114633. #ifdef FLOAT_LOOKUP
  114634. #define COS_LOOKUP_SZ 128
  114635. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114636. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114637. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114638. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114639. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114640. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114641. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114642. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114643. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114644. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114645. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114646. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114647. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114648. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114649. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114650. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114651. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114652. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114653. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114654. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114655. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114656. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114657. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114658. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114659. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114660. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114661. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114662. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114663. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114664. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114665. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114666. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114667. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114668. -1.0000000000000f,
  114669. };
  114670. #define INVSQ_LOOKUP_SZ 32
  114671. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114672. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114673. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114674. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114675. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114676. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114677. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114678. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114679. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114680. 1.000000000000f,
  114681. };
  114682. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114683. #define INVSQ2EXP_LOOKUP_MAX 32
  114684. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114685. INVSQ2EXP_LOOKUP_MIN+1]={
  114686. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114687. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114688. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114689. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114690. 256.f, 181.019336f, 128.f, 90.50966799f,
  114691. 64.f, 45.254834f, 32.f, 22.627417f,
  114692. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114693. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114694. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114695. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114696. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114697. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114698. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114699. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114700. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114701. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114702. 1.525878906e-05f,
  114703. };
  114704. #endif
  114705. #define FROMdB_LOOKUP_SZ 35
  114706. #define FROMdB2_LOOKUP_SZ 32
  114707. #define FROMdB_SHIFT 5
  114708. #define FROMdB2_SHIFT 3
  114709. #define FROMdB2_MASK 31
  114710. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114711. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114712. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114713. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114714. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114715. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114716. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114717. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114718. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114719. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114720. };
  114721. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114722. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114723. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114724. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114725. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114726. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114727. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114728. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114729. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114730. };
  114731. #ifdef INT_LOOKUP
  114732. #define INVSQ_LOOKUP_I_SHIFT 10
  114733. #define INVSQ_LOOKUP_I_MASK 1023
  114734. static long INVSQ_LOOKUP_I[64+1]={
  114735. 92682l, 91966l, 91267l, 90583l,
  114736. 89915l, 89261l, 88621l, 87995l,
  114737. 87381l, 86781l, 86192l, 85616l,
  114738. 85051l, 84497l, 83953l, 83420l,
  114739. 82897l, 82384l, 81880l, 81385l,
  114740. 80899l, 80422l, 79953l, 79492l,
  114741. 79039l, 78594l, 78156l, 77726l,
  114742. 77302l, 76885l, 76475l, 76072l,
  114743. 75674l, 75283l, 74898l, 74519l,
  114744. 74146l, 73778l, 73415l, 73058l,
  114745. 72706l, 72359l, 72016l, 71679l,
  114746. 71347l, 71019l, 70695l, 70376l,
  114747. 70061l, 69750l, 69444l, 69141l,
  114748. 68842l, 68548l, 68256l, 67969l,
  114749. 67685l, 67405l, 67128l, 66855l,
  114750. 66585l, 66318l, 66054l, 65794l,
  114751. 65536l,
  114752. };
  114753. #define COS_LOOKUP_I_SHIFT 9
  114754. #define COS_LOOKUP_I_MASK 511
  114755. #define COS_LOOKUP_I_SZ 128
  114756. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114757. 16384l, 16379l, 16364l, 16340l,
  114758. 16305l, 16261l, 16207l, 16143l,
  114759. 16069l, 15986l, 15893l, 15791l,
  114760. 15679l, 15557l, 15426l, 15286l,
  114761. 15137l, 14978l, 14811l, 14635l,
  114762. 14449l, 14256l, 14053l, 13842l,
  114763. 13623l, 13395l, 13160l, 12916l,
  114764. 12665l, 12406l, 12140l, 11866l,
  114765. 11585l, 11297l, 11003l, 10702l,
  114766. 10394l, 10080l, 9760l, 9434l,
  114767. 9102l, 8765l, 8423l, 8076l,
  114768. 7723l, 7366l, 7005l, 6639l,
  114769. 6270l, 5897l, 5520l, 5139l,
  114770. 4756l, 4370l, 3981l, 3590l,
  114771. 3196l, 2801l, 2404l, 2006l,
  114772. 1606l, 1205l, 804l, 402l,
  114773. 0l, -401l, -803l, -1204l,
  114774. -1605l, -2005l, -2403l, -2800l,
  114775. -3195l, -3589l, -3980l, -4369l,
  114776. -4755l, -5138l, -5519l, -5896l,
  114777. -6269l, -6638l, -7004l, -7365l,
  114778. -7722l, -8075l, -8422l, -8764l,
  114779. -9101l, -9433l, -9759l, -10079l,
  114780. -10393l, -10701l, -11002l, -11296l,
  114781. -11584l, -11865l, -12139l, -12405l,
  114782. -12664l, -12915l, -13159l, -13394l,
  114783. -13622l, -13841l, -14052l, -14255l,
  114784. -14448l, -14634l, -14810l, -14977l,
  114785. -15136l, -15285l, -15425l, -15556l,
  114786. -15678l, -15790l, -15892l, -15985l,
  114787. -16068l, -16142l, -16206l, -16260l,
  114788. -16304l, -16339l, -16363l, -16378l,
  114789. -16383l,
  114790. };
  114791. #endif
  114792. #endif
  114793. /*** End of inlined file: lookup_data.h ***/
  114794. #ifdef FLOAT_LOOKUP
  114795. /* interpolated lookup based cos function, domain 0 to PI only */
  114796. float vorbis_coslook(float a){
  114797. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114798. int i=vorbis_ftoi(d-.5);
  114799. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114800. }
  114801. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114802. float vorbis_invsqlook(float a){
  114803. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114804. int i=vorbis_ftoi(d-.5f);
  114805. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114806. }
  114807. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114808. float vorbis_invsq2explook(int a){
  114809. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114810. }
  114811. #include <stdio.h>
  114812. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114813. float vorbis_fromdBlook(float a){
  114814. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114815. return (i<0)?1.f:
  114816. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114817. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114818. }
  114819. #endif
  114820. #ifdef INT_LOOKUP
  114821. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114822. 16.16 format
  114823. returns in m.8 format */
  114824. long vorbis_invsqlook_i(long a,long e){
  114825. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114826. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114827. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114828. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114829. d)>>16); /* result 1.16 */
  114830. e+=32;
  114831. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114832. e=(e>>1)-8;
  114833. return(val>>e);
  114834. }
  114835. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114836. /* a is in n.12 format */
  114837. float vorbis_fromdBlook_i(long a){
  114838. int i=(-a)>>(12-FROMdB2_SHIFT);
  114839. return (i<0)?1.f:
  114840. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114841. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114842. }
  114843. /* interpolated lookup based cos function, domain 0 to PI only */
  114844. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114845. long vorbis_coslook_i(long a){
  114846. int i=a>>COS_LOOKUP_I_SHIFT;
  114847. int d=a&COS_LOOKUP_I_MASK;
  114848. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114849. COS_LOOKUP_I_SHIFT);
  114850. }
  114851. #endif
  114852. #endif
  114853. /*** End of inlined file: lookup.c ***/
  114854. /* catch this in the build system; we #include for
  114855. compilers (like gcc) that can't inline across
  114856. modules */
  114857. /* side effect: changes *lsp to cosines of lsp */
  114858. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114859. float amp,float ampoffset){
  114860. int i;
  114861. float wdel=M_PI/ln;
  114862. vorbis_fpu_control fpu;
  114863. (void) fpu; // to avoid an unused variable warning
  114864. vorbis_fpu_setround(&fpu);
  114865. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114866. i=0;
  114867. while(i<n){
  114868. int k=map[i];
  114869. int qexp;
  114870. float p=.7071067812f;
  114871. float q=.7071067812f;
  114872. float w=vorbis_coslook(wdel*k);
  114873. float *ftmp=lsp;
  114874. int c=m>>1;
  114875. do{
  114876. q*=ftmp[0]-w;
  114877. p*=ftmp[1]-w;
  114878. ftmp+=2;
  114879. }while(--c);
  114880. if(m&1){
  114881. /* odd order filter; slightly assymetric */
  114882. /* the last coefficient */
  114883. q*=ftmp[0]-w;
  114884. q*=q;
  114885. p*=p*(1.f-w*w);
  114886. }else{
  114887. /* even order filter; still symmetric */
  114888. q*=q*(1.f+w);
  114889. p*=p*(1.f-w);
  114890. }
  114891. q=frexp(p+q,&qexp);
  114892. q=vorbis_fromdBlook(amp*
  114893. vorbis_invsqlook(q)*
  114894. vorbis_invsq2explook(qexp+m)-
  114895. ampoffset);
  114896. do{
  114897. curve[i++]*=q;
  114898. }while(map[i]==k);
  114899. }
  114900. vorbis_fpu_restore(fpu);
  114901. }
  114902. #else
  114903. #ifdef INT_LOOKUP
  114904. /*** Start of inlined file: lookup.c ***/
  114905. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114906. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114907. // tasks..
  114908. #if JUCE_MSVC
  114909. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114910. #endif
  114911. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114912. #if JUCE_USE_OGGVORBIS
  114913. #include <math.h>
  114914. /*** Start of inlined file: lookup.h ***/
  114915. #ifndef _V_LOOKUP_H_
  114916. #ifdef FLOAT_LOOKUP
  114917. extern float vorbis_coslook(float a);
  114918. extern float vorbis_invsqlook(float a);
  114919. extern float vorbis_invsq2explook(int a);
  114920. extern float vorbis_fromdBlook(float a);
  114921. #endif
  114922. #ifdef INT_LOOKUP
  114923. extern long vorbis_invsqlook_i(long a,long e);
  114924. extern long vorbis_coslook_i(long a);
  114925. extern float vorbis_fromdBlook_i(long a);
  114926. #endif
  114927. #endif
  114928. /*** End of inlined file: lookup.h ***/
  114929. /*** Start of inlined file: lookup_data.h ***/
  114930. #ifndef _V_LOOKUP_DATA_H_
  114931. #ifdef FLOAT_LOOKUP
  114932. #define COS_LOOKUP_SZ 128
  114933. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114934. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114935. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114936. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114937. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114938. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114939. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114940. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114941. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114942. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114943. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114944. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114945. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114946. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114947. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114948. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114949. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114950. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114951. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114952. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114953. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114954. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114955. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114956. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114957. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114958. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114959. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114960. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114961. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114962. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114963. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114964. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114965. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114966. -1.0000000000000f,
  114967. };
  114968. #define INVSQ_LOOKUP_SZ 32
  114969. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114970. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114971. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114972. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114973. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114974. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114975. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114976. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114977. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114978. 1.000000000000f,
  114979. };
  114980. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114981. #define INVSQ2EXP_LOOKUP_MAX 32
  114982. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114983. INVSQ2EXP_LOOKUP_MIN+1]={
  114984. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114985. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114986. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114987. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114988. 256.f, 181.019336f, 128.f, 90.50966799f,
  114989. 64.f, 45.254834f, 32.f, 22.627417f,
  114990. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114991. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114992. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114993. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114994. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114995. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114996. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114997. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114998. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114999. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  115000. 1.525878906e-05f,
  115001. };
  115002. #endif
  115003. #define FROMdB_LOOKUP_SZ 35
  115004. #define FROMdB2_LOOKUP_SZ 32
  115005. #define FROMdB_SHIFT 5
  115006. #define FROMdB2_SHIFT 3
  115007. #define FROMdB2_MASK 31
  115008. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  115009. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  115010. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  115011. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  115012. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  115013. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  115014. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  115015. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  115016. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  115017. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  115018. };
  115019. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  115020. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  115021. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  115022. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  115023. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  115024. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  115025. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  115026. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  115027. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  115028. };
  115029. #ifdef INT_LOOKUP
  115030. #define INVSQ_LOOKUP_I_SHIFT 10
  115031. #define INVSQ_LOOKUP_I_MASK 1023
  115032. static long INVSQ_LOOKUP_I[64+1]={
  115033. 92682l, 91966l, 91267l, 90583l,
  115034. 89915l, 89261l, 88621l, 87995l,
  115035. 87381l, 86781l, 86192l, 85616l,
  115036. 85051l, 84497l, 83953l, 83420l,
  115037. 82897l, 82384l, 81880l, 81385l,
  115038. 80899l, 80422l, 79953l, 79492l,
  115039. 79039l, 78594l, 78156l, 77726l,
  115040. 77302l, 76885l, 76475l, 76072l,
  115041. 75674l, 75283l, 74898l, 74519l,
  115042. 74146l, 73778l, 73415l, 73058l,
  115043. 72706l, 72359l, 72016l, 71679l,
  115044. 71347l, 71019l, 70695l, 70376l,
  115045. 70061l, 69750l, 69444l, 69141l,
  115046. 68842l, 68548l, 68256l, 67969l,
  115047. 67685l, 67405l, 67128l, 66855l,
  115048. 66585l, 66318l, 66054l, 65794l,
  115049. 65536l,
  115050. };
  115051. #define COS_LOOKUP_I_SHIFT 9
  115052. #define COS_LOOKUP_I_MASK 511
  115053. #define COS_LOOKUP_I_SZ 128
  115054. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  115055. 16384l, 16379l, 16364l, 16340l,
  115056. 16305l, 16261l, 16207l, 16143l,
  115057. 16069l, 15986l, 15893l, 15791l,
  115058. 15679l, 15557l, 15426l, 15286l,
  115059. 15137l, 14978l, 14811l, 14635l,
  115060. 14449l, 14256l, 14053l, 13842l,
  115061. 13623l, 13395l, 13160l, 12916l,
  115062. 12665l, 12406l, 12140l, 11866l,
  115063. 11585l, 11297l, 11003l, 10702l,
  115064. 10394l, 10080l, 9760l, 9434l,
  115065. 9102l, 8765l, 8423l, 8076l,
  115066. 7723l, 7366l, 7005l, 6639l,
  115067. 6270l, 5897l, 5520l, 5139l,
  115068. 4756l, 4370l, 3981l, 3590l,
  115069. 3196l, 2801l, 2404l, 2006l,
  115070. 1606l, 1205l, 804l, 402l,
  115071. 0l, -401l, -803l, -1204l,
  115072. -1605l, -2005l, -2403l, -2800l,
  115073. -3195l, -3589l, -3980l, -4369l,
  115074. -4755l, -5138l, -5519l, -5896l,
  115075. -6269l, -6638l, -7004l, -7365l,
  115076. -7722l, -8075l, -8422l, -8764l,
  115077. -9101l, -9433l, -9759l, -10079l,
  115078. -10393l, -10701l, -11002l, -11296l,
  115079. -11584l, -11865l, -12139l, -12405l,
  115080. -12664l, -12915l, -13159l, -13394l,
  115081. -13622l, -13841l, -14052l, -14255l,
  115082. -14448l, -14634l, -14810l, -14977l,
  115083. -15136l, -15285l, -15425l, -15556l,
  115084. -15678l, -15790l, -15892l, -15985l,
  115085. -16068l, -16142l, -16206l, -16260l,
  115086. -16304l, -16339l, -16363l, -16378l,
  115087. -16383l,
  115088. };
  115089. #endif
  115090. #endif
  115091. /*** End of inlined file: lookup_data.h ***/
  115092. #ifdef FLOAT_LOOKUP
  115093. /* interpolated lookup based cos function, domain 0 to PI only */
  115094. float vorbis_coslook(float a){
  115095. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  115096. int i=vorbis_ftoi(d-.5);
  115097. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  115098. }
  115099. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115100. float vorbis_invsqlook(float a){
  115101. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  115102. int i=vorbis_ftoi(d-.5f);
  115103. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  115104. }
  115105. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115106. float vorbis_invsq2explook(int a){
  115107. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  115108. }
  115109. #include <stdio.h>
  115110. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115111. float vorbis_fromdBlook(float a){
  115112. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  115113. return (i<0)?1.f:
  115114. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115115. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115116. }
  115117. #endif
  115118. #ifdef INT_LOOKUP
  115119. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  115120. 16.16 format
  115121. returns in m.8 format */
  115122. long vorbis_invsqlook_i(long a,long e){
  115123. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  115124. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  115125. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  115126. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  115127. d)>>16); /* result 1.16 */
  115128. e+=32;
  115129. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  115130. e=(e>>1)-8;
  115131. return(val>>e);
  115132. }
  115133. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115134. /* a is in n.12 format */
  115135. float vorbis_fromdBlook_i(long a){
  115136. int i=(-a)>>(12-FROMdB2_SHIFT);
  115137. return (i<0)?1.f:
  115138. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115139. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115140. }
  115141. /* interpolated lookup based cos function, domain 0 to PI only */
  115142. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  115143. long vorbis_coslook_i(long a){
  115144. int i=a>>COS_LOOKUP_I_SHIFT;
  115145. int d=a&COS_LOOKUP_I_MASK;
  115146. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  115147. COS_LOOKUP_I_SHIFT);
  115148. }
  115149. #endif
  115150. #endif
  115151. /*** End of inlined file: lookup.c ***/
  115152. /* catch this in the build system; we #include for
  115153. compilers (like gcc) that can't inline across
  115154. modules */
  115155. static int MLOOP_1[64]={
  115156. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  115157. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  115158. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115159. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115160. };
  115161. static int MLOOP_2[64]={
  115162. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  115163. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  115164. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115165. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115166. };
  115167. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  115168. /* side effect: changes *lsp to cosines of lsp */
  115169. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115170. float amp,float ampoffset){
  115171. /* 0 <= m < 256 */
  115172. /* set up for using all int later */
  115173. int i;
  115174. int ampoffseti=rint(ampoffset*4096.f);
  115175. int ampi=rint(amp*16.f);
  115176. long *ilsp=alloca(m*sizeof(*ilsp));
  115177. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  115178. i=0;
  115179. while(i<n){
  115180. int j,k=map[i];
  115181. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  115182. unsigned long qi=46341;
  115183. int qexp=0,shift;
  115184. long wi=vorbis_coslook_i(k*65536/ln);
  115185. qi*=labs(ilsp[0]-wi);
  115186. pi*=labs(ilsp[1]-wi);
  115187. for(j=3;j<m;j+=2){
  115188. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115189. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115190. shift=MLOOP_3[(pi|qi)>>16];
  115191. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115192. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115193. qexp+=shift;
  115194. }
  115195. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115196. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115197. shift=MLOOP_3[(pi|qi)>>16];
  115198. /* pi,qi normalized collectively, both tracked using qexp */
  115199. if(m&1){
  115200. /* odd order filter; slightly assymetric */
  115201. /* the last coefficient */
  115202. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115203. pi=(pi>>shift)<<14;
  115204. qexp+=shift;
  115205. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115206. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115207. shift=MLOOP_3[(pi|qi)>>16];
  115208. pi>>=shift;
  115209. qi>>=shift;
  115210. qexp+=shift-14*((m+1)>>1);
  115211. pi=((pi*pi)>>16);
  115212. qi=((qi*qi)>>16);
  115213. qexp=qexp*2+m;
  115214. pi*=(1<<14)-((wi*wi)>>14);
  115215. qi+=pi>>14;
  115216. }else{
  115217. /* even order filter; still symmetric */
  115218. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115219. worth tracking step by step */
  115220. pi>>=shift;
  115221. qi>>=shift;
  115222. qexp+=shift-7*m;
  115223. pi=((pi*pi)>>16);
  115224. qi=((qi*qi)>>16);
  115225. qexp=qexp*2+m;
  115226. pi*=(1<<14)-wi;
  115227. qi*=(1<<14)+wi;
  115228. qi=(qi+pi)>>14;
  115229. }
  115230. /* we've let the normalization drift because it wasn't important;
  115231. however, for the lookup, things must be normalized again. We
  115232. need at most one right shift or a number of left shifts */
  115233. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115234. qi>>=1; qexp++;
  115235. }else
  115236. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115237. qi<<=1; qexp--;
  115238. }
  115239. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115240. vorbis_invsqlook_i(qi,qexp)-
  115241. /* m.8, m+n<=8 */
  115242. ampoffseti); /* 8.12[0] */
  115243. curve[i]*=amp;
  115244. while(map[++i]==k)curve[i]*=amp;
  115245. }
  115246. }
  115247. #else
  115248. /* old, nonoptimized but simple version for any poor sap who needs to
  115249. figure out what the hell this code does, or wants the other
  115250. fraction of a dB precision */
  115251. /* side effect: changes *lsp to cosines of lsp */
  115252. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115253. float amp,float ampoffset){
  115254. int i;
  115255. float wdel=M_PI/ln;
  115256. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115257. i=0;
  115258. while(i<n){
  115259. int j,k=map[i];
  115260. float p=.5f;
  115261. float q=.5f;
  115262. float w=2.f*cos(wdel*k);
  115263. for(j=1;j<m;j+=2){
  115264. q *= w-lsp[j-1];
  115265. p *= w-lsp[j];
  115266. }
  115267. if(j==m){
  115268. /* odd order filter; slightly assymetric */
  115269. /* the last coefficient */
  115270. q*=w-lsp[j-1];
  115271. p*=p*(4.f-w*w);
  115272. q*=q;
  115273. }else{
  115274. /* even order filter; still symmetric */
  115275. p*=p*(2.f-w);
  115276. q*=q*(2.f+w);
  115277. }
  115278. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115279. curve[i]*=q;
  115280. while(map[++i]==k)curve[i]*=q;
  115281. }
  115282. }
  115283. #endif
  115284. #endif
  115285. static void cheby(float *g, int ord) {
  115286. int i, j;
  115287. g[0] *= .5f;
  115288. for(i=2; i<= ord; i++) {
  115289. for(j=ord; j >= i; j--) {
  115290. g[j-2] -= g[j];
  115291. g[j] += g[j];
  115292. }
  115293. }
  115294. }
  115295. static int comp(const void *a,const void *b){
  115296. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115297. }
  115298. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115299. but there are root sets for which it gets into limit cycles
  115300. (exacerbated by zero suppression) and fails. We can't afford to
  115301. fail, even if the failure is 1 in 100,000,000, so we now use
  115302. Laguerre and later polish with Newton-Raphson (which can then
  115303. afford to fail) */
  115304. #define EPSILON 10e-7
  115305. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115306. int i,m;
  115307. double lastdelta=0.f;
  115308. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115309. for(i=0;i<=ord;i++)defl[i]=a[i];
  115310. for(m=ord;m>0;m--){
  115311. double newx=0.f,delta;
  115312. /* iterate a root */
  115313. while(1){
  115314. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115315. /* eval the polynomial and its first two derivatives */
  115316. for(i=m;i>0;i--){
  115317. ppp = newx*ppp + pp;
  115318. pp = newx*pp + p;
  115319. p = newx*p + defl[i-1];
  115320. }
  115321. /* Laguerre's method */
  115322. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115323. if(denom<0)
  115324. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115325. if(pp>0){
  115326. denom = pp + sqrt(denom);
  115327. if(denom<EPSILON)denom=EPSILON;
  115328. }else{
  115329. denom = pp - sqrt(denom);
  115330. if(denom>-(EPSILON))denom=-(EPSILON);
  115331. }
  115332. delta = m*p/denom;
  115333. newx -= delta;
  115334. if(delta<0.f)delta*=-1;
  115335. if(fabs(delta/newx)<10e-12)break;
  115336. lastdelta=delta;
  115337. }
  115338. r[m-1]=newx;
  115339. /* forward deflation */
  115340. for(i=m;i>0;i--)
  115341. defl[i-1]+=newx*defl[i];
  115342. defl++;
  115343. }
  115344. return(0);
  115345. }
  115346. /* for spit-and-polish only */
  115347. static int Newton_Raphson(float *a,int ord,float *r){
  115348. int i, k, count=0;
  115349. double error=1.f;
  115350. double *root=(double*)alloca(ord*sizeof(*root));
  115351. for(i=0; i<ord;i++) root[i] = r[i];
  115352. while(error>1e-20){
  115353. error=0;
  115354. for(i=0; i<ord; i++) { /* Update each point. */
  115355. double pp=0.,delta;
  115356. double rooti=root[i];
  115357. double p=a[ord];
  115358. for(k=ord-1; k>= 0; k--) {
  115359. pp= pp* rooti + p;
  115360. p = p * rooti + a[k];
  115361. }
  115362. delta = p/pp;
  115363. root[i] -= delta;
  115364. error+= delta*delta;
  115365. }
  115366. if(count>40)return(-1);
  115367. count++;
  115368. }
  115369. /* Replaced the original bubble sort with a real sort. With your
  115370. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115371. for(i=0; i<ord;i++) r[i] = root[i];
  115372. return(0);
  115373. }
  115374. /* Convert lpc coefficients to lsp coefficients */
  115375. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115376. int order2=(m+1)>>1;
  115377. int g1_order,g2_order;
  115378. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115379. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115380. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115381. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115382. int i;
  115383. /* even and odd are slightly different base cases */
  115384. g1_order=(m+1)>>1;
  115385. g2_order=(m) >>1;
  115386. /* Compute the lengths of the x polynomials. */
  115387. /* Compute the first half of K & R F1 & F2 polynomials. */
  115388. /* Compute half of the symmetric and antisymmetric polynomials. */
  115389. /* Remove the roots at +1 and -1. */
  115390. g1[g1_order] = 1.f;
  115391. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115392. g2[g2_order] = 1.f;
  115393. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115394. if(g1_order>g2_order){
  115395. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115396. }else{
  115397. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115398. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115399. }
  115400. /* Convert into polynomials in cos(alpha) */
  115401. cheby(g1,g1_order);
  115402. cheby(g2,g2_order);
  115403. /* Find the roots of the 2 even polynomials.*/
  115404. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115405. Laguerre_With_Deflation(g2,g2_order,g2r))
  115406. return(-1);
  115407. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115408. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115409. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115410. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115411. for(i=0;i<g1_order;i++)
  115412. lsp[i*2] = acos(g1r[i]);
  115413. for(i=0;i<g2_order;i++)
  115414. lsp[i*2+1] = acos(g2r[i]);
  115415. return(0);
  115416. }
  115417. #endif
  115418. /*** End of inlined file: lsp.c ***/
  115419. /*** Start of inlined file: mapping0.c ***/
  115420. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115421. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115422. // tasks..
  115423. #if JUCE_MSVC
  115424. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115425. #endif
  115426. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115427. #if JUCE_USE_OGGVORBIS
  115428. #include <stdlib.h>
  115429. #include <stdio.h>
  115430. #include <string.h>
  115431. #include <math.h>
  115432. /* simplistic, wasteful way of doing this (unique lookup for each
  115433. mode/submapping); there should be a central repository for
  115434. identical lookups. That will require minor work, so I'm putting it
  115435. off as low priority.
  115436. Why a lookup for each backend in a given mode? Because the
  115437. blocksize is set by the mode, and low backend lookups may require
  115438. parameters from other areas of the mode/mapping */
  115439. static void mapping0_free_info(vorbis_info_mapping *i){
  115440. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115441. if(info){
  115442. memset(info,0,sizeof(*info));
  115443. _ogg_free(info);
  115444. }
  115445. }
  115446. static int ilog3(unsigned int v){
  115447. int ret=0;
  115448. if(v)--v;
  115449. while(v){
  115450. ret++;
  115451. v>>=1;
  115452. }
  115453. return(ret);
  115454. }
  115455. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115456. oggpack_buffer *opb){
  115457. int i;
  115458. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115459. /* another 'we meant to do it this way' hack... up to beta 4, we
  115460. packed 4 binary zeros here to signify one submapping in use. We
  115461. now redefine that to mean four bitflags that indicate use of
  115462. deeper features; bit0:submappings, bit1:coupling,
  115463. bit2,3:reserved. This is backward compatable with all actual uses
  115464. of the beta code. */
  115465. if(info->submaps>1){
  115466. oggpack_write(opb,1,1);
  115467. oggpack_write(opb,info->submaps-1,4);
  115468. }else
  115469. oggpack_write(opb,0,1);
  115470. if(info->coupling_steps>0){
  115471. oggpack_write(opb,1,1);
  115472. oggpack_write(opb,info->coupling_steps-1,8);
  115473. for(i=0;i<info->coupling_steps;i++){
  115474. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115475. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115476. }
  115477. }else
  115478. oggpack_write(opb,0,1);
  115479. oggpack_write(opb,0,2); /* 2,3:reserved */
  115480. /* we don't write the channel submappings if we only have one... */
  115481. if(info->submaps>1){
  115482. for(i=0;i<vi->channels;i++)
  115483. oggpack_write(opb,info->chmuxlist[i],4);
  115484. }
  115485. for(i=0;i<info->submaps;i++){
  115486. oggpack_write(opb,0,8); /* time submap unused */
  115487. oggpack_write(opb,info->floorsubmap[i],8);
  115488. oggpack_write(opb,info->residuesubmap[i],8);
  115489. }
  115490. }
  115491. /* also responsible for range checking */
  115492. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115493. int i;
  115494. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115495. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115496. memset(info,0,sizeof(*info));
  115497. if(oggpack_read(opb,1))
  115498. info->submaps=oggpack_read(opb,4)+1;
  115499. else
  115500. info->submaps=1;
  115501. if(oggpack_read(opb,1)){
  115502. info->coupling_steps=oggpack_read(opb,8)+1;
  115503. for(i=0;i<info->coupling_steps;i++){
  115504. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115505. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115506. if(testM<0 ||
  115507. testA<0 ||
  115508. testM==testA ||
  115509. testM>=vi->channels ||
  115510. testA>=vi->channels) goto err_out;
  115511. }
  115512. }
  115513. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115514. if(info->submaps>1){
  115515. for(i=0;i<vi->channels;i++){
  115516. info->chmuxlist[i]=oggpack_read(opb,4);
  115517. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115518. }
  115519. }
  115520. for(i=0;i<info->submaps;i++){
  115521. oggpack_read(opb,8); /* time submap unused */
  115522. info->floorsubmap[i]=oggpack_read(opb,8);
  115523. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115524. info->residuesubmap[i]=oggpack_read(opb,8);
  115525. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115526. }
  115527. return info;
  115528. err_out:
  115529. mapping0_free_info(info);
  115530. return(NULL);
  115531. }
  115532. #if 0
  115533. static long seq=0;
  115534. static ogg_int64_t total=0;
  115535. static float FLOOR1_fromdB_LOOKUP[256]={
  115536. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115537. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115538. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115539. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115540. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115541. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115542. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115543. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115544. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115545. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115546. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115547. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115548. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115549. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115550. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115551. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115552. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115553. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115554. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115555. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115556. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115557. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115558. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115559. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115560. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115561. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115562. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115563. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115564. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115565. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115566. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115567. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115568. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115569. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115570. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115571. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115572. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115573. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115574. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115575. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115576. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115577. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115578. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115579. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115580. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115581. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115582. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115583. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115584. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115585. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115586. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115587. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115588. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115589. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115590. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115591. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115592. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115593. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115594. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115595. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115596. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115597. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115598. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115599. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115600. };
  115601. #endif
  115602. extern int *floor1_fit(vorbis_block *vb,void *look,
  115603. const float *logmdct, /* in */
  115604. const float *logmask);
  115605. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115606. int *A,int *B,
  115607. int del);
  115608. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115609. void*look,
  115610. int *post,int *ilogmask);
  115611. static int mapping0_forward(vorbis_block *vb){
  115612. vorbis_dsp_state *vd=vb->vd;
  115613. vorbis_info *vi=vd->vi;
  115614. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115615. private_state *b=(private_state*)vb->vd->backend_state;
  115616. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115617. int n=vb->pcmend;
  115618. int i,j,k;
  115619. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115620. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115621. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115622. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115623. float global_ampmax=vbi->ampmax;
  115624. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115625. int blocktype=vbi->blocktype;
  115626. int modenumber=vb->W;
  115627. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115628. vorbis_look_psy *psy_look=
  115629. b->psy+blocktype+(vb->W?2:0);
  115630. vb->mode=modenumber;
  115631. for(i=0;i<vi->channels;i++){
  115632. float scale=4.f/n;
  115633. float scale_dB;
  115634. float *pcm =vb->pcm[i];
  115635. float *logfft =pcm;
  115636. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115637. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115638. todB estimation used on IEEE 754
  115639. compliant machines had a bug that
  115640. returned dB values about a third
  115641. of a decibel too high. The bug
  115642. was harmless because tunings
  115643. implicitly took that into
  115644. account. However, fixing the bug
  115645. in the estimator requires
  115646. changing all the tunings as well.
  115647. For now, it's easier to sync
  115648. things back up here, and
  115649. recalibrate the tunings in the
  115650. next major model upgrade. */
  115651. #if 0
  115652. if(vi->channels==2)
  115653. if(i==0)
  115654. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115655. else
  115656. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115657. #endif
  115658. /* window the PCM data */
  115659. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115660. #if 0
  115661. if(vi->channels==2)
  115662. if(i==0)
  115663. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115664. else
  115665. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115666. #endif
  115667. /* transform the PCM data */
  115668. /* only MDCT right now.... */
  115669. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115670. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115671. drft_forward(&b->fft_look[vb->W],pcm);
  115672. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115673. original todB estimation used on
  115674. IEEE 754 compliant machines had a
  115675. bug that returned dB values about
  115676. a third of a decibel too high.
  115677. The bug was harmless because
  115678. tunings implicitly took that into
  115679. account. However, fixing the bug
  115680. in the estimator requires
  115681. changing all the tunings as well.
  115682. For now, it's easier to sync
  115683. things back up here, and
  115684. recalibrate the tunings in the
  115685. next major model upgrade. */
  115686. local_ampmax[i]=logfft[0];
  115687. for(j=1;j<n-1;j+=2){
  115688. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115689. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115690. .345 is a hack; the original todB
  115691. estimation used on IEEE 754
  115692. compliant machines had a bug that
  115693. returned dB values about a third
  115694. of a decibel too high. The bug
  115695. was harmless because tunings
  115696. implicitly took that into
  115697. account. However, fixing the bug
  115698. in the estimator requires
  115699. changing all the tunings as well.
  115700. For now, it's easier to sync
  115701. things back up here, and
  115702. recalibrate the tunings in the
  115703. next major model upgrade. */
  115704. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115705. }
  115706. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115707. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115708. #if 0
  115709. if(vi->channels==2){
  115710. if(i==0){
  115711. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115712. }else{
  115713. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115714. }
  115715. }
  115716. #endif
  115717. }
  115718. {
  115719. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115720. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115721. for(i=0;i<vi->channels;i++){
  115722. /* the encoder setup assumes that all the modes used by any
  115723. specific bitrate tweaking use the same floor */
  115724. int submap=info->chmuxlist[i];
  115725. /* the following makes things clearer to *me* anyway */
  115726. float *mdct =gmdct[i];
  115727. float *logfft =vb->pcm[i];
  115728. float *logmdct =logfft+n/2;
  115729. float *logmask =logfft;
  115730. vb->mode=modenumber;
  115731. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115732. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115733. for(j=0;j<n/2;j++)
  115734. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115735. todB estimation used on IEEE 754
  115736. compliant machines had a bug that
  115737. returned dB values about a third
  115738. of a decibel too high. The bug
  115739. was harmless because tunings
  115740. implicitly took that into
  115741. account. However, fixing the bug
  115742. in the estimator requires
  115743. changing all the tunings as well.
  115744. For now, it's easier to sync
  115745. things back up here, and
  115746. recalibrate the tunings in the
  115747. next major model upgrade. */
  115748. #if 0
  115749. if(vi->channels==2){
  115750. if(i==0)
  115751. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115752. else
  115753. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115754. }else{
  115755. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115756. }
  115757. #endif
  115758. /* first step; noise masking. Not only does 'noise masking'
  115759. give us curves from which we can decide how much resolution
  115760. to give noise parts of the spectrum, it also implicitly hands
  115761. us a tonality estimate (the larger the value in the
  115762. 'noise_depth' vector, the more tonal that area is) */
  115763. _vp_noisemask(psy_look,
  115764. logmdct,
  115765. noise); /* noise does not have by-frequency offset
  115766. bias applied yet */
  115767. #if 0
  115768. if(vi->channels==2){
  115769. if(i==0)
  115770. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115771. else
  115772. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115773. }
  115774. #endif
  115775. /* second step: 'all the other crap'; all the stuff that isn't
  115776. computed/fit for bitrate management goes in the second psy
  115777. vector. This includes tone masking, peak limiting and ATH */
  115778. _vp_tonemask(psy_look,
  115779. logfft,
  115780. tone,
  115781. global_ampmax,
  115782. local_ampmax[i]);
  115783. #if 0
  115784. if(vi->channels==2){
  115785. if(i==0)
  115786. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115787. else
  115788. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115789. }
  115790. #endif
  115791. /* third step; we offset the noise vectors, overlay tone
  115792. masking. We then do a floor1-specific line fit. If we're
  115793. performing bitrate management, the line fit is performed
  115794. multiple times for up/down tweakage on demand. */
  115795. #if 0
  115796. {
  115797. float aotuv[psy_look->n];
  115798. #endif
  115799. _vp_offset_and_mix(psy_look,
  115800. noise,
  115801. tone,
  115802. 1,
  115803. logmask,
  115804. mdct,
  115805. logmdct);
  115806. #if 0
  115807. if(vi->channels==2){
  115808. if(i==0)
  115809. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115810. else
  115811. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115812. }
  115813. }
  115814. #endif
  115815. #if 0
  115816. if(vi->channels==2){
  115817. if(i==0)
  115818. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115819. else
  115820. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115821. }
  115822. #endif
  115823. /* this algorithm is hardwired to floor 1 for now; abort out if
  115824. we're *not* floor1. This won't happen unless someone has
  115825. broken the encode setup lib. Guard it anyway. */
  115826. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115827. floor_posts[i][PACKETBLOBS/2]=
  115828. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115829. logmdct,
  115830. logmask);
  115831. /* are we managing bitrate? If so, perform two more fits for
  115832. later rate tweaking (fits represent hi/lo) */
  115833. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115834. /* higher rate by way of lower noise curve */
  115835. _vp_offset_and_mix(psy_look,
  115836. noise,
  115837. tone,
  115838. 2,
  115839. logmask,
  115840. mdct,
  115841. logmdct);
  115842. #if 0
  115843. if(vi->channels==2){
  115844. if(i==0)
  115845. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115846. else
  115847. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115848. }
  115849. #endif
  115850. floor_posts[i][PACKETBLOBS-1]=
  115851. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115852. logmdct,
  115853. logmask);
  115854. /* lower rate by way of higher noise curve */
  115855. _vp_offset_and_mix(psy_look,
  115856. noise,
  115857. tone,
  115858. 0,
  115859. logmask,
  115860. mdct,
  115861. logmdct);
  115862. #if 0
  115863. if(vi->channels==2)
  115864. if(i==0)
  115865. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115866. else
  115867. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115868. #endif
  115869. floor_posts[i][0]=
  115870. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115871. logmdct,
  115872. logmask);
  115873. /* we also interpolate a range of intermediate curves for
  115874. intermediate rates */
  115875. for(k=1;k<PACKETBLOBS/2;k++)
  115876. floor_posts[i][k]=
  115877. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115878. floor_posts[i][0],
  115879. floor_posts[i][PACKETBLOBS/2],
  115880. k*65536/(PACKETBLOBS/2));
  115881. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115882. floor_posts[i][k]=
  115883. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115884. floor_posts[i][PACKETBLOBS/2],
  115885. floor_posts[i][PACKETBLOBS-1],
  115886. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115887. }
  115888. }
  115889. }
  115890. vbi->ampmax=global_ampmax;
  115891. /*
  115892. the next phases are performed once for vbr-only and PACKETBLOB
  115893. times for bitrate managed modes.
  115894. 1) encode actual mode being used
  115895. 2) encode the floor for each channel, compute coded mask curve/res
  115896. 3) normalize and couple.
  115897. 4) encode residue
  115898. 5) save packet bytes to the packetblob vector
  115899. */
  115900. /* iterate over the many masking curve fits we've created */
  115901. {
  115902. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115903. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115904. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115905. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115906. float **mag_memo;
  115907. int **mag_sort;
  115908. if(info->coupling_steps){
  115909. mag_memo=_vp_quantize_couple_memo(vb,
  115910. &ci->psy_g_param,
  115911. psy_look,
  115912. info,
  115913. gmdct);
  115914. mag_sort=_vp_quantize_couple_sort(vb,
  115915. psy_look,
  115916. info,
  115917. mag_memo);
  115918. hf_reduction(&ci->psy_g_param,
  115919. psy_look,
  115920. info,
  115921. mag_memo);
  115922. }
  115923. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115924. if(psy_look->vi->normal_channel_p){
  115925. for(i=0;i<vi->channels;i++){
  115926. float *mdct =gmdct[i];
  115927. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115928. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115929. }
  115930. }
  115931. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115932. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115933. k++){
  115934. oggpack_buffer *opb=vbi->packetblob[k];
  115935. /* start out our new packet blob with packet type and mode */
  115936. /* Encode the packet type */
  115937. oggpack_write(opb,0,1);
  115938. /* Encode the modenumber */
  115939. /* Encode frame mode, pre,post windowsize, then dispatch */
  115940. oggpack_write(opb,modenumber,b->modebits);
  115941. if(vb->W){
  115942. oggpack_write(opb,vb->lW,1);
  115943. oggpack_write(opb,vb->nW,1);
  115944. }
  115945. /* encode floor, compute masking curve, sep out residue */
  115946. for(i=0;i<vi->channels;i++){
  115947. int submap=info->chmuxlist[i];
  115948. float *mdct =gmdct[i];
  115949. float *res =vb->pcm[i];
  115950. int *ilogmask=ilogmaskch[i]=
  115951. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115952. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115953. floor_posts[i][k],
  115954. ilogmask);
  115955. #if 0
  115956. {
  115957. char buf[80];
  115958. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115959. float work[n/2];
  115960. for(j=0;j<n/2;j++)
  115961. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115962. _analysis_output(buf,seq,work,n/2,1,1,0);
  115963. }
  115964. #endif
  115965. _vp_remove_floor(psy_look,
  115966. mdct,
  115967. ilogmask,
  115968. res,
  115969. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115970. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115971. #if 0
  115972. {
  115973. char buf[80];
  115974. float work[n/2];
  115975. for(j=0;j<n/2;j++)
  115976. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115977. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115978. _analysis_output(buf,seq,work,n/2,1,1,0);
  115979. }
  115980. #endif
  115981. }
  115982. /* our iteration is now based on masking curve, not prequant and
  115983. coupling. Only one prequant/coupling step */
  115984. /* quantize/couple */
  115985. /* incomplete implementation that assumes the tree is all depth
  115986. one, or no tree at all */
  115987. if(info->coupling_steps){
  115988. _vp_couple(k,
  115989. &ci->psy_g_param,
  115990. psy_look,
  115991. info,
  115992. vb->pcm,
  115993. mag_memo,
  115994. mag_sort,
  115995. ilogmaskch,
  115996. nonzero,
  115997. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115998. }
  115999. /* classify and encode by submap */
  116000. for(i=0;i<info->submaps;i++){
  116001. int ch_in_bundle=0;
  116002. long **classifications;
  116003. int resnum=info->residuesubmap[i];
  116004. for(j=0;j<vi->channels;j++){
  116005. if(info->chmuxlist[j]==i){
  116006. zerobundle[ch_in_bundle]=0;
  116007. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  116008. res_bundle[ch_in_bundle]=vb->pcm[j];
  116009. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  116010. }
  116011. }
  116012. classifications=_residue_P[ci->residue_type[resnum]]->
  116013. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  116014. _residue_P[ci->residue_type[resnum]]->
  116015. forward(opb,vb,b->residue[resnum],
  116016. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  116017. }
  116018. /* ok, done encoding. Next protopacket. */
  116019. }
  116020. }
  116021. #if 0
  116022. seq++;
  116023. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  116024. #endif
  116025. return(0);
  116026. }
  116027. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  116028. vorbis_dsp_state *vd=vb->vd;
  116029. vorbis_info *vi=vd->vi;
  116030. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  116031. private_state *b=(private_state*)vd->backend_state;
  116032. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  116033. int i,j;
  116034. long n=vb->pcmend=ci->blocksizes[vb->W];
  116035. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  116036. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  116037. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  116038. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  116039. /* recover the spectral envelope; store it in the PCM vector for now */
  116040. for(i=0;i<vi->channels;i++){
  116041. int submap=info->chmuxlist[i];
  116042. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116043. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  116044. if(floormemo[i])
  116045. nonzero[i]=1;
  116046. else
  116047. nonzero[i]=0;
  116048. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  116049. }
  116050. /* channel coupling can 'dirty' the nonzero listing */
  116051. for(i=0;i<info->coupling_steps;i++){
  116052. if(nonzero[info->coupling_mag[i]] ||
  116053. nonzero[info->coupling_ang[i]]){
  116054. nonzero[info->coupling_mag[i]]=1;
  116055. nonzero[info->coupling_ang[i]]=1;
  116056. }
  116057. }
  116058. /* recover the residue into our working vectors */
  116059. for(i=0;i<info->submaps;i++){
  116060. int ch_in_bundle=0;
  116061. for(j=0;j<vi->channels;j++){
  116062. if(info->chmuxlist[j]==i){
  116063. if(nonzero[j])
  116064. zerobundle[ch_in_bundle]=1;
  116065. else
  116066. zerobundle[ch_in_bundle]=0;
  116067. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  116068. }
  116069. }
  116070. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  116071. inverse(vb,b->residue[info->residuesubmap[i]],
  116072. pcmbundle,zerobundle,ch_in_bundle);
  116073. }
  116074. /* channel coupling */
  116075. for(i=info->coupling_steps-1;i>=0;i--){
  116076. float *pcmM=vb->pcm[info->coupling_mag[i]];
  116077. float *pcmA=vb->pcm[info->coupling_ang[i]];
  116078. for(j=0;j<n/2;j++){
  116079. float mag=pcmM[j];
  116080. float ang=pcmA[j];
  116081. if(mag>0)
  116082. if(ang>0){
  116083. pcmM[j]=mag;
  116084. pcmA[j]=mag-ang;
  116085. }else{
  116086. pcmA[j]=mag;
  116087. pcmM[j]=mag+ang;
  116088. }
  116089. else
  116090. if(ang>0){
  116091. pcmM[j]=mag;
  116092. pcmA[j]=mag+ang;
  116093. }else{
  116094. pcmA[j]=mag;
  116095. pcmM[j]=mag-ang;
  116096. }
  116097. }
  116098. }
  116099. /* compute and apply spectral envelope */
  116100. for(i=0;i<vi->channels;i++){
  116101. float *pcm=vb->pcm[i];
  116102. int submap=info->chmuxlist[i];
  116103. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116104. inverse2(vb,b->flr[info->floorsubmap[submap]],
  116105. floormemo[i],pcm);
  116106. }
  116107. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  116108. /* only MDCT right now.... */
  116109. for(i=0;i<vi->channels;i++){
  116110. float *pcm=vb->pcm[i];
  116111. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  116112. }
  116113. /* all done! */
  116114. return(0);
  116115. }
  116116. /* export hooks */
  116117. vorbis_func_mapping mapping0_exportbundle={
  116118. &mapping0_pack,
  116119. &mapping0_unpack,
  116120. &mapping0_free_info,
  116121. &mapping0_forward,
  116122. &mapping0_inverse
  116123. };
  116124. #endif
  116125. /*** End of inlined file: mapping0.c ***/
  116126. /*** Start of inlined file: mdct.c ***/
  116127. /* this can also be run as an integer transform by uncommenting a
  116128. define in mdct.h; the integerization is a first pass and although
  116129. it's likely stable for Vorbis, the dynamic range is constrained and
  116130. roundoff isn't done (so it's noisy). Consider it functional, but
  116131. only a starting point. There's no point on a machine with an FPU */
  116132. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116133. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116134. // tasks..
  116135. #if JUCE_MSVC
  116136. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116137. #endif
  116138. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116139. #if JUCE_USE_OGGVORBIS
  116140. #include <stdio.h>
  116141. #include <stdlib.h>
  116142. #include <string.h>
  116143. #include <math.h>
  116144. /* build lookups for trig functions; also pre-figure scaling and
  116145. some window function algebra. */
  116146. void mdct_init(mdct_lookup *lookup,int n){
  116147. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  116148. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  116149. int i;
  116150. int n2=n>>1;
  116151. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  116152. lookup->n=n;
  116153. lookup->trig=T;
  116154. lookup->bitrev=bitrev;
  116155. /* trig lookups... */
  116156. for(i=0;i<n/4;i++){
  116157. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  116158. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  116159. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  116160. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  116161. }
  116162. for(i=0;i<n/8;i++){
  116163. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  116164. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  116165. }
  116166. /* bitreverse lookup... */
  116167. {
  116168. int mask=(1<<(log2n-1))-1,i,j;
  116169. int msb=1<<(log2n-2);
  116170. for(i=0;i<n/8;i++){
  116171. int acc=0;
  116172. for(j=0;msb>>j;j++)
  116173. if((msb>>j)&i)acc|=1<<j;
  116174. bitrev[i*2]=((~acc)&mask)-1;
  116175. bitrev[i*2+1]=acc;
  116176. }
  116177. }
  116178. lookup->scale=FLOAT_CONV(4.f/n);
  116179. }
  116180. /* 8 point butterfly (in place, 4 register) */
  116181. STIN void mdct_butterfly_8(DATA_TYPE *x){
  116182. REG_TYPE r0 = x[6] + x[2];
  116183. REG_TYPE r1 = x[6] - x[2];
  116184. REG_TYPE r2 = x[4] + x[0];
  116185. REG_TYPE r3 = x[4] - x[0];
  116186. x[6] = r0 + r2;
  116187. x[4] = r0 - r2;
  116188. r0 = x[5] - x[1];
  116189. r2 = x[7] - x[3];
  116190. x[0] = r1 + r0;
  116191. x[2] = r1 - r0;
  116192. r0 = x[5] + x[1];
  116193. r1 = x[7] + x[3];
  116194. x[3] = r2 + r3;
  116195. x[1] = r2 - r3;
  116196. x[7] = r1 + r0;
  116197. x[5] = r1 - r0;
  116198. }
  116199. /* 16 point butterfly (in place, 4 register) */
  116200. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116201. REG_TYPE r0 = x[1] - x[9];
  116202. REG_TYPE r1 = x[0] - x[8];
  116203. x[8] += x[0];
  116204. x[9] += x[1];
  116205. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116206. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116207. r0 = x[3] - x[11];
  116208. r1 = x[10] - x[2];
  116209. x[10] += x[2];
  116210. x[11] += x[3];
  116211. x[2] = r0;
  116212. x[3] = r1;
  116213. r0 = x[12] - x[4];
  116214. r1 = x[13] - x[5];
  116215. x[12] += x[4];
  116216. x[13] += x[5];
  116217. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116218. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116219. r0 = x[14] - x[6];
  116220. r1 = x[15] - x[7];
  116221. x[14] += x[6];
  116222. x[15] += x[7];
  116223. x[6] = r0;
  116224. x[7] = r1;
  116225. mdct_butterfly_8(x);
  116226. mdct_butterfly_8(x+8);
  116227. }
  116228. /* 32 point butterfly (in place, 4 register) */
  116229. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116230. REG_TYPE r0 = x[30] - x[14];
  116231. REG_TYPE r1 = x[31] - x[15];
  116232. x[30] += x[14];
  116233. x[31] += x[15];
  116234. x[14] = r0;
  116235. x[15] = r1;
  116236. r0 = x[28] - x[12];
  116237. r1 = x[29] - x[13];
  116238. x[28] += x[12];
  116239. x[29] += x[13];
  116240. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116241. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116242. r0 = x[26] - x[10];
  116243. r1 = x[27] - x[11];
  116244. x[26] += x[10];
  116245. x[27] += x[11];
  116246. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116247. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116248. r0 = x[24] - x[8];
  116249. r1 = x[25] - x[9];
  116250. x[24] += x[8];
  116251. x[25] += x[9];
  116252. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116253. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116254. r0 = x[22] - x[6];
  116255. r1 = x[7] - x[23];
  116256. x[22] += x[6];
  116257. x[23] += x[7];
  116258. x[6] = r1;
  116259. x[7] = r0;
  116260. r0 = x[4] - x[20];
  116261. r1 = x[5] - x[21];
  116262. x[20] += x[4];
  116263. x[21] += x[5];
  116264. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116265. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116266. r0 = x[2] - x[18];
  116267. r1 = x[3] - x[19];
  116268. x[18] += x[2];
  116269. x[19] += x[3];
  116270. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116271. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116272. r0 = x[0] - x[16];
  116273. r1 = x[1] - x[17];
  116274. x[16] += x[0];
  116275. x[17] += x[1];
  116276. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116277. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116278. mdct_butterfly_16(x);
  116279. mdct_butterfly_16(x+16);
  116280. }
  116281. /* N point first stage butterfly (in place, 2 register) */
  116282. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116283. DATA_TYPE *x,
  116284. int points){
  116285. DATA_TYPE *x1 = x + points - 8;
  116286. DATA_TYPE *x2 = x + (points>>1) - 8;
  116287. REG_TYPE r0;
  116288. REG_TYPE r1;
  116289. do{
  116290. r0 = x1[6] - x2[6];
  116291. r1 = x1[7] - x2[7];
  116292. x1[6] += x2[6];
  116293. x1[7] += x2[7];
  116294. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116295. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116296. r0 = x1[4] - x2[4];
  116297. r1 = x1[5] - x2[5];
  116298. x1[4] += x2[4];
  116299. x1[5] += x2[5];
  116300. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116301. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116302. r0 = x1[2] - x2[2];
  116303. r1 = x1[3] - x2[3];
  116304. x1[2] += x2[2];
  116305. x1[3] += x2[3];
  116306. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116307. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116308. r0 = x1[0] - x2[0];
  116309. r1 = x1[1] - x2[1];
  116310. x1[0] += x2[0];
  116311. x1[1] += x2[1];
  116312. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116313. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116314. x1-=8;
  116315. x2-=8;
  116316. T+=16;
  116317. }while(x2>=x);
  116318. }
  116319. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116320. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116321. DATA_TYPE *x,
  116322. int points,
  116323. int trigint){
  116324. DATA_TYPE *x1 = x + points - 8;
  116325. DATA_TYPE *x2 = x + (points>>1) - 8;
  116326. REG_TYPE r0;
  116327. REG_TYPE r1;
  116328. do{
  116329. r0 = x1[6] - x2[6];
  116330. r1 = x1[7] - x2[7];
  116331. x1[6] += x2[6];
  116332. x1[7] += x2[7];
  116333. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116334. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116335. T+=trigint;
  116336. r0 = x1[4] - x2[4];
  116337. r1 = x1[5] - x2[5];
  116338. x1[4] += x2[4];
  116339. x1[5] += x2[5];
  116340. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116341. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116342. T+=trigint;
  116343. r0 = x1[2] - x2[2];
  116344. r1 = x1[3] - x2[3];
  116345. x1[2] += x2[2];
  116346. x1[3] += x2[3];
  116347. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116348. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116349. T+=trigint;
  116350. r0 = x1[0] - x2[0];
  116351. r1 = x1[1] - x2[1];
  116352. x1[0] += x2[0];
  116353. x1[1] += x2[1];
  116354. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116355. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116356. T+=trigint;
  116357. x1-=8;
  116358. x2-=8;
  116359. }while(x2>=x);
  116360. }
  116361. STIN void mdct_butterflies(mdct_lookup *init,
  116362. DATA_TYPE *x,
  116363. int points){
  116364. DATA_TYPE *T=init->trig;
  116365. int stages=init->log2n-5;
  116366. int i,j;
  116367. if(--stages>0){
  116368. mdct_butterfly_first(T,x,points);
  116369. }
  116370. for(i=1;--stages>0;i++){
  116371. for(j=0;j<(1<<i);j++)
  116372. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116373. }
  116374. for(j=0;j<points;j+=32)
  116375. mdct_butterfly_32(x+j);
  116376. }
  116377. void mdct_clear(mdct_lookup *l){
  116378. if(l){
  116379. if(l->trig)_ogg_free(l->trig);
  116380. if(l->bitrev)_ogg_free(l->bitrev);
  116381. memset(l,0,sizeof(*l));
  116382. }
  116383. }
  116384. STIN void mdct_bitreverse(mdct_lookup *init,
  116385. DATA_TYPE *x){
  116386. int n = init->n;
  116387. int *bit = init->bitrev;
  116388. DATA_TYPE *w0 = x;
  116389. DATA_TYPE *w1 = x = w0+(n>>1);
  116390. DATA_TYPE *T = init->trig+n;
  116391. do{
  116392. DATA_TYPE *x0 = x+bit[0];
  116393. DATA_TYPE *x1 = x+bit[1];
  116394. REG_TYPE r0 = x0[1] - x1[1];
  116395. REG_TYPE r1 = x0[0] + x1[0];
  116396. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116397. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116398. w1 -= 4;
  116399. r0 = HALVE(x0[1] + x1[1]);
  116400. r1 = HALVE(x0[0] - x1[0]);
  116401. w0[0] = r0 + r2;
  116402. w1[2] = r0 - r2;
  116403. w0[1] = r1 + r3;
  116404. w1[3] = r3 - r1;
  116405. x0 = x+bit[2];
  116406. x1 = x+bit[3];
  116407. r0 = x0[1] - x1[1];
  116408. r1 = x0[0] + x1[0];
  116409. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116410. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116411. r0 = HALVE(x0[1] + x1[1]);
  116412. r1 = HALVE(x0[0] - x1[0]);
  116413. w0[2] = r0 + r2;
  116414. w1[0] = r0 - r2;
  116415. w0[3] = r1 + r3;
  116416. w1[1] = r3 - r1;
  116417. T += 4;
  116418. bit += 4;
  116419. w0 += 4;
  116420. }while(w0<w1);
  116421. }
  116422. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116423. int n=init->n;
  116424. int n2=n>>1;
  116425. int n4=n>>2;
  116426. /* rotate */
  116427. DATA_TYPE *iX = in+n2-7;
  116428. DATA_TYPE *oX = out+n2+n4;
  116429. DATA_TYPE *T = init->trig+n4;
  116430. do{
  116431. oX -= 4;
  116432. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116433. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116434. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116435. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116436. iX -= 8;
  116437. T += 4;
  116438. }while(iX>=in);
  116439. iX = in+n2-8;
  116440. oX = out+n2+n4;
  116441. T = init->trig+n4;
  116442. do{
  116443. T -= 4;
  116444. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116445. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116446. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116447. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116448. iX -= 8;
  116449. oX += 4;
  116450. }while(iX>=in);
  116451. mdct_butterflies(init,out+n2,n2);
  116452. mdct_bitreverse(init,out);
  116453. /* roatate + window */
  116454. {
  116455. DATA_TYPE *oX1=out+n2+n4;
  116456. DATA_TYPE *oX2=out+n2+n4;
  116457. DATA_TYPE *iX =out;
  116458. T =init->trig+n2;
  116459. do{
  116460. oX1-=4;
  116461. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116462. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116463. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116464. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116465. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116466. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116467. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116468. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116469. oX2+=4;
  116470. iX += 8;
  116471. T += 8;
  116472. }while(iX<oX1);
  116473. iX=out+n2+n4;
  116474. oX1=out+n4;
  116475. oX2=oX1;
  116476. do{
  116477. oX1-=4;
  116478. iX-=4;
  116479. oX2[0] = -(oX1[3] = iX[3]);
  116480. oX2[1] = -(oX1[2] = iX[2]);
  116481. oX2[2] = -(oX1[1] = iX[1]);
  116482. oX2[3] = -(oX1[0] = iX[0]);
  116483. oX2+=4;
  116484. }while(oX2<iX);
  116485. iX=out+n2+n4;
  116486. oX1=out+n2+n4;
  116487. oX2=out+n2;
  116488. do{
  116489. oX1-=4;
  116490. oX1[0]= iX[3];
  116491. oX1[1]= iX[2];
  116492. oX1[2]= iX[1];
  116493. oX1[3]= iX[0];
  116494. iX+=4;
  116495. }while(oX1>oX2);
  116496. }
  116497. }
  116498. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116499. int n=init->n;
  116500. int n2=n>>1;
  116501. int n4=n>>2;
  116502. int n8=n>>3;
  116503. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116504. DATA_TYPE *w2=w+n2;
  116505. /* rotate */
  116506. /* window + rotate + step 1 */
  116507. REG_TYPE r0;
  116508. REG_TYPE r1;
  116509. DATA_TYPE *x0=in+n2+n4;
  116510. DATA_TYPE *x1=x0+1;
  116511. DATA_TYPE *T=init->trig+n2;
  116512. int i=0;
  116513. for(i=0;i<n8;i+=2){
  116514. x0 -=4;
  116515. T-=2;
  116516. r0= x0[2] + x1[0];
  116517. r1= x0[0] + x1[2];
  116518. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116519. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116520. x1 +=4;
  116521. }
  116522. x1=in+1;
  116523. for(;i<n2-n8;i+=2){
  116524. T-=2;
  116525. x0 -=4;
  116526. r0= x0[2] - x1[0];
  116527. r1= x0[0] - x1[2];
  116528. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116529. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116530. x1 +=4;
  116531. }
  116532. x0=in+n;
  116533. for(;i<n2;i+=2){
  116534. T-=2;
  116535. x0 -=4;
  116536. r0= -x0[2] - x1[0];
  116537. r1= -x0[0] - x1[2];
  116538. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116539. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116540. x1 +=4;
  116541. }
  116542. mdct_butterflies(init,w+n2,n2);
  116543. mdct_bitreverse(init,w);
  116544. /* roatate + window */
  116545. T=init->trig+n2;
  116546. x0=out+n2;
  116547. for(i=0;i<n4;i++){
  116548. x0--;
  116549. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116550. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116551. w+=2;
  116552. T+=2;
  116553. }
  116554. }
  116555. #endif
  116556. /*** End of inlined file: mdct.c ***/
  116557. /*** Start of inlined file: psy.c ***/
  116558. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116559. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116560. // tasks..
  116561. #if JUCE_MSVC
  116562. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116563. #endif
  116564. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116565. #if JUCE_USE_OGGVORBIS
  116566. #include <stdlib.h>
  116567. #include <math.h>
  116568. #include <string.h>
  116569. /*** Start of inlined file: masking.h ***/
  116570. #ifndef _V_MASKING_H_
  116571. #define _V_MASKING_H_
  116572. /* more detailed ATH; the bass if flat to save stressing the floor
  116573. overly for only a bin or two of savings. */
  116574. #define MAX_ATH 88
  116575. static float ATH[]={
  116576. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116577. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116578. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116579. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116580. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116581. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116582. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116583. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116584. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116585. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116586. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116587. };
  116588. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116589. replaced by an empirically collected data set. The previously
  116590. published values were, far too often, simply on crack. */
  116591. #define EHMER_OFFSET 16
  116592. #define EHMER_MAX 56
  116593. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116594. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116595. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116596. for collection of these curves) */
  116597. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116598. /* 62.5 Hz */
  116599. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116600. -60, -60, -60, -60, -62, -62, -65, -73,
  116601. -69, -68, -68, -67, -70, -70, -72, -74,
  116602. -75, -79, -79, -80, -83, -88, -93, -100,
  116603. -110, -999, -999, -999, -999, -999, -999, -999,
  116604. -999, -999, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999},
  116606. { -48, -48, -48, -48, -48, -48, -48, -48,
  116607. -48, -48, -48, -48, -48, -53, -61, -66,
  116608. -66, -68, -67, -70, -76, -76, -72, -73,
  116609. -75, -76, -78, -79, -83, -88, -93, -100,
  116610. -110, -999, -999, -999, -999, -999, -999, -999,
  116611. -999, -999, -999, -999, -999, -999, -999, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999},
  116613. { -37, -37, -37, -37, -37, -37, -37, -37,
  116614. -38, -40, -42, -46, -48, -53, -55, -62,
  116615. -65, -58, -56, -56, -61, -60, -65, -67,
  116616. -69, -71, -77, -77, -78, -80, -82, -84,
  116617. -88, -93, -98, -106, -112, -999, -999, -999,
  116618. -999, -999, -999, -999, -999, -999, -999, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999},
  116620. { -25, -25, -25, -25, -25, -25, -25, -25,
  116621. -25, -26, -27, -29, -32, -38, -48, -52,
  116622. -52, -50, -48, -48, -51, -52, -54, -60,
  116623. -67, -67, -66, -68, -69, -73, -73, -76,
  116624. -80, -81, -81, -85, -85, -86, -88, -93,
  116625. -100, -110, -999, -999, -999, -999, -999, -999,
  116626. -999, -999, -999, -999, -999, -999, -999, -999},
  116627. { -16, -16, -16, -16, -16, -16, -16, -16,
  116628. -17, -19, -20, -22, -26, -28, -31, -40,
  116629. -47, -39, -39, -40, -42, -43, -47, -51,
  116630. -57, -52, -55, -55, -60, -58, -62, -63,
  116631. -70, -67, -69, -72, -73, -77, -80, -82,
  116632. -83, -87, -90, -94, -98, -104, -115, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999},
  116634. { -8, -8, -8, -8, -8, -8, -8, -8,
  116635. -8, -8, -10, -11, -15, -19, -25, -30,
  116636. -34, -31, -30, -31, -29, -32, -35, -42,
  116637. -48, -42, -44, -46, -50, -50, -51, -52,
  116638. -59, -54, -55, -55, -58, -62, -63, -66,
  116639. -72, -73, -76, -75, -78, -80, -80, -81,
  116640. -84, -88, -90, -94, -98, -101, -106, -110}},
  116641. /* 88Hz */
  116642. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116643. -66, -66, -66, -66, -66, -67, -67, -67,
  116644. -76, -72, -71, -74, -76, -76, -75, -78,
  116645. -79, -79, -81, -83, -86, -89, -93, -97,
  116646. -100, -105, -110, -999, -999, -999, -999, -999,
  116647. -999, -999, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -999, -999, -999, -999, -999, -999},
  116649. { -47, -47, -47, -47, -47, -47, -47, -47,
  116650. -47, -47, -47, -48, -51, -55, -59, -66,
  116651. -66, -66, -67, -66, -68, -69, -70, -74,
  116652. -79, -77, -77, -78, -80, -81, -82, -84,
  116653. -86, -88, -91, -95, -100, -108, -116, -999,
  116654. -999, -999, -999, -999, -999, -999, -999, -999,
  116655. -999, -999, -999, -999, -999, -999, -999, -999},
  116656. { -36, -36, -36, -36, -36, -36, -36, -36,
  116657. -36, -37, -37, -41, -44, -48, -51, -58,
  116658. -62, -60, -57, -59, -59, -60, -63, -65,
  116659. -72, -71, -70, -72, -74, -77, -76, -78,
  116660. -81, -81, -80, -83, -86, -91, -96, -100,
  116661. -105, -110, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999},
  116663. { -28, -28, -28, -28, -28, -28, -28, -28,
  116664. -28, -30, -32, -32, -33, -35, -41, -49,
  116665. -50, -49, -47, -48, -48, -52, -51, -57,
  116666. -65, -61, -59, -61, -64, -69, -70, -74,
  116667. -77, -77, -78, -81, -84, -85, -87, -90,
  116668. -92, -96, -100, -107, -112, -999, -999, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999},
  116670. { -19, -19, -19, -19, -19, -19, -19, -19,
  116671. -20, -21, -23, -27, -30, -35, -36, -41,
  116672. -46, -44, -42, -40, -41, -41, -43, -48,
  116673. -55, -53, -52, -53, -56, -59, -58, -60,
  116674. -67, -66, -69, -71, -72, -75, -79, -81,
  116675. -84, -87, -90, -93, -97, -101, -107, -114,
  116676. -999, -999, -999, -999, -999, -999, -999, -999},
  116677. { -9, -9, -9, -9, -9, -9, -9, -9,
  116678. -11, -12, -12, -15, -16, -20, -23, -30,
  116679. -37, -34, -33, -34, -31, -32, -32, -38,
  116680. -47, -44, -41, -40, -47, -49, -46, -46,
  116681. -58, -50, -50, -54, -58, -62, -64, -67,
  116682. -67, -70, -72, -76, -79, -83, -87, -91,
  116683. -96, -100, -104, -110, -999, -999, -999, -999}},
  116684. /* 125 Hz */
  116685. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116686. -62, -62, -63, -64, -66, -67, -66, -68,
  116687. -75, -72, -76, -75, -76, -78, -79, -82,
  116688. -84, -85, -90, -94, -101, -110, -999, -999,
  116689. -999, -999, -999, -999, -999, -999, -999, -999,
  116690. -999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -999, -999, -999, -999, -999, -999, -999},
  116692. { -59, -59, -59, -59, -59, -59, -59, -59,
  116693. -59, -59, -59, -60, -60, -61, -63, -66,
  116694. -71, -68, -70, -70, -71, -72, -72, -75,
  116695. -81, -78, -79, -82, -83, -86, -90, -97,
  116696. -103, -113, -999, -999, -999, -999, -999, -999,
  116697. -999, -999, -999, -999, -999, -999, -999, -999,
  116698. -999, -999, -999, -999, -999, -999, -999, -999},
  116699. { -53, -53, -53, -53, -53, -53, -53, -53,
  116700. -53, -54, -55, -57, -56, -57, -55, -61,
  116701. -65, -60, -60, -62, -63, -63, -66, -68,
  116702. -74, -73, -75, -75, -78, -80, -80, -82,
  116703. -85, -90, -96, -101, -108, -999, -999, -999,
  116704. -999, -999, -999, -999, -999, -999, -999, -999,
  116705. -999, -999, -999, -999, -999, -999, -999, -999},
  116706. { -46, -46, -46, -46, -46, -46, -46, -46,
  116707. -46, -46, -47, -47, -47, -47, -48, -51,
  116708. -57, -51, -49, -50, -51, -53, -54, -59,
  116709. -66, -60, -62, -67, -67, -70, -72, -75,
  116710. -76, -78, -81, -85, -88, -94, -97, -104,
  116711. -112, -999, -999, -999, -999, -999, -999, -999,
  116712. -999, -999, -999, -999, -999, -999, -999, -999},
  116713. { -36, -36, -36, -36, -36, -36, -36, -36,
  116714. -39, -41, -42, -42, -39, -38, -41, -43,
  116715. -52, -44, -40, -39, -37, -37, -40, -47,
  116716. -54, -50, -48, -50, -55, -61, -59, -62,
  116717. -66, -66, -66, -69, -69, -73, -74, -74,
  116718. -75, -77, -79, -82, -87, -91, -95, -100,
  116719. -108, -115, -999, -999, -999, -999, -999, -999},
  116720. { -28, -26, -24, -22, -20, -20, -23, -29,
  116721. -30, -31, -28, -27, -28, -28, -28, -35,
  116722. -40, -33, -32, -29, -30, -30, -30, -37,
  116723. -45, -41, -37, -38, -45, -47, -47, -48,
  116724. -53, -49, -48, -50, -49, -49, -51, -52,
  116725. -58, -56, -57, -56, -60, -61, -62, -70,
  116726. -72, -74, -78, -83, -88, -93, -100, -106}},
  116727. /* 177 Hz */
  116728. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116729. -999, -110, -105, -100, -95, -91, -87, -83,
  116730. -80, -78, -76, -78, -78, -81, -83, -85,
  116731. -86, -85, -86, -87, -90, -97, -107, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999,
  116733. -999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -999, -999, -999, -999, -999},
  116735. {-999, -999, -999, -110, -105, -100, -95, -90,
  116736. -85, -81, -77, -73, -70, -67, -67, -68,
  116737. -75, -73, -70, -69, -70, -72, -75, -79,
  116738. -84, -83, -84, -86, -88, -89, -89, -93,
  116739. -98, -105, -112, -999, -999, -999, -999, -999,
  116740. -999, -999, -999, -999, -999, -999, -999, -999,
  116741. -999, -999, -999, -999, -999, -999, -999, -999},
  116742. {-105, -100, -95, -90, -85, -80, -76, -71,
  116743. -68, -68, -65, -63, -63, -62, -62, -64,
  116744. -65, -64, -61, -62, -63, -64, -66, -68,
  116745. -73, -73, -74, -75, -76, -81, -83, -85,
  116746. -88, -89, -92, -95, -100, -108, -999, -999,
  116747. -999, -999, -999, -999, -999, -999, -999, -999,
  116748. -999, -999, -999, -999, -999, -999, -999, -999},
  116749. { -80, -75, -71, -68, -65, -63, -62, -61,
  116750. -61, -61, -61, -59, -56, -57, -53, -50,
  116751. -58, -52, -50, -50, -52, -53, -54, -58,
  116752. -67, -63, -67, -68, -72, -75, -78, -80,
  116753. -81, -81, -82, -85, -89, -90, -93, -97,
  116754. -101, -107, -114, -999, -999, -999, -999, -999,
  116755. -999, -999, -999, -999, -999, -999, -999, -999},
  116756. { -65, -61, -59, -57, -56, -55, -55, -56,
  116757. -56, -57, -55, -53, -52, -47, -44, -44,
  116758. -50, -44, -41, -39, -39, -42, -40, -46,
  116759. -51, -49, -50, -53, -54, -63, -60, -61,
  116760. -62, -66, -66, -66, -70, -73, -74, -75,
  116761. -76, -75, -79, -85, -89, -91, -96, -102,
  116762. -110, -999, -999, -999, -999, -999, -999, -999},
  116763. { -52, -50, -49, -49, -48, -48, -48, -49,
  116764. -50, -50, -49, -46, -43, -39, -35, -33,
  116765. -38, -36, -32, -29, -32, -32, -32, -35,
  116766. -44, -39, -38, -38, -46, -50, -45, -46,
  116767. -53, -50, -50, -50, -54, -54, -53, -53,
  116768. -56, -57, -59, -66, -70, -72, -74, -79,
  116769. -83, -85, -90, -97, -114, -999, -999, -999}},
  116770. /* 250 Hz */
  116771. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116772. -100, -95, -90, -86, -80, -75, -75, -79,
  116773. -80, -79, -80, -81, -82, -88, -95, -103,
  116774. -110, -999, -999, -999, -999, -999, -999, -999,
  116775. -999, -999, -999, -999, -999, -999, -999, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -999, -999, -999, -999, -999},
  116778. {-999, -999, -999, -999, -108, -103, -98, -93,
  116779. -88, -83, -79, -78, -75, -71, -67, -68,
  116780. -73, -73, -72, -73, -75, -77, -80, -82,
  116781. -88, -93, -100, -107, -114, -999, -999, -999,
  116782. -999, -999, -999, -999, -999, -999, -999, -999,
  116783. -999, -999, -999, -999, -999, -999, -999, -999,
  116784. -999, -999, -999, -999, -999, -999, -999, -999},
  116785. {-999, -999, -999, -110, -105, -101, -96, -90,
  116786. -86, -81, -77, -73, -69, -66, -61, -62,
  116787. -66, -64, -62, -65, -66, -70, -72, -76,
  116788. -81, -80, -84, -90, -95, -102, -110, -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, -107, -103, -97, -92, -88,
  116793. -83, -79, -74, -70, -66, -59, -53, -58,
  116794. -62, -55, -54, -54, -54, -58, -61, -62,
  116795. -72, -70, -72, -75, -78, -80, -81, -80,
  116796. -83, -83, -88, -93, -100, -107, -115, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999,
  116798. -999, -999, -999, -999, -999, -999, -999, -999},
  116799. {-999, -999, -999, -105, -100, -95, -90, -85,
  116800. -80, -75, -70, -66, -62, -56, -48, -44,
  116801. -48, -46, -46, -43, -46, -48, -48, -51,
  116802. -58, -58, -59, -60, -62, -62, -61, -61,
  116803. -65, -64, -65, -68, -70, -74, -75, -78,
  116804. -81, -86, -95, -110, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999},
  116806. {-999, -999, -105, -100, -95, -90, -85, -80,
  116807. -75, -70, -65, -61, -55, -49, -39, -33,
  116808. -40, -35, -32, -38, -40, -33, -35, -37,
  116809. -46, -41, -45, -44, -46, -42, -45, -46,
  116810. -52, -50, -50, -50, -54, -54, -55, -57,
  116811. -62, -64, -66, -68, -70, -76, -81, -90,
  116812. -100, -110, -999, -999, -999, -999, -999, -999}},
  116813. /* 354 hz */
  116814. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116815. -105, -98, -90, -85, -82, -83, -80, -78,
  116816. -84, -79, -80, -83, -87, -89, -91, -93,
  116817. -99, -106, -117, -999, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -999, -999, -999, -999, -999},
  116821. {-999, -999, -999, -999, -999, -999, -999, -999,
  116822. -105, -98, -90, -85, -80, -75, -70, -68,
  116823. -74, -72, -74, -77, -80, -82, -85, -87,
  116824. -92, -89, -91, -95, -100, -106, -112, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999,
  116826. -999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -999, -999, -999, -999, -999, -999, -999},
  116828. {-999, -999, -999, -999, -999, -999, -999, -999,
  116829. -105, -98, -90, -83, -75, -71, -63, -64,
  116830. -67, -62, -64, -67, -70, -73, -77, -81,
  116831. -84, -83, -85, -89, -90, -93, -98, -104,
  116832. -109, -114, -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, -999, -999, -999,
  116836. -103, -96, -88, -81, -75, -68, -58, -54,
  116837. -56, -54, -56, -56, -58, -60, -63, -66,
  116838. -74, -69, -72, -72, -75, -74, -77, -81,
  116839. -81, -82, -84, -87, -93, -96, -99, -104,
  116840. -110, -999, -999, -999, -999, -999, -999, -999,
  116841. -999, -999, -999, -999, -999, -999, -999, -999},
  116842. {-999, -999, -999, -999, -999, -108, -102, -96,
  116843. -91, -85, -80, -74, -68, -60, -51, -46,
  116844. -48, -46, -43, -45, -47, -47, -49, -48,
  116845. -56, -53, -55, -58, -57, -63, -58, -60,
  116846. -66, -64, -67, -70, -70, -74, -77, -84,
  116847. -86, -89, -91, -93, -94, -101, -109, -118,
  116848. -999, -999, -999, -999, -999, -999, -999, -999},
  116849. {-999, -999, -999, -108, -103, -98, -93, -88,
  116850. -83, -78, -73, -68, -60, -53, -44, -35,
  116851. -38, -38, -34, -34, -36, -40, -41, -44,
  116852. -51, -45, -46, -47, -46, -54, -50, -49,
  116853. -50, -50, -50, -51, -54, -57, -58, -60,
  116854. -66, -66, -66, -64, -65, -68, -77, -82,
  116855. -87, -95, -110, -999, -999, -999, -999, -999}},
  116856. /* 500 Hz */
  116857. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116858. -107, -102, -97, -92, -87, -83, -78, -75,
  116859. -82, -79, -83, -85, -89, -92, -95, -98,
  116860. -101, -105, -109, -113, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -999, -999, -999, -999, -999},
  116864. {-999, -999, -999, -999, -999, -999, -999, -106,
  116865. -100, -95, -90, -86, -81, -78, -74, -69,
  116866. -74, -74, -76, -79, -83, -84, -86, -89,
  116867. -92, -97, -93, -100, -103, -107, -110, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999,
  116869. -999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -999, -999, -999, -999, -999, -999},
  116871. {-999, -999, -999, -999, -999, -999, -106, -100,
  116872. -95, -90, -87, -83, -80, -75, -69, -60,
  116873. -66, -66, -68, -70, -74, -78, -79, -81,
  116874. -81, -83, -84, -87, -93, -96, -99, -103,
  116875. -107, -110, -999, -999, -999, -999, -999, -999,
  116876. -999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -999, -999, -999, -999, -999},
  116878. {-999, -999, -999, -999, -999, -108, -103, -98,
  116879. -93, -89, -85, -82, -78, -71, -62, -55,
  116880. -58, -58, -54, -54, -55, -59, -61, -62,
  116881. -70, -66, -66, -67, -70, -72, -75, -78,
  116882. -84, -84, -84, -88, -91, -90, -95, -98,
  116883. -102, -103, -106, -110, -999, -999, -999, -999,
  116884. -999, -999, -999, -999, -999, -999, -999, -999},
  116885. {-999, -999, -999, -999, -108, -103, -98, -94,
  116886. -90, -87, -82, -79, -73, -67, -58, -47,
  116887. -50, -45, -41, -45, -48, -44, -44, -49,
  116888. -54, -51, -48, -47, -49, -50, -51, -57,
  116889. -58, -60, -63, -69, -70, -69, -71, -74,
  116890. -78, -82, -90, -95, -101, -105, -110, -999,
  116891. -999, -999, -999, -999, -999, -999, -999, -999},
  116892. {-999, -999, -999, -105, -101, -97, -93, -90,
  116893. -85, -80, -77, -72, -65, -56, -48, -37,
  116894. -40, -36, -34, -40, -50, -47, -38, -41,
  116895. -47, -38, -35, -39, -38, -43, -40, -45,
  116896. -50, -45, -44, -47, -50, -55, -48, -48,
  116897. -52, -66, -70, -76, -82, -90, -97, -105,
  116898. -110, -999, -999, -999, -999, -999, -999, -999}},
  116899. /* 707 Hz */
  116900. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116901. -999, -108, -103, -98, -93, -86, -79, -76,
  116902. -83, -81, -85, -87, -89, -93, -98, -102,
  116903. -107, -112, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -999, -999, -999, -999, -999},
  116907. {-999, -999, -999, -999, -999, -999, -999, -999,
  116908. -999, -108, -103, -98, -93, -86, -79, -71,
  116909. -77, -74, -77, -79, -81, -84, -85, -90,
  116910. -92, -93, -92, -98, -101, -108, -112, -999,
  116911. -999, -999, -999, -999, -999, -999, -999, -999,
  116912. -999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -999, -999, -999, -999, -999, -999, -999},
  116914. {-999, -999, -999, -999, -999, -999, -999, -999,
  116915. -108, -103, -98, -93, -87, -78, -68, -65,
  116916. -66, -62, -65, -67, -70, -73, -75, -78,
  116917. -82, -82, -83, -84, -91, -93, -98, -102,
  116918. -106, -110, -999, -999, -999, -999, -999, -999,
  116919. -999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -999, -999, -999, -999, -999, -999},
  116921. {-999, -999, -999, -999, -999, -999, -999, -999,
  116922. -105, -100, -95, -90, -82, -74, -62, -57,
  116923. -58, -56, -51, -52, -52, -54, -54, -58,
  116924. -66, -59, -60, -63, -66, -69, -73, -79,
  116925. -83, -84, -80, -81, -81, -82, -88, -92,
  116926. -98, -105, -113, -999, -999, -999, -999, -999,
  116927. -999, -999, -999, -999, -999, -999, -999, -999},
  116928. {-999, -999, -999, -999, -999, -999, -999, -107,
  116929. -102, -97, -92, -84, -79, -69, -57, -47,
  116930. -52, -47, -44, -45, -50, -52, -42, -42,
  116931. -53, -43, -43, -48, -51, -56, -55, -52,
  116932. -57, -59, -61, -62, -67, -71, -78, -83,
  116933. -86, -94, -98, -103, -110, -999, -999, -999,
  116934. -999, -999, -999, -999, -999, -999, -999, -999},
  116935. {-999, -999, -999, -999, -999, -999, -105, -100,
  116936. -95, -90, -84, -78, -70, -61, -51, -41,
  116937. -40, -38, -40, -46, -52, -51, -41, -40,
  116938. -46, -40, -38, -38, -41, -46, -41, -46,
  116939. -47, -43, -43, -45, -41, -45, -56, -67,
  116940. -68, -83, -87, -90, -95, -102, -107, -113,
  116941. -999, -999, -999, -999, -999, -999, -999, -999}},
  116942. /* 1000 Hz */
  116943. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116944. -999, -109, -105, -101, -96, -91, -84, -77,
  116945. -82, -82, -85, -89, -94, -100, -106, -110,
  116946. -999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -999, -999, -999, -999, -999},
  116950. {-999, -999, -999, -999, -999, -999, -999, -999,
  116951. -999, -106, -103, -98, -92, -85, -80, -71,
  116952. -75, -72, -76, -80, -84, -86, -89, -93,
  116953. -100, -107, -113, -999, -999, -999, -999, -999,
  116954. -999, -999, -999, -999, -999, -999, -999, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -999, -999, -999, -999, -999},
  116957. {-999, -999, -999, -999, -999, -999, -999, -107,
  116958. -104, -101, -97, -92, -88, -84, -80, -64,
  116959. -66, -63, -64, -66, -69, -73, -77, -83,
  116960. -83, -86, -91, -98, -104, -111, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999,
  116962. -999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -999, -999, -999, -999},
  116964. {-999, -999, -999, -999, -999, -999, -999, -107,
  116965. -104, -101, -97, -92, -90, -84, -74, -57,
  116966. -58, -52, -55, -54, -50, -52, -50, -52,
  116967. -63, -62, -69, -76, -77, -78, -78, -79,
  116968. -82, -88, -94, -100, -106, -111, -999, -999,
  116969. -999, -999, -999, -999, -999, -999, -999, -999,
  116970. -999, -999, -999, -999, -999, -999, -999, -999},
  116971. {-999, -999, -999, -999, -999, -999, -106, -102,
  116972. -98, -95, -90, -85, -83, -78, -70, -50,
  116973. -50, -41, -44, -49, -47, -50, -50, -44,
  116974. -55, -46, -47, -48, -48, -54, -49, -49,
  116975. -58, -62, -71, -81, -87, -92, -97, -102,
  116976. -108, -114, -999, -999, -999, -999, -999, -999,
  116977. -999, -999, -999, -999, -999, -999, -999, -999},
  116978. {-999, -999, -999, -999, -999, -999, -106, -102,
  116979. -98, -95, -90, -85, -83, -78, -70, -45,
  116980. -43, -41, -47, -50, -51, -50, -49, -45,
  116981. -47, -41, -44, -41, -39, -43, -38, -37,
  116982. -40, -41, -44, -50, -58, -65, -73, -79,
  116983. -85, -92, -97, -101, -105, -109, -113, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999}},
  116985. /* 1414 Hz */
  116986. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116987. -999, -999, -999, -107, -100, -95, -87, -81,
  116988. -85, -83, -88, -93, -100, -107, -114, -999,
  116989. -999, -999, -999, -999, -999, -999, -999, -999,
  116990. -999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -999, -999, -999, -999, -999,
  116992. -999, -999, -999, -999, -999, -999, -999, -999},
  116993. {-999, -999, -999, -999, -999, -999, -999, -999,
  116994. -999, -999, -107, -101, -95, -88, -83, -76,
  116995. -73, -72, -79, -84, -90, -95, -100, -105,
  116996. -110, -115, -999, -999, -999, -999, -999, -999,
  116997. -999, -999, -999, -999, -999, -999, -999, -999,
  116998. -999, -999, -999, -999, -999, -999, -999, -999,
  116999. -999, -999, -999, -999, -999, -999, -999, -999},
  117000. {-999, -999, -999, -999, -999, -999, -999, -999,
  117001. -999, -999, -104, -98, -92, -87, -81, -70,
  117002. -65, -62, -67, -71, -74, -80, -85, -91,
  117003. -95, -99, -103, -108, -111, -114, -999, -999,
  117004. -999, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -999, -999, -999, -999},
  117007. {-999, -999, -999, -999, -999, -999, -999, -999,
  117008. -999, -999, -103, -97, -90, -85, -76, -60,
  117009. -56, -54, -60, -62, -61, -56, -63, -65,
  117010. -73, -74, -77, -75, -78, -81, -86, -87,
  117011. -88, -91, -94, -98, -103, -110, -999, -999,
  117012. -999, -999, -999, -999, -999, -999, -999, -999,
  117013. -999, -999, -999, -999, -999, -999, -999, -999},
  117014. {-999, -999, -999, -999, -999, -999, -999, -105,
  117015. -100, -97, -92, -86, -81, -79, -70, -57,
  117016. -51, -47, -51, -58, -60, -56, -53, -50,
  117017. -58, -52, -50, -50, -53, -55, -64, -69,
  117018. -71, -85, -82, -78, -81, -85, -95, -102,
  117019. -112, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -999, -999, -999, -999, -999, -999, -999},
  117021. {-999, -999, -999, -999, -999, -999, -999, -105,
  117022. -100, -97, -92, -85, -83, -79, -72, -49,
  117023. -40, -43, -43, -54, -56, -51, -50, -40,
  117024. -43, -38, -36, -35, -37, -38, -37, -44,
  117025. -54, -60, -57, -60, -70, -75, -84, -92,
  117026. -103, -112, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -999, -999, -999, -999}},
  117028. /* 2000 Hz */
  117029. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117030. -999, -999, -999, -110, -102, -95, -89, -82,
  117031. -83, -84, -90, -92, -99, -107, -113, -999,
  117032. -999, -999, -999, -999, -999, -999, -999, -999,
  117033. -999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -999, -999, -999, -999,
  117035. -999, -999, -999, -999, -999, -999, -999, -999},
  117036. {-999, -999, -999, -999, -999, -999, -999, -999,
  117037. -999, -999, -107, -101, -95, -89, -83, -72,
  117038. -74, -78, -85, -88, -88, -90, -92, -98,
  117039. -105, -111, -999, -999, -999, -999, -999, -999,
  117040. -999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -999, -999, -999, -999,
  117042. -999, -999, -999, -999, -999, -999, -999, -999},
  117043. {-999, -999, -999, -999, -999, -999, -999, -999,
  117044. -999, -109, -103, -97, -93, -87, -81, -70,
  117045. -70, -67, -75, -73, -76, -79, -81, -83,
  117046. -88, -89, -97, -103, -110, -999, -999, -999,
  117047. -999, -999, -999, -999, -999, -999, -999, -999,
  117048. -999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -999, -999, -999, -999},
  117050. {-999, -999, -999, -999, -999, -999, -999, -999,
  117051. -999, -107, -100, -94, -88, -83, -75, -63,
  117052. -59, -59, -63, -66, -60, -62, -67, -67,
  117053. -77, -76, -81, -88, -86, -92, -96, -102,
  117054. -109, -116, -999, -999, -999, -999, -999, -999,
  117055. -999, -999, -999, -999, -999, -999, -999, -999,
  117056. -999, -999, -999, -999, -999, -999, -999, -999},
  117057. {-999, -999, -999, -999, -999, -999, -999, -999,
  117058. -999, -105, -98, -92, -86, -81, -73, -56,
  117059. -52, -47, -55, -60, -58, -52, -51, -45,
  117060. -49, -50, -53, -54, -61, -71, -70, -69,
  117061. -78, -79, -87, -90, -96, -104, -112, -999,
  117062. -999, -999, -999, -999, -999, -999, -999, -999,
  117063. -999, -999, -999, -999, -999, -999, -999, -999},
  117064. {-999, -999, -999, -999, -999, -999, -999, -999,
  117065. -999, -103, -96, -90, -86, -78, -70, -51,
  117066. -42, -47, -48, -55, -54, -54, -53, -42,
  117067. -35, -28, -33, -38, -37, -44, -47, -49,
  117068. -54, -63, -68, -78, -82, -89, -94, -99,
  117069. -104, -109, -114, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -999, -999, -999, -999, -999}},
  117071. /* 2828 Hz */
  117072. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117073. -999, -999, -999, -999, -110, -100, -90, -79,
  117074. -85, -81, -82, -82, -89, -94, -99, -103,
  117075. -109, -115, -999, -999, -999, -999, -999, -999,
  117076. -999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -999, -999, -999, -999, -999,
  117078. -999, -999, -999, -999, -999, -999, -999, -999},
  117079. {-999, -999, -999, -999, -999, -999, -999, -999,
  117080. -999, -999, -999, -999, -105, -97, -85, -72,
  117081. -74, -70, -70, -70, -76, -85, -91, -93,
  117082. -97, -103, -109, -115, -999, -999, -999, -999,
  117083. -999, -999, -999, -999, -999, -999, -999, -999,
  117084. -999, -999, -999, -999, -999, -999, -999, -999,
  117085. -999, -999, -999, -999, -999, -999, -999, -999},
  117086. {-999, -999, -999, -999, -999, -999, -999, -999,
  117087. -999, -999, -999, -999, -112, -93, -81, -68,
  117088. -62, -60, -60, -57, -63, -70, -77, -82,
  117089. -90, -93, -98, -104, -109, -113, -999, -999,
  117090. -999, -999, -999, -999, -999, -999, -999, -999,
  117091. -999, -999, -999, -999, -999, -999, -999, -999,
  117092. -999, -999, -999, -999, -999, -999, -999, -999},
  117093. {-999, -999, -999, -999, -999, -999, -999, -999,
  117094. -999, -999, -999, -113, -100, -93, -84, -63,
  117095. -58, -48, -53, -54, -52, -52, -57, -64,
  117096. -66, -76, -83, -81, -85, -85, -90, -95,
  117097. -98, -101, -103, -106, -108, -111, -999, -999,
  117098. -999, -999, -999, -999, -999, -999, -999, -999,
  117099. -999, -999, -999, -999, -999, -999, -999, -999},
  117100. {-999, -999, -999, -999, -999, -999, -999, -999,
  117101. -999, -999, -999, -105, -95, -86, -74, -53,
  117102. -50, -38, -43, -49, -43, -42, -39, -39,
  117103. -46, -52, -57, -56, -72, -69, -74, -81,
  117104. -87, -92, -94, -97, -99, -102, -105, -108,
  117105. -999, -999, -999, -999, -999, -999, -999, -999,
  117106. -999, -999, -999, -999, -999, -999, -999, -999},
  117107. {-999, -999, -999, -999, -999, -999, -999, -999,
  117108. -999, -999, -108, -99, -90, -76, -66, -45,
  117109. -43, -41, -44, -47, -43, -47, -40, -30,
  117110. -31, -31, -39, -33, -40, -41, -43, -53,
  117111. -59, -70, -73, -77, -79, -82, -84, -87,
  117112. -999, -999, -999, -999, -999, -999, -999, -999,
  117113. -999, -999, -999, -999, -999, -999, -999, -999}},
  117114. /* 4000 Hz */
  117115. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117116. -999, -999, -999, -999, -999, -110, -91, -76,
  117117. -75, -85, -93, -98, -104, -110, -999, -999,
  117118. -999, -999, -999, -999, -999, -999, -999, -999,
  117119. -999, -999, -999, -999, -999, -999, -999, -999,
  117120. -999, -999, -999, -999, -999, -999, -999, -999,
  117121. -999, -999, -999, -999, -999, -999, -999, -999},
  117122. {-999, -999, -999, -999, -999, -999, -999, -999,
  117123. -999, -999, -999, -999, -999, -110, -91, -70,
  117124. -70, -75, -86, -89, -94, -98, -101, -106,
  117125. -110, -999, -999, -999, -999, -999, -999, -999,
  117126. -999, -999, -999, -999, -999, -999, -999, -999,
  117127. -999, -999, -999, -999, -999, -999, -999, -999,
  117128. -999, -999, -999, -999, -999, -999, -999, -999},
  117129. {-999, -999, -999, -999, -999, -999, -999, -999,
  117130. -999, -999, -999, -999, -110, -95, -80, -60,
  117131. -65, -64, -74, -83, -88, -91, -95, -99,
  117132. -103, -107, -110, -999, -999, -999, -999, -999,
  117133. -999, -999, -999, -999, -999, -999, -999, -999,
  117134. -999, -999, -999, -999, -999, -999, -999, -999,
  117135. -999, -999, -999, -999, -999, -999, -999, -999},
  117136. {-999, -999, -999, -999, -999, -999, -999, -999,
  117137. -999, -999, -999, -999, -110, -95, -80, -58,
  117138. -55, -49, -66, -68, -71, -78, -78, -80,
  117139. -88, -85, -89, -97, -100, -105, -110, -999,
  117140. -999, -999, -999, -999, -999, -999, -999, -999,
  117141. -999, -999, -999, -999, -999, -999, -999, -999,
  117142. -999, -999, -999, -999, -999, -999, -999, -999},
  117143. {-999, -999, -999, -999, -999, -999, -999, -999,
  117144. -999, -999, -999, -999, -110, -95, -80, -53,
  117145. -52, -41, -59, -59, -49, -58, -56, -63,
  117146. -86, -79, -90, -93, -98, -103, -107, -112,
  117147. -999, -999, -999, -999, -999, -999, -999, -999,
  117148. -999, -999, -999, -999, -999, -999, -999, -999,
  117149. -999, -999, -999, -999, -999, -999, -999, -999},
  117150. {-999, -999, -999, -999, -999, -999, -999, -999,
  117151. -999, -999, -999, -110, -97, -91, -73, -45,
  117152. -40, -33, -53, -61, -49, -54, -50, -50,
  117153. -60, -52, -67, -74, -81, -92, -96, -100,
  117154. -105, -110, -999, -999, -999, -999, -999, -999,
  117155. -999, -999, -999, -999, -999, -999, -999, -999,
  117156. -999, -999, -999, -999, -999, -999, -999, -999}},
  117157. /* 5657 Hz */
  117158. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117159. -999, -999, -999, -113, -106, -99, -92, -77,
  117160. -80, -88, -97, -106, -115, -999, -999, -999,
  117161. -999, -999, -999, -999, -999, -999, -999, -999,
  117162. -999, -999, -999, -999, -999, -999, -999, -999,
  117163. -999, -999, -999, -999, -999, -999, -999, -999,
  117164. -999, -999, -999, -999, -999, -999, -999, -999},
  117165. {-999, -999, -999, -999, -999, -999, -999, -999,
  117166. -999, -999, -116, -109, -102, -95, -89, -74,
  117167. -72, -88, -87, -95, -102, -109, -116, -999,
  117168. -999, -999, -999, -999, -999, -999, -999, -999,
  117169. -999, -999, -999, -999, -999, -999, -999, -999,
  117170. -999, -999, -999, -999, -999, -999, -999, -999,
  117171. -999, -999, -999, -999, -999, -999, -999, -999},
  117172. {-999, -999, -999, -999, -999, -999, -999, -999,
  117173. -999, -999, -116, -109, -102, -95, -89, -75,
  117174. -66, -74, -77, -78, -86, -87, -90, -96,
  117175. -105, -115, -999, -999, -999, -999, -999, -999,
  117176. -999, -999, -999, -999, -999, -999, -999, -999,
  117177. -999, -999, -999, -999, -999, -999, -999, -999,
  117178. -999, -999, -999, -999, -999, -999, -999, -999},
  117179. {-999, -999, -999, -999, -999, -999, -999, -999,
  117180. -999, -999, -115, -108, -101, -94, -88, -66,
  117181. -56, -61, -70, -65, -78, -72, -83, -84,
  117182. -93, -98, -105, -110, -999, -999, -999, -999,
  117183. -999, -999, -999, -999, -999, -999, -999, -999,
  117184. -999, -999, -999, -999, -999, -999, -999, -999,
  117185. -999, -999, -999, -999, -999, -999, -999, -999},
  117186. {-999, -999, -999, -999, -999, -999, -999, -999,
  117187. -999, -999, -110, -105, -95, -89, -82, -57,
  117188. -52, -52, -59, -56, -59, -58, -69, -67,
  117189. -88, -82, -82, -89, -94, -100, -108, -999,
  117190. -999, -999, -999, -999, -999, -999, -999, -999,
  117191. -999, -999, -999, -999, -999, -999, -999, -999,
  117192. -999, -999, -999, -999, -999, -999, -999, -999},
  117193. {-999, -999, -999, -999, -999, -999, -999, -999,
  117194. -999, -110, -101, -96, -90, -83, -77, -54,
  117195. -43, -38, -50, -48, -52, -48, -42, -42,
  117196. -51, -52, -53, -59, -65, -71, -78, -85,
  117197. -95, -999, -999, -999, -999, -999, -999, -999,
  117198. -999, -999, -999, -999, -999, -999, -999, -999,
  117199. -999, -999, -999, -999, -999, -999, -999, -999}},
  117200. /* 8000 Hz */
  117201. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117202. -999, -999, -999, -999, -120, -105, -86, -68,
  117203. -78, -79, -90, -100, -110, -999, -999, -999,
  117204. -999, -999, -999, -999, -999, -999, -999, -999,
  117205. -999, -999, -999, -999, -999, -999, -999, -999,
  117206. -999, -999, -999, -999, -999, -999, -999, -999,
  117207. -999, -999, -999, -999, -999, -999, -999, -999},
  117208. {-999, -999, -999, -999, -999, -999, -999, -999,
  117209. -999, -999, -999, -999, -120, -105, -86, -66,
  117210. -73, -77, -88, -96, -105, -115, -999, -999,
  117211. -999, -999, -999, -999, -999, -999, -999, -999,
  117212. -999, -999, -999, -999, -999, -999, -999, -999,
  117213. -999, -999, -999, -999, -999, -999, -999, -999,
  117214. -999, -999, -999, -999, -999, -999, -999, -999},
  117215. {-999, -999, -999, -999, -999, -999, -999, -999,
  117216. -999, -999, -999, -120, -105, -92, -80, -61,
  117217. -64, -68, -80, -87, -92, -100, -110, -999,
  117218. -999, -999, -999, -999, -999, -999, -999, -999,
  117219. -999, -999, -999, -999, -999, -999, -999, -999,
  117220. -999, -999, -999, -999, -999, -999, -999, -999,
  117221. -999, -999, -999, -999, -999, -999, -999, -999},
  117222. {-999, -999, -999, -999, -999, -999, -999, -999,
  117223. -999, -999, -999, -120, -104, -91, -79, -52,
  117224. -60, -54, -64, -69, -77, -80, -82, -84,
  117225. -85, -87, -88, -90, -999, -999, -999, -999,
  117226. -999, -999, -999, -999, -999, -999, -999, -999,
  117227. -999, -999, -999, -999, -999, -999, -999, -999,
  117228. -999, -999, -999, -999, -999, -999, -999, -999},
  117229. {-999, -999, -999, -999, -999, -999, -999, -999,
  117230. -999, -999, -999, -118, -100, -87, -77, -49,
  117231. -50, -44, -58, -61, -61, -67, -65, -62,
  117232. -62, -62, -65, -68, -999, -999, -999, -999,
  117233. -999, -999, -999, -999, -999, -999, -999, -999,
  117234. -999, -999, -999, -999, -999, -999, -999, -999,
  117235. -999, -999, -999, -999, -999, -999, -999, -999},
  117236. {-999, -999, -999, -999, -999, -999, -999, -999,
  117237. -999, -999, -999, -115, -98, -84, -62, -49,
  117238. -44, -38, -46, -49, -49, -46, -39, -37,
  117239. -39, -40, -42, -43, -999, -999, -999, -999,
  117240. -999, -999, -999, -999, -999, -999, -999, -999,
  117241. -999, -999, -999, -999, -999, -999, -999, -999,
  117242. -999, -999, -999, -999, -999, -999, -999, -999}},
  117243. /* 11314 Hz */
  117244. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117245. -999, -999, -999, -999, -999, -110, -88, -74,
  117246. -77, -82, -82, -85, -90, -94, -99, -104,
  117247. -999, -999, -999, -999, -999, -999, -999, -999,
  117248. -999, -999, -999, -999, -999, -999, -999, -999,
  117249. -999, -999, -999, -999, -999, -999, -999, -999,
  117250. -999, -999, -999, -999, -999, -999, -999, -999},
  117251. {-999, -999, -999, -999, -999, -999, -999, -999,
  117252. -999, -999, -999, -999, -999, -110, -88, -66,
  117253. -70, -81, -80, -81, -84, -88, -91, -93,
  117254. -999, -999, -999, -999, -999, -999, -999, -999,
  117255. -999, -999, -999, -999, -999, -999, -999, -999,
  117256. -999, -999, -999, -999, -999, -999, -999, -999,
  117257. -999, -999, -999, -999, -999, -999, -999, -999},
  117258. {-999, -999, -999, -999, -999, -999, -999, -999,
  117259. -999, -999, -999, -999, -999, -110, -88, -61,
  117260. -63, -70, -71, -74, -77, -80, -83, -85,
  117261. -999, -999, -999, -999, -999, -999, -999, -999,
  117262. -999, -999, -999, -999, -999, -999, -999, -999,
  117263. -999, -999, -999, -999, -999, -999, -999, -999,
  117264. -999, -999, -999, -999, -999, -999, -999, -999},
  117265. {-999, -999, -999, -999, -999, -999, -999, -999,
  117266. -999, -999, -999, -999, -999, -110, -86, -62,
  117267. -63, -62, -62, -58, -52, -50, -50, -52,
  117268. -54, -999, -999, -999, -999, -999, -999, -999,
  117269. -999, -999, -999, -999, -999, -999, -999, -999,
  117270. -999, -999, -999, -999, -999, -999, -999, -999,
  117271. -999, -999, -999, -999, -999, -999, -999, -999},
  117272. {-999, -999, -999, -999, -999, -999, -999, -999,
  117273. -999, -999, -999, -999, -118, -108, -84, -53,
  117274. -50, -50, -50, -55, -47, -45, -40, -40,
  117275. -40, -999, -999, -999, -999, -999, -999, -999,
  117276. -999, -999, -999, -999, -999, -999, -999, -999,
  117277. -999, -999, -999, -999, -999, -999, -999, -999,
  117278. -999, -999, -999, -999, -999, -999, -999, -999},
  117279. {-999, -999, -999, -999, -999, -999, -999, -999,
  117280. -999, -999, -999, -999, -118, -100, -73, -43,
  117281. -37, -42, -43, -53, -38, -37, -35, -35,
  117282. -38, -999, -999, -999, -999, -999, -999, -999,
  117283. -999, -999, -999, -999, -999, -999, -999, -999,
  117284. -999, -999, -999, -999, -999, -999, -999, -999,
  117285. -999, -999, -999, -999, -999, -999, -999, -999}},
  117286. /* 16000 Hz */
  117287. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117288. -999, -999, -999, -110, -100, -91, -84, -74,
  117289. -80, -80, -80, -80, -80, -999, -999, -999,
  117290. -999, -999, -999, -999, -999, -999, -999, -999,
  117291. -999, -999, -999, -999, -999, -999, -999, -999,
  117292. -999, -999, -999, -999, -999, -999, -999, -999,
  117293. -999, -999, -999, -999, -999, -999, -999, -999},
  117294. {-999, -999, -999, -999, -999, -999, -999, -999,
  117295. -999, -999, -999, -110, -100, -91, -84, -74,
  117296. -68, -68, -68, -68, -68, -999, -999, -999,
  117297. -999, -999, -999, -999, -999, -999, -999, -999,
  117298. -999, -999, -999, -999, -999, -999, -999, -999,
  117299. -999, -999, -999, -999, -999, -999, -999, -999,
  117300. -999, -999, -999, -999, -999, -999, -999, -999},
  117301. {-999, -999, -999, -999, -999, -999, -999, -999,
  117302. -999, -999, -999, -110, -100, -86, -78, -70,
  117303. -60, -45, -30, -21, -999, -999, -999, -999,
  117304. -999, -999, -999, -999, -999, -999, -999, -999,
  117305. -999, -999, -999, -999, -999, -999, -999, -999,
  117306. -999, -999, -999, -999, -999, -999, -999, -999,
  117307. -999, -999, -999, -999, -999, -999, -999, -999},
  117308. {-999, -999, -999, -999, -999, -999, -999, -999,
  117309. -999, -999, -999, -110, -100, -87, -78, -67,
  117310. -48, -38, -29, -21, -999, -999, -999, -999,
  117311. -999, -999, -999, -999, -999, -999, -999, -999,
  117312. -999, -999, -999, -999, -999, -999, -999, -999,
  117313. -999, -999, -999, -999, -999, -999, -999, -999,
  117314. -999, -999, -999, -999, -999, -999, -999, -999},
  117315. {-999, -999, -999, -999, -999, -999, -999, -999,
  117316. -999, -999, -999, -110, -100, -86, -69, -56,
  117317. -45, -35, -33, -29, -999, -999, -999, -999,
  117318. -999, -999, -999, -999, -999, -999, -999, -999,
  117319. -999, -999, -999, -999, -999, -999, -999, -999,
  117320. -999, -999, -999, -999, -999, -999, -999, -999,
  117321. -999, -999, -999, -999, -999, -999, -999, -999},
  117322. {-999, -999, -999, -999, -999, -999, -999, -999,
  117323. -999, -999, -999, -110, -100, -83, -71, -48,
  117324. -27, -38, -37, -34, -999, -999, -999, -999,
  117325. -999, -999, -999, -999, -999, -999, -999, -999,
  117326. -999, -999, -999, -999, -999, -999, -999, -999,
  117327. -999, -999, -999, -999, -999, -999, -999, -999,
  117328. -999, -999, -999, -999, -999, -999, -999, -999}}
  117329. };
  117330. #endif
  117331. /*** End of inlined file: masking.h ***/
  117332. #define NEGINF -9999.f
  117333. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117334. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117335. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117336. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117337. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117338. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117339. look->channels=vi->channels;
  117340. look->ampmax=-9999.;
  117341. look->gi=gi;
  117342. return(look);
  117343. }
  117344. void _vp_global_free(vorbis_look_psy_global *look){
  117345. if(look){
  117346. memset(look,0,sizeof(*look));
  117347. _ogg_free(look);
  117348. }
  117349. }
  117350. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117351. if(i){
  117352. memset(i,0,sizeof(*i));
  117353. _ogg_free(i);
  117354. }
  117355. }
  117356. void _vi_psy_free(vorbis_info_psy *i){
  117357. if(i){
  117358. memset(i,0,sizeof(*i));
  117359. _ogg_free(i);
  117360. }
  117361. }
  117362. static void min_curve(float *c,
  117363. float *c2){
  117364. int i;
  117365. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117366. }
  117367. static void max_curve(float *c,
  117368. float *c2){
  117369. int i;
  117370. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117371. }
  117372. static void attenuate_curve(float *c,float att){
  117373. int i;
  117374. for(i=0;i<EHMER_MAX;i++)
  117375. c[i]+=att;
  117376. }
  117377. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117378. float center_boost, float center_decay_rate){
  117379. int i,j,k,m;
  117380. float ath[EHMER_MAX];
  117381. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117382. float athc[P_LEVELS][EHMER_MAX];
  117383. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117384. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117385. memset(workc,0,sizeof(workc));
  117386. for(i=0;i<P_BANDS;i++){
  117387. /* we add back in the ATH to avoid low level curves falling off to
  117388. -infinity and unnecessarily cutting off high level curves in the
  117389. curve limiting (last step). */
  117390. /* A half-band's settings must be valid over the whole band, and
  117391. it's better to mask too little than too much */
  117392. int ath_offset=i*4;
  117393. for(j=0;j<EHMER_MAX;j++){
  117394. float min=999.;
  117395. for(k=0;k<4;k++)
  117396. if(j+k+ath_offset<MAX_ATH){
  117397. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117398. }else{
  117399. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117400. }
  117401. ath[j]=min;
  117402. }
  117403. /* copy curves into working space, replicate the 50dB curve to 30
  117404. and 40, replicate the 100dB curve to 110 */
  117405. for(j=0;j<6;j++)
  117406. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117407. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117408. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117409. /* apply centered curve boost/decay */
  117410. for(j=0;j<P_LEVELS;j++){
  117411. for(k=0;k<EHMER_MAX;k++){
  117412. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117413. if(adj<0. && center_boost>0)adj=0.;
  117414. if(adj>0. && center_boost<0)adj=0.;
  117415. workc[i][j][k]+=adj;
  117416. }
  117417. }
  117418. /* normalize curves so the driving amplitude is 0dB */
  117419. /* make temp curves with the ATH overlayed */
  117420. for(j=0;j<P_LEVELS;j++){
  117421. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117422. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117423. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117424. max_curve(athc[j],workc[i][j]);
  117425. }
  117426. /* Now limit the louder curves.
  117427. the idea is this: We don't know what the playback attenuation
  117428. will be; 0dB SL moves every time the user twiddles the volume
  117429. knob. So that means we have to use a single 'most pessimal' curve
  117430. for all masking amplitudes, right? Wrong. The *loudest* sound
  117431. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117432. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117433. etc... */
  117434. for(j=1;j<P_LEVELS;j++){
  117435. min_curve(athc[j],athc[j-1]);
  117436. min_curve(workc[i][j],athc[j]);
  117437. }
  117438. }
  117439. for(i=0;i<P_BANDS;i++){
  117440. int hi_curve,lo_curve,bin;
  117441. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117442. /* low frequency curves are measured with greater resolution than
  117443. the MDCT/FFT will actually give us; we want the curve applied
  117444. to the tone data to be pessimistic and thus apply the minimum
  117445. masking possible for a given bin. That means that a single bin
  117446. could span more than one octave and that the curve will be a
  117447. composite of multiple octaves. It also may mean that a single
  117448. bin may span > an eighth of an octave and that the eighth
  117449. octave values may also be composited. */
  117450. /* which octave curves will we be compositing? */
  117451. bin=floor(fromOC(i*.5)/binHz);
  117452. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117453. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117454. if(lo_curve>i)lo_curve=i;
  117455. if(lo_curve<0)lo_curve=0;
  117456. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117457. for(m=0;m<P_LEVELS;m++){
  117458. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117459. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117460. /* render the curve into bins, then pull values back into curve.
  117461. The point is that any inherent subsampling aliasing results in
  117462. a safe minimum */
  117463. for(k=lo_curve;k<=hi_curve;k++){
  117464. int l=0;
  117465. for(j=0;j<EHMER_MAX;j++){
  117466. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117467. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117468. if(lo_bin<0)lo_bin=0;
  117469. if(lo_bin>n)lo_bin=n;
  117470. if(lo_bin<l)l=lo_bin;
  117471. if(hi_bin<0)hi_bin=0;
  117472. if(hi_bin>n)hi_bin=n;
  117473. for(;l<hi_bin && l<n;l++)
  117474. if(brute_buffer[l]>workc[k][m][j])
  117475. brute_buffer[l]=workc[k][m][j];
  117476. }
  117477. for(;l<n;l++)
  117478. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117479. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117480. }
  117481. /* be equally paranoid about being valid up to next half ocatve */
  117482. if(i+1<P_BANDS){
  117483. int l=0;
  117484. k=i+1;
  117485. for(j=0;j<EHMER_MAX;j++){
  117486. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117487. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117488. if(lo_bin<0)lo_bin=0;
  117489. if(lo_bin>n)lo_bin=n;
  117490. if(lo_bin<l)l=lo_bin;
  117491. if(hi_bin<0)hi_bin=0;
  117492. if(hi_bin>n)hi_bin=n;
  117493. for(;l<hi_bin && l<n;l++)
  117494. if(brute_buffer[l]>workc[k][m][j])
  117495. brute_buffer[l]=workc[k][m][j];
  117496. }
  117497. for(;l<n;l++)
  117498. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117499. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117500. }
  117501. for(j=0;j<EHMER_MAX;j++){
  117502. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117503. if(bin<0){
  117504. ret[i][m][j+2]=-999.;
  117505. }else{
  117506. if(bin>=n){
  117507. ret[i][m][j+2]=-999.;
  117508. }else{
  117509. ret[i][m][j+2]=brute_buffer[bin];
  117510. }
  117511. }
  117512. }
  117513. /* add fenceposts */
  117514. for(j=0;j<EHMER_OFFSET;j++)
  117515. if(ret[i][m][j+2]>-200.f)break;
  117516. ret[i][m][0]=j;
  117517. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117518. if(ret[i][m][j+2]>-200.f)
  117519. break;
  117520. ret[i][m][1]=j;
  117521. }
  117522. }
  117523. return(ret);
  117524. }
  117525. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117526. vorbis_info_psy_global *gi,int n,long rate){
  117527. long i,j,lo=-99,hi=1;
  117528. long maxoc;
  117529. memset(p,0,sizeof(*p));
  117530. p->eighth_octave_lines=gi->eighth_octave_lines;
  117531. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117532. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117533. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117534. p->total_octave_lines=maxoc-p->firstoc+1;
  117535. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117536. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117537. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117538. p->vi=vi;
  117539. p->n=n;
  117540. p->rate=rate;
  117541. /* AoTuV HF weighting */
  117542. p->m_val = 1.;
  117543. if(rate < 26000) p->m_val = 0;
  117544. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117545. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117546. /* set up the lookups for a given blocksize and sample rate */
  117547. for(i=0,j=0;i<MAX_ATH-1;i++){
  117548. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117549. float base=ATH[i];
  117550. if(j<endpos){
  117551. float delta=(ATH[i+1]-base)/(endpos-j);
  117552. for(;j<endpos && j<n;j++){
  117553. p->ath[j]=base+100.;
  117554. base+=delta;
  117555. }
  117556. }
  117557. }
  117558. for(i=0;i<n;i++){
  117559. float bark=toBARK(rate/(2*n)*i);
  117560. for(;lo+vi->noisewindowlomin<i &&
  117561. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117562. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117563. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117564. p->bark[i]=((lo-1)<<16)+(hi-1);
  117565. }
  117566. for(i=0;i<n;i++)
  117567. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117568. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117569. vi->tone_centerboost,vi->tone_decay);
  117570. /* set up rolling noise median */
  117571. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117572. for(i=0;i<P_NOISECURVES;i++)
  117573. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117574. for(i=0;i<n;i++){
  117575. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117576. int inthalfoc;
  117577. float del;
  117578. if(halfoc<0)halfoc=0;
  117579. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117580. inthalfoc=(int)halfoc;
  117581. del=halfoc-inthalfoc;
  117582. for(j=0;j<P_NOISECURVES;j++)
  117583. p->noiseoffset[j][i]=
  117584. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117585. p->vi->noiseoff[j][inthalfoc+1]*del;
  117586. }
  117587. #if 0
  117588. {
  117589. static int ls=0;
  117590. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117591. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117592. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117593. }
  117594. #endif
  117595. }
  117596. void _vp_psy_clear(vorbis_look_psy *p){
  117597. int i,j;
  117598. if(p){
  117599. if(p->ath)_ogg_free(p->ath);
  117600. if(p->octave)_ogg_free(p->octave);
  117601. if(p->bark)_ogg_free(p->bark);
  117602. if(p->tonecurves){
  117603. for(i=0;i<P_BANDS;i++){
  117604. for(j=0;j<P_LEVELS;j++){
  117605. _ogg_free(p->tonecurves[i][j]);
  117606. }
  117607. _ogg_free(p->tonecurves[i]);
  117608. }
  117609. _ogg_free(p->tonecurves);
  117610. }
  117611. if(p->noiseoffset){
  117612. for(i=0;i<P_NOISECURVES;i++){
  117613. _ogg_free(p->noiseoffset[i]);
  117614. }
  117615. _ogg_free(p->noiseoffset);
  117616. }
  117617. memset(p,0,sizeof(*p));
  117618. }
  117619. }
  117620. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117621. static void seed_curve(float *seed,
  117622. const float **curves,
  117623. float amp,
  117624. int oc, int n,
  117625. int linesper,float dBoffset){
  117626. int i,post1;
  117627. int seedptr;
  117628. const float *posts,*curve;
  117629. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117630. choice=max(choice,0);
  117631. choice=min(choice,P_LEVELS-1);
  117632. posts=curves[choice];
  117633. curve=posts+2;
  117634. post1=(int)posts[1];
  117635. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117636. for(i=posts[0];i<post1;i++){
  117637. if(seedptr>0){
  117638. float lin=amp+curve[i];
  117639. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117640. }
  117641. seedptr+=linesper;
  117642. if(seedptr>=n)break;
  117643. }
  117644. }
  117645. static void seed_loop(vorbis_look_psy *p,
  117646. const float ***curves,
  117647. const float *f,
  117648. const float *flr,
  117649. float *seed,
  117650. float specmax){
  117651. vorbis_info_psy *vi=p->vi;
  117652. long n=p->n,i;
  117653. float dBoffset=vi->max_curve_dB-specmax;
  117654. /* prime the working vector with peak values */
  117655. for(i=0;i<n;i++){
  117656. float max=f[i];
  117657. long oc=p->octave[i];
  117658. while(i+1<n && p->octave[i+1]==oc){
  117659. i++;
  117660. if(f[i]>max)max=f[i];
  117661. }
  117662. if(max+6.f>flr[i]){
  117663. oc=oc>>p->shiftoc;
  117664. if(oc>=P_BANDS)oc=P_BANDS-1;
  117665. if(oc<0)oc=0;
  117666. seed_curve(seed,
  117667. curves[oc],
  117668. max,
  117669. p->octave[i]-p->firstoc,
  117670. p->total_octave_lines,
  117671. p->eighth_octave_lines,
  117672. dBoffset);
  117673. }
  117674. }
  117675. }
  117676. static void seed_chase(float *seeds, int linesper, long n){
  117677. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117678. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117679. long stack=0;
  117680. long pos=0;
  117681. long i;
  117682. for(i=0;i<n;i++){
  117683. if(stack<2){
  117684. posstack[stack]=i;
  117685. ampstack[stack++]=seeds[i];
  117686. }else{
  117687. while(1){
  117688. if(seeds[i]<ampstack[stack-1]){
  117689. posstack[stack]=i;
  117690. ampstack[stack++]=seeds[i];
  117691. break;
  117692. }else{
  117693. if(i<posstack[stack-1]+linesper){
  117694. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117695. i<posstack[stack-2]+linesper){
  117696. /* we completely overlap, making stack-1 irrelevant. pop it */
  117697. stack--;
  117698. continue;
  117699. }
  117700. }
  117701. posstack[stack]=i;
  117702. ampstack[stack++]=seeds[i];
  117703. break;
  117704. }
  117705. }
  117706. }
  117707. }
  117708. /* the stack now contains only the positions that are relevant. Scan
  117709. 'em straight through */
  117710. for(i=0;i<stack;i++){
  117711. long endpos;
  117712. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117713. endpos=posstack[i+1];
  117714. }else{
  117715. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117716. discarded in short frames */
  117717. }
  117718. if(endpos>n)endpos=n;
  117719. for(;pos<endpos;pos++)
  117720. seeds[pos]=ampstack[i];
  117721. }
  117722. /* there. Linear time. I now remember this was on a problem set I
  117723. had in Grad Skool... I didn't solve it at the time ;-) */
  117724. }
  117725. /* bleaugh, this is more complicated than it needs to be */
  117726. #include<stdio.h>
  117727. static void max_seeds(vorbis_look_psy *p,
  117728. float *seed,
  117729. float *flr){
  117730. long n=p->total_octave_lines;
  117731. int linesper=p->eighth_octave_lines;
  117732. long linpos=0;
  117733. long pos;
  117734. seed_chase(seed,linesper,n); /* for masking */
  117735. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117736. while(linpos+1<p->n){
  117737. float minV=seed[pos];
  117738. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117739. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117740. while(pos+1<=end){
  117741. pos++;
  117742. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117743. minV=seed[pos];
  117744. }
  117745. end=pos+p->firstoc;
  117746. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117747. if(flr[linpos]<minV)flr[linpos]=minV;
  117748. }
  117749. {
  117750. float minV=seed[p->total_octave_lines-1];
  117751. for(;linpos<p->n;linpos++)
  117752. if(flr[linpos]<minV)flr[linpos]=minV;
  117753. }
  117754. }
  117755. static void bark_noise_hybridmp(int n,const long *b,
  117756. const float *f,
  117757. float *noise,
  117758. const float offset,
  117759. const int fixed){
  117760. float *N=(float*) alloca(n*sizeof(*N));
  117761. float *X=(float*) alloca(n*sizeof(*N));
  117762. float *XX=(float*) alloca(n*sizeof(*N));
  117763. float *Y=(float*) alloca(n*sizeof(*N));
  117764. float *XY=(float*) alloca(n*sizeof(*N));
  117765. float tN, tX, tXX, tY, tXY;
  117766. int i;
  117767. int lo, hi;
  117768. float R, A, B, D;
  117769. float w, x, y;
  117770. tN = tX = tXX = tY = tXY = 0.f;
  117771. y = f[0] + offset;
  117772. if (y < 1.f) y = 1.f;
  117773. w = y * y * .5;
  117774. tN += w;
  117775. tX += w;
  117776. tY += w * y;
  117777. N[0] = tN;
  117778. X[0] = tX;
  117779. XX[0] = tXX;
  117780. Y[0] = tY;
  117781. XY[0] = tXY;
  117782. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117783. y = f[i] + offset;
  117784. if (y < 1.f) y = 1.f;
  117785. w = y * y;
  117786. tN += w;
  117787. tX += w * x;
  117788. tXX += w * x * x;
  117789. tY += w * y;
  117790. tXY += w * x * y;
  117791. N[i] = tN;
  117792. X[i] = tX;
  117793. XX[i] = tXX;
  117794. Y[i] = tY;
  117795. XY[i] = tXY;
  117796. }
  117797. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117798. lo = b[i] >> 16;
  117799. if( lo>=0 ) break;
  117800. hi = b[i] & 0xffff;
  117801. tN = N[hi] + N[-lo];
  117802. tX = X[hi] - X[-lo];
  117803. tXX = XX[hi] + XX[-lo];
  117804. tY = Y[hi] + Y[-lo];
  117805. tXY = XY[hi] - XY[-lo];
  117806. A = tY * tXX - tX * tXY;
  117807. B = tN * tXY - tX * tY;
  117808. D = tN * tXX - tX * tX;
  117809. R = (A + x * B) / D;
  117810. if (R < 0.f)
  117811. R = 0.f;
  117812. noise[i] = R - offset;
  117813. }
  117814. for ( ;; i++, x += 1.f) {
  117815. lo = b[i] >> 16;
  117816. hi = b[i] & 0xffff;
  117817. if(hi>=n)break;
  117818. tN = N[hi] - N[lo];
  117819. tX = X[hi] - X[lo];
  117820. tXX = XX[hi] - XX[lo];
  117821. tY = Y[hi] - Y[lo];
  117822. tXY = XY[hi] - XY[lo];
  117823. A = tY * tXX - tX * tXY;
  117824. B = tN * tXY - tX * tY;
  117825. D = tN * tXX - tX * tX;
  117826. R = (A + x * B) / D;
  117827. if (R < 0.f) R = 0.f;
  117828. noise[i] = R - offset;
  117829. }
  117830. for ( ; i < n; i++, x += 1.f) {
  117831. R = (A + x * B) / D;
  117832. if (R < 0.f) R = 0.f;
  117833. noise[i] = R - offset;
  117834. }
  117835. if (fixed <= 0) return;
  117836. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117837. hi = i + fixed / 2;
  117838. lo = hi - fixed;
  117839. if(lo>=0)break;
  117840. tN = N[hi] + N[-lo];
  117841. tX = X[hi] - X[-lo];
  117842. tXX = XX[hi] + XX[-lo];
  117843. tY = Y[hi] + Y[-lo];
  117844. tXY = XY[hi] - XY[-lo];
  117845. A = tY * tXX - tX * tXY;
  117846. B = tN * tXY - tX * tY;
  117847. D = tN * tXX - tX * tX;
  117848. R = (A + x * B) / D;
  117849. if (R - offset < noise[i]) noise[i] = R - offset;
  117850. }
  117851. for ( ;; i++, x += 1.f) {
  117852. hi = i + fixed / 2;
  117853. lo = hi - fixed;
  117854. if(hi>=n)break;
  117855. tN = N[hi] - N[lo];
  117856. tX = X[hi] - X[lo];
  117857. tXX = XX[hi] - XX[lo];
  117858. tY = Y[hi] - Y[lo];
  117859. tXY = XY[hi] - XY[lo];
  117860. A = tY * tXX - tX * tXY;
  117861. B = tN * tXY - tX * tY;
  117862. D = tN * tXX - tX * tX;
  117863. R = (A + x * B) / D;
  117864. if (R - offset < noise[i]) noise[i] = R - offset;
  117865. }
  117866. for ( ; i < n; i++, x += 1.f) {
  117867. R = (A + x * B) / D;
  117868. if (R - offset < noise[i]) noise[i] = R - offset;
  117869. }
  117870. }
  117871. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117872. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117873. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117874. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117875. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117876. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117877. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117878. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117879. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117880. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117881. 973377.F, 913981.F, 858210.F, 805842.F,
  117882. 756669.F, 710497.F, 667142.F, 626433.F,
  117883. 588208.F, 552316.F, 518613.F, 486967.F,
  117884. 457252.F, 429351.F, 403152.F, 378551.F,
  117885. 355452.F, 333762.F, 313396.F, 294273.F,
  117886. 276316.F, 259455.F, 243623.F, 228757.F,
  117887. 214798.F, 201691.F, 189384.F, 177828.F,
  117888. 166977.F, 156788.F, 147221.F, 138237.F,
  117889. 129802.F, 121881.F, 114444.F, 107461.F,
  117890. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117891. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117892. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117893. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117894. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117895. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117896. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117897. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117898. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117899. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117900. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117901. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117902. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117903. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117904. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117905. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117906. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117907. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117908. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117909. 842.910F, 791.475F, 743.179F, 697.830F,
  117910. 655.249F, 615.265F, 577.722F, 542.469F,
  117911. 509.367F, 478.286F, 449.101F, 421.696F,
  117912. 395.964F, 371.803F, 349.115F, 327.812F,
  117913. 307.809F, 289.026F, 271.390F, 254.830F,
  117914. 239.280F, 224.679F, 210.969F, 198.096F,
  117915. 186.008F, 174.658F, 164.000F, 153.993F,
  117916. 144.596F, 135.773F, 127.488F, 119.708F,
  117917. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117918. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117919. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117920. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117921. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117922. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117923. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117924. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117925. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117926. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117927. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117928. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117929. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117930. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117931. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117932. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117933. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117934. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117935. 1.20790F, 1.13419F, 1.06499F, 1.F
  117936. };
  117937. void _vp_remove_floor(vorbis_look_psy *p,
  117938. float *mdct,
  117939. int *codedflr,
  117940. float *residue,
  117941. int sliding_lowpass){
  117942. int i,n=p->n;
  117943. if(sliding_lowpass>n)sliding_lowpass=n;
  117944. for(i=0;i<sliding_lowpass;i++){
  117945. residue[i]=
  117946. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117947. }
  117948. for(;i<n;i++)
  117949. residue[i]=0.;
  117950. }
  117951. void _vp_noisemask(vorbis_look_psy *p,
  117952. float *logmdct,
  117953. float *logmask){
  117954. int i,n=p->n;
  117955. float *work=(float*) alloca(n*sizeof(*work));
  117956. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117957. 140.,-1);
  117958. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117959. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117960. p->vi->noisewindowfixed);
  117961. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117962. #if 0
  117963. {
  117964. static int seq=0;
  117965. float work2[n];
  117966. for(i=0;i<n;i++){
  117967. work2[i]=logmask[i]+work[i];
  117968. }
  117969. if(seq&1)
  117970. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117971. else
  117972. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117973. if(seq&1)
  117974. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117975. else
  117976. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117977. seq++;
  117978. }
  117979. #endif
  117980. for(i=0;i<n;i++){
  117981. int dB=logmask[i]+.5;
  117982. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117983. if(dB<0)dB=0;
  117984. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117985. }
  117986. }
  117987. void _vp_tonemask(vorbis_look_psy *p,
  117988. float *logfft,
  117989. float *logmask,
  117990. float global_specmax,
  117991. float local_specmax){
  117992. int i,n=p->n;
  117993. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117994. float att=local_specmax+p->vi->ath_adjatt;
  117995. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117996. /* set the ATH (floating below localmax, not global max by a
  117997. specified att) */
  117998. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117999. for(i=0;i<n;i++)
  118000. logmask[i]=p->ath[i]+att;
  118001. /* tone masking */
  118002. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  118003. max_seeds(p,seed,logmask);
  118004. }
  118005. void _vp_offset_and_mix(vorbis_look_psy *p,
  118006. float *noise,
  118007. float *tone,
  118008. int offset_select,
  118009. float *logmask,
  118010. float *mdct,
  118011. float *logmdct){
  118012. int i,n=p->n;
  118013. float de, coeffi, cx;/* AoTuV */
  118014. float toneatt=p->vi->tone_masteratt[offset_select];
  118015. cx = p->m_val;
  118016. for(i=0;i<n;i++){
  118017. float val= noise[i]+p->noiseoffset[offset_select][i];
  118018. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  118019. logmask[i]=max(val,tone[i]+toneatt);
  118020. /* AoTuV */
  118021. /** @ M1 **
  118022. The following codes improve a noise problem.
  118023. A fundamental idea uses the value of masking and carries out
  118024. the relative compensation of the MDCT.
  118025. However, this code is not perfect and all noise problems cannot be solved.
  118026. by Aoyumi @ 2004/04/18
  118027. */
  118028. if(offset_select == 1) {
  118029. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  118030. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  118031. if(val > coeffi){
  118032. /* mdct value is > -17.2 dB below floor */
  118033. de = 1.0-((val-coeffi)*0.005*cx);
  118034. /* pro-rated attenuation:
  118035. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  118036. -0.77 dB boost if mdct value is 0dB (relative to floor)
  118037. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  118038. etc... */
  118039. if(de < 0) de = 0.0001;
  118040. }else
  118041. /* mdct value is <= -17.2 dB below floor */
  118042. de = 1.0-((val-coeffi)*0.0003*cx);
  118043. /* pro-rated attenuation:
  118044. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  118045. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  118046. etc... */
  118047. mdct[i] *= de;
  118048. }
  118049. }
  118050. }
  118051. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  118052. vorbis_info *vi=vd->vi;
  118053. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  118054. vorbis_info_psy_global *gi=&ci->psy_g_param;
  118055. int n=ci->blocksizes[vd->W]/2;
  118056. float secs=(float)n/vi->rate;
  118057. amp+=secs*gi->ampmax_att_per_sec;
  118058. if(amp<-9999)amp=-9999;
  118059. return(amp);
  118060. }
  118061. static void couple_lossless(float A, float B,
  118062. float *qA, float *qB){
  118063. int test1=fabs(*qA)>fabs(*qB);
  118064. test1-= fabs(*qA)<fabs(*qB);
  118065. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  118066. if(test1==1){
  118067. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  118068. }else{
  118069. float temp=*qB;
  118070. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  118071. *qA=temp;
  118072. }
  118073. if(*qB>fabs(*qA)*1.9999f){
  118074. *qB= -fabs(*qA)*2.f;
  118075. *qA= -*qA;
  118076. }
  118077. }
  118078. static float hypot_lookup[32]={
  118079. -0.009935, -0.011245, -0.012726, -0.014397,
  118080. -0.016282, -0.018407, -0.020800, -0.023494,
  118081. -0.026522, -0.029923, -0.033737, -0.038010,
  118082. -0.042787, -0.048121, -0.054064, -0.060671,
  118083. -0.068000, -0.076109, -0.085054, -0.094892,
  118084. -0.105675, -0.117451, -0.130260, -0.144134,
  118085. -0.159093, -0.175146, -0.192286, -0.210490,
  118086. -0.229718, -0.249913, -0.271001, -0.292893};
  118087. static void precomputed_couple_point(float premag,
  118088. int floorA,int floorB,
  118089. float *mag, float *ang){
  118090. int test=(floorA>floorB)-1;
  118091. int offset=31-abs(floorA-floorB);
  118092. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  118093. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  118094. *mag=premag*floormag;
  118095. *ang=0.f;
  118096. }
  118097. /* just like below, this is currently set up to only do
  118098. single-step-depth coupling. Otherwise, we'd have to do more
  118099. copying (which will be inevitable later) */
  118100. /* doing the real circular magnitude calculation is audibly superior
  118101. to (A+B)/sqrt(2) */
  118102. static float dipole_hypot(float a, float b){
  118103. if(a>0.){
  118104. if(b>0.)return sqrt(a*a+b*b);
  118105. if(a>-b)return sqrt(a*a-b*b);
  118106. return -sqrt(b*b-a*a);
  118107. }
  118108. if(b<0.)return -sqrt(a*a+b*b);
  118109. if(-a>b)return -sqrt(a*a-b*b);
  118110. return sqrt(b*b-a*a);
  118111. }
  118112. static float round_hypot(float a, float b){
  118113. if(a>0.){
  118114. if(b>0.)return sqrt(a*a+b*b);
  118115. if(a>-b)return sqrt(a*a+b*b);
  118116. return -sqrt(b*b+a*a);
  118117. }
  118118. if(b<0.)return -sqrt(a*a+b*b);
  118119. if(-a>b)return -sqrt(a*a+b*b);
  118120. return sqrt(b*b+a*a);
  118121. }
  118122. /* revert to round hypot for now */
  118123. float **_vp_quantize_couple_memo(vorbis_block *vb,
  118124. vorbis_info_psy_global *g,
  118125. vorbis_look_psy *p,
  118126. vorbis_info_mapping0 *vi,
  118127. float **mdct){
  118128. int i,j,n=p->n;
  118129. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118130. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118131. for(i=0;i<vi->coupling_steps;i++){
  118132. float *mdctM=mdct[vi->coupling_mag[i]];
  118133. float *mdctA=mdct[vi->coupling_ang[i]];
  118134. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118135. for(j=0;j<limit;j++)
  118136. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  118137. for(;j<n;j++)
  118138. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  118139. }
  118140. return(ret);
  118141. }
  118142. /* this is for per-channel noise normalization */
  118143. static int apsort(const void *a, const void *b){
  118144. float f1=fabs(**(float**)a);
  118145. float f2=fabs(**(float**)b);
  118146. return (f1<f2)-(f1>f2);
  118147. }
  118148. int **_vp_quantize_couple_sort(vorbis_block *vb,
  118149. vorbis_look_psy *p,
  118150. vorbis_info_mapping0 *vi,
  118151. float **mags){
  118152. if(p->vi->normal_point_p){
  118153. int i,j,k,n=p->n;
  118154. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118155. int partition=p->vi->normal_partition;
  118156. float **work=(float**) alloca(sizeof(*work)*partition);
  118157. for(i=0;i<vi->coupling_steps;i++){
  118158. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118159. for(j=0;j<n;j+=partition){
  118160. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  118161. qsort(work,partition,sizeof(*work),apsort);
  118162. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  118163. }
  118164. }
  118165. return(ret);
  118166. }
  118167. return(NULL);
  118168. }
  118169. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  118170. float *magnitudes,int *sortedindex){
  118171. int i,j,n=p->n;
  118172. vorbis_info_psy *vi=p->vi;
  118173. int partition=vi->normal_partition;
  118174. float **work=(float**) alloca(sizeof(*work)*partition);
  118175. int start=vi->normal_start;
  118176. for(j=start;j<n;j+=partition){
  118177. if(j+partition>n)partition=n-j;
  118178. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  118179. qsort(work,partition,sizeof(*work),apsort);
  118180. for(i=0;i<partition;i++){
  118181. sortedindex[i+j-start]=work[i]-magnitudes;
  118182. }
  118183. }
  118184. }
  118185. void _vp_noise_normalize(vorbis_look_psy *p,
  118186. float *in,float *out,int *sortedindex){
  118187. int flag=0,i,j=0,n=p->n;
  118188. vorbis_info_psy *vi=p->vi;
  118189. int partition=vi->normal_partition;
  118190. int start=vi->normal_start;
  118191. if(start>n)start=n;
  118192. if(vi->normal_channel_p){
  118193. for(;j<start;j++)
  118194. out[j]=rint(in[j]);
  118195. for(;j+partition<=n;j+=partition){
  118196. float acc=0.;
  118197. int k;
  118198. for(i=j;i<j+partition;i++)
  118199. acc+=in[i]*in[i];
  118200. for(i=0;i<partition;i++){
  118201. k=sortedindex[i+j-start];
  118202. if(in[k]*in[k]>=.25f){
  118203. out[k]=rint(in[k]);
  118204. acc-=in[k]*in[k];
  118205. flag=1;
  118206. }else{
  118207. if(acc<vi->normal_thresh)break;
  118208. out[k]=unitnorm(in[k]);
  118209. acc-=1.;
  118210. }
  118211. }
  118212. for(;i<partition;i++){
  118213. k=sortedindex[i+j-start];
  118214. out[k]=0.;
  118215. }
  118216. }
  118217. }
  118218. for(;j<n;j++)
  118219. out[j]=rint(in[j]);
  118220. }
  118221. void _vp_couple(int blobno,
  118222. vorbis_info_psy_global *g,
  118223. vorbis_look_psy *p,
  118224. vorbis_info_mapping0 *vi,
  118225. float **res,
  118226. float **mag_memo,
  118227. int **mag_sort,
  118228. int **ifloor,
  118229. int *nonzero,
  118230. int sliding_lowpass){
  118231. int i,j,k,n=p->n;
  118232. /* perform any requested channel coupling */
  118233. /* point stereo can only be used in a first stage (in this encoder)
  118234. because of the dependency on floor lookups */
  118235. for(i=0;i<vi->coupling_steps;i++){
  118236. /* once we're doing multistage coupling in which a channel goes
  118237. through more than one coupling step, the floor vector
  118238. magnitudes will also have to be recalculated an propogated
  118239. along with PCM. Right now, we're not (that will wait until 5.1
  118240. most likely), so the code isn't here yet. The memory management
  118241. here is all assuming single depth couplings anyway. */
  118242. /* make sure coupling a zero and a nonzero channel results in two
  118243. nonzero channels. */
  118244. if(nonzero[vi->coupling_mag[i]] ||
  118245. nonzero[vi->coupling_ang[i]]){
  118246. float *rM=res[vi->coupling_mag[i]];
  118247. float *rA=res[vi->coupling_ang[i]];
  118248. float *qM=rM+n;
  118249. float *qA=rA+n;
  118250. int *floorM=ifloor[vi->coupling_mag[i]];
  118251. int *floorA=ifloor[vi->coupling_ang[i]];
  118252. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118253. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118254. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118255. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118256. int pointlimit=limit;
  118257. nonzero[vi->coupling_mag[i]]=1;
  118258. nonzero[vi->coupling_ang[i]]=1;
  118259. /* The threshold of a stereo is changed with the size of n */
  118260. if(n > 1000)
  118261. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118262. for(j=0;j<p->n;j+=partition){
  118263. float acc=0.f;
  118264. for(k=0;k<partition;k++){
  118265. int l=k+j;
  118266. if(l<sliding_lowpass){
  118267. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118268. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118269. precomputed_couple_point(mag_memo[i][l],
  118270. floorM[l],floorA[l],
  118271. qM+l,qA+l);
  118272. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118273. }else{
  118274. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118275. }
  118276. }else{
  118277. qM[l]=0.;
  118278. qA[l]=0.;
  118279. }
  118280. }
  118281. if(p->vi->normal_point_p){
  118282. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118283. int l=mag_sort[i][j+k];
  118284. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118285. qM[l]=unitnorm(qM[l]);
  118286. acc-=1.f;
  118287. }
  118288. }
  118289. }
  118290. }
  118291. }
  118292. }
  118293. }
  118294. /* AoTuV */
  118295. /** @ M2 **
  118296. The boost problem by the combination of noise normalization and point stereo is eased.
  118297. However, this is a temporary patch.
  118298. by Aoyumi @ 2004/04/18
  118299. */
  118300. void hf_reduction(vorbis_info_psy_global *g,
  118301. vorbis_look_psy *p,
  118302. vorbis_info_mapping0 *vi,
  118303. float **mdct){
  118304. int i,j,n=p->n, de=0.3*p->m_val;
  118305. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118306. for(i=0; i<vi->coupling_steps; i++){
  118307. /* for(j=start; j<limit; j++){} // ???*/
  118308. for(j=limit; j<n; j++)
  118309. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118310. }
  118311. }
  118312. #endif
  118313. /*** End of inlined file: psy.c ***/
  118314. /*** Start of inlined file: registry.c ***/
  118315. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118316. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118317. // tasks..
  118318. #if JUCE_MSVC
  118319. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118320. #endif
  118321. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118322. #if JUCE_USE_OGGVORBIS
  118323. /* seems like major overkill now; the backend numbers will grow into
  118324. the infrastructure soon enough */
  118325. extern vorbis_func_floor floor0_exportbundle;
  118326. extern vorbis_func_floor floor1_exportbundle;
  118327. extern vorbis_func_residue residue0_exportbundle;
  118328. extern vorbis_func_residue residue1_exportbundle;
  118329. extern vorbis_func_residue residue2_exportbundle;
  118330. extern vorbis_func_mapping mapping0_exportbundle;
  118331. vorbis_func_floor *_floor_P[]={
  118332. &floor0_exportbundle,
  118333. &floor1_exportbundle,
  118334. };
  118335. vorbis_func_residue *_residue_P[]={
  118336. &residue0_exportbundle,
  118337. &residue1_exportbundle,
  118338. &residue2_exportbundle,
  118339. };
  118340. vorbis_func_mapping *_mapping_P[]={
  118341. &mapping0_exportbundle,
  118342. };
  118343. #endif
  118344. /*** End of inlined file: registry.c ***/
  118345. /*** Start of inlined file: res0.c ***/
  118346. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118347. encode/decode loops are coded for clarity and performance is not
  118348. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118349. it's slow. */
  118350. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118351. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118352. // tasks..
  118353. #if JUCE_MSVC
  118354. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118355. #endif
  118356. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118357. #if JUCE_USE_OGGVORBIS
  118358. #include <stdlib.h>
  118359. #include <string.h>
  118360. #include <math.h>
  118361. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118362. #include <stdio.h>
  118363. #endif
  118364. typedef struct {
  118365. vorbis_info_residue0 *info;
  118366. int parts;
  118367. int stages;
  118368. codebook *fullbooks;
  118369. codebook *phrasebook;
  118370. codebook ***partbooks;
  118371. int partvals;
  118372. int **decodemap;
  118373. long postbits;
  118374. long phrasebits;
  118375. long frames;
  118376. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118377. int train_seq;
  118378. long *training_data[8][64];
  118379. float training_max[8][64];
  118380. float training_min[8][64];
  118381. float tmin;
  118382. float tmax;
  118383. #endif
  118384. } vorbis_look_residue0;
  118385. void res0_free_info(vorbis_info_residue *i){
  118386. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118387. if(info){
  118388. memset(info,0,sizeof(*info));
  118389. _ogg_free(info);
  118390. }
  118391. }
  118392. void res0_free_look(vorbis_look_residue *i){
  118393. int j;
  118394. if(i){
  118395. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118396. #ifdef TRAIN_RES
  118397. {
  118398. int j,k,l;
  118399. for(j=0;j<look->parts;j++){
  118400. /*fprintf(stderr,"partition %d: ",j);*/
  118401. for(k=0;k<8;k++)
  118402. if(look->training_data[k][j]){
  118403. char buffer[80];
  118404. FILE *of;
  118405. codebook *statebook=look->partbooks[j][k];
  118406. /* long and short into the same bucket by current convention */
  118407. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118408. of=fopen(buffer,"a");
  118409. for(l=0;l<statebook->entries;l++)
  118410. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118411. fclose(of);
  118412. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118413. look->training_min[k][j],look->training_max[k][j]);*/
  118414. _ogg_free(look->training_data[k][j]);
  118415. look->training_data[k][j]=NULL;
  118416. }
  118417. /*fprintf(stderr,"\n");*/
  118418. }
  118419. }
  118420. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118421. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118422. (float)look->phrasebits/look->frames,
  118423. (float)look->postbits/look->frames,
  118424. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118425. #endif
  118426. /*vorbis_info_residue0 *info=look->info;
  118427. fprintf(stderr,
  118428. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118429. "(%g/frame) \n",look->frames,look->phrasebits,
  118430. look->resbitsflat,
  118431. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118432. for(j=0;j<look->parts;j++){
  118433. long acc=0;
  118434. fprintf(stderr,"\t[%d] == ",j);
  118435. for(k=0;k<look->stages;k++)
  118436. if((info->secondstages[j]>>k)&1){
  118437. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118438. acc+=look->resbits[j][k];
  118439. }
  118440. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118441. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118442. }
  118443. fprintf(stderr,"\n");*/
  118444. for(j=0;j<look->parts;j++)
  118445. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118446. _ogg_free(look->partbooks);
  118447. for(j=0;j<look->partvals;j++)
  118448. _ogg_free(look->decodemap[j]);
  118449. _ogg_free(look->decodemap);
  118450. memset(look,0,sizeof(*look));
  118451. _ogg_free(look);
  118452. }
  118453. }
  118454. static int icount(unsigned int v){
  118455. int ret=0;
  118456. while(v){
  118457. ret+=v&1;
  118458. v>>=1;
  118459. }
  118460. return(ret);
  118461. }
  118462. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118463. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118464. int j,acc=0;
  118465. oggpack_write(opb,info->begin,24);
  118466. oggpack_write(opb,info->end,24);
  118467. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118468. code with a partitioned book */
  118469. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118470. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118471. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118472. bitmask of one indicates this partition class has bits to write
  118473. this pass */
  118474. for(j=0;j<info->partitions;j++){
  118475. if(ilog(info->secondstages[j])>3){
  118476. /* yes, this is a minor hack due to not thinking ahead */
  118477. oggpack_write(opb,info->secondstages[j],3);
  118478. oggpack_write(opb,1,1);
  118479. oggpack_write(opb,info->secondstages[j]>>3,5);
  118480. }else
  118481. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118482. acc+=icount(info->secondstages[j]);
  118483. }
  118484. for(j=0;j<acc;j++)
  118485. oggpack_write(opb,info->booklist[j],8);
  118486. }
  118487. /* vorbis_info is for range checking */
  118488. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118489. int j,acc=0;
  118490. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118491. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118492. info->begin=oggpack_read(opb,24);
  118493. info->end=oggpack_read(opb,24);
  118494. info->grouping=oggpack_read(opb,24)+1;
  118495. info->partitions=oggpack_read(opb,6)+1;
  118496. info->groupbook=oggpack_read(opb,8);
  118497. for(j=0;j<info->partitions;j++){
  118498. int cascade=oggpack_read(opb,3);
  118499. if(oggpack_read(opb,1))
  118500. cascade|=(oggpack_read(opb,5)<<3);
  118501. info->secondstages[j]=cascade;
  118502. acc+=icount(cascade);
  118503. }
  118504. for(j=0;j<acc;j++)
  118505. info->booklist[j]=oggpack_read(opb,8);
  118506. if(info->groupbook>=ci->books)goto errout;
  118507. for(j=0;j<acc;j++)
  118508. if(info->booklist[j]>=ci->books)goto errout;
  118509. return(info);
  118510. errout:
  118511. res0_free_info(info);
  118512. return(NULL);
  118513. }
  118514. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118515. vorbis_info_residue *vr){
  118516. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118517. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118518. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118519. int j,k,acc=0;
  118520. int dim;
  118521. int maxstage=0;
  118522. look->info=info;
  118523. look->parts=info->partitions;
  118524. look->fullbooks=ci->fullbooks;
  118525. look->phrasebook=ci->fullbooks+info->groupbook;
  118526. dim=look->phrasebook->dim;
  118527. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118528. for(j=0;j<look->parts;j++){
  118529. int stages=ilog(info->secondstages[j]);
  118530. if(stages){
  118531. if(stages>maxstage)maxstage=stages;
  118532. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118533. for(k=0;k<stages;k++)
  118534. if(info->secondstages[j]&(1<<k)){
  118535. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118536. #ifdef TRAIN_RES
  118537. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118538. sizeof(***look->training_data));
  118539. #endif
  118540. }
  118541. }
  118542. }
  118543. look->partvals=rint(pow((float)look->parts,(float)dim));
  118544. look->stages=maxstage;
  118545. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118546. for(j=0;j<look->partvals;j++){
  118547. long val=j;
  118548. long mult=look->partvals/look->parts;
  118549. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118550. for(k=0;k<dim;k++){
  118551. long deco=val/mult;
  118552. val-=deco*mult;
  118553. mult/=look->parts;
  118554. look->decodemap[j][k]=deco;
  118555. }
  118556. }
  118557. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118558. {
  118559. static int train_seq=0;
  118560. look->train_seq=train_seq++;
  118561. }
  118562. #endif
  118563. return(look);
  118564. }
  118565. /* break an abstraction and copy some code for performance purposes */
  118566. static int local_book_besterror(codebook *book,float *a){
  118567. int dim=book->dim,i,k,o;
  118568. int best=0;
  118569. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118570. /* find the quant val of each scalar */
  118571. for(k=0,o=dim;k<dim;++k){
  118572. float val=a[--o];
  118573. i=tt->threshvals>>1;
  118574. if(val<tt->quantthresh[i]){
  118575. if(val<tt->quantthresh[i-1]){
  118576. for(--i;i>0;--i)
  118577. if(val>=tt->quantthresh[i-1])
  118578. break;
  118579. }
  118580. }else{
  118581. for(++i;i<tt->threshvals-1;++i)
  118582. if(val<tt->quantthresh[i])break;
  118583. }
  118584. best=(best*tt->quantvals)+tt->quantmap[i];
  118585. }
  118586. /* regular lattices are easy :-) */
  118587. if(book->c->lengthlist[best]<=0){
  118588. const static_codebook *c=book->c;
  118589. int i,j;
  118590. float bestf=0.f;
  118591. float *e=book->valuelist;
  118592. best=-1;
  118593. for(i=0;i<book->entries;i++){
  118594. if(c->lengthlist[i]>0){
  118595. float thisx=0.f;
  118596. for(j=0;j<dim;j++){
  118597. float val=(e[j]-a[j]);
  118598. thisx+=val*val;
  118599. }
  118600. if(best==-1 || thisx<bestf){
  118601. bestf=thisx;
  118602. best=i;
  118603. }
  118604. }
  118605. e+=dim;
  118606. }
  118607. }
  118608. {
  118609. float *ptr=book->valuelist+best*dim;
  118610. for(i=0;i<dim;i++)
  118611. *a++ -= *ptr++;
  118612. }
  118613. return(best);
  118614. }
  118615. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118616. codebook *book,long *acc){
  118617. int i,bits=0;
  118618. int dim=book->dim;
  118619. int step=n/dim;
  118620. for(i=0;i<step;i++){
  118621. int entry=local_book_besterror(book,vec+i*dim);
  118622. #ifdef TRAIN_RES
  118623. acc[entry]++;
  118624. #endif
  118625. bits+=vorbis_book_encode(book,entry,opb);
  118626. }
  118627. return(bits);
  118628. }
  118629. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118630. float **in,int ch){
  118631. long i,j,k;
  118632. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118633. vorbis_info_residue0 *info=look->info;
  118634. /* move all this setup out later */
  118635. int samples_per_partition=info->grouping;
  118636. int possible_partitions=info->partitions;
  118637. int n=info->end-info->begin;
  118638. int partvals=n/samples_per_partition;
  118639. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118640. float scale=100./samples_per_partition;
  118641. /* we find the partition type for each partition of each
  118642. channel. We'll go back and do the interleaved encoding in a
  118643. bit. For now, clarity */
  118644. for(i=0;i<ch;i++){
  118645. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118646. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118647. }
  118648. for(i=0;i<partvals;i++){
  118649. int offset=i*samples_per_partition+info->begin;
  118650. for(j=0;j<ch;j++){
  118651. float max=0.;
  118652. float ent=0.;
  118653. for(k=0;k<samples_per_partition;k++){
  118654. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118655. ent+=fabs(rint(in[j][offset+k]));
  118656. }
  118657. ent*=scale;
  118658. for(k=0;k<possible_partitions-1;k++)
  118659. if(max<=info->classmetric1[k] &&
  118660. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118661. break;
  118662. partword[j][i]=k;
  118663. }
  118664. }
  118665. #ifdef TRAIN_RESAUX
  118666. {
  118667. FILE *of;
  118668. char buffer[80];
  118669. for(i=0;i<ch;i++){
  118670. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118671. of=fopen(buffer,"a");
  118672. for(j=0;j<partvals;j++)
  118673. fprintf(of,"%ld, ",partword[i][j]);
  118674. fprintf(of,"\n");
  118675. fclose(of);
  118676. }
  118677. }
  118678. #endif
  118679. look->frames++;
  118680. return(partword);
  118681. }
  118682. /* designed for stereo or other modes where the partition size is an
  118683. integer multiple of the number of channels encoded in the current
  118684. submap */
  118685. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118686. int ch){
  118687. long i,j,k,l;
  118688. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118689. vorbis_info_residue0 *info=look->info;
  118690. /* move all this setup out later */
  118691. int samples_per_partition=info->grouping;
  118692. int possible_partitions=info->partitions;
  118693. int n=info->end-info->begin;
  118694. int partvals=n/samples_per_partition;
  118695. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118696. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118697. FILE *of;
  118698. char buffer[80];
  118699. #endif
  118700. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118701. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118702. for(i=0,l=info->begin/ch;i<partvals;i++){
  118703. float magmax=0.f;
  118704. float angmax=0.f;
  118705. for(j=0;j<samples_per_partition;j+=ch){
  118706. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118707. for(k=1;k<ch;k++)
  118708. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118709. l++;
  118710. }
  118711. for(j=0;j<possible_partitions-1;j++)
  118712. if(magmax<=info->classmetric1[j] &&
  118713. angmax<=info->classmetric2[j])
  118714. break;
  118715. partword[0][i]=j;
  118716. }
  118717. #ifdef TRAIN_RESAUX
  118718. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118719. of=fopen(buffer,"a");
  118720. for(i=0;i<partvals;i++)
  118721. fprintf(of,"%ld, ",partword[0][i]);
  118722. fprintf(of,"\n");
  118723. fclose(of);
  118724. #endif
  118725. look->frames++;
  118726. return(partword);
  118727. }
  118728. static int _01forward(oggpack_buffer *opb,
  118729. vorbis_block *vb,vorbis_look_residue *vl,
  118730. float **in,int ch,
  118731. long **partword,
  118732. int (*encode)(oggpack_buffer *,float *,int,
  118733. codebook *,long *)){
  118734. long i,j,k,s;
  118735. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118736. vorbis_info_residue0 *info=look->info;
  118737. /* move all this setup out later */
  118738. int samples_per_partition=info->grouping;
  118739. int possible_partitions=info->partitions;
  118740. int partitions_per_word=look->phrasebook->dim;
  118741. int n=info->end-info->begin;
  118742. int partvals=n/samples_per_partition;
  118743. long resbits[128];
  118744. long resvals[128];
  118745. #ifdef TRAIN_RES
  118746. for(i=0;i<ch;i++)
  118747. for(j=info->begin;j<info->end;j++){
  118748. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118749. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118750. }
  118751. #endif
  118752. memset(resbits,0,sizeof(resbits));
  118753. memset(resvals,0,sizeof(resvals));
  118754. /* we code the partition words for each channel, then the residual
  118755. words for a partition per channel until we've written all the
  118756. residual words for that partition word. Then write the next
  118757. partition channel words... */
  118758. for(s=0;s<look->stages;s++){
  118759. for(i=0;i<partvals;){
  118760. /* first we encode a partition codeword for each channel */
  118761. if(s==0){
  118762. for(j=0;j<ch;j++){
  118763. long val=partword[j][i];
  118764. for(k=1;k<partitions_per_word;k++){
  118765. val*=possible_partitions;
  118766. if(i+k<partvals)
  118767. val+=partword[j][i+k];
  118768. }
  118769. /* training hack */
  118770. if(val<look->phrasebook->entries)
  118771. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118772. #if 0 /*def TRAIN_RES*/
  118773. else
  118774. fprintf(stderr,"!");
  118775. #endif
  118776. }
  118777. }
  118778. /* now we encode interleaved residual values for the partitions */
  118779. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118780. long offset=i*samples_per_partition+info->begin;
  118781. for(j=0;j<ch;j++){
  118782. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118783. if(info->secondstages[partword[j][i]]&(1<<s)){
  118784. codebook *statebook=look->partbooks[partword[j][i]][s];
  118785. if(statebook){
  118786. int ret;
  118787. long *accumulator=NULL;
  118788. #ifdef TRAIN_RES
  118789. accumulator=look->training_data[s][partword[j][i]];
  118790. {
  118791. int l;
  118792. float *samples=in[j]+offset;
  118793. for(l=0;l<samples_per_partition;l++){
  118794. if(samples[l]<look->training_min[s][partword[j][i]])
  118795. look->training_min[s][partword[j][i]]=samples[l];
  118796. if(samples[l]>look->training_max[s][partword[j][i]])
  118797. look->training_max[s][partword[j][i]]=samples[l];
  118798. }
  118799. }
  118800. #endif
  118801. ret=encode(opb,in[j]+offset,samples_per_partition,
  118802. statebook,accumulator);
  118803. look->postbits+=ret;
  118804. resbits[partword[j][i]]+=ret;
  118805. }
  118806. }
  118807. }
  118808. }
  118809. }
  118810. }
  118811. /*{
  118812. long total=0;
  118813. long totalbits=0;
  118814. fprintf(stderr,"%d :: ",vb->mode);
  118815. for(k=0;k<possible_partitions;k++){
  118816. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118817. total+=resvals[k];
  118818. totalbits+=resbits[k];
  118819. }
  118820. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118821. }*/
  118822. return(0);
  118823. }
  118824. /* a truncated packet here just means 'stop working'; it's not an error */
  118825. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118826. float **in,int ch,
  118827. long (*decodepart)(codebook *, float *,
  118828. oggpack_buffer *,int)){
  118829. long i,j,k,l,s;
  118830. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118831. vorbis_info_residue0 *info=look->info;
  118832. /* move all this setup out later */
  118833. int samples_per_partition=info->grouping;
  118834. int partitions_per_word=look->phrasebook->dim;
  118835. int n=info->end-info->begin;
  118836. int partvals=n/samples_per_partition;
  118837. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118838. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118839. for(j=0;j<ch;j++)
  118840. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118841. for(s=0;s<look->stages;s++){
  118842. /* each loop decodes on partition codeword containing
  118843. partitions_pre_word partitions */
  118844. for(i=0,l=0;i<partvals;l++){
  118845. if(s==0){
  118846. /* fetch the partition word for each channel */
  118847. for(j=0;j<ch;j++){
  118848. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118849. if(temp==-1)goto eopbreak;
  118850. partword[j][l]=look->decodemap[temp];
  118851. if(partword[j][l]==NULL)goto errout;
  118852. }
  118853. }
  118854. /* now we decode residual values for the partitions */
  118855. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118856. for(j=0;j<ch;j++){
  118857. long offset=info->begin+i*samples_per_partition;
  118858. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118859. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118860. if(stagebook){
  118861. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118862. samples_per_partition)==-1)goto eopbreak;
  118863. }
  118864. }
  118865. }
  118866. }
  118867. }
  118868. errout:
  118869. eopbreak:
  118870. return(0);
  118871. }
  118872. #if 0
  118873. /* residue 0 and 1 are just slight variants of one another. 0 is
  118874. interleaved, 1 is not */
  118875. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118876. float **in,int *nonzero,int ch){
  118877. /* we encode only the nonzero parts of a bundle */
  118878. int i,used=0;
  118879. for(i=0;i<ch;i++)
  118880. if(nonzero[i])
  118881. in[used++]=in[i];
  118882. if(used)
  118883. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118884. return(_01class(vb,vl,in,used));
  118885. else
  118886. return(0);
  118887. }
  118888. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118889. float **in,float **out,int *nonzero,int ch,
  118890. long **partword){
  118891. /* we encode only the nonzero parts of a bundle */
  118892. int i,j,used=0,n=vb->pcmend/2;
  118893. for(i=0;i<ch;i++)
  118894. if(nonzero[i]){
  118895. if(out)
  118896. for(j=0;j<n;j++)
  118897. out[i][j]+=in[i][j];
  118898. in[used++]=in[i];
  118899. }
  118900. if(used){
  118901. int ret=_01forward(vb,vl,in,used,partword,
  118902. _interleaved_encodepart);
  118903. if(out){
  118904. used=0;
  118905. for(i=0;i<ch;i++)
  118906. if(nonzero[i]){
  118907. for(j=0;j<n;j++)
  118908. out[i][j]-=in[used][j];
  118909. used++;
  118910. }
  118911. }
  118912. return(ret);
  118913. }else{
  118914. return(0);
  118915. }
  118916. }
  118917. #endif
  118918. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118919. float **in,int *nonzero,int ch){
  118920. int i,used=0;
  118921. for(i=0;i<ch;i++)
  118922. if(nonzero[i])
  118923. in[used++]=in[i];
  118924. if(used)
  118925. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118926. else
  118927. return(0);
  118928. }
  118929. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118930. float **in,float **out,int *nonzero,int ch,
  118931. long **partword){
  118932. int i,j,used=0,n=vb->pcmend/2;
  118933. for(i=0;i<ch;i++)
  118934. if(nonzero[i]){
  118935. if(out)
  118936. for(j=0;j<n;j++)
  118937. out[i][j]+=in[i][j];
  118938. in[used++]=in[i];
  118939. }
  118940. if(used){
  118941. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118942. if(out){
  118943. used=0;
  118944. for(i=0;i<ch;i++)
  118945. if(nonzero[i]){
  118946. for(j=0;j<n;j++)
  118947. out[i][j]-=in[used][j];
  118948. used++;
  118949. }
  118950. }
  118951. return(ret);
  118952. }else{
  118953. return(0);
  118954. }
  118955. }
  118956. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118957. float **in,int *nonzero,int ch){
  118958. int i,used=0;
  118959. for(i=0;i<ch;i++)
  118960. if(nonzero[i])
  118961. in[used++]=in[i];
  118962. if(used)
  118963. return(_01class(vb,vl,in,used));
  118964. else
  118965. return(0);
  118966. }
  118967. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118968. float **in,int *nonzero,int ch){
  118969. int i,used=0;
  118970. for(i=0;i<ch;i++)
  118971. if(nonzero[i])
  118972. in[used++]=in[i];
  118973. if(used)
  118974. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118975. else
  118976. return(0);
  118977. }
  118978. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118979. float **in,int *nonzero,int ch){
  118980. int i,used=0;
  118981. for(i=0;i<ch;i++)
  118982. if(nonzero[i])used++;
  118983. if(used)
  118984. return(_2class(vb,vl,in,ch));
  118985. else
  118986. return(0);
  118987. }
  118988. /* res2 is slightly more different; all the channels are interleaved
  118989. into a single vector and encoded. */
  118990. int res2_forward(oggpack_buffer *opb,
  118991. vorbis_block *vb,vorbis_look_residue *vl,
  118992. float **in,float **out,int *nonzero,int ch,
  118993. long **partword){
  118994. long i,j,k,n=vb->pcmend/2,used=0;
  118995. /* don't duplicate the code; use a working vector hack for now and
  118996. reshape ourselves into a single channel res1 */
  118997. /* ugly; reallocs for each coupling pass :-( */
  118998. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118999. for(i=0;i<ch;i++){
  119000. float *pcm=in[i];
  119001. if(nonzero[i])used++;
  119002. for(j=0,k=i;j<n;j++,k+=ch)
  119003. work[k]=pcm[j];
  119004. }
  119005. if(used){
  119006. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  119007. /* update the sofar vector */
  119008. if(out){
  119009. for(i=0;i<ch;i++){
  119010. float *pcm=in[i];
  119011. float *sofar=out[i];
  119012. for(j=0,k=i;j<n;j++,k+=ch)
  119013. sofar[j]+=pcm[j]-work[k];
  119014. }
  119015. }
  119016. return(ret);
  119017. }else{
  119018. return(0);
  119019. }
  119020. }
  119021. /* duplicate code here as speed is somewhat more important */
  119022. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  119023. float **in,int *nonzero,int ch){
  119024. long i,k,l,s;
  119025. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  119026. vorbis_info_residue0 *info=look->info;
  119027. /* move all this setup out later */
  119028. int samples_per_partition=info->grouping;
  119029. int partitions_per_word=look->phrasebook->dim;
  119030. int n=info->end-info->begin;
  119031. int partvals=n/samples_per_partition;
  119032. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  119033. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  119034. for(i=0;i<ch;i++)if(nonzero[i])break;
  119035. if(i==ch)return(0); /* no nonzero vectors */
  119036. for(s=0;s<look->stages;s++){
  119037. for(i=0,l=0;i<partvals;l++){
  119038. if(s==0){
  119039. /* fetch the partition word */
  119040. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  119041. if(temp==-1)goto eopbreak;
  119042. partword[l]=look->decodemap[temp];
  119043. if(partword[l]==NULL)goto errout;
  119044. }
  119045. /* now we decode residual values for the partitions */
  119046. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  119047. if(info->secondstages[partword[l][k]]&(1<<s)){
  119048. codebook *stagebook=look->partbooks[partword[l][k]][s];
  119049. if(stagebook){
  119050. if(vorbis_book_decodevv_add(stagebook,in,
  119051. i*samples_per_partition+info->begin,ch,
  119052. &vb->opb,samples_per_partition)==-1)
  119053. goto eopbreak;
  119054. }
  119055. }
  119056. }
  119057. }
  119058. errout:
  119059. eopbreak:
  119060. return(0);
  119061. }
  119062. vorbis_func_residue residue0_exportbundle={
  119063. NULL,
  119064. &res0_unpack,
  119065. &res0_look,
  119066. &res0_free_info,
  119067. &res0_free_look,
  119068. NULL,
  119069. NULL,
  119070. &res0_inverse
  119071. };
  119072. vorbis_func_residue residue1_exportbundle={
  119073. &res0_pack,
  119074. &res0_unpack,
  119075. &res0_look,
  119076. &res0_free_info,
  119077. &res0_free_look,
  119078. &res1_class,
  119079. &res1_forward,
  119080. &res1_inverse
  119081. };
  119082. vorbis_func_residue residue2_exportbundle={
  119083. &res0_pack,
  119084. &res0_unpack,
  119085. &res0_look,
  119086. &res0_free_info,
  119087. &res0_free_look,
  119088. &res2_class,
  119089. &res2_forward,
  119090. &res2_inverse
  119091. };
  119092. #endif
  119093. /*** End of inlined file: res0.c ***/
  119094. /*** Start of inlined file: sharedbook.c ***/
  119095. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119096. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119097. // tasks..
  119098. #if JUCE_MSVC
  119099. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119100. #endif
  119101. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119102. #if JUCE_USE_OGGVORBIS
  119103. #include <stdlib.h>
  119104. #include <math.h>
  119105. #include <string.h>
  119106. /**** pack/unpack helpers ******************************************/
  119107. int _ilog(unsigned int v){
  119108. int ret=0;
  119109. while(v){
  119110. ret++;
  119111. v>>=1;
  119112. }
  119113. return(ret);
  119114. }
  119115. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119116. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119117. Why not IEEE? It's just not that important here. */
  119118. #define VQ_FEXP 10
  119119. #define VQ_FMAN 21
  119120. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119121. /* doesn't currently guard under/overflow */
  119122. long _float32_pack(float val){
  119123. int sign=0;
  119124. long exp;
  119125. long mant;
  119126. if(val<0){
  119127. sign=0x80000000;
  119128. val= -val;
  119129. }
  119130. exp= floor(log(val)/log(2.f));
  119131. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119132. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119133. return(sign|exp|mant);
  119134. }
  119135. float _float32_unpack(long val){
  119136. double mant=val&0x1fffff;
  119137. int sign=val&0x80000000;
  119138. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119139. if(sign)mant= -mant;
  119140. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119141. }
  119142. /* given a list of word lengths, generate a list of codewords. Works
  119143. for length ordered or unordered, always assigns the lowest valued
  119144. codewords first. Extended to handle unused entries (length 0) */
  119145. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119146. long i,j,count=0;
  119147. ogg_uint32_t marker[33];
  119148. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119149. memset(marker,0,sizeof(marker));
  119150. for(i=0;i<n;i++){
  119151. long length=l[i];
  119152. if(length>0){
  119153. ogg_uint32_t entry=marker[length];
  119154. /* when we claim a node for an entry, we also claim the nodes
  119155. below it (pruning off the imagined tree that may have dangled
  119156. from it) as well as blocking the use of any nodes directly
  119157. above for leaves */
  119158. /* update ourself */
  119159. if(length<32 && (entry>>length)){
  119160. /* error condition; the lengths must specify an overpopulated tree */
  119161. _ogg_free(r);
  119162. return(NULL);
  119163. }
  119164. r[count++]=entry;
  119165. /* Look to see if the next shorter marker points to the node
  119166. above. if so, update it and repeat. */
  119167. {
  119168. for(j=length;j>0;j--){
  119169. if(marker[j]&1){
  119170. /* have to jump branches */
  119171. if(j==1)
  119172. marker[1]++;
  119173. else
  119174. marker[j]=marker[j-1]<<1;
  119175. break; /* invariant says next upper marker would already
  119176. have been moved if it was on the same path */
  119177. }
  119178. marker[j]++;
  119179. }
  119180. }
  119181. /* prune the tree; the implicit invariant says all the longer
  119182. markers were dangling from our just-taken node. Dangle them
  119183. from our *new* node. */
  119184. for(j=length+1;j<33;j++)
  119185. if((marker[j]>>1) == entry){
  119186. entry=marker[j];
  119187. marker[j]=marker[j-1]<<1;
  119188. }else
  119189. break;
  119190. }else
  119191. if(sparsecount==0)count++;
  119192. }
  119193. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119194. endian */
  119195. for(i=0,count=0;i<n;i++){
  119196. ogg_uint32_t temp=0;
  119197. for(j=0;j<l[i];j++){
  119198. temp<<=1;
  119199. temp|=(r[count]>>j)&1;
  119200. }
  119201. if(sparsecount){
  119202. if(l[i])
  119203. r[count++]=temp;
  119204. }else
  119205. r[count++]=temp;
  119206. }
  119207. return(r);
  119208. }
  119209. /* there might be a straightforward one-line way to do the below
  119210. that's portable and totally safe against roundoff, but I haven't
  119211. thought of it. Therefore, we opt on the side of caution */
  119212. long _book_maptype1_quantvals(const static_codebook *b){
  119213. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119214. /* the above *should* be reliable, but we'll not assume that FP is
  119215. ever reliable when bitstream sync is at stake; verify via integer
  119216. means that vals really is the greatest value of dim for which
  119217. vals^b->bim <= b->entries */
  119218. /* treat the above as an initial guess */
  119219. while(1){
  119220. long acc=1;
  119221. long acc1=1;
  119222. int i;
  119223. for(i=0;i<b->dim;i++){
  119224. acc*=vals;
  119225. acc1*=vals+1;
  119226. }
  119227. if(acc<=b->entries && acc1>b->entries){
  119228. return(vals);
  119229. }else{
  119230. if(acc>b->entries){
  119231. vals--;
  119232. }else{
  119233. vals++;
  119234. }
  119235. }
  119236. }
  119237. }
  119238. /* unpack the quantized list of values for encode/decode ***********/
  119239. /* we need to deal with two map types: in map type 1, the values are
  119240. generated algorithmically (each column of the vector counts through
  119241. the values in the quant vector). in map type 2, all the values came
  119242. in in an explicit list. Both value lists must be unpacked */
  119243. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119244. long j,k,count=0;
  119245. if(b->maptype==1 || b->maptype==2){
  119246. int quantvals;
  119247. float mindel=_float32_unpack(b->q_min);
  119248. float delta=_float32_unpack(b->q_delta);
  119249. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119250. /* maptype 1 and 2 both use a quantized value vector, but
  119251. different sizes */
  119252. switch(b->maptype){
  119253. case 1:
  119254. /* most of the time, entries%dimensions == 0, but we need to be
  119255. well defined. We define that the possible vales at each
  119256. scalar is values == entries/dim. If entries%dim != 0, we'll
  119257. have 'too few' values (values*dim<entries), which means that
  119258. we'll have 'left over' entries; left over entries use zeroed
  119259. values (and are wasted). So don't generate codebooks like
  119260. that */
  119261. quantvals=_book_maptype1_quantvals(b);
  119262. for(j=0;j<b->entries;j++){
  119263. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119264. float last=0.f;
  119265. int indexdiv=1;
  119266. for(k=0;k<b->dim;k++){
  119267. int index= (j/indexdiv)%quantvals;
  119268. float val=b->quantlist[index];
  119269. val=fabs(val)*delta+mindel+last;
  119270. if(b->q_sequencep)last=val;
  119271. if(sparsemap)
  119272. r[sparsemap[count]*b->dim+k]=val;
  119273. else
  119274. r[count*b->dim+k]=val;
  119275. indexdiv*=quantvals;
  119276. }
  119277. count++;
  119278. }
  119279. }
  119280. break;
  119281. case 2:
  119282. for(j=0;j<b->entries;j++){
  119283. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119284. float last=0.f;
  119285. for(k=0;k<b->dim;k++){
  119286. float val=b->quantlist[j*b->dim+k];
  119287. val=fabs(val)*delta+mindel+last;
  119288. if(b->q_sequencep)last=val;
  119289. if(sparsemap)
  119290. r[sparsemap[count]*b->dim+k]=val;
  119291. else
  119292. r[count*b->dim+k]=val;
  119293. }
  119294. count++;
  119295. }
  119296. }
  119297. break;
  119298. }
  119299. return(r);
  119300. }
  119301. return(NULL);
  119302. }
  119303. void vorbis_staticbook_clear(static_codebook *b){
  119304. if(b->allocedp){
  119305. if(b->quantlist)_ogg_free(b->quantlist);
  119306. if(b->lengthlist)_ogg_free(b->lengthlist);
  119307. if(b->nearest_tree){
  119308. _ogg_free(b->nearest_tree->ptr0);
  119309. _ogg_free(b->nearest_tree->ptr1);
  119310. _ogg_free(b->nearest_tree->p);
  119311. _ogg_free(b->nearest_tree->q);
  119312. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119313. _ogg_free(b->nearest_tree);
  119314. }
  119315. if(b->thresh_tree){
  119316. _ogg_free(b->thresh_tree->quantthresh);
  119317. _ogg_free(b->thresh_tree->quantmap);
  119318. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119319. _ogg_free(b->thresh_tree);
  119320. }
  119321. memset(b,0,sizeof(*b));
  119322. }
  119323. }
  119324. void vorbis_staticbook_destroy(static_codebook *b){
  119325. if(b->allocedp){
  119326. vorbis_staticbook_clear(b);
  119327. _ogg_free(b);
  119328. }
  119329. }
  119330. void vorbis_book_clear(codebook *b){
  119331. /* static book is not cleared; we're likely called on the lookup and
  119332. the static codebook belongs to the info struct */
  119333. if(b->valuelist)_ogg_free(b->valuelist);
  119334. if(b->codelist)_ogg_free(b->codelist);
  119335. if(b->dec_index)_ogg_free(b->dec_index);
  119336. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119337. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119338. memset(b,0,sizeof(*b));
  119339. }
  119340. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119341. memset(c,0,sizeof(*c));
  119342. c->c=s;
  119343. c->entries=s->entries;
  119344. c->used_entries=s->entries;
  119345. c->dim=s->dim;
  119346. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119347. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119348. return(0);
  119349. }
  119350. static int sort32a(const void *a,const void *b){
  119351. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119352. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119353. }
  119354. /* decode codebook arrangement is more heavily optimized than encode */
  119355. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119356. int i,j,n=0,tabn;
  119357. int *sortindex;
  119358. memset(c,0,sizeof(*c));
  119359. /* count actually used entries */
  119360. for(i=0;i<s->entries;i++)
  119361. if(s->lengthlist[i]>0)
  119362. n++;
  119363. c->entries=s->entries;
  119364. c->used_entries=n;
  119365. c->dim=s->dim;
  119366. /* two different remappings go on here.
  119367. First, we collapse the likely sparse codebook down only to
  119368. actually represented values/words. This collapsing needs to be
  119369. indexed as map-valueless books are used to encode original entry
  119370. positions as integers.
  119371. Second, we reorder all vectors, including the entry index above,
  119372. by sorted bitreversed codeword to allow treeless decode. */
  119373. {
  119374. /* perform sort */
  119375. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119376. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119377. if(codes==NULL)goto err_out;
  119378. for(i=0;i<n;i++){
  119379. codes[i]=ogg_bitreverse(codes[i]);
  119380. codep[i]=codes+i;
  119381. }
  119382. qsort(codep,n,sizeof(*codep),sort32a);
  119383. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119384. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119385. /* the index is a reverse index */
  119386. for(i=0;i<n;i++){
  119387. int position=codep[i]-codes;
  119388. sortindex[position]=i;
  119389. }
  119390. for(i=0;i<n;i++)
  119391. c->codelist[sortindex[i]]=codes[i];
  119392. _ogg_free(codes);
  119393. }
  119394. c->valuelist=_book_unquantize(s,n,sortindex);
  119395. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119396. for(n=0,i=0;i<s->entries;i++)
  119397. if(s->lengthlist[i]>0)
  119398. c->dec_index[sortindex[n++]]=i;
  119399. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119400. for(n=0,i=0;i<s->entries;i++)
  119401. if(s->lengthlist[i]>0)
  119402. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119403. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119404. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119405. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119406. tabn=1<<c->dec_firsttablen;
  119407. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119408. c->dec_maxlength=0;
  119409. for(i=0;i<n;i++){
  119410. if(c->dec_maxlength<c->dec_codelengths[i])
  119411. c->dec_maxlength=c->dec_codelengths[i];
  119412. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119413. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119414. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119415. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119416. }
  119417. }
  119418. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119419. hints for the non-direct-hits */
  119420. {
  119421. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119422. long lo=0,hi=0;
  119423. for(i=0;i<tabn;i++){
  119424. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119425. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119426. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119427. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119428. /* we only actually have 15 bits per hint to play with here.
  119429. In order to overflow gracefully (nothing breaks, efficiency
  119430. just drops), encode as the difference from the extremes. */
  119431. {
  119432. unsigned long loval=lo;
  119433. unsigned long hival=n-hi;
  119434. if(loval>0x7fff)loval=0x7fff;
  119435. if(hival>0x7fff)hival=0x7fff;
  119436. c->dec_firsttable[ogg_bitreverse(word)]=
  119437. 0x80000000UL | (loval<<15) | hival;
  119438. }
  119439. }
  119440. }
  119441. }
  119442. return(0);
  119443. err_out:
  119444. vorbis_book_clear(c);
  119445. return(-1);
  119446. }
  119447. static float _dist(int el,float *ref, float *b,int step){
  119448. int i;
  119449. float acc=0.f;
  119450. for(i=0;i<el;i++){
  119451. float val=(ref[i]-b[i*step]);
  119452. acc+=val*val;
  119453. }
  119454. return(acc);
  119455. }
  119456. int _best(codebook *book, float *a, int step){
  119457. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119458. #if 0
  119459. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119460. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119461. #endif
  119462. int dim=book->dim;
  119463. int k,o;
  119464. /*int savebest=-1;
  119465. float saverr;*/
  119466. /* do we have a threshhold encode hint? */
  119467. if(tt){
  119468. int index=0,i;
  119469. /* find the quant val of each scalar */
  119470. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119471. i=tt->threshvals>>1;
  119472. if(a[o]<tt->quantthresh[i]){
  119473. for(;i>0;i--)
  119474. if(a[o]>=tt->quantthresh[i-1])
  119475. break;
  119476. }else{
  119477. for(i++;i<tt->threshvals-1;i++)
  119478. if(a[o]<tt->quantthresh[i])break;
  119479. }
  119480. index=(index*tt->quantvals)+tt->quantmap[i];
  119481. }
  119482. /* regular lattices are easy :-) */
  119483. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119484. use a decision tree after all
  119485. and fall through*/
  119486. return(index);
  119487. }
  119488. #if 0
  119489. /* do we have a pigeonhole encode hint? */
  119490. if(pt){
  119491. const static_codebook *c=book->c;
  119492. int i,besti=-1;
  119493. float best=0.f;
  119494. int entry=0;
  119495. /* dealing with sequentialness is a pain in the ass */
  119496. if(c->q_sequencep){
  119497. int pv;
  119498. long mul=1;
  119499. float qlast=0;
  119500. for(k=0,o=0;k<dim;k++,o+=step){
  119501. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119502. if(pv<0 || pv>=pt->mapentries)break;
  119503. entry+=pt->pigeonmap[pv]*mul;
  119504. mul*=pt->quantvals;
  119505. qlast+=pv*pt->del+pt->min;
  119506. }
  119507. }else{
  119508. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119509. int pv=(int)((a[o]-pt->min)/pt->del);
  119510. if(pv<0 || pv>=pt->mapentries)break;
  119511. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119512. }
  119513. }
  119514. /* must be within the pigeonholable range; if we quant outside (or
  119515. in an entry that we define no list for), brute force it */
  119516. if(k==dim && pt->fitlength[entry]){
  119517. /* search the abbreviated list */
  119518. long *list=pt->fitlist+pt->fitmap[entry];
  119519. for(i=0;i<pt->fitlength[entry];i++){
  119520. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119521. if(besti==-1 || this<best){
  119522. best=this;
  119523. besti=list[i];
  119524. }
  119525. }
  119526. return(besti);
  119527. }
  119528. }
  119529. if(nt){
  119530. /* optimized using the decision tree */
  119531. while(1){
  119532. float c=0.f;
  119533. float *p=book->valuelist+nt->p[ptr];
  119534. float *q=book->valuelist+nt->q[ptr];
  119535. for(k=0,o=0;k<dim;k++,o+=step)
  119536. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119537. if(c>0.f) /* in A */
  119538. ptr= -nt->ptr0[ptr];
  119539. else /* in B */
  119540. ptr= -nt->ptr1[ptr];
  119541. if(ptr<=0)break;
  119542. }
  119543. return(-ptr);
  119544. }
  119545. #endif
  119546. /* brute force it! */
  119547. {
  119548. const static_codebook *c=book->c;
  119549. int i,besti=-1;
  119550. float best=0.f;
  119551. float *e=book->valuelist;
  119552. for(i=0;i<book->entries;i++){
  119553. if(c->lengthlist[i]>0){
  119554. float thisx=_dist(dim,e,a,step);
  119555. if(besti==-1 || thisx<best){
  119556. best=thisx;
  119557. besti=i;
  119558. }
  119559. }
  119560. e+=dim;
  119561. }
  119562. /*if(savebest!=-1 && savebest!=besti){
  119563. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119564. "original:");
  119565. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119566. fprintf(stderr,"\n"
  119567. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119568. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119569. (book->valuelist+savebest*dim)[i]);
  119570. fprintf(stderr,"\n"
  119571. "bruteforce (entry %d, err %g):",besti,best);
  119572. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119573. (book->valuelist+besti*dim)[i]);
  119574. fprintf(stderr,"\n");
  119575. }*/
  119576. return(besti);
  119577. }
  119578. }
  119579. long vorbis_book_codeword(codebook *book,int entry){
  119580. if(book->c) /* only use with encode; decode optimizations are
  119581. allowed to break this */
  119582. return book->codelist[entry];
  119583. return -1;
  119584. }
  119585. long vorbis_book_codelen(codebook *book,int entry){
  119586. if(book->c) /* only use with encode; decode optimizations are
  119587. allowed to break this */
  119588. return book->c->lengthlist[entry];
  119589. return -1;
  119590. }
  119591. #ifdef _V_SELFTEST
  119592. /* Unit tests of the dequantizer; this stuff will be OK
  119593. cross-platform, I simply want to be sure that special mapping cases
  119594. actually work properly; a bug could go unnoticed for a while */
  119595. #include <stdio.h>
  119596. /* cases:
  119597. no mapping
  119598. full, explicit mapping
  119599. algorithmic mapping
  119600. nonsequential
  119601. sequential
  119602. */
  119603. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119604. static long partial_quantlist1[]={0,7,2};
  119605. /* no mapping */
  119606. static_codebook test1={
  119607. 4,16,
  119608. NULL,
  119609. 0,
  119610. 0,0,0,0,
  119611. NULL,
  119612. NULL,NULL
  119613. };
  119614. static float *test1_result=NULL;
  119615. /* linear, full mapping, nonsequential */
  119616. static_codebook test2={
  119617. 4,3,
  119618. NULL,
  119619. 2,
  119620. -533200896,1611661312,4,0,
  119621. full_quantlist1,
  119622. NULL,NULL
  119623. };
  119624. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119625. /* linear, full mapping, sequential */
  119626. static_codebook test3={
  119627. 4,3,
  119628. NULL,
  119629. 2,
  119630. -533200896,1611661312,4,1,
  119631. full_quantlist1,
  119632. NULL,NULL
  119633. };
  119634. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119635. /* linear, algorithmic mapping, nonsequential */
  119636. static_codebook test4={
  119637. 3,27,
  119638. NULL,
  119639. 1,
  119640. -533200896,1611661312,4,0,
  119641. partial_quantlist1,
  119642. NULL,NULL
  119643. };
  119644. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119645. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119646. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119647. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119648. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119649. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119650. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119651. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119652. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119653. /* linear, algorithmic mapping, sequential */
  119654. static_codebook test5={
  119655. 3,27,
  119656. NULL,
  119657. 1,
  119658. -533200896,1611661312,4,1,
  119659. partial_quantlist1,
  119660. NULL,NULL
  119661. };
  119662. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119663. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119664. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119665. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119666. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119667. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119668. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119669. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119670. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119671. void run_test(static_codebook *b,float *comp){
  119672. float *out=_book_unquantize(b,b->entries,NULL);
  119673. int i;
  119674. if(comp){
  119675. if(!out){
  119676. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119677. exit(1);
  119678. }
  119679. for(i=0;i<b->entries*b->dim;i++)
  119680. if(fabs(out[i]-comp[i])>.0001){
  119681. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119682. "position %d, %g != %g\n",i,out[i],comp[i]);
  119683. exit(1);
  119684. }
  119685. }else{
  119686. if(out){
  119687. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119688. " correct result should have been NULL\n");
  119689. exit(1);
  119690. }
  119691. }
  119692. }
  119693. int main(){
  119694. /* run the nine dequant tests, and compare to the hand-rolled results */
  119695. fprintf(stderr,"Dequant test 1... ");
  119696. run_test(&test1,test1_result);
  119697. fprintf(stderr,"OK\nDequant test 2... ");
  119698. run_test(&test2,test2_result);
  119699. fprintf(stderr,"OK\nDequant test 3... ");
  119700. run_test(&test3,test3_result);
  119701. fprintf(stderr,"OK\nDequant test 4... ");
  119702. run_test(&test4,test4_result);
  119703. fprintf(stderr,"OK\nDequant test 5... ");
  119704. run_test(&test5,test5_result);
  119705. fprintf(stderr,"OK\n\n");
  119706. return(0);
  119707. }
  119708. #endif
  119709. #endif
  119710. /*** End of inlined file: sharedbook.c ***/
  119711. /*** Start of inlined file: smallft.c ***/
  119712. /* FFT implementation from OggSquish, minus cosine transforms,
  119713. * minus all but radix 2/4 case. In Vorbis we only need this
  119714. * cut-down version.
  119715. *
  119716. * To do more than just power-of-two sized vectors, see the full
  119717. * version I wrote for NetLib.
  119718. *
  119719. * Note that the packing is a little strange; rather than the FFT r/i
  119720. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119721. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119722. * FORTRAN version
  119723. */
  119724. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119725. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119726. // tasks..
  119727. #if JUCE_MSVC
  119728. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119729. #endif
  119730. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119731. #if JUCE_USE_OGGVORBIS
  119732. #include <stdlib.h>
  119733. #include <string.h>
  119734. #include <math.h>
  119735. static void drfti1(int n, float *wa, int *ifac){
  119736. static int ntryh[4] = { 4,2,3,5 };
  119737. static float tpi = 6.28318530717958648f;
  119738. float arg,argh,argld,fi;
  119739. int ntry=0,i,j=-1;
  119740. int k1, l1, l2, ib;
  119741. int ld, ii, ip, is, nq, nr;
  119742. int ido, ipm, nfm1;
  119743. int nl=n;
  119744. int nf=0;
  119745. L101:
  119746. j++;
  119747. if (j < 4)
  119748. ntry=ntryh[j];
  119749. else
  119750. ntry+=2;
  119751. L104:
  119752. nq=nl/ntry;
  119753. nr=nl-ntry*nq;
  119754. if (nr!=0) goto L101;
  119755. nf++;
  119756. ifac[nf+1]=ntry;
  119757. nl=nq;
  119758. if(ntry!=2)goto L107;
  119759. if(nf==1)goto L107;
  119760. for (i=1;i<nf;i++){
  119761. ib=nf-i+1;
  119762. ifac[ib+1]=ifac[ib];
  119763. }
  119764. ifac[2] = 2;
  119765. L107:
  119766. if(nl!=1)goto L104;
  119767. ifac[0]=n;
  119768. ifac[1]=nf;
  119769. argh=tpi/n;
  119770. is=0;
  119771. nfm1=nf-1;
  119772. l1=1;
  119773. if(nfm1==0)return;
  119774. for (k1=0;k1<nfm1;k1++){
  119775. ip=ifac[k1+2];
  119776. ld=0;
  119777. l2=l1*ip;
  119778. ido=n/l2;
  119779. ipm=ip-1;
  119780. for (j=0;j<ipm;j++){
  119781. ld+=l1;
  119782. i=is;
  119783. argld=(float)ld*argh;
  119784. fi=0.f;
  119785. for (ii=2;ii<ido;ii+=2){
  119786. fi+=1.f;
  119787. arg=fi*argld;
  119788. wa[i++]=cos(arg);
  119789. wa[i++]=sin(arg);
  119790. }
  119791. is+=ido;
  119792. }
  119793. l1=l2;
  119794. }
  119795. }
  119796. static void fdrffti(int n, float *wsave, int *ifac){
  119797. if (n == 1) return;
  119798. drfti1(n, wsave+n, ifac);
  119799. }
  119800. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119801. int i,k;
  119802. float ti2,tr2;
  119803. int t0,t1,t2,t3,t4,t5,t6;
  119804. t1=0;
  119805. t0=(t2=l1*ido);
  119806. t3=ido<<1;
  119807. for(k=0;k<l1;k++){
  119808. ch[t1<<1]=cc[t1]+cc[t2];
  119809. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119810. t1+=ido;
  119811. t2+=ido;
  119812. }
  119813. if(ido<2)return;
  119814. if(ido==2)goto L105;
  119815. t1=0;
  119816. t2=t0;
  119817. for(k=0;k<l1;k++){
  119818. t3=t2;
  119819. t4=(t1<<1)+(ido<<1);
  119820. t5=t1;
  119821. t6=t1+t1;
  119822. for(i=2;i<ido;i+=2){
  119823. t3+=2;
  119824. t4-=2;
  119825. t5+=2;
  119826. t6+=2;
  119827. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119828. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119829. ch[t6]=cc[t5]+ti2;
  119830. ch[t4]=ti2-cc[t5];
  119831. ch[t6-1]=cc[t5-1]+tr2;
  119832. ch[t4-1]=cc[t5-1]-tr2;
  119833. }
  119834. t1+=ido;
  119835. t2+=ido;
  119836. }
  119837. if(ido%2==1)return;
  119838. L105:
  119839. t3=(t2=(t1=ido)-1);
  119840. t2+=t0;
  119841. for(k=0;k<l1;k++){
  119842. ch[t1]=-cc[t2];
  119843. ch[t1-1]=cc[t3];
  119844. t1+=ido<<1;
  119845. t2+=ido;
  119846. t3+=ido;
  119847. }
  119848. }
  119849. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119850. float *wa2,float *wa3){
  119851. static float hsqt2 = .70710678118654752f;
  119852. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119853. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119854. t0=l1*ido;
  119855. t1=t0;
  119856. t4=t1<<1;
  119857. t2=t1+(t1<<1);
  119858. t3=0;
  119859. for(k=0;k<l1;k++){
  119860. tr1=cc[t1]+cc[t2];
  119861. tr2=cc[t3]+cc[t4];
  119862. ch[t5=t3<<2]=tr1+tr2;
  119863. ch[(ido<<2)+t5-1]=tr2-tr1;
  119864. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119865. ch[t5]=cc[t2]-cc[t1];
  119866. t1+=ido;
  119867. t2+=ido;
  119868. t3+=ido;
  119869. t4+=ido;
  119870. }
  119871. if(ido<2)return;
  119872. if(ido==2)goto L105;
  119873. t1=0;
  119874. for(k=0;k<l1;k++){
  119875. t2=t1;
  119876. t4=t1<<2;
  119877. t5=(t6=ido<<1)+t4;
  119878. for(i=2;i<ido;i+=2){
  119879. t3=(t2+=2);
  119880. t4+=2;
  119881. t5-=2;
  119882. t3+=t0;
  119883. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119884. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119885. t3+=t0;
  119886. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119887. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119888. t3+=t0;
  119889. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119890. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119891. tr1=cr2+cr4;
  119892. tr4=cr4-cr2;
  119893. ti1=ci2+ci4;
  119894. ti4=ci2-ci4;
  119895. ti2=cc[t2]+ci3;
  119896. ti3=cc[t2]-ci3;
  119897. tr2=cc[t2-1]+cr3;
  119898. tr3=cc[t2-1]-cr3;
  119899. ch[t4-1]=tr1+tr2;
  119900. ch[t4]=ti1+ti2;
  119901. ch[t5-1]=tr3-ti4;
  119902. ch[t5]=tr4-ti3;
  119903. ch[t4+t6-1]=ti4+tr3;
  119904. ch[t4+t6]=tr4+ti3;
  119905. ch[t5+t6-1]=tr2-tr1;
  119906. ch[t5+t6]=ti1-ti2;
  119907. }
  119908. t1+=ido;
  119909. }
  119910. if(ido&1)return;
  119911. L105:
  119912. t2=(t1=t0+ido-1)+(t0<<1);
  119913. t3=ido<<2;
  119914. t4=ido;
  119915. t5=ido<<1;
  119916. t6=ido;
  119917. for(k=0;k<l1;k++){
  119918. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119919. tr1=hsqt2*(cc[t1]-cc[t2]);
  119920. ch[t4-1]=tr1+cc[t6-1];
  119921. ch[t4+t5-1]=cc[t6-1]-tr1;
  119922. ch[t4]=ti1-cc[t1+t0];
  119923. ch[t4+t5]=ti1+cc[t1+t0];
  119924. t1+=ido;
  119925. t2+=ido;
  119926. t4+=t3;
  119927. t6+=ido;
  119928. }
  119929. }
  119930. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119931. float *c2,float *ch,float *ch2,float *wa){
  119932. static float tpi=6.283185307179586f;
  119933. int idij,ipph,i,j,k,l,ic,ik,is;
  119934. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119935. float dc2,ai1,ai2,ar1,ar2,ds2;
  119936. int nbd;
  119937. float dcp,arg,dsp,ar1h,ar2h;
  119938. int idp2,ipp2;
  119939. arg=tpi/(float)ip;
  119940. dcp=cos(arg);
  119941. dsp=sin(arg);
  119942. ipph=(ip+1)>>1;
  119943. ipp2=ip;
  119944. idp2=ido;
  119945. nbd=(ido-1)>>1;
  119946. t0=l1*ido;
  119947. t10=ip*ido;
  119948. if(ido==1)goto L119;
  119949. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119950. t1=0;
  119951. for(j=1;j<ip;j++){
  119952. t1+=t0;
  119953. t2=t1;
  119954. for(k=0;k<l1;k++){
  119955. ch[t2]=c1[t2];
  119956. t2+=ido;
  119957. }
  119958. }
  119959. is=-ido;
  119960. t1=0;
  119961. if(nbd>l1){
  119962. for(j=1;j<ip;j++){
  119963. t1+=t0;
  119964. is+=ido;
  119965. t2= -ido+t1;
  119966. for(k=0;k<l1;k++){
  119967. idij=is-1;
  119968. t2+=ido;
  119969. t3=t2;
  119970. for(i=2;i<ido;i+=2){
  119971. idij+=2;
  119972. t3+=2;
  119973. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119974. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119975. }
  119976. }
  119977. }
  119978. }else{
  119979. for(j=1;j<ip;j++){
  119980. is+=ido;
  119981. idij=is-1;
  119982. t1+=t0;
  119983. t2=t1;
  119984. for(i=2;i<ido;i+=2){
  119985. idij+=2;
  119986. t2+=2;
  119987. t3=t2;
  119988. for(k=0;k<l1;k++){
  119989. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119990. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119991. t3+=ido;
  119992. }
  119993. }
  119994. }
  119995. }
  119996. t1=0;
  119997. t2=ipp2*t0;
  119998. if(nbd<l1){
  119999. for(j=1;j<ipph;j++){
  120000. t1+=t0;
  120001. t2-=t0;
  120002. t3=t1;
  120003. t4=t2;
  120004. for(i=2;i<ido;i+=2){
  120005. t3+=2;
  120006. t4+=2;
  120007. t5=t3-ido;
  120008. t6=t4-ido;
  120009. for(k=0;k<l1;k++){
  120010. t5+=ido;
  120011. t6+=ido;
  120012. c1[t5-1]=ch[t5-1]+ch[t6-1];
  120013. c1[t6-1]=ch[t5]-ch[t6];
  120014. c1[t5]=ch[t5]+ch[t6];
  120015. c1[t6]=ch[t6-1]-ch[t5-1];
  120016. }
  120017. }
  120018. }
  120019. }else{
  120020. for(j=1;j<ipph;j++){
  120021. t1+=t0;
  120022. t2-=t0;
  120023. t3=t1;
  120024. t4=t2;
  120025. for(k=0;k<l1;k++){
  120026. t5=t3;
  120027. t6=t4;
  120028. for(i=2;i<ido;i+=2){
  120029. t5+=2;
  120030. t6+=2;
  120031. c1[t5-1]=ch[t5-1]+ch[t6-1];
  120032. c1[t6-1]=ch[t5]-ch[t6];
  120033. c1[t5]=ch[t5]+ch[t6];
  120034. c1[t6]=ch[t6-1]-ch[t5-1];
  120035. }
  120036. t3+=ido;
  120037. t4+=ido;
  120038. }
  120039. }
  120040. }
  120041. L119:
  120042. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120043. t1=0;
  120044. t2=ipp2*idl1;
  120045. for(j=1;j<ipph;j++){
  120046. t1+=t0;
  120047. t2-=t0;
  120048. t3=t1-ido;
  120049. t4=t2-ido;
  120050. for(k=0;k<l1;k++){
  120051. t3+=ido;
  120052. t4+=ido;
  120053. c1[t3]=ch[t3]+ch[t4];
  120054. c1[t4]=ch[t4]-ch[t3];
  120055. }
  120056. }
  120057. ar1=1.f;
  120058. ai1=0.f;
  120059. t1=0;
  120060. t2=ipp2*idl1;
  120061. t3=(ip-1)*idl1;
  120062. for(l=1;l<ipph;l++){
  120063. t1+=idl1;
  120064. t2-=idl1;
  120065. ar1h=dcp*ar1-dsp*ai1;
  120066. ai1=dcp*ai1+dsp*ar1;
  120067. ar1=ar1h;
  120068. t4=t1;
  120069. t5=t2;
  120070. t6=t3;
  120071. t7=idl1;
  120072. for(ik=0;ik<idl1;ik++){
  120073. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  120074. ch2[t5++]=ai1*c2[t6++];
  120075. }
  120076. dc2=ar1;
  120077. ds2=ai1;
  120078. ar2=ar1;
  120079. ai2=ai1;
  120080. t4=idl1;
  120081. t5=(ipp2-1)*idl1;
  120082. for(j=2;j<ipph;j++){
  120083. t4+=idl1;
  120084. t5-=idl1;
  120085. ar2h=dc2*ar2-ds2*ai2;
  120086. ai2=dc2*ai2+ds2*ar2;
  120087. ar2=ar2h;
  120088. t6=t1;
  120089. t7=t2;
  120090. t8=t4;
  120091. t9=t5;
  120092. for(ik=0;ik<idl1;ik++){
  120093. ch2[t6++]+=ar2*c2[t8++];
  120094. ch2[t7++]+=ai2*c2[t9++];
  120095. }
  120096. }
  120097. }
  120098. t1=0;
  120099. for(j=1;j<ipph;j++){
  120100. t1+=idl1;
  120101. t2=t1;
  120102. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  120103. }
  120104. if(ido<l1)goto L132;
  120105. t1=0;
  120106. t2=0;
  120107. for(k=0;k<l1;k++){
  120108. t3=t1;
  120109. t4=t2;
  120110. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  120111. t1+=ido;
  120112. t2+=t10;
  120113. }
  120114. goto L135;
  120115. L132:
  120116. for(i=0;i<ido;i++){
  120117. t1=i;
  120118. t2=i;
  120119. for(k=0;k<l1;k++){
  120120. cc[t2]=ch[t1];
  120121. t1+=ido;
  120122. t2+=t10;
  120123. }
  120124. }
  120125. L135:
  120126. t1=0;
  120127. t2=ido<<1;
  120128. t3=0;
  120129. t4=ipp2*t0;
  120130. for(j=1;j<ipph;j++){
  120131. t1+=t2;
  120132. t3+=t0;
  120133. t4-=t0;
  120134. t5=t1;
  120135. t6=t3;
  120136. t7=t4;
  120137. for(k=0;k<l1;k++){
  120138. cc[t5-1]=ch[t6];
  120139. cc[t5]=ch[t7];
  120140. t5+=t10;
  120141. t6+=ido;
  120142. t7+=ido;
  120143. }
  120144. }
  120145. if(ido==1)return;
  120146. if(nbd<l1)goto L141;
  120147. t1=-ido;
  120148. t3=0;
  120149. t4=0;
  120150. t5=ipp2*t0;
  120151. for(j=1;j<ipph;j++){
  120152. t1+=t2;
  120153. t3+=t2;
  120154. t4+=t0;
  120155. t5-=t0;
  120156. t6=t1;
  120157. t7=t3;
  120158. t8=t4;
  120159. t9=t5;
  120160. for(k=0;k<l1;k++){
  120161. for(i=2;i<ido;i+=2){
  120162. ic=idp2-i;
  120163. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120164. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120165. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120166. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120167. }
  120168. t6+=t10;
  120169. t7+=t10;
  120170. t8+=ido;
  120171. t9+=ido;
  120172. }
  120173. }
  120174. return;
  120175. L141:
  120176. t1=-ido;
  120177. t3=0;
  120178. t4=0;
  120179. t5=ipp2*t0;
  120180. for(j=1;j<ipph;j++){
  120181. t1+=t2;
  120182. t3+=t2;
  120183. t4+=t0;
  120184. t5-=t0;
  120185. for(i=2;i<ido;i+=2){
  120186. t6=idp2+t1-i;
  120187. t7=i+t3;
  120188. t8=i+t4;
  120189. t9=i+t5;
  120190. for(k=0;k<l1;k++){
  120191. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120192. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120193. cc[t7]=ch[t8]+ch[t9];
  120194. cc[t6]=ch[t9]-ch[t8];
  120195. t6+=t10;
  120196. t7+=t10;
  120197. t8+=ido;
  120198. t9+=ido;
  120199. }
  120200. }
  120201. }
  120202. }
  120203. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120204. int i,k1,l1,l2;
  120205. int na,kh,nf;
  120206. int ip,iw,ido,idl1,ix2,ix3;
  120207. nf=ifac[1];
  120208. na=1;
  120209. l2=n;
  120210. iw=n;
  120211. for(k1=0;k1<nf;k1++){
  120212. kh=nf-k1;
  120213. ip=ifac[kh+1];
  120214. l1=l2/ip;
  120215. ido=n/l2;
  120216. idl1=ido*l1;
  120217. iw-=(ip-1)*ido;
  120218. na=1-na;
  120219. if(ip!=4)goto L102;
  120220. ix2=iw+ido;
  120221. ix3=ix2+ido;
  120222. if(na!=0)
  120223. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120224. else
  120225. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120226. goto L110;
  120227. L102:
  120228. if(ip!=2)goto L104;
  120229. if(na!=0)goto L103;
  120230. dradf2(ido,l1,c,ch,wa+iw-1);
  120231. goto L110;
  120232. L103:
  120233. dradf2(ido,l1,ch,c,wa+iw-1);
  120234. goto L110;
  120235. L104:
  120236. if(ido==1)na=1-na;
  120237. if(na!=0)goto L109;
  120238. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120239. na=1;
  120240. goto L110;
  120241. L109:
  120242. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120243. na=0;
  120244. L110:
  120245. l2=l1;
  120246. }
  120247. if(na==1)return;
  120248. for(i=0;i<n;i++)c[i]=ch[i];
  120249. }
  120250. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120251. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120252. float ti2,tr2;
  120253. t0=l1*ido;
  120254. t1=0;
  120255. t2=0;
  120256. t3=(ido<<1)-1;
  120257. for(k=0;k<l1;k++){
  120258. ch[t1]=cc[t2]+cc[t3+t2];
  120259. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120260. t2=(t1+=ido)<<1;
  120261. }
  120262. if(ido<2)return;
  120263. if(ido==2)goto L105;
  120264. t1=0;
  120265. t2=0;
  120266. for(k=0;k<l1;k++){
  120267. t3=t1;
  120268. t5=(t4=t2)+(ido<<1);
  120269. t6=t0+t1;
  120270. for(i=2;i<ido;i+=2){
  120271. t3+=2;
  120272. t4+=2;
  120273. t5-=2;
  120274. t6+=2;
  120275. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120276. tr2=cc[t4-1]-cc[t5-1];
  120277. ch[t3]=cc[t4]-cc[t5];
  120278. ti2=cc[t4]+cc[t5];
  120279. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120280. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120281. }
  120282. t2=(t1+=ido)<<1;
  120283. }
  120284. if(ido%2==1)return;
  120285. L105:
  120286. t1=ido-1;
  120287. t2=ido-1;
  120288. for(k=0;k<l1;k++){
  120289. ch[t1]=cc[t2]+cc[t2];
  120290. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120291. t1+=ido;
  120292. t2+=ido<<1;
  120293. }
  120294. }
  120295. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120296. float *wa2){
  120297. static float taur = -.5f;
  120298. static float taui = .8660254037844386f;
  120299. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120300. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120301. t0=l1*ido;
  120302. t1=0;
  120303. t2=t0<<1;
  120304. t3=ido<<1;
  120305. t4=ido+(ido<<1);
  120306. t5=0;
  120307. for(k=0;k<l1;k++){
  120308. tr2=cc[t3-1]+cc[t3-1];
  120309. cr2=cc[t5]+(taur*tr2);
  120310. ch[t1]=cc[t5]+tr2;
  120311. ci3=taui*(cc[t3]+cc[t3]);
  120312. ch[t1+t0]=cr2-ci3;
  120313. ch[t1+t2]=cr2+ci3;
  120314. t1+=ido;
  120315. t3+=t4;
  120316. t5+=t4;
  120317. }
  120318. if(ido==1)return;
  120319. t1=0;
  120320. t3=ido<<1;
  120321. for(k=0;k<l1;k++){
  120322. t7=t1+(t1<<1);
  120323. t6=(t5=t7+t3);
  120324. t8=t1;
  120325. t10=(t9=t1+t0)+t0;
  120326. for(i=2;i<ido;i+=2){
  120327. t5+=2;
  120328. t6-=2;
  120329. t7+=2;
  120330. t8+=2;
  120331. t9+=2;
  120332. t10+=2;
  120333. tr2=cc[t5-1]+cc[t6-1];
  120334. cr2=cc[t7-1]+(taur*tr2);
  120335. ch[t8-1]=cc[t7-1]+tr2;
  120336. ti2=cc[t5]-cc[t6];
  120337. ci2=cc[t7]+(taur*ti2);
  120338. ch[t8]=cc[t7]+ti2;
  120339. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120340. ci3=taui*(cc[t5]+cc[t6]);
  120341. dr2=cr2-ci3;
  120342. dr3=cr2+ci3;
  120343. di2=ci2+cr3;
  120344. di3=ci2-cr3;
  120345. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120346. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120347. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120348. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120349. }
  120350. t1+=ido;
  120351. }
  120352. }
  120353. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120354. float *wa2,float *wa3){
  120355. static float sqrt2=1.414213562373095f;
  120356. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120357. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120358. t0=l1*ido;
  120359. t1=0;
  120360. t2=ido<<2;
  120361. t3=0;
  120362. t6=ido<<1;
  120363. for(k=0;k<l1;k++){
  120364. t4=t3+t6;
  120365. t5=t1;
  120366. tr3=cc[t4-1]+cc[t4-1];
  120367. tr4=cc[t4]+cc[t4];
  120368. tr1=cc[t3]-cc[(t4+=t6)-1];
  120369. tr2=cc[t3]+cc[t4-1];
  120370. ch[t5]=tr2+tr3;
  120371. ch[t5+=t0]=tr1-tr4;
  120372. ch[t5+=t0]=tr2-tr3;
  120373. ch[t5+=t0]=tr1+tr4;
  120374. t1+=ido;
  120375. t3+=t2;
  120376. }
  120377. if(ido<2)return;
  120378. if(ido==2)goto L105;
  120379. t1=0;
  120380. for(k=0;k<l1;k++){
  120381. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120382. t7=t1;
  120383. for(i=2;i<ido;i+=2){
  120384. t2+=2;
  120385. t3+=2;
  120386. t4-=2;
  120387. t5-=2;
  120388. t7+=2;
  120389. ti1=cc[t2]+cc[t5];
  120390. ti2=cc[t2]-cc[t5];
  120391. ti3=cc[t3]-cc[t4];
  120392. tr4=cc[t3]+cc[t4];
  120393. tr1=cc[t2-1]-cc[t5-1];
  120394. tr2=cc[t2-1]+cc[t5-1];
  120395. ti4=cc[t3-1]-cc[t4-1];
  120396. tr3=cc[t3-1]+cc[t4-1];
  120397. ch[t7-1]=tr2+tr3;
  120398. cr3=tr2-tr3;
  120399. ch[t7]=ti2+ti3;
  120400. ci3=ti2-ti3;
  120401. cr2=tr1-tr4;
  120402. cr4=tr1+tr4;
  120403. ci2=ti1+ti4;
  120404. ci4=ti1-ti4;
  120405. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120406. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120407. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120408. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120409. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120410. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120411. }
  120412. t1+=ido;
  120413. }
  120414. if(ido%2 == 1)return;
  120415. L105:
  120416. t1=ido;
  120417. t2=ido<<2;
  120418. t3=ido-1;
  120419. t4=ido+(ido<<1);
  120420. for(k=0;k<l1;k++){
  120421. t5=t3;
  120422. ti1=cc[t1]+cc[t4];
  120423. ti2=cc[t4]-cc[t1];
  120424. tr1=cc[t1-1]-cc[t4-1];
  120425. tr2=cc[t1-1]+cc[t4-1];
  120426. ch[t5]=tr2+tr2;
  120427. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120428. ch[t5+=t0]=ti2+ti2;
  120429. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120430. t3+=ido;
  120431. t1+=t2;
  120432. t4+=t2;
  120433. }
  120434. }
  120435. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120436. float *c2,float *ch,float *ch2,float *wa){
  120437. static float tpi=6.283185307179586f;
  120438. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120439. t11,t12;
  120440. float dc2,ai1,ai2,ar1,ar2,ds2;
  120441. int nbd;
  120442. float dcp,arg,dsp,ar1h,ar2h;
  120443. int ipp2;
  120444. t10=ip*ido;
  120445. t0=l1*ido;
  120446. arg=tpi/(float)ip;
  120447. dcp=cos(arg);
  120448. dsp=sin(arg);
  120449. nbd=(ido-1)>>1;
  120450. ipp2=ip;
  120451. ipph=(ip+1)>>1;
  120452. if(ido<l1)goto L103;
  120453. t1=0;
  120454. t2=0;
  120455. for(k=0;k<l1;k++){
  120456. t3=t1;
  120457. t4=t2;
  120458. for(i=0;i<ido;i++){
  120459. ch[t3]=cc[t4];
  120460. t3++;
  120461. t4++;
  120462. }
  120463. t1+=ido;
  120464. t2+=t10;
  120465. }
  120466. goto L106;
  120467. L103:
  120468. t1=0;
  120469. for(i=0;i<ido;i++){
  120470. t2=t1;
  120471. t3=t1;
  120472. for(k=0;k<l1;k++){
  120473. ch[t2]=cc[t3];
  120474. t2+=ido;
  120475. t3+=t10;
  120476. }
  120477. t1++;
  120478. }
  120479. L106:
  120480. t1=0;
  120481. t2=ipp2*t0;
  120482. t7=(t5=ido<<1);
  120483. for(j=1;j<ipph;j++){
  120484. t1+=t0;
  120485. t2-=t0;
  120486. t3=t1;
  120487. t4=t2;
  120488. t6=t5;
  120489. for(k=0;k<l1;k++){
  120490. ch[t3]=cc[t6-1]+cc[t6-1];
  120491. ch[t4]=cc[t6]+cc[t6];
  120492. t3+=ido;
  120493. t4+=ido;
  120494. t6+=t10;
  120495. }
  120496. t5+=t7;
  120497. }
  120498. if (ido == 1)goto L116;
  120499. if(nbd<l1)goto L112;
  120500. t1=0;
  120501. t2=ipp2*t0;
  120502. t7=0;
  120503. for(j=1;j<ipph;j++){
  120504. t1+=t0;
  120505. t2-=t0;
  120506. t3=t1;
  120507. t4=t2;
  120508. t7+=(ido<<1);
  120509. t8=t7;
  120510. for(k=0;k<l1;k++){
  120511. t5=t3;
  120512. t6=t4;
  120513. t9=t8;
  120514. t11=t8;
  120515. for(i=2;i<ido;i+=2){
  120516. t5+=2;
  120517. t6+=2;
  120518. t9+=2;
  120519. t11-=2;
  120520. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120521. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120522. ch[t5]=cc[t9]-cc[t11];
  120523. ch[t6]=cc[t9]+cc[t11];
  120524. }
  120525. t3+=ido;
  120526. t4+=ido;
  120527. t8+=t10;
  120528. }
  120529. }
  120530. goto L116;
  120531. L112:
  120532. t1=0;
  120533. t2=ipp2*t0;
  120534. t7=0;
  120535. for(j=1;j<ipph;j++){
  120536. t1+=t0;
  120537. t2-=t0;
  120538. t3=t1;
  120539. t4=t2;
  120540. t7+=(ido<<1);
  120541. t8=t7;
  120542. t9=t7;
  120543. for(i=2;i<ido;i+=2){
  120544. t3+=2;
  120545. t4+=2;
  120546. t8+=2;
  120547. t9-=2;
  120548. t5=t3;
  120549. t6=t4;
  120550. t11=t8;
  120551. t12=t9;
  120552. for(k=0;k<l1;k++){
  120553. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120554. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120555. ch[t5]=cc[t11]-cc[t12];
  120556. ch[t6]=cc[t11]+cc[t12];
  120557. t5+=ido;
  120558. t6+=ido;
  120559. t11+=t10;
  120560. t12+=t10;
  120561. }
  120562. }
  120563. }
  120564. L116:
  120565. ar1=1.f;
  120566. ai1=0.f;
  120567. t1=0;
  120568. t9=(t2=ipp2*idl1);
  120569. t3=(ip-1)*idl1;
  120570. for(l=1;l<ipph;l++){
  120571. t1+=idl1;
  120572. t2-=idl1;
  120573. ar1h=dcp*ar1-dsp*ai1;
  120574. ai1=dcp*ai1+dsp*ar1;
  120575. ar1=ar1h;
  120576. t4=t1;
  120577. t5=t2;
  120578. t6=0;
  120579. t7=idl1;
  120580. t8=t3;
  120581. for(ik=0;ik<idl1;ik++){
  120582. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120583. c2[t5++]=ai1*ch2[t8++];
  120584. }
  120585. dc2=ar1;
  120586. ds2=ai1;
  120587. ar2=ar1;
  120588. ai2=ai1;
  120589. t6=idl1;
  120590. t7=t9-idl1;
  120591. for(j=2;j<ipph;j++){
  120592. t6+=idl1;
  120593. t7-=idl1;
  120594. ar2h=dc2*ar2-ds2*ai2;
  120595. ai2=dc2*ai2+ds2*ar2;
  120596. ar2=ar2h;
  120597. t4=t1;
  120598. t5=t2;
  120599. t11=t6;
  120600. t12=t7;
  120601. for(ik=0;ik<idl1;ik++){
  120602. c2[t4++]+=ar2*ch2[t11++];
  120603. c2[t5++]+=ai2*ch2[t12++];
  120604. }
  120605. }
  120606. }
  120607. t1=0;
  120608. for(j=1;j<ipph;j++){
  120609. t1+=idl1;
  120610. t2=t1;
  120611. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120612. }
  120613. t1=0;
  120614. t2=ipp2*t0;
  120615. for(j=1;j<ipph;j++){
  120616. t1+=t0;
  120617. t2-=t0;
  120618. t3=t1;
  120619. t4=t2;
  120620. for(k=0;k<l1;k++){
  120621. ch[t3]=c1[t3]-c1[t4];
  120622. ch[t4]=c1[t3]+c1[t4];
  120623. t3+=ido;
  120624. t4+=ido;
  120625. }
  120626. }
  120627. if(ido==1)goto L132;
  120628. if(nbd<l1)goto L128;
  120629. t1=0;
  120630. t2=ipp2*t0;
  120631. for(j=1;j<ipph;j++){
  120632. t1+=t0;
  120633. t2-=t0;
  120634. t3=t1;
  120635. t4=t2;
  120636. for(k=0;k<l1;k++){
  120637. t5=t3;
  120638. t6=t4;
  120639. for(i=2;i<ido;i+=2){
  120640. t5+=2;
  120641. t6+=2;
  120642. ch[t5-1]=c1[t5-1]-c1[t6];
  120643. ch[t6-1]=c1[t5-1]+c1[t6];
  120644. ch[t5]=c1[t5]+c1[t6-1];
  120645. ch[t6]=c1[t5]-c1[t6-1];
  120646. }
  120647. t3+=ido;
  120648. t4+=ido;
  120649. }
  120650. }
  120651. goto L132;
  120652. L128:
  120653. t1=0;
  120654. t2=ipp2*t0;
  120655. for(j=1;j<ipph;j++){
  120656. t1+=t0;
  120657. t2-=t0;
  120658. t3=t1;
  120659. t4=t2;
  120660. for(i=2;i<ido;i+=2){
  120661. t3+=2;
  120662. t4+=2;
  120663. t5=t3;
  120664. t6=t4;
  120665. for(k=0;k<l1;k++){
  120666. ch[t5-1]=c1[t5-1]-c1[t6];
  120667. ch[t6-1]=c1[t5-1]+c1[t6];
  120668. ch[t5]=c1[t5]+c1[t6-1];
  120669. ch[t6]=c1[t5]-c1[t6-1];
  120670. t5+=ido;
  120671. t6+=ido;
  120672. }
  120673. }
  120674. }
  120675. L132:
  120676. if(ido==1)return;
  120677. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120678. t1=0;
  120679. for(j=1;j<ip;j++){
  120680. t2=(t1+=t0);
  120681. for(k=0;k<l1;k++){
  120682. c1[t2]=ch[t2];
  120683. t2+=ido;
  120684. }
  120685. }
  120686. if(nbd>l1)goto L139;
  120687. is= -ido-1;
  120688. t1=0;
  120689. for(j=1;j<ip;j++){
  120690. is+=ido;
  120691. t1+=t0;
  120692. idij=is;
  120693. t2=t1;
  120694. for(i=2;i<ido;i+=2){
  120695. t2+=2;
  120696. idij+=2;
  120697. t3=t2;
  120698. for(k=0;k<l1;k++){
  120699. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120700. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120701. t3+=ido;
  120702. }
  120703. }
  120704. }
  120705. return;
  120706. L139:
  120707. is= -ido-1;
  120708. t1=0;
  120709. for(j=1;j<ip;j++){
  120710. is+=ido;
  120711. t1+=t0;
  120712. t2=t1;
  120713. for(k=0;k<l1;k++){
  120714. idij=is;
  120715. t3=t2;
  120716. for(i=2;i<ido;i+=2){
  120717. idij+=2;
  120718. t3+=2;
  120719. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120720. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120721. }
  120722. t2+=ido;
  120723. }
  120724. }
  120725. }
  120726. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120727. int i,k1,l1,l2;
  120728. int na;
  120729. int nf,ip,iw,ix2,ix3,ido,idl1;
  120730. nf=ifac[1];
  120731. na=0;
  120732. l1=1;
  120733. iw=1;
  120734. for(k1=0;k1<nf;k1++){
  120735. ip=ifac[k1 + 2];
  120736. l2=ip*l1;
  120737. ido=n/l2;
  120738. idl1=ido*l1;
  120739. if(ip!=4)goto L103;
  120740. ix2=iw+ido;
  120741. ix3=ix2+ido;
  120742. if(na!=0)
  120743. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120744. else
  120745. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120746. na=1-na;
  120747. goto L115;
  120748. L103:
  120749. if(ip!=2)goto L106;
  120750. if(na!=0)
  120751. dradb2(ido,l1,ch,c,wa+iw-1);
  120752. else
  120753. dradb2(ido,l1,c,ch,wa+iw-1);
  120754. na=1-na;
  120755. goto L115;
  120756. L106:
  120757. if(ip!=3)goto L109;
  120758. ix2=iw+ido;
  120759. if(na!=0)
  120760. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120761. else
  120762. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120763. na=1-na;
  120764. goto L115;
  120765. L109:
  120766. /* The radix five case can be translated later..... */
  120767. /* if(ip!=5)goto L112;
  120768. ix2=iw+ido;
  120769. ix3=ix2+ido;
  120770. ix4=ix3+ido;
  120771. if(na!=0)
  120772. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120773. else
  120774. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120775. na=1-na;
  120776. goto L115;
  120777. L112:*/
  120778. if(na!=0)
  120779. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120780. else
  120781. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120782. if(ido==1)na=1-na;
  120783. L115:
  120784. l1=l2;
  120785. iw+=(ip-1)*ido;
  120786. }
  120787. if(na==0)return;
  120788. for(i=0;i<n;i++)c[i]=ch[i];
  120789. }
  120790. void drft_forward(drft_lookup *l,float *data){
  120791. if(l->n==1)return;
  120792. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120793. }
  120794. void drft_backward(drft_lookup *l,float *data){
  120795. if (l->n==1)return;
  120796. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120797. }
  120798. void drft_init(drft_lookup *l,int n){
  120799. l->n=n;
  120800. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120801. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120802. fdrffti(n, l->trigcache, l->splitcache);
  120803. }
  120804. void drft_clear(drft_lookup *l){
  120805. if(l){
  120806. if(l->trigcache)_ogg_free(l->trigcache);
  120807. if(l->splitcache)_ogg_free(l->splitcache);
  120808. memset(l,0,sizeof(*l));
  120809. }
  120810. }
  120811. #endif
  120812. /*** End of inlined file: smallft.c ***/
  120813. /*** Start of inlined file: synthesis.c ***/
  120814. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120815. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120816. // tasks..
  120817. #if JUCE_MSVC
  120818. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120819. #endif
  120820. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120821. #if JUCE_USE_OGGVORBIS
  120822. #include <stdio.h>
  120823. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120824. vorbis_dsp_state *vd=vb->vd;
  120825. private_state *b=(private_state*)vd->backend_state;
  120826. vorbis_info *vi=vd->vi;
  120827. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120828. oggpack_buffer *opb=&vb->opb;
  120829. int type,mode,i;
  120830. /* first things first. Make sure decode is ready */
  120831. _vorbis_block_ripcord(vb);
  120832. oggpack_readinit(opb,op->packet,op->bytes);
  120833. /* Check the packet type */
  120834. if(oggpack_read(opb,1)!=0){
  120835. /* Oops. This is not an audio data packet */
  120836. return(OV_ENOTAUDIO);
  120837. }
  120838. /* read our mode and pre/post windowsize */
  120839. mode=oggpack_read(opb,b->modebits);
  120840. if(mode==-1)return(OV_EBADPACKET);
  120841. vb->mode=mode;
  120842. vb->W=ci->mode_param[mode]->blockflag;
  120843. if(vb->W){
  120844. /* this doesn;t get mapped through mode selection as it's used
  120845. only for window selection */
  120846. vb->lW=oggpack_read(opb,1);
  120847. vb->nW=oggpack_read(opb,1);
  120848. if(vb->nW==-1) return(OV_EBADPACKET);
  120849. }else{
  120850. vb->lW=0;
  120851. vb->nW=0;
  120852. }
  120853. /* more setup */
  120854. vb->granulepos=op->granulepos;
  120855. vb->sequence=op->packetno;
  120856. vb->eofflag=op->e_o_s;
  120857. /* alloc pcm passback storage */
  120858. vb->pcmend=ci->blocksizes[vb->W];
  120859. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120860. for(i=0;i<vi->channels;i++)
  120861. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120862. /* unpack_header enforces range checking */
  120863. type=ci->map_type[ci->mode_param[mode]->mapping];
  120864. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120865. mapping]));
  120866. }
  120867. /* used to track pcm position without actually performing decode.
  120868. Useful for sequential 'fast forward' */
  120869. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120870. vorbis_dsp_state *vd=vb->vd;
  120871. private_state *b=(private_state*)vd->backend_state;
  120872. vorbis_info *vi=vd->vi;
  120873. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120874. oggpack_buffer *opb=&vb->opb;
  120875. int mode;
  120876. /* first things first. Make sure decode is ready */
  120877. _vorbis_block_ripcord(vb);
  120878. oggpack_readinit(opb,op->packet,op->bytes);
  120879. /* Check the packet type */
  120880. if(oggpack_read(opb,1)!=0){
  120881. /* Oops. This is not an audio data packet */
  120882. return(OV_ENOTAUDIO);
  120883. }
  120884. /* read our mode and pre/post windowsize */
  120885. mode=oggpack_read(opb,b->modebits);
  120886. if(mode==-1)return(OV_EBADPACKET);
  120887. vb->mode=mode;
  120888. vb->W=ci->mode_param[mode]->blockflag;
  120889. if(vb->W){
  120890. vb->lW=oggpack_read(opb,1);
  120891. vb->nW=oggpack_read(opb,1);
  120892. if(vb->nW==-1) return(OV_EBADPACKET);
  120893. }else{
  120894. vb->lW=0;
  120895. vb->nW=0;
  120896. }
  120897. /* more setup */
  120898. vb->granulepos=op->granulepos;
  120899. vb->sequence=op->packetno;
  120900. vb->eofflag=op->e_o_s;
  120901. /* no pcm */
  120902. vb->pcmend=0;
  120903. vb->pcm=NULL;
  120904. return(0);
  120905. }
  120906. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120907. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120908. oggpack_buffer opb;
  120909. int mode;
  120910. oggpack_readinit(&opb,op->packet,op->bytes);
  120911. /* Check the packet type */
  120912. if(oggpack_read(&opb,1)!=0){
  120913. /* Oops. This is not an audio data packet */
  120914. return(OV_ENOTAUDIO);
  120915. }
  120916. {
  120917. int modebits=0;
  120918. int v=ci->modes;
  120919. while(v>1){
  120920. modebits++;
  120921. v>>=1;
  120922. }
  120923. /* read our mode and pre/post windowsize */
  120924. mode=oggpack_read(&opb,modebits);
  120925. }
  120926. if(mode==-1)return(OV_EBADPACKET);
  120927. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120928. }
  120929. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120930. /* set / clear half-sample-rate mode */
  120931. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120932. /* right now, our MDCT can't handle < 64 sample windows. */
  120933. if(ci->blocksizes[0]<=64 && flag)return -1;
  120934. ci->halfrate_flag=(flag?1:0);
  120935. return 0;
  120936. }
  120937. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120938. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120939. return ci->halfrate_flag;
  120940. }
  120941. #endif
  120942. /*** End of inlined file: synthesis.c ***/
  120943. /*** Start of inlined file: vorbisenc.c ***/
  120944. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120945. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120946. // tasks..
  120947. #if JUCE_MSVC
  120948. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120949. #endif
  120950. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120951. #if JUCE_USE_OGGVORBIS
  120952. #include <stdlib.h>
  120953. #include <string.h>
  120954. #include <math.h>
  120955. /* careful with this; it's using static array sizing to make managing
  120956. all the modes a little less annoying. If we use a residue backend
  120957. with > 12 partition types, or a different division of iteration,
  120958. this needs to be updated. */
  120959. typedef struct {
  120960. static_codebook *books[12][3];
  120961. } static_bookblock;
  120962. typedef struct {
  120963. int res_type;
  120964. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120965. vorbis_info_residue0 *res;
  120966. static_codebook *book_aux;
  120967. static_codebook *book_aux_managed;
  120968. static_bookblock *books_base;
  120969. static_bookblock *books_base_managed;
  120970. } vorbis_residue_template;
  120971. typedef struct {
  120972. vorbis_info_mapping0 *map;
  120973. vorbis_residue_template *res;
  120974. } vorbis_mapping_template;
  120975. typedef struct vp_adjblock{
  120976. int block[P_BANDS];
  120977. } vp_adjblock;
  120978. typedef struct {
  120979. int data[NOISE_COMPAND_LEVELS];
  120980. } compandblock;
  120981. /* high level configuration information for setting things up
  120982. step-by-step with the detailed vorbis_encode_ctl interface.
  120983. There's a fair amount of redundancy such that interactive setup
  120984. does not directly deal with any vorbis_info or codec_setup_info
  120985. initialization; it's all stored (until full init) in this highlevel
  120986. setup, then flushed out to the real codec setup structs later. */
  120987. typedef struct {
  120988. int att[P_NOISECURVES];
  120989. float boost;
  120990. float decay;
  120991. } att3;
  120992. typedef struct { int data[P_NOISECURVES]; } adj3;
  120993. typedef struct {
  120994. int pre[PACKETBLOBS];
  120995. int post[PACKETBLOBS];
  120996. float kHz[PACKETBLOBS];
  120997. float lowpasskHz[PACKETBLOBS];
  120998. } adj_stereo;
  120999. typedef struct {
  121000. int lo;
  121001. int hi;
  121002. int fixed;
  121003. } noiseguard;
  121004. typedef struct {
  121005. int data[P_NOISECURVES][17];
  121006. } noise3;
  121007. typedef struct {
  121008. int mappings;
  121009. double *rate_mapping;
  121010. double *quality_mapping;
  121011. int coupling_restriction;
  121012. long samplerate_min_restriction;
  121013. long samplerate_max_restriction;
  121014. int *blocksize_short;
  121015. int *blocksize_long;
  121016. att3 *psy_tone_masteratt;
  121017. int *psy_tone_0dB;
  121018. int *psy_tone_dBsuppress;
  121019. vp_adjblock *psy_tone_adj_impulse;
  121020. vp_adjblock *psy_tone_adj_long;
  121021. vp_adjblock *psy_tone_adj_other;
  121022. noiseguard *psy_noiseguards;
  121023. noise3 *psy_noise_bias_impulse;
  121024. noise3 *psy_noise_bias_padding;
  121025. noise3 *psy_noise_bias_trans;
  121026. noise3 *psy_noise_bias_long;
  121027. int *psy_noise_dBsuppress;
  121028. compandblock *psy_noise_compand;
  121029. double *psy_noise_compand_short_mapping;
  121030. double *psy_noise_compand_long_mapping;
  121031. int *psy_noise_normal_start[2];
  121032. int *psy_noise_normal_partition[2];
  121033. double *psy_noise_normal_thresh;
  121034. int *psy_ath_float;
  121035. int *psy_ath_abs;
  121036. double *psy_lowpass;
  121037. vorbis_info_psy_global *global_params;
  121038. double *global_mapping;
  121039. adj_stereo *stereo_modes;
  121040. static_codebook ***floor_books;
  121041. vorbis_info_floor1 *floor_params;
  121042. int *floor_short_mapping;
  121043. int *floor_long_mapping;
  121044. vorbis_mapping_template *maps;
  121045. } ve_setup_data_template;
  121046. /* a few static coder conventions */
  121047. static vorbis_info_mode _mode_template[2]={
  121048. {0,0,0,0},
  121049. {1,0,0,1}
  121050. };
  121051. static vorbis_info_mapping0 _map_nominal[2]={
  121052. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  121053. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  121054. };
  121055. /*** Start of inlined file: setup_44.h ***/
  121056. /*** Start of inlined file: floor_all.h ***/
  121057. /*** Start of inlined file: floor_books.h ***/
  121058. static long _huff_lengthlist_line_256x7_0sub1[] = {
  121059. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  121060. };
  121061. static static_codebook _huff_book_line_256x7_0sub1 = {
  121062. 1, 9,
  121063. _huff_lengthlist_line_256x7_0sub1,
  121064. 0, 0, 0, 0, 0,
  121065. NULL,
  121066. NULL,
  121067. NULL,
  121068. NULL,
  121069. 0
  121070. };
  121071. static long _huff_lengthlist_line_256x7_0sub2[] = {
  121072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  121073. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  121074. };
  121075. static static_codebook _huff_book_line_256x7_0sub2 = {
  121076. 1, 25,
  121077. _huff_lengthlist_line_256x7_0sub2,
  121078. 0, 0, 0, 0, 0,
  121079. NULL,
  121080. NULL,
  121081. NULL,
  121082. NULL,
  121083. 0
  121084. };
  121085. static long _huff_lengthlist_line_256x7_0sub3[] = {
  121086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  121088. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  121089. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  121090. };
  121091. static static_codebook _huff_book_line_256x7_0sub3 = {
  121092. 1, 64,
  121093. _huff_lengthlist_line_256x7_0sub3,
  121094. 0, 0, 0, 0, 0,
  121095. NULL,
  121096. NULL,
  121097. NULL,
  121098. NULL,
  121099. 0
  121100. };
  121101. static long _huff_lengthlist_line_256x7_1sub1[] = {
  121102. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  121103. };
  121104. static static_codebook _huff_book_line_256x7_1sub1 = {
  121105. 1, 9,
  121106. _huff_lengthlist_line_256x7_1sub1,
  121107. 0, 0, 0, 0, 0,
  121108. NULL,
  121109. NULL,
  121110. NULL,
  121111. NULL,
  121112. 0
  121113. };
  121114. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121116. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121117. };
  121118. static static_codebook _huff_book_line_256x7_1sub2 = {
  121119. 1, 25,
  121120. _huff_lengthlist_line_256x7_1sub2,
  121121. 0, 0, 0, 0, 0,
  121122. NULL,
  121123. NULL,
  121124. NULL,
  121125. NULL,
  121126. 0
  121127. };
  121128. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121131. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121132. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121133. };
  121134. static static_codebook _huff_book_line_256x7_1sub3 = {
  121135. 1, 64,
  121136. _huff_lengthlist_line_256x7_1sub3,
  121137. 0, 0, 0, 0, 0,
  121138. NULL,
  121139. NULL,
  121140. NULL,
  121141. NULL,
  121142. 0
  121143. };
  121144. static long _huff_lengthlist_line_256x7_class0[] = {
  121145. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121146. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121147. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121148. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121149. };
  121150. static static_codebook _huff_book_line_256x7_class0 = {
  121151. 1, 64,
  121152. _huff_lengthlist_line_256x7_class0,
  121153. 0, 0, 0, 0, 0,
  121154. NULL,
  121155. NULL,
  121156. NULL,
  121157. NULL,
  121158. 0
  121159. };
  121160. static long _huff_lengthlist_line_256x7_class1[] = {
  121161. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121162. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121163. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121164. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121165. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121166. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121167. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121168. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121169. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121170. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121171. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121172. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121173. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121174. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121175. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121176. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121177. };
  121178. static static_codebook _huff_book_line_256x7_class1 = {
  121179. 1, 256,
  121180. _huff_lengthlist_line_256x7_class1,
  121181. 0, 0, 0, 0, 0,
  121182. NULL,
  121183. NULL,
  121184. NULL,
  121185. NULL,
  121186. 0
  121187. };
  121188. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121189. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121190. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121191. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121192. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121193. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121194. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121195. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121196. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121197. };
  121198. static static_codebook _huff_book_line_512x17_0sub0 = {
  121199. 1, 128,
  121200. _huff_lengthlist_line_512x17_0sub0,
  121201. 0, 0, 0, 0, 0,
  121202. NULL,
  121203. NULL,
  121204. NULL,
  121205. NULL,
  121206. 0
  121207. };
  121208. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121209. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121210. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121211. };
  121212. static static_codebook _huff_book_line_512x17_1sub0 = {
  121213. 1, 32,
  121214. _huff_lengthlist_line_512x17_1sub0,
  121215. 0, 0, 0, 0, 0,
  121216. NULL,
  121217. NULL,
  121218. NULL,
  121219. NULL,
  121220. 0
  121221. };
  121222. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121225. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121226. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121227. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121228. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121229. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121230. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121231. };
  121232. static static_codebook _huff_book_line_512x17_1sub1 = {
  121233. 1, 128,
  121234. _huff_lengthlist_line_512x17_1sub1,
  121235. 0, 0, 0, 0, 0,
  121236. NULL,
  121237. NULL,
  121238. NULL,
  121239. NULL,
  121240. 0
  121241. };
  121242. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121243. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121244. 5, 3,
  121245. };
  121246. static static_codebook _huff_book_line_512x17_2sub1 = {
  121247. 1, 18,
  121248. _huff_lengthlist_line_512x17_2sub1,
  121249. 0, 0, 0, 0, 0,
  121250. NULL,
  121251. NULL,
  121252. NULL,
  121253. NULL,
  121254. 0
  121255. };
  121256. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121258. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121259. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121260. 9, 8,
  121261. };
  121262. static static_codebook _huff_book_line_512x17_2sub2 = {
  121263. 1, 50,
  121264. _huff_lengthlist_line_512x17_2sub2,
  121265. 0, 0, 0, 0, 0,
  121266. NULL,
  121267. NULL,
  121268. NULL,
  121269. NULL,
  121270. 0
  121271. };
  121272. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121276. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121277. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121278. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121281. };
  121282. static static_codebook _huff_book_line_512x17_2sub3 = {
  121283. 1, 128,
  121284. _huff_lengthlist_line_512x17_2sub3,
  121285. 0, 0, 0, 0, 0,
  121286. NULL,
  121287. NULL,
  121288. NULL,
  121289. NULL,
  121290. 0
  121291. };
  121292. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121293. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121294. 5, 5,
  121295. };
  121296. static static_codebook _huff_book_line_512x17_3sub1 = {
  121297. 1, 18,
  121298. _huff_lengthlist_line_512x17_3sub1,
  121299. 0, 0, 0, 0, 0,
  121300. NULL,
  121301. NULL,
  121302. NULL,
  121303. NULL,
  121304. 0
  121305. };
  121306. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121308. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121309. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121310. 11,14,
  121311. };
  121312. static static_codebook _huff_book_line_512x17_3sub2 = {
  121313. 1, 50,
  121314. _huff_lengthlist_line_512x17_3sub2,
  121315. 0, 0, 0, 0, 0,
  121316. NULL,
  121317. NULL,
  121318. NULL,
  121319. NULL,
  121320. 0
  121321. };
  121322. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121326. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121327. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121328. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121329. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121330. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121331. };
  121332. static static_codebook _huff_book_line_512x17_3sub3 = {
  121333. 1, 128,
  121334. _huff_lengthlist_line_512x17_3sub3,
  121335. 0, 0, 0, 0, 0,
  121336. NULL,
  121337. NULL,
  121338. NULL,
  121339. NULL,
  121340. 0
  121341. };
  121342. static long _huff_lengthlist_line_512x17_class1[] = {
  121343. 1, 2, 3, 6, 5, 4, 7, 7,
  121344. };
  121345. static static_codebook _huff_book_line_512x17_class1 = {
  121346. 1, 8,
  121347. _huff_lengthlist_line_512x17_class1,
  121348. 0, 0, 0, 0, 0,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. NULL,
  121353. 0
  121354. };
  121355. static long _huff_lengthlist_line_512x17_class2[] = {
  121356. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121357. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121358. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121359. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121360. };
  121361. static static_codebook _huff_book_line_512x17_class2 = {
  121362. 1, 64,
  121363. _huff_lengthlist_line_512x17_class2,
  121364. 0, 0, 0, 0, 0,
  121365. NULL,
  121366. NULL,
  121367. NULL,
  121368. NULL,
  121369. 0
  121370. };
  121371. static long _huff_lengthlist_line_512x17_class3[] = {
  121372. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121373. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121374. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121375. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121376. };
  121377. static static_codebook _huff_book_line_512x17_class3 = {
  121378. 1, 64,
  121379. _huff_lengthlist_line_512x17_class3,
  121380. 0, 0, 0, 0, 0,
  121381. NULL,
  121382. NULL,
  121383. NULL,
  121384. NULL,
  121385. 0
  121386. };
  121387. static long _huff_lengthlist_line_128x4_class0[] = {
  121388. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121389. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121390. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121391. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121392. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121393. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121394. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121395. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121396. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121397. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121398. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121399. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121400. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121401. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121402. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121403. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121404. };
  121405. static static_codebook _huff_book_line_128x4_class0 = {
  121406. 1, 256,
  121407. _huff_lengthlist_line_128x4_class0,
  121408. 0, 0, 0, 0, 0,
  121409. NULL,
  121410. NULL,
  121411. NULL,
  121412. NULL,
  121413. 0
  121414. };
  121415. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121416. 2, 2, 2, 2,
  121417. };
  121418. static static_codebook _huff_book_line_128x4_0sub0 = {
  121419. 1, 4,
  121420. _huff_lengthlist_line_128x4_0sub0,
  121421. 0, 0, 0, 0, 0,
  121422. NULL,
  121423. NULL,
  121424. NULL,
  121425. NULL,
  121426. 0
  121427. };
  121428. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121429. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121430. };
  121431. static static_codebook _huff_book_line_128x4_0sub1 = {
  121432. 1, 10,
  121433. _huff_lengthlist_line_128x4_0sub1,
  121434. 0, 0, 0, 0, 0,
  121435. NULL,
  121436. NULL,
  121437. NULL,
  121438. NULL,
  121439. 0
  121440. };
  121441. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121443. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121444. };
  121445. static static_codebook _huff_book_line_128x4_0sub2 = {
  121446. 1, 25,
  121447. _huff_lengthlist_line_128x4_0sub2,
  121448. 0, 0, 0, 0, 0,
  121449. NULL,
  121450. NULL,
  121451. NULL,
  121452. NULL,
  121453. 0
  121454. };
  121455. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121458. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121459. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121460. };
  121461. static static_codebook _huff_book_line_128x4_0sub3 = {
  121462. 1, 64,
  121463. _huff_lengthlist_line_128x4_0sub3,
  121464. 0, 0, 0, 0, 0,
  121465. NULL,
  121466. NULL,
  121467. NULL,
  121468. NULL,
  121469. 0
  121470. };
  121471. static long _huff_lengthlist_line_256x4_class0[] = {
  121472. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121473. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121474. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121475. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121476. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121477. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121478. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121479. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121480. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121481. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121482. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121483. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121484. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121485. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121486. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121487. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121488. };
  121489. static static_codebook _huff_book_line_256x4_class0 = {
  121490. 1, 256,
  121491. _huff_lengthlist_line_256x4_class0,
  121492. 0, 0, 0, 0, 0,
  121493. NULL,
  121494. NULL,
  121495. NULL,
  121496. NULL,
  121497. 0
  121498. };
  121499. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121500. 2, 2, 2, 2,
  121501. };
  121502. static static_codebook _huff_book_line_256x4_0sub0 = {
  121503. 1, 4,
  121504. _huff_lengthlist_line_256x4_0sub0,
  121505. 0, 0, 0, 0, 0,
  121506. NULL,
  121507. NULL,
  121508. NULL,
  121509. NULL,
  121510. 0
  121511. };
  121512. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121513. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121514. };
  121515. static static_codebook _huff_book_line_256x4_0sub1 = {
  121516. 1, 10,
  121517. _huff_lengthlist_line_256x4_0sub1,
  121518. 0, 0, 0, 0, 0,
  121519. NULL,
  121520. NULL,
  121521. NULL,
  121522. NULL,
  121523. 0
  121524. };
  121525. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121527. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121528. };
  121529. static static_codebook _huff_book_line_256x4_0sub2 = {
  121530. 1, 25,
  121531. _huff_lengthlist_line_256x4_0sub2,
  121532. 0, 0, 0, 0, 0,
  121533. NULL,
  121534. NULL,
  121535. NULL,
  121536. NULL,
  121537. 0
  121538. };
  121539. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121542. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121543. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121544. };
  121545. static static_codebook _huff_book_line_256x4_0sub3 = {
  121546. 1, 64,
  121547. _huff_lengthlist_line_256x4_0sub3,
  121548. 0, 0, 0, 0, 0,
  121549. NULL,
  121550. NULL,
  121551. NULL,
  121552. NULL,
  121553. 0
  121554. };
  121555. static long _huff_lengthlist_line_128x7_class0[] = {
  121556. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121557. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121558. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121559. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121560. };
  121561. static static_codebook _huff_book_line_128x7_class0 = {
  121562. 1, 64,
  121563. _huff_lengthlist_line_128x7_class0,
  121564. 0, 0, 0, 0, 0,
  121565. NULL,
  121566. NULL,
  121567. NULL,
  121568. NULL,
  121569. 0
  121570. };
  121571. static long _huff_lengthlist_line_128x7_class1[] = {
  121572. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121573. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121574. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121575. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121576. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121577. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121578. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121579. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121580. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121581. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121582. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121583. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121584. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121585. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121586. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121587. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121588. };
  121589. static static_codebook _huff_book_line_128x7_class1 = {
  121590. 1, 256,
  121591. _huff_lengthlist_line_128x7_class1,
  121592. 0, 0, 0, 0, 0,
  121593. NULL,
  121594. NULL,
  121595. NULL,
  121596. NULL,
  121597. 0
  121598. };
  121599. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121600. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121601. };
  121602. static static_codebook _huff_book_line_128x7_0sub1 = {
  121603. 1, 9,
  121604. _huff_lengthlist_line_128x7_0sub1,
  121605. 0, 0, 0, 0, 0,
  121606. NULL,
  121607. NULL,
  121608. NULL,
  121609. NULL,
  121610. 0
  121611. };
  121612. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121614. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121615. };
  121616. static static_codebook _huff_book_line_128x7_0sub2 = {
  121617. 1, 25,
  121618. _huff_lengthlist_line_128x7_0sub2,
  121619. 0, 0, 0, 0, 0,
  121620. NULL,
  121621. NULL,
  121622. NULL,
  121623. NULL,
  121624. 0
  121625. };
  121626. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121629. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121630. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121631. };
  121632. static static_codebook _huff_book_line_128x7_0sub3 = {
  121633. 1, 64,
  121634. _huff_lengthlist_line_128x7_0sub3,
  121635. 0, 0, 0, 0, 0,
  121636. NULL,
  121637. NULL,
  121638. NULL,
  121639. NULL,
  121640. 0
  121641. };
  121642. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121643. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121644. };
  121645. static static_codebook _huff_book_line_128x7_1sub1 = {
  121646. 1, 9,
  121647. _huff_lengthlist_line_128x7_1sub1,
  121648. 0, 0, 0, 0, 0,
  121649. NULL,
  121650. NULL,
  121651. NULL,
  121652. NULL,
  121653. 0
  121654. };
  121655. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121657. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121658. };
  121659. static static_codebook _huff_book_line_128x7_1sub2 = {
  121660. 1, 25,
  121661. _huff_lengthlist_line_128x7_1sub2,
  121662. 0, 0, 0, 0, 0,
  121663. NULL,
  121664. NULL,
  121665. NULL,
  121666. NULL,
  121667. 0
  121668. };
  121669. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121672. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121673. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121674. };
  121675. static static_codebook _huff_book_line_128x7_1sub3 = {
  121676. 1, 64,
  121677. _huff_lengthlist_line_128x7_1sub3,
  121678. 0, 0, 0, 0, 0,
  121679. NULL,
  121680. NULL,
  121681. NULL,
  121682. NULL,
  121683. 0
  121684. };
  121685. static long _huff_lengthlist_line_128x11_class1[] = {
  121686. 1, 6, 3, 7, 2, 4, 5, 7,
  121687. };
  121688. static static_codebook _huff_book_line_128x11_class1 = {
  121689. 1, 8,
  121690. _huff_lengthlist_line_128x11_class1,
  121691. 0, 0, 0, 0, 0,
  121692. NULL,
  121693. NULL,
  121694. NULL,
  121695. NULL,
  121696. 0
  121697. };
  121698. static long _huff_lengthlist_line_128x11_class2[] = {
  121699. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121700. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121701. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121702. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121703. };
  121704. static static_codebook _huff_book_line_128x11_class2 = {
  121705. 1, 64,
  121706. _huff_lengthlist_line_128x11_class2,
  121707. 0, 0, 0, 0, 0,
  121708. NULL,
  121709. NULL,
  121710. NULL,
  121711. NULL,
  121712. 0
  121713. };
  121714. static long _huff_lengthlist_line_128x11_class3[] = {
  121715. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121716. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121717. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121718. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121719. };
  121720. static static_codebook _huff_book_line_128x11_class3 = {
  121721. 1, 64,
  121722. _huff_lengthlist_line_128x11_class3,
  121723. 0, 0, 0, 0, 0,
  121724. NULL,
  121725. NULL,
  121726. NULL,
  121727. NULL,
  121728. 0
  121729. };
  121730. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121731. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121732. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121733. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121734. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121735. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121736. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121737. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121738. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121739. };
  121740. static static_codebook _huff_book_line_128x11_0sub0 = {
  121741. 1, 128,
  121742. _huff_lengthlist_line_128x11_0sub0,
  121743. 0, 0, 0, 0, 0,
  121744. NULL,
  121745. NULL,
  121746. NULL,
  121747. NULL,
  121748. 0
  121749. };
  121750. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121751. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121752. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121753. };
  121754. static static_codebook _huff_book_line_128x11_1sub0 = {
  121755. 1, 32,
  121756. _huff_lengthlist_line_128x11_1sub0,
  121757. 0, 0, 0, 0, 0,
  121758. NULL,
  121759. NULL,
  121760. NULL,
  121761. NULL,
  121762. 0
  121763. };
  121764. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121768. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121769. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121770. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121771. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121772. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121773. };
  121774. static static_codebook _huff_book_line_128x11_1sub1 = {
  121775. 1, 128,
  121776. _huff_lengthlist_line_128x11_1sub1,
  121777. 0, 0, 0, 0, 0,
  121778. NULL,
  121779. NULL,
  121780. NULL,
  121781. NULL,
  121782. 0
  121783. };
  121784. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121785. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121786. 5, 5,
  121787. };
  121788. static static_codebook _huff_book_line_128x11_2sub1 = {
  121789. 1, 18,
  121790. _huff_lengthlist_line_128x11_2sub1,
  121791. 0, 0, 0, 0, 0,
  121792. NULL,
  121793. NULL,
  121794. NULL,
  121795. NULL,
  121796. 0
  121797. };
  121798. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121800. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121801. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121802. 8,11,
  121803. };
  121804. static static_codebook _huff_book_line_128x11_2sub2 = {
  121805. 1, 50,
  121806. _huff_lengthlist_line_128x11_2sub2,
  121807. 0, 0, 0, 0, 0,
  121808. NULL,
  121809. NULL,
  121810. NULL,
  121811. NULL,
  121812. 0
  121813. };
  121814. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121818. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121819. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121820. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121821. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121822. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121823. };
  121824. static static_codebook _huff_book_line_128x11_2sub3 = {
  121825. 1, 128,
  121826. _huff_lengthlist_line_128x11_2sub3,
  121827. 0, 0, 0, 0, 0,
  121828. NULL,
  121829. NULL,
  121830. NULL,
  121831. NULL,
  121832. 0
  121833. };
  121834. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121835. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121836. 5, 4,
  121837. };
  121838. static static_codebook _huff_book_line_128x11_3sub1 = {
  121839. 1, 18,
  121840. _huff_lengthlist_line_128x11_3sub1,
  121841. 0, 0, 0, 0, 0,
  121842. NULL,
  121843. NULL,
  121844. NULL,
  121845. NULL,
  121846. 0
  121847. };
  121848. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121850. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121851. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121852. 12, 6,
  121853. };
  121854. static static_codebook _huff_book_line_128x11_3sub2 = {
  121855. 1, 50,
  121856. _huff_lengthlist_line_128x11_3sub2,
  121857. 0, 0, 0, 0, 0,
  121858. NULL,
  121859. NULL,
  121860. NULL,
  121861. NULL,
  121862. 0
  121863. };
  121864. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121868. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121869. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121873. };
  121874. static static_codebook _huff_book_line_128x11_3sub3 = {
  121875. 1, 128,
  121876. _huff_lengthlist_line_128x11_3sub3,
  121877. 0, 0, 0, 0, 0,
  121878. NULL,
  121879. NULL,
  121880. NULL,
  121881. NULL,
  121882. 0
  121883. };
  121884. static long _huff_lengthlist_line_128x17_class1[] = {
  121885. 1, 3, 4, 7, 2, 5, 6, 7,
  121886. };
  121887. static static_codebook _huff_book_line_128x17_class1 = {
  121888. 1, 8,
  121889. _huff_lengthlist_line_128x17_class1,
  121890. 0, 0, 0, 0, 0,
  121891. NULL,
  121892. NULL,
  121893. NULL,
  121894. NULL,
  121895. 0
  121896. };
  121897. static long _huff_lengthlist_line_128x17_class2[] = {
  121898. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121899. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121900. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121901. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121902. };
  121903. static static_codebook _huff_book_line_128x17_class2 = {
  121904. 1, 64,
  121905. _huff_lengthlist_line_128x17_class2,
  121906. 0, 0, 0, 0, 0,
  121907. NULL,
  121908. NULL,
  121909. NULL,
  121910. NULL,
  121911. 0
  121912. };
  121913. static long _huff_lengthlist_line_128x17_class3[] = {
  121914. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121915. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121916. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121917. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121918. };
  121919. static static_codebook _huff_book_line_128x17_class3 = {
  121920. 1, 64,
  121921. _huff_lengthlist_line_128x17_class3,
  121922. 0, 0, 0, 0, 0,
  121923. NULL,
  121924. NULL,
  121925. NULL,
  121926. NULL,
  121927. 0
  121928. };
  121929. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121930. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121931. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121932. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121933. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121934. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121935. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121936. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121937. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121938. };
  121939. static static_codebook _huff_book_line_128x17_0sub0 = {
  121940. 1, 128,
  121941. _huff_lengthlist_line_128x17_0sub0,
  121942. 0, 0, 0, 0, 0,
  121943. NULL,
  121944. NULL,
  121945. NULL,
  121946. NULL,
  121947. 0
  121948. };
  121949. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121950. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121951. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121952. };
  121953. static static_codebook _huff_book_line_128x17_1sub0 = {
  121954. 1, 32,
  121955. _huff_lengthlist_line_128x17_1sub0,
  121956. 0, 0, 0, 0, 0,
  121957. NULL,
  121958. NULL,
  121959. NULL,
  121960. NULL,
  121961. 0
  121962. };
  121963. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121967. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121968. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121969. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121970. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121971. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121972. };
  121973. static static_codebook _huff_book_line_128x17_1sub1 = {
  121974. 1, 128,
  121975. _huff_lengthlist_line_128x17_1sub1,
  121976. 0, 0, 0, 0, 0,
  121977. NULL,
  121978. NULL,
  121979. NULL,
  121980. NULL,
  121981. 0
  121982. };
  121983. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121984. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121985. 9, 4,
  121986. };
  121987. static static_codebook _huff_book_line_128x17_2sub1 = {
  121988. 1, 18,
  121989. _huff_lengthlist_line_128x17_2sub1,
  121990. 0, 0, 0, 0, 0,
  121991. NULL,
  121992. NULL,
  121993. NULL,
  121994. NULL,
  121995. 0
  121996. };
  121997. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121999. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  122000. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  122001. 13,13,
  122002. };
  122003. static static_codebook _huff_book_line_128x17_2sub2 = {
  122004. 1, 50,
  122005. _huff_lengthlist_line_128x17_2sub2,
  122006. 0, 0, 0, 0, 0,
  122007. NULL,
  122008. NULL,
  122009. NULL,
  122010. NULL,
  122011. 0
  122012. };
  122013. static long _huff_lengthlist_line_128x17_2sub3[] = {
  122014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122017. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122018. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  122019. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122020. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122021. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122022. };
  122023. static static_codebook _huff_book_line_128x17_2sub3 = {
  122024. 1, 128,
  122025. _huff_lengthlist_line_128x17_2sub3,
  122026. 0, 0, 0, 0, 0,
  122027. NULL,
  122028. NULL,
  122029. NULL,
  122030. NULL,
  122031. 0
  122032. };
  122033. static long _huff_lengthlist_line_128x17_3sub1[] = {
  122034. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  122035. 6, 4,
  122036. };
  122037. static static_codebook _huff_book_line_128x17_3sub1 = {
  122038. 1, 18,
  122039. _huff_lengthlist_line_128x17_3sub1,
  122040. 0, 0, 0, 0, 0,
  122041. NULL,
  122042. NULL,
  122043. NULL,
  122044. NULL,
  122045. 0
  122046. };
  122047. static long _huff_lengthlist_line_128x17_3sub2[] = {
  122048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122049. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  122050. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  122051. 10, 8,
  122052. };
  122053. static static_codebook _huff_book_line_128x17_3sub2 = {
  122054. 1, 50,
  122055. _huff_lengthlist_line_128x17_3sub2,
  122056. 0, 0, 0, 0, 0,
  122057. NULL,
  122058. NULL,
  122059. NULL,
  122060. NULL,
  122061. 0
  122062. };
  122063. static long _huff_lengthlist_line_128x17_3sub3[] = {
  122064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122067. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  122068. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  122069. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122070. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122071. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122072. };
  122073. static static_codebook _huff_book_line_128x17_3sub3 = {
  122074. 1, 128,
  122075. _huff_lengthlist_line_128x17_3sub3,
  122076. 0, 0, 0, 0, 0,
  122077. NULL,
  122078. NULL,
  122079. NULL,
  122080. NULL,
  122081. 0
  122082. };
  122083. static long _huff_lengthlist_line_1024x27_class1[] = {
  122084. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  122085. };
  122086. static static_codebook _huff_book_line_1024x27_class1 = {
  122087. 1, 16,
  122088. _huff_lengthlist_line_1024x27_class1,
  122089. 0, 0, 0, 0, 0,
  122090. NULL,
  122091. NULL,
  122092. NULL,
  122093. NULL,
  122094. 0
  122095. };
  122096. static long _huff_lengthlist_line_1024x27_class2[] = {
  122097. 1, 4, 2, 6, 3, 7, 5, 7,
  122098. };
  122099. static static_codebook _huff_book_line_1024x27_class2 = {
  122100. 1, 8,
  122101. _huff_lengthlist_line_1024x27_class2,
  122102. 0, 0, 0, 0, 0,
  122103. NULL,
  122104. NULL,
  122105. NULL,
  122106. NULL,
  122107. 0
  122108. };
  122109. static long _huff_lengthlist_line_1024x27_class3[] = {
  122110. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  122111. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  122112. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  122113. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  122114. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122115. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122116. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122117. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122118. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122119. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122120. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122121. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122122. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122123. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122124. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122125. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122126. };
  122127. static static_codebook _huff_book_line_1024x27_class3 = {
  122128. 1, 256,
  122129. _huff_lengthlist_line_1024x27_class3,
  122130. 0, 0, 0, 0, 0,
  122131. NULL,
  122132. NULL,
  122133. NULL,
  122134. NULL,
  122135. 0
  122136. };
  122137. static long _huff_lengthlist_line_1024x27_class4[] = {
  122138. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122139. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122140. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122141. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122142. };
  122143. static static_codebook _huff_book_line_1024x27_class4 = {
  122144. 1, 64,
  122145. _huff_lengthlist_line_1024x27_class4,
  122146. 0, 0, 0, 0, 0,
  122147. NULL,
  122148. NULL,
  122149. NULL,
  122150. NULL,
  122151. 0
  122152. };
  122153. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122154. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122155. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122156. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122157. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122158. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122159. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122160. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122161. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122162. };
  122163. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122164. 1, 128,
  122165. _huff_lengthlist_line_1024x27_0sub0,
  122166. 0, 0, 0, 0, 0,
  122167. NULL,
  122168. NULL,
  122169. NULL,
  122170. NULL,
  122171. 0
  122172. };
  122173. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122174. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122175. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122176. };
  122177. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122178. 1, 32,
  122179. _huff_lengthlist_line_1024x27_1sub0,
  122180. 0, 0, 0, 0, 0,
  122181. NULL,
  122182. NULL,
  122183. NULL,
  122184. NULL,
  122185. 0
  122186. };
  122187. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122190. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122191. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122192. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122193. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122194. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122195. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122196. };
  122197. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122198. 1, 128,
  122199. _huff_lengthlist_line_1024x27_1sub1,
  122200. 0, 0, 0, 0, 0,
  122201. NULL,
  122202. NULL,
  122203. NULL,
  122204. NULL,
  122205. 0
  122206. };
  122207. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122208. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122209. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122210. };
  122211. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122212. 1, 32,
  122213. _huff_lengthlist_line_1024x27_2sub0,
  122214. 0, 0, 0, 0, 0,
  122215. NULL,
  122216. NULL,
  122217. NULL,
  122218. NULL,
  122219. 0
  122220. };
  122221. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122224. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122225. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122226. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122227. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122228. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122229. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122230. };
  122231. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122232. 1, 128,
  122233. _huff_lengthlist_line_1024x27_2sub1,
  122234. 0, 0, 0, 0, 0,
  122235. NULL,
  122236. NULL,
  122237. NULL,
  122238. NULL,
  122239. 0
  122240. };
  122241. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122242. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122243. 5, 5,
  122244. };
  122245. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122246. 1, 18,
  122247. _huff_lengthlist_line_1024x27_3sub1,
  122248. 0, 0, 0, 0, 0,
  122249. NULL,
  122250. NULL,
  122251. NULL,
  122252. NULL,
  122253. 0
  122254. };
  122255. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122257. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122258. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122259. 9,11,
  122260. };
  122261. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122262. 1, 50,
  122263. _huff_lengthlist_line_1024x27_3sub2,
  122264. 0, 0, 0, 0, 0,
  122265. NULL,
  122266. NULL,
  122267. NULL,
  122268. NULL,
  122269. 0
  122270. };
  122271. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122275. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122276. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122277. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122278. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122279. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122280. };
  122281. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122282. 1, 128,
  122283. _huff_lengthlist_line_1024x27_3sub3,
  122284. 0, 0, 0, 0, 0,
  122285. NULL,
  122286. NULL,
  122287. NULL,
  122288. NULL,
  122289. 0
  122290. };
  122291. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122292. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122293. 5, 4,
  122294. };
  122295. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122296. 1, 18,
  122297. _huff_lengthlist_line_1024x27_4sub1,
  122298. 0, 0, 0, 0, 0,
  122299. NULL,
  122300. NULL,
  122301. NULL,
  122302. NULL,
  122303. 0
  122304. };
  122305. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122308. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122309. 9,12,
  122310. };
  122311. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122312. 1, 50,
  122313. _huff_lengthlist_line_1024x27_4sub2,
  122314. 0, 0, 0, 0, 0,
  122315. NULL,
  122316. NULL,
  122317. NULL,
  122318. NULL,
  122319. 0
  122320. };
  122321. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122326. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122327. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122328. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122329. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122330. };
  122331. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122332. 1, 128,
  122333. _huff_lengthlist_line_1024x27_4sub3,
  122334. 0, 0, 0, 0, 0,
  122335. NULL,
  122336. NULL,
  122337. NULL,
  122338. NULL,
  122339. 0
  122340. };
  122341. static long _huff_lengthlist_line_2048x27_class1[] = {
  122342. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122343. };
  122344. static static_codebook _huff_book_line_2048x27_class1 = {
  122345. 1, 16,
  122346. _huff_lengthlist_line_2048x27_class1,
  122347. 0, 0, 0, 0, 0,
  122348. NULL,
  122349. NULL,
  122350. NULL,
  122351. NULL,
  122352. 0
  122353. };
  122354. static long _huff_lengthlist_line_2048x27_class2[] = {
  122355. 1, 2, 3, 6, 4, 7, 5, 7,
  122356. };
  122357. static static_codebook _huff_book_line_2048x27_class2 = {
  122358. 1, 8,
  122359. _huff_lengthlist_line_2048x27_class2,
  122360. 0, 0, 0, 0, 0,
  122361. NULL,
  122362. NULL,
  122363. NULL,
  122364. NULL,
  122365. 0
  122366. };
  122367. static long _huff_lengthlist_line_2048x27_class3[] = {
  122368. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122369. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122370. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122371. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122372. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122373. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122374. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122375. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122376. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122377. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122378. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122379. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122380. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122381. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122382. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122383. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122384. };
  122385. static static_codebook _huff_book_line_2048x27_class3 = {
  122386. 1, 256,
  122387. _huff_lengthlist_line_2048x27_class3,
  122388. 0, 0, 0, 0, 0,
  122389. NULL,
  122390. NULL,
  122391. NULL,
  122392. NULL,
  122393. 0
  122394. };
  122395. static long _huff_lengthlist_line_2048x27_class4[] = {
  122396. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122397. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122398. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122399. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122400. };
  122401. static static_codebook _huff_book_line_2048x27_class4 = {
  122402. 1, 64,
  122403. _huff_lengthlist_line_2048x27_class4,
  122404. 0, 0, 0, 0, 0,
  122405. NULL,
  122406. NULL,
  122407. NULL,
  122408. NULL,
  122409. 0
  122410. };
  122411. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122412. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122413. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122414. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122415. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122416. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122417. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122418. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122419. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122420. };
  122421. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122422. 1, 128,
  122423. _huff_lengthlist_line_2048x27_0sub0,
  122424. 0, 0, 0, 0, 0,
  122425. NULL,
  122426. NULL,
  122427. NULL,
  122428. NULL,
  122429. 0
  122430. };
  122431. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122432. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122433. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122434. };
  122435. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122436. 1, 32,
  122437. _huff_lengthlist_line_2048x27_1sub0,
  122438. 0, 0, 0, 0, 0,
  122439. NULL,
  122440. NULL,
  122441. NULL,
  122442. NULL,
  122443. 0
  122444. };
  122445. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122449. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122450. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122451. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122452. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122453. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122454. };
  122455. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122456. 1, 128,
  122457. _huff_lengthlist_line_2048x27_1sub1,
  122458. 0, 0, 0, 0, 0,
  122459. NULL,
  122460. NULL,
  122461. NULL,
  122462. NULL,
  122463. 0
  122464. };
  122465. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122466. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122467. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122468. };
  122469. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122470. 1, 32,
  122471. _huff_lengthlist_line_2048x27_2sub0,
  122472. 0, 0, 0, 0, 0,
  122473. NULL,
  122474. NULL,
  122475. NULL,
  122476. NULL,
  122477. 0
  122478. };
  122479. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122483. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122484. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122485. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122486. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122487. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122488. };
  122489. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122490. 1, 128,
  122491. _huff_lengthlist_line_2048x27_2sub1,
  122492. 0, 0, 0, 0, 0,
  122493. NULL,
  122494. NULL,
  122495. NULL,
  122496. NULL,
  122497. 0
  122498. };
  122499. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122500. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122501. 5, 5,
  122502. };
  122503. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122504. 1, 18,
  122505. _huff_lengthlist_line_2048x27_3sub1,
  122506. 0, 0, 0, 0, 0,
  122507. NULL,
  122508. NULL,
  122509. NULL,
  122510. NULL,
  122511. 0
  122512. };
  122513. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122516. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122517. 10,12,
  122518. };
  122519. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122520. 1, 50,
  122521. _huff_lengthlist_line_2048x27_3sub2,
  122522. 0, 0, 0, 0, 0,
  122523. NULL,
  122524. NULL,
  122525. NULL,
  122526. NULL,
  122527. 0
  122528. };
  122529. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122534. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122535. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122536. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122537. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122538. };
  122539. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122540. 1, 128,
  122541. _huff_lengthlist_line_2048x27_3sub3,
  122542. 0, 0, 0, 0, 0,
  122543. NULL,
  122544. NULL,
  122545. NULL,
  122546. NULL,
  122547. 0
  122548. };
  122549. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122550. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122551. 4, 5,
  122552. };
  122553. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122554. 1, 18,
  122555. _huff_lengthlist_line_2048x27_4sub1,
  122556. 0, 0, 0, 0, 0,
  122557. NULL,
  122558. NULL,
  122559. NULL,
  122560. NULL,
  122561. 0
  122562. };
  122563. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122566. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122567. 10,10,
  122568. };
  122569. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122570. 1, 50,
  122571. _huff_lengthlist_line_2048x27_4sub2,
  122572. 0, 0, 0, 0, 0,
  122573. NULL,
  122574. NULL,
  122575. NULL,
  122576. NULL,
  122577. 0
  122578. };
  122579. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122584. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122585. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122586. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122587. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122588. };
  122589. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122590. 1, 128,
  122591. _huff_lengthlist_line_2048x27_4sub3,
  122592. 0, 0, 0, 0, 0,
  122593. NULL,
  122594. NULL,
  122595. NULL,
  122596. NULL,
  122597. 0
  122598. };
  122599. static long _huff_lengthlist_line_256x4low_class0[] = {
  122600. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122601. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122602. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122603. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122604. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122605. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122606. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122607. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122608. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122609. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122610. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122611. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122612. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122613. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122614. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122615. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122616. };
  122617. static static_codebook _huff_book_line_256x4low_class0 = {
  122618. 1, 256,
  122619. _huff_lengthlist_line_256x4low_class0,
  122620. 0, 0, 0, 0, 0,
  122621. NULL,
  122622. NULL,
  122623. NULL,
  122624. NULL,
  122625. 0
  122626. };
  122627. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122628. 1, 3, 2, 3,
  122629. };
  122630. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122631. 1, 4,
  122632. _huff_lengthlist_line_256x4low_0sub0,
  122633. 0, 0, 0, 0, 0,
  122634. NULL,
  122635. NULL,
  122636. NULL,
  122637. NULL,
  122638. 0
  122639. };
  122640. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122641. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122642. };
  122643. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122644. 1, 10,
  122645. _huff_lengthlist_line_256x4low_0sub1,
  122646. 0, 0, 0, 0, 0,
  122647. NULL,
  122648. NULL,
  122649. NULL,
  122650. NULL,
  122651. 0
  122652. };
  122653. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122655. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122656. };
  122657. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122658. 1, 25,
  122659. _huff_lengthlist_line_256x4low_0sub2,
  122660. 0, 0, 0, 0, 0,
  122661. NULL,
  122662. NULL,
  122663. NULL,
  122664. NULL,
  122665. 0
  122666. };
  122667. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  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, 3, 4, 2, 4, 3, 5, 4,
  122670. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122671. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122672. };
  122673. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122674. 1, 64,
  122675. _huff_lengthlist_line_256x4low_0sub3,
  122676. 0, 0, 0, 0, 0,
  122677. NULL,
  122678. NULL,
  122679. NULL,
  122680. NULL,
  122681. 0
  122682. };
  122683. /*** End of inlined file: floor_books.h ***/
  122684. static static_codebook *_floor_128x4_books[]={
  122685. &_huff_book_line_128x4_class0,
  122686. &_huff_book_line_128x4_0sub0,
  122687. &_huff_book_line_128x4_0sub1,
  122688. &_huff_book_line_128x4_0sub2,
  122689. &_huff_book_line_128x4_0sub3,
  122690. };
  122691. static static_codebook *_floor_256x4_books[]={
  122692. &_huff_book_line_256x4_class0,
  122693. &_huff_book_line_256x4_0sub0,
  122694. &_huff_book_line_256x4_0sub1,
  122695. &_huff_book_line_256x4_0sub2,
  122696. &_huff_book_line_256x4_0sub3,
  122697. };
  122698. static static_codebook *_floor_128x7_books[]={
  122699. &_huff_book_line_128x7_class0,
  122700. &_huff_book_line_128x7_class1,
  122701. &_huff_book_line_128x7_0sub1,
  122702. &_huff_book_line_128x7_0sub2,
  122703. &_huff_book_line_128x7_0sub3,
  122704. &_huff_book_line_128x7_1sub1,
  122705. &_huff_book_line_128x7_1sub2,
  122706. &_huff_book_line_128x7_1sub3,
  122707. };
  122708. static static_codebook *_floor_256x7_books[]={
  122709. &_huff_book_line_256x7_class0,
  122710. &_huff_book_line_256x7_class1,
  122711. &_huff_book_line_256x7_0sub1,
  122712. &_huff_book_line_256x7_0sub2,
  122713. &_huff_book_line_256x7_0sub3,
  122714. &_huff_book_line_256x7_1sub1,
  122715. &_huff_book_line_256x7_1sub2,
  122716. &_huff_book_line_256x7_1sub3,
  122717. };
  122718. static static_codebook *_floor_128x11_books[]={
  122719. &_huff_book_line_128x11_class1,
  122720. &_huff_book_line_128x11_class2,
  122721. &_huff_book_line_128x11_class3,
  122722. &_huff_book_line_128x11_0sub0,
  122723. &_huff_book_line_128x11_1sub0,
  122724. &_huff_book_line_128x11_1sub1,
  122725. &_huff_book_line_128x11_2sub1,
  122726. &_huff_book_line_128x11_2sub2,
  122727. &_huff_book_line_128x11_2sub3,
  122728. &_huff_book_line_128x11_3sub1,
  122729. &_huff_book_line_128x11_3sub2,
  122730. &_huff_book_line_128x11_3sub3,
  122731. };
  122732. static static_codebook *_floor_128x17_books[]={
  122733. &_huff_book_line_128x17_class1,
  122734. &_huff_book_line_128x17_class2,
  122735. &_huff_book_line_128x17_class3,
  122736. &_huff_book_line_128x17_0sub0,
  122737. &_huff_book_line_128x17_1sub0,
  122738. &_huff_book_line_128x17_1sub1,
  122739. &_huff_book_line_128x17_2sub1,
  122740. &_huff_book_line_128x17_2sub2,
  122741. &_huff_book_line_128x17_2sub3,
  122742. &_huff_book_line_128x17_3sub1,
  122743. &_huff_book_line_128x17_3sub2,
  122744. &_huff_book_line_128x17_3sub3,
  122745. };
  122746. static static_codebook *_floor_256x4low_books[]={
  122747. &_huff_book_line_256x4low_class0,
  122748. &_huff_book_line_256x4low_0sub0,
  122749. &_huff_book_line_256x4low_0sub1,
  122750. &_huff_book_line_256x4low_0sub2,
  122751. &_huff_book_line_256x4low_0sub3,
  122752. };
  122753. static static_codebook *_floor_1024x27_books[]={
  122754. &_huff_book_line_1024x27_class1,
  122755. &_huff_book_line_1024x27_class2,
  122756. &_huff_book_line_1024x27_class3,
  122757. &_huff_book_line_1024x27_class4,
  122758. &_huff_book_line_1024x27_0sub0,
  122759. &_huff_book_line_1024x27_1sub0,
  122760. &_huff_book_line_1024x27_1sub1,
  122761. &_huff_book_line_1024x27_2sub0,
  122762. &_huff_book_line_1024x27_2sub1,
  122763. &_huff_book_line_1024x27_3sub1,
  122764. &_huff_book_line_1024x27_3sub2,
  122765. &_huff_book_line_1024x27_3sub3,
  122766. &_huff_book_line_1024x27_4sub1,
  122767. &_huff_book_line_1024x27_4sub2,
  122768. &_huff_book_line_1024x27_4sub3,
  122769. };
  122770. static static_codebook *_floor_2048x27_books[]={
  122771. &_huff_book_line_2048x27_class1,
  122772. &_huff_book_line_2048x27_class2,
  122773. &_huff_book_line_2048x27_class3,
  122774. &_huff_book_line_2048x27_class4,
  122775. &_huff_book_line_2048x27_0sub0,
  122776. &_huff_book_line_2048x27_1sub0,
  122777. &_huff_book_line_2048x27_1sub1,
  122778. &_huff_book_line_2048x27_2sub0,
  122779. &_huff_book_line_2048x27_2sub1,
  122780. &_huff_book_line_2048x27_3sub1,
  122781. &_huff_book_line_2048x27_3sub2,
  122782. &_huff_book_line_2048x27_3sub3,
  122783. &_huff_book_line_2048x27_4sub1,
  122784. &_huff_book_line_2048x27_4sub2,
  122785. &_huff_book_line_2048x27_4sub3,
  122786. };
  122787. static static_codebook *_floor_512x17_books[]={
  122788. &_huff_book_line_512x17_class1,
  122789. &_huff_book_line_512x17_class2,
  122790. &_huff_book_line_512x17_class3,
  122791. &_huff_book_line_512x17_0sub0,
  122792. &_huff_book_line_512x17_1sub0,
  122793. &_huff_book_line_512x17_1sub1,
  122794. &_huff_book_line_512x17_2sub1,
  122795. &_huff_book_line_512x17_2sub2,
  122796. &_huff_book_line_512x17_2sub3,
  122797. &_huff_book_line_512x17_3sub1,
  122798. &_huff_book_line_512x17_3sub2,
  122799. &_huff_book_line_512x17_3sub3,
  122800. };
  122801. static static_codebook **_floor_books[10]={
  122802. _floor_128x4_books,
  122803. _floor_256x4_books,
  122804. _floor_128x7_books,
  122805. _floor_256x7_books,
  122806. _floor_128x11_books,
  122807. _floor_128x17_books,
  122808. _floor_256x4low_books,
  122809. _floor_1024x27_books,
  122810. _floor_2048x27_books,
  122811. _floor_512x17_books,
  122812. };
  122813. static vorbis_info_floor1 _floor[10]={
  122814. /* 128 x 4 */
  122815. {
  122816. 1,{0},{4},{2},{0},
  122817. {{1,2,3,4}},
  122818. 4,{0,128, 33,8,16,70},
  122819. 60,30,500, 1.,18., -1
  122820. },
  122821. /* 256 x 4 */
  122822. {
  122823. 1,{0},{4},{2},{0},
  122824. {{1,2,3,4}},
  122825. 4,{0,256, 66,16,32,140},
  122826. 60,30,500, 1.,18., -1
  122827. },
  122828. /* 128 x 7 */
  122829. {
  122830. 2,{0,1},{3,4},{2,2},{0,1},
  122831. {{-1,2,3,4},{-1,5,6,7}},
  122832. 4,{0,128, 14,4,58, 2,8,28,90},
  122833. 60,30,500, 1.,18., -1
  122834. },
  122835. /* 256 x 7 */
  122836. {
  122837. 2,{0,1},{3,4},{2,2},{0,1},
  122838. {{-1,2,3,4},{-1,5,6,7}},
  122839. 4,{0,256, 28,8,116, 4,16,56,180},
  122840. 60,30,500, 1.,18., -1
  122841. },
  122842. /* 128 x 11 */
  122843. {
  122844. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122845. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122846. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122847. 60,30,500, 1,18., -1
  122848. },
  122849. /* 128 x 17 */
  122850. {
  122851. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122852. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122853. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122854. 60,30,500, 1,18., -1
  122855. },
  122856. /* 256 x 4 (low bitrate version) */
  122857. {
  122858. 1,{0},{4},{2},{0},
  122859. {{1,2,3,4}},
  122860. 4,{0,256, 66,16,32,140},
  122861. 60,30,500, 1.,18., -1
  122862. },
  122863. /* 1024 x 27 */
  122864. {
  122865. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122866. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122867. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122868. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122869. 60,30,500, 3,18., -1 /* lowpass */
  122870. },
  122871. /* 2048 x 27 */
  122872. {
  122873. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122874. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122875. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122876. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122877. 60,30,500, 3,18., -1 /* lowpass */
  122878. },
  122879. /* 512 x 17 */
  122880. {
  122881. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122882. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122883. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122884. 7,23,39, 55,79,110, 156,232,360},
  122885. 60,30,500, 1,18., -1 /* lowpass! */
  122886. },
  122887. };
  122888. /*** End of inlined file: floor_all.h ***/
  122889. /*** Start of inlined file: residue_44.h ***/
  122890. /*** Start of inlined file: res_books_stereo.h ***/
  122891. static long _vq_quantlist__16c0_s_p1_0[] = {
  122892. 1,
  122893. 0,
  122894. 2,
  122895. };
  122896. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122897. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122898. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122903. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122908. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  122943. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122948. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122953. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122989. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122994. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122999. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123307. 0,
  123308. };
  123309. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123310. -0.5, 0.5,
  123311. };
  123312. static long _vq_quantmap__16c0_s_p1_0[] = {
  123313. 1, 0, 2,
  123314. };
  123315. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123316. _vq_quantthresh__16c0_s_p1_0,
  123317. _vq_quantmap__16c0_s_p1_0,
  123318. 3,
  123319. 3
  123320. };
  123321. static static_codebook _16c0_s_p1_0 = {
  123322. 8, 6561,
  123323. _vq_lengthlist__16c0_s_p1_0,
  123324. 1, -535822336, 1611661312, 2, 0,
  123325. _vq_quantlist__16c0_s_p1_0,
  123326. NULL,
  123327. &_vq_auxt__16c0_s_p1_0,
  123328. NULL,
  123329. 0
  123330. };
  123331. static long _vq_quantlist__16c0_s_p2_0[] = {
  123332. 2,
  123333. 1,
  123334. 3,
  123335. 0,
  123336. 4,
  123337. };
  123338. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0,
  123379. };
  123380. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123381. -1.5, -0.5, 0.5, 1.5,
  123382. };
  123383. static long _vq_quantmap__16c0_s_p2_0[] = {
  123384. 3, 1, 0, 2, 4,
  123385. };
  123386. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123387. _vq_quantthresh__16c0_s_p2_0,
  123388. _vq_quantmap__16c0_s_p2_0,
  123389. 5,
  123390. 5
  123391. };
  123392. static static_codebook _16c0_s_p2_0 = {
  123393. 4, 625,
  123394. _vq_lengthlist__16c0_s_p2_0,
  123395. 1, -533725184, 1611661312, 3, 0,
  123396. _vq_quantlist__16c0_s_p2_0,
  123397. NULL,
  123398. &_vq_auxt__16c0_s_p2_0,
  123399. NULL,
  123400. 0
  123401. };
  123402. static long _vq_quantlist__16c0_s_p3_0[] = {
  123403. 2,
  123404. 1,
  123405. 3,
  123406. 0,
  123407. 4,
  123408. };
  123409. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123410. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0,
  123450. };
  123451. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123452. -1.5, -0.5, 0.5, 1.5,
  123453. };
  123454. static long _vq_quantmap__16c0_s_p3_0[] = {
  123455. 3, 1, 0, 2, 4,
  123456. };
  123457. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123458. _vq_quantthresh__16c0_s_p3_0,
  123459. _vq_quantmap__16c0_s_p3_0,
  123460. 5,
  123461. 5
  123462. };
  123463. static static_codebook _16c0_s_p3_0 = {
  123464. 4, 625,
  123465. _vq_lengthlist__16c0_s_p3_0,
  123466. 1, -533725184, 1611661312, 3, 0,
  123467. _vq_quantlist__16c0_s_p3_0,
  123468. NULL,
  123469. &_vq_auxt__16c0_s_p3_0,
  123470. NULL,
  123471. 0
  123472. };
  123473. static long _vq_quantlist__16c0_s_p4_0[] = {
  123474. 4,
  123475. 3,
  123476. 5,
  123477. 2,
  123478. 6,
  123479. 1,
  123480. 7,
  123481. 0,
  123482. 8,
  123483. };
  123484. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123485. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123486. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123487. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123488. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123489. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0,
  123491. };
  123492. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123493. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123494. };
  123495. static long _vq_quantmap__16c0_s_p4_0[] = {
  123496. 7, 5, 3, 1, 0, 2, 4, 6,
  123497. 8,
  123498. };
  123499. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123500. _vq_quantthresh__16c0_s_p4_0,
  123501. _vq_quantmap__16c0_s_p4_0,
  123502. 9,
  123503. 9
  123504. };
  123505. static static_codebook _16c0_s_p4_0 = {
  123506. 2, 81,
  123507. _vq_lengthlist__16c0_s_p4_0,
  123508. 1, -531628032, 1611661312, 4, 0,
  123509. _vq_quantlist__16c0_s_p4_0,
  123510. NULL,
  123511. &_vq_auxt__16c0_s_p4_0,
  123512. NULL,
  123513. 0
  123514. };
  123515. static long _vq_quantlist__16c0_s_p5_0[] = {
  123516. 4,
  123517. 3,
  123518. 5,
  123519. 2,
  123520. 6,
  123521. 1,
  123522. 7,
  123523. 0,
  123524. 8,
  123525. };
  123526. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123527. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123528. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123529. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123530. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123531. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123532. 10,
  123533. };
  123534. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123535. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123536. };
  123537. static long _vq_quantmap__16c0_s_p5_0[] = {
  123538. 7, 5, 3, 1, 0, 2, 4, 6,
  123539. 8,
  123540. };
  123541. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123542. _vq_quantthresh__16c0_s_p5_0,
  123543. _vq_quantmap__16c0_s_p5_0,
  123544. 9,
  123545. 9
  123546. };
  123547. static static_codebook _16c0_s_p5_0 = {
  123548. 2, 81,
  123549. _vq_lengthlist__16c0_s_p5_0,
  123550. 1, -531628032, 1611661312, 4, 0,
  123551. _vq_quantlist__16c0_s_p5_0,
  123552. NULL,
  123553. &_vq_auxt__16c0_s_p5_0,
  123554. NULL,
  123555. 0
  123556. };
  123557. static long _vq_quantlist__16c0_s_p6_0[] = {
  123558. 8,
  123559. 7,
  123560. 9,
  123561. 6,
  123562. 10,
  123563. 5,
  123564. 11,
  123565. 4,
  123566. 12,
  123567. 3,
  123568. 13,
  123569. 2,
  123570. 14,
  123571. 1,
  123572. 15,
  123573. 0,
  123574. 16,
  123575. };
  123576. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123577. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123578. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123579. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123580. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123581. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123582. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123583. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123584. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123585. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123586. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123587. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123588. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123589. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123590. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123591. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123592. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123593. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123595. 14,
  123596. };
  123597. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123598. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123599. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123600. };
  123601. static long _vq_quantmap__16c0_s_p6_0[] = {
  123602. 15, 13, 11, 9, 7, 5, 3, 1,
  123603. 0, 2, 4, 6, 8, 10, 12, 14,
  123604. 16,
  123605. };
  123606. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123607. _vq_quantthresh__16c0_s_p6_0,
  123608. _vq_quantmap__16c0_s_p6_0,
  123609. 17,
  123610. 17
  123611. };
  123612. static static_codebook _16c0_s_p6_0 = {
  123613. 2, 289,
  123614. _vq_lengthlist__16c0_s_p6_0,
  123615. 1, -529530880, 1611661312, 5, 0,
  123616. _vq_quantlist__16c0_s_p6_0,
  123617. NULL,
  123618. &_vq_auxt__16c0_s_p6_0,
  123619. NULL,
  123620. 0
  123621. };
  123622. static long _vq_quantlist__16c0_s_p7_0[] = {
  123623. 1,
  123624. 0,
  123625. 2,
  123626. };
  123627. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123628. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123629. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123630. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123631. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123632. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123633. 13,
  123634. };
  123635. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123636. -5.5, 5.5,
  123637. };
  123638. static long _vq_quantmap__16c0_s_p7_0[] = {
  123639. 1, 0, 2,
  123640. };
  123641. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123642. _vq_quantthresh__16c0_s_p7_0,
  123643. _vq_quantmap__16c0_s_p7_0,
  123644. 3,
  123645. 3
  123646. };
  123647. static static_codebook _16c0_s_p7_0 = {
  123648. 4, 81,
  123649. _vq_lengthlist__16c0_s_p7_0,
  123650. 1, -529137664, 1618345984, 2, 0,
  123651. _vq_quantlist__16c0_s_p7_0,
  123652. NULL,
  123653. &_vq_auxt__16c0_s_p7_0,
  123654. NULL,
  123655. 0
  123656. };
  123657. static long _vq_quantlist__16c0_s_p7_1[] = {
  123658. 5,
  123659. 4,
  123660. 6,
  123661. 3,
  123662. 7,
  123663. 2,
  123664. 8,
  123665. 1,
  123666. 9,
  123667. 0,
  123668. 10,
  123669. };
  123670. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123671. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123672. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123673. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123674. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123675. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123676. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123677. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123678. 11,11,11, 9, 9, 9, 9,10,10,
  123679. };
  123680. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123681. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123682. 3.5, 4.5,
  123683. };
  123684. static long _vq_quantmap__16c0_s_p7_1[] = {
  123685. 9, 7, 5, 3, 1, 0, 2, 4,
  123686. 6, 8, 10,
  123687. };
  123688. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123689. _vq_quantthresh__16c0_s_p7_1,
  123690. _vq_quantmap__16c0_s_p7_1,
  123691. 11,
  123692. 11
  123693. };
  123694. static static_codebook _16c0_s_p7_1 = {
  123695. 2, 121,
  123696. _vq_lengthlist__16c0_s_p7_1,
  123697. 1, -531365888, 1611661312, 4, 0,
  123698. _vq_quantlist__16c0_s_p7_1,
  123699. NULL,
  123700. &_vq_auxt__16c0_s_p7_1,
  123701. NULL,
  123702. 0
  123703. };
  123704. static long _vq_quantlist__16c0_s_p8_0[] = {
  123705. 6,
  123706. 5,
  123707. 7,
  123708. 4,
  123709. 8,
  123710. 3,
  123711. 9,
  123712. 2,
  123713. 10,
  123714. 1,
  123715. 11,
  123716. 0,
  123717. 12,
  123718. };
  123719. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123720. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123721. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123722. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123723. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123724. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123725. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123726. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123727. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123728. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123729. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123730. 0,12,13,13,12,13,14,14,14,
  123731. };
  123732. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123733. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123734. 12.5, 17.5, 22.5, 27.5,
  123735. };
  123736. static long _vq_quantmap__16c0_s_p8_0[] = {
  123737. 11, 9, 7, 5, 3, 1, 0, 2,
  123738. 4, 6, 8, 10, 12,
  123739. };
  123740. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123741. _vq_quantthresh__16c0_s_p8_0,
  123742. _vq_quantmap__16c0_s_p8_0,
  123743. 13,
  123744. 13
  123745. };
  123746. static static_codebook _16c0_s_p8_0 = {
  123747. 2, 169,
  123748. _vq_lengthlist__16c0_s_p8_0,
  123749. 1, -526516224, 1616117760, 4, 0,
  123750. _vq_quantlist__16c0_s_p8_0,
  123751. NULL,
  123752. &_vq_auxt__16c0_s_p8_0,
  123753. NULL,
  123754. 0
  123755. };
  123756. static long _vq_quantlist__16c0_s_p8_1[] = {
  123757. 2,
  123758. 1,
  123759. 3,
  123760. 0,
  123761. 4,
  123762. };
  123763. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123764. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123765. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123766. };
  123767. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123768. -1.5, -0.5, 0.5, 1.5,
  123769. };
  123770. static long _vq_quantmap__16c0_s_p8_1[] = {
  123771. 3, 1, 0, 2, 4,
  123772. };
  123773. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123774. _vq_quantthresh__16c0_s_p8_1,
  123775. _vq_quantmap__16c0_s_p8_1,
  123776. 5,
  123777. 5
  123778. };
  123779. static static_codebook _16c0_s_p8_1 = {
  123780. 2, 25,
  123781. _vq_lengthlist__16c0_s_p8_1,
  123782. 1, -533725184, 1611661312, 3, 0,
  123783. _vq_quantlist__16c0_s_p8_1,
  123784. NULL,
  123785. &_vq_auxt__16c0_s_p8_1,
  123786. NULL,
  123787. 0
  123788. };
  123789. static long _vq_quantlist__16c0_s_p9_0[] = {
  123790. 1,
  123791. 0,
  123792. 2,
  123793. };
  123794. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123795. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123796. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123797. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123798. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123799. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123800. 7,
  123801. };
  123802. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123803. -157.5, 157.5,
  123804. };
  123805. static long _vq_quantmap__16c0_s_p9_0[] = {
  123806. 1, 0, 2,
  123807. };
  123808. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123809. _vq_quantthresh__16c0_s_p9_0,
  123810. _vq_quantmap__16c0_s_p9_0,
  123811. 3,
  123812. 3
  123813. };
  123814. static static_codebook _16c0_s_p9_0 = {
  123815. 4, 81,
  123816. _vq_lengthlist__16c0_s_p9_0,
  123817. 1, -518803456, 1628680192, 2, 0,
  123818. _vq_quantlist__16c0_s_p9_0,
  123819. NULL,
  123820. &_vq_auxt__16c0_s_p9_0,
  123821. NULL,
  123822. 0
  123823. };
  123824. static long _vq_quantlist__16c0_s_p9_1[] = {
  123825. 7,
  123826. 6,
  123827. 8,
  123828. 5,
  123829. 9,
  123830. 4,
  123831. 10,
  123832. 3,
  123833. 11,
  123834. 2,
  123835. 12,
  123836. 1,
  123837. 13,
  123838. 0,
  123839. 14,
  123840. };
  123841. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123842. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123843. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123844. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123845. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123846. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123847. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123848. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123849. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123850. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123851. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123856. 10,
  123857. };
  123858. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123859. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123860. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123861. };
  123862. static long _vq_quantmap__16c0_s_p9_1[] = {
  123863. 13, 11, 9, 7, 5, 3, 1, 0,
  123864. 2, 4, 6, 8, 10, 12, 14,
  123865. };
  123866. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123867. _vq_quantthresh__16c0_s_p9_1,
  123868. _vq_quantmap__16c0_s_p9_1,
  123869. 15,
  123870. 15
  123871. };
  123872. static static_codebook _16c0_s_p9_1 = {
  123873. 2, 225,
  123874. _vq_lengthlist__16c0_s_p9_1,
  123875. 1, -520986624, 1620377600, 4, 0,
  123876. _vq_quantlist__16c0_s_p9_1,
  123877. NULL,
  123878. &_vq_auxt__16c0_s_p9_1,
  123879. NULL,
  123880. 0
  123881. };
  123882. static long _vq_quantlist__16c0_s_p9_2[] = {
  123883. 10,
  123884. 9,
  123885. 11,
  123886. 8,
  123887. 12,
  123888. 7,
  123889. 13,
  123890. 6,
  123891. 14,
  123892. 5,
  123893. 15,
  123894. 4,
  123895. 16,
  123896. 3,
  123897. 17,
  123898. 2,
  123899. 18,
  123900. 1,
  123901. 19,
  123902. 0,
  123903. 20,
  123904. };
  123905. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123906. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123907. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123908. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123909. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123910. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123911. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123912. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123913. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123914. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123915. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123916. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123917. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123918. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123919. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123920. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123921. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123922. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123923. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123924. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123925. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123926. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123927. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123928. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123929. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123930. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123931. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123932. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123933. 10,11,10,10,11, 9,10,10,10,
  123934. };
  123935. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123936. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123937. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123938. 6.5, 7.5, 8.5, 9.5,
  123939. };
  123940. static long _vq_quantmap__16c0_s_p9_2[] = {
  123941. 19, 17, 15, 13, 11, 9, 7, 5,
  123942. 3, 1, 0, 2, 4, 6, 8, 10,
  123943. 12, 14, 16, 18, 20,
  123944. };
  123945. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123946. _vq_quantthresh__16c0_s_p9_2,
  123947. _vq_quantmap__16c0_s_p9_2,
  123948. 21,
  123949. 21
  123950. };
  123951. static static_codebook _16c0_s_p9_2 = {
  123952. 2, 441,
  123953. _vq_lengthlist__16c0_s_p9_2,
  123954. 1, -529268736, 1611661312, 5, 0,
  123955. _vq_quantlist__16c0_s_p9_2,
  123956. NULL,
  123957. &_vq_auxt__16c0_s_p9_2,
  123958. NULL,
  123959. 0
  123960. };
  123961. static long _huff_lengthlist__16c0_s_single[] = {
  123962. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123963. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123964. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123965. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123966. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123967. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123968. 16,16,18,18,
  123969. };
  123970. static static_codebook _huff_book__16c0_s_single = {
  123971. 2, 100,
  123972. _huff_lengthlist__16c0_s_single,
  123973. 0, 0, 0, 0, 0,
  123974. NULL,
  123975. NULL,
  123976. NULL,
  123977. NULL,
  123978. 0
  123979. };
  123980. static long _huff_lengthlist__16c1_s_long[] = {
  123981. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123982. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123983. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123984. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123985. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123986. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123987. 12,11,11,13,
  123988. };
  123989. static static_codebook _huff_book__16c1_s_long = {
  123990. 2, 100,
  123991. _huff_lengthlist__16c1_s_long,
  123992. 0, 0, 0, 0, 0,
  123993. NULL,
  123994. NULL,
  123995. NULL,
  123996. NULL,
  123997. 0
  123998. };
  123999. static long _vq_quantlist__16c1_s_p1_0[] = {
  124000. 1,
  124001. 0,
  124002. 2,
  124003. };
  124004. static long _vq_lengthlist__16c1_s_p1_0[] = {
  124005. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124006. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  124011. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  124016. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  124051. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  124056. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  124061. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124097. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124102. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124107. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124415. 0,
  124416. };
  124417. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124418. -0.5, 0.5,
  124419. };
  124420. static long _vq_quantmap__16c1_s_p1_0[] = {
  124421. 1, 0, 2,
  124422. };
  124423. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124424. _vq_quantthresh__16c1_s_p1_0,
  124425. _vq_quantmap__16c1_s_p1_0,
  124426. 3,
  124427. 3
  124428. };
  124429. static static_codebook _16c1_s_p1_0 = {
  124430. 8, 6561,
  124431. _vq_lengthlist__16c1_s_p1_0,
  124432. 1, -535822336, 1611661312, 2, 0,
  124433. _vq_quantlist__16c1_s_p1_0,
  124434. NULL,
  124435. &_vq_auxt__16c1_s_p1_0,
  124436. NULL,
  124437. 0
  124438. };
  124439. static long _vq_quantlist__16c1_s_p2_0[] = {
  124440. 2,
  124441. 1,
  124442. 3,
  124443. 0,
  124444. 4,
  124445. };
  124446. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124486. 0,
  124487. };
  124488. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124489. -1.5, -0.5, 0.5, 1.5,
  124490. };
  124491. static long _vq_quantmap__16c1_s_p2_0[] = {
  124492. 3, 1, 0, 2, 4,
  124493. };
  124494. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124495. _vq_quantthresh__16c1_s_p2_0,
  124496. _vq_quantmap__16c1_s_p2_0,
  124497. 5,
  124498. 5
  124499. };
  124500. static static_codebook _16c1_s_p2_0 = {
  124501. 4, 625,
  124502. _vq_lengthlist__16c1_s_p2_0,
  124503. 1, -533725184, 1611661312, 3, 0,
  124504. _vq_quantlist__16c1_s_p2_0,
  124505. NULL,
  124506. &_vq_auxt__16c1_s_p2_0,
  124507. NULL,
  124508. 0
  124509. };
  124510. static long _vq_quantlist__16c1_s_p3_0[] = {
  124511. 2,
  124512. 1,
  124513. 3,
  124514. 0,
  124515. 4,
  124516. };
  124517. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124518. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124521. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124524. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124557. 0,
  124558. };
  124559. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124560. -1.5, -0.5, 0.5, 1.5,
  124561. };
  124562. static long _vq_quantmap__16c1_s_p3_0[] = {
  124563. 3, 1, 0, 2, 4,
  124564. };
  124565. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124566. _vq_quantthresh__16c1_s_p3_0,
  124567. _vq_quantmap__16c1_s_p3_0,
  124568. 5,
  124569. 5
  124570. };
  124571. static static_codebook _16c1_s_p3_0 = {
  124572. 4, 625,
  124573. _vq_lengthlist__16c1_s_p3_0,
  124574. 1, -533725184, 1611661312, 3, 0,
  124575. _vq_quantlist__16c1_s_p3_0,
  124576. NULL,
  124577. &_vq_auxt__16c1_s_p3_0,
  124578. NULL,
  124579. 0
  124580. };
  124581. static long _vq_quantlist__16c1_s_p4_0[] = {
  124582. 4,
  124583. 3,
  124584. 5,
  124585. 2,
  124586. 6,
  124587. 1,
  124588. 7,
  124589. 0,
  124590. 8,
  124591. };
  124592. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124593. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124594. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124595. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124596. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124597. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124598. 0,
  124599. };
  124600. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124601. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124602. };
  124603. static long _vq_quantmap__16c1_s_p4_0[] = {
  124604. 7, 5, 3, 1, 0, 2, 4, 6,
  124605. 8,
  124606. };
  124607. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124608. _vq_quantthresh__16c1_s_p4_0,
  124609. _vq_quantmap__16c1_s_p4_0,
  124610. 9,
  124611. 9
  124612. };
  124613. static static_codebook _16c1_s_p4_0 = {
  124614. 2, 81,
  124615. _vq_lengthlist__16c1_s_p4_0,
  124616. 1, -531628032, 1611661312, 4, 0,
  124617. _vq_quantlist__16c1_s_p4_0,
  124618. NULL,
  124619. &_vq_auxt__16c1_s_p4_0,
  124620. NULL,
  124621. 0
  124622. };
  124623. static long _vq_quantlist__16c1_s_p5_0[] = {
  124624. 4,
  124625. 3,
  124626. 5,
  124627. 2,
  124628. 6,
  124629. 1,
  124630. 7,
  124631. 0,
  124632. 8,
  124633. };
  124634. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124635. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124636. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124637. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124638. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124639. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124640. 10,
  124641. };
  124642. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124643. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124644. };
  124645. static long _vq_quantmap__16c1_s_p5_0[] = {
  124646. 7, 5, 3, 1, 0, 2, 4, 6,
  124647. 8,
  124648. };
  124649. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124650. _vq_quantthresh__16c1_s_p5_0,
  124651. _vq_quantmap__16c1_s_p5_0,
  124652. 9,
  124653. 9
  124654. };
  124655. static static_codebook _16c1_s_p5_0 = {
  124656. 2, 81,
  124657. _vq_lengthlist__16c1_s_p5_0,
  124658. 1, -531628032, 1611661312, 4, 0,
  124659. _vq_quantlist__16c1_s_p5_0,
  124660. NULL,
  124661. &_vq_auxt__16c1_s_p5_0,
  124662. NULL,
  124663. 0
  124664. };
  124665. static long _vq_quantlist__16c1_s_p6_0[] = {
  124666. 8,
  124667. 7,
  124668. 9,
  124669. 6,
  124670. 10,
  124671. 5,
  124672. 11,
  124673. 4,
  124674. 12,
  124675. 3,
  124676. 13,
  124677. 2,
  124678. 14,
  124679. 1,
  124680. 15,
  124681. 0,
  124682. 16,
  124683. };
  124684. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124685. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124686. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124687. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124688. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124689. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124690. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124691. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124692. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124693. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124694. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124695. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124696. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124697. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124698. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124699. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124700. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124701. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124703. 14,
  124704. };
  124705. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124706. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124707. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124708. };
  124709. static long _vq_quantmap__16c1_s_p6_0[] = {
  124710. 15, 13, 11, 9, 7, 5, 3, 1,
  124711. 0, 2, 4, 6, 8, 10, 12, 14,
  124712. 16,
  124713. };
  124714. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124715. _vq_quantthresh__16c1_s_p6_0,
  124716. _vq_quantmap__16c1_s_p6_0,
  124717. 17,
  124718. 17
  124719. };
  124720. static static_codebook _16c1_s_p6_0 = {
  124721. 2, 289,
  124722. _vq_lengthlist__16c1_s_p6_0,
  124723. 1, -529530880, 1611661312, 5, 0,
  124724. _vq_quantlist__16c1_s_p6_0,
  124725. NULL,
  124726. &_vq_auxt__16c1_s_p6_0,
  124727. NULL,
  124728. 0
  124729. };
  124730. static long _vq_quantlist__16c1_s_p7_0[] = {
  124731. 1,
  124732. 0,
  124733. 2,
  124734. };
  124735. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124736. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124737. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124738. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124739. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124740. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124741. 11,
  124742. };
  124743. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124744. -5.5, 5.5,
  124745. };
  124746. static long _vq_quantmap__16c1_s_p7_0[] = {
  124747. 1, 0, 2,
  124748. };
  124749. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124750. _vq_quantthresh__16c1_s_p7_0,
  124751. _vq_quantmap__16c1_s_p7_0,
  124752. 3,
  124753. 3
  124754. };
  124755. static static_codebook _16c1_s_p7_0 = {
  124756. 4, 81,
  124757. _vq_lengthlist__16c1_s_p7_0,
  124758. 1, -529137664, 1618345984, 2, 0,
  124759. _vq_quantlist__16c1_s_p7_0,
  124760. NULL,
  124761. &_vq_auxt__16c1_s_p7_0,
  124762. NULL,
  124763. 0
  124764. };
  124765. static long _vq_quantlist__16c1_s_p7_1[] = {
  124766. 5,
  124767. 4,
  124768. 6,
  124769. 3,
  124770. 7,
  124771. 2,
  124772. 8,
  124773. 1,
  124774. 9,
  124775. 0,
  124776. 10,
  124777. };
  124778. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124779. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124780. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124781. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124782. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124783. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124784. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124785. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124786. 10,10,10, 8, 8, 8, 8, 9, 9,
  124787. };
  124788. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124789. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124790. 3.5, 4.5,
  124791. };
  124792. static long _vq_quantmap__16c1_s_p7_1[] = {
  124793. 9, 7, 5, 3, 1, 0, 2, 4,
  124794. 6, 8, 10,
  124795. };
  124796. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124797. _vq_quantthresh__16c1_s_p7_1,
  124798. _vq_quantmap__16c1_s_p7_1,
  124799. 11,
  124800. 11
  124801. };
  124802. static static_codebook _16c1_s_p7_1 = {
  124803. 2, 121,
  124804. _vq_lengthlist__16c1_s_p7_1,
  124805. 1, -531365888, 1611661312, 4, 0,
  124806. _vq_quantlist__16c1_s_p7_1,
  124807. NULL,
  124808. &_vq_auxt__16c1_s_p7_1,
  124809. NULL,
  124810. 0
  124811. };
  124812. static long _vq_quantlist__16c1_s_p8_0[] = {
  124813. 6,
  124814. 5,
  124815. 7,
  124816. 4,
  124817. 8,
  124818. 3,
  124819. 9,
  124820. 2,
  124821. 10,
  124822. 1,
  124823. 11,
  124824. 0,
  124825. 12,
  124826. };
  124827. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124828. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124829. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124830. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124831. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124832. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124833. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124834. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124835. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124836. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124837. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124838. 0,12,12,12,12,13,13,14,15,
  124839. };
  124840. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124841. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124842. 12.5, 17.5, 22.5, 27.5,
  124843. };
  124844. static long _vq_quantmap__16c1_s_p8_0[] = {
  124845. 11, 9, 7, 5, 3, 1, 0, 2,
  124846. 4, 6, 8, 10, 12,
  124847. };
  124848. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124849. _vq_quantthresh__16c1_s_p8_0,
  124850. _vq_quantmap__16c1_s_p8_0,
  124851. 13,
  124852. 13
  124853. };
  124854. static static_codebook _16c1_s_p8_0 = {
  124855. 2, 169,
  124856. _vq_lengthlist__16c1_s_p8_0,
  124857. 1, -526516224, 1616117760, 4, 0,
  124858. _vq_quantlist__16c1_s_p8_0,
  124859. NULL,
  124860. &_vq_auxt__16c1_s_p8_0,
  124861. NULL,
  124862. 0
  124863. };
  124864. static long _vq_quantlist__16c1_s_p8_1[] = {
  124865. 2,
  124866. 1,
  124867. 3,
  124868. 0,
  124869. 4,
  124870. };
  124871. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124872. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124873. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124874. };
  124875. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124876. -1.5, -0.5, 0.5, 1.5,
  124877. };
  124878. static long _vq_quantmap__16c1_s_p8_1[] = {
  124879. 3, 1, 0, 2, 4,
  124880. };
  124881. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124882. _vq_quantthresh__16c1_s_p8_1,
  124883. _vq_quantmap__16c1_s_p8_1,
  124884. 5,
  124885. 5
  124886. };
  124887. static static_codebook _16c1_s_p8_1 = {
  124888. 2, 25,
  124889. _vq_lengthlist__16c1_s_p8_1,
  124890. 1, -533725184, 1611661312, 3, 0,
  124891. _vq_quantlist__16c1_s_p8_1,
  124892. NULL,
  124893. &_vq_auxt__16c1_s_p8_1,
  124894. NULL,
  124895. 0
  124896. };
  124897. static long _vq_quantlist__16c1_s_p9_0[] = {
  124898. 6,
  124899. 5,
  124900. 7,
  124901. 4,
  124902. 8,
  124903. 3,
  124904. 9,
  124905. 2,
  124906. 10,
  124907. 1,
  124908. 11,
  124909. 0,
  124910. 12,
  124911. };
  124912. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124913. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124914. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124915. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124916. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124917. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124918. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124919. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124920. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124921. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124922. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124923. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124924. };
  124925. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124926. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124927. 787.5, 1102.5, 1417.5, 1732.5,
  124928. };
  124929. static long _vq_quantmap__16c1_s_p9_0[] = {
  124930. 11, 9, 7, 5, 3, 1, 0, 2,
  124931. 4, 6, 8, 10, 12,
  124932. };
  124933. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124934. _vq_quantthresh__16c1_s_p9_0,
  124935. _vq_quantmap__16c1_s_p9_0,
  124936. 13,
  124937. 13
  124938. };
  124939. static static_codebook _16c1_s_p9_0 = {
  124940. 2, 169,
  124941. _vq_lengthlist__16c1_s_p9_0,
  124942. 1, -513964032, 1628680192, 4, 0,
  124943. _vq_quantlist__16c1_s_p9_0,
  124944. NULL,
  124945. &_vq_auxt__16c1_s_p9_0,
  124946. NULL,
  124947. 0
  124948. };
  124949. static long _vq_quantlist__16c1_s_p9_1[] = {
  124950. 7,
  124951. 6,
  124952. 8,
  124953. 5,
  124954. 9,
  124955. 4,
  124956. 10,
  124957. 3,
  124958. 11,
  124959. 2,
  124960. 12,
  124961. 1,
  124962. 13,
  124963. 0,
  124964. 14,
  124965. };
  124966. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124967. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124968. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124969. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124970. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124971. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124972. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124973. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124974. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124975. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124976. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124977. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124978. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124979. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124980. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124981. 13,
  124982. };
  124983. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124984. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124985. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124986. };
  124987. static long _vq_quantmap__16c1_s_p9_1[] = {
  124988. 13, 11, 9, 7, 5, 3, 1, 0,
  124989. 2, 4, 6, 8, 10, 12, 14,
  124990. };
  124991. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124992. _vq_quantthresh__16c1_s_p9_1,
  124993. _vq_quantmap__16c1_s_p9_1,
  124994. 15,
  124995. 15
  124996. };
  124997. static static_codebook _16c1_s_p9_1 = {
  124998. 2, 225,
  124999. _vq_lengthlist__16c1_s_p9_1,
  125000. 1, -520986624, 1620377600, 4, 0,
  125001. _vq_quantlist__16c1_s_p9_1,
  125002. NULL,
  125003. &_vq_auxt__16c1_s_p9_1,
  125004. NULL,
  125005. 0
  125006. };
  125007. static long _vq_quantlist__16c1_s_p9_2[] = {
  125008. 10,
  125009. 9,
  125010. 11,
  125011. 8,
  125012. 12,
  125013. 7,
  125014. 13,
  125015. 6,
  125016. 14,
  125017. 5,
  125018. 15,
  125019. 4,
  125020. 16,
  125021. 3,
  125022. 17,
  125023. 2,
  125024. 18,
  125025. 1,
  125026. 19,
  125027. 0,
  125028. 20,
  125029. };
  125030. static long _vq_lengthlist__16c1_s_p9_2[] = {
  125031. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  125032. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  125033. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  125034. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  125035. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  125036. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  125037. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  125038. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  125039. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  125040. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  125041. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  125042. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  125043. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  125044. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  125045. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  125046. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  125047. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  125048. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  125049. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  125050. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  125051. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  125052. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  125053. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  125054. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  125055. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  125056. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  125057. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  125058. 11,11,11,11,12,11,11,12,11,
  125059. };
  125060. static float _vq_quantthresh__16c1_s_p9_2[] = {
  125061. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125062. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125063. 6.5, 7.5, 8.5, 9.5,
  125064. };
  125065. static long _vq_quantmap__16c1_s_p9_2[] = {
  125066. 19, 17, 15, 13, 11, 9, 7, 5,
  125067. 3, 1, 0, 2, 4, 6, 8, 10,
  125068. 12, 14, 16, 18, 20,
  125069. };
  125070. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  125071. _vq_quantthresh__16c1_s_p9_2,
  125072. _vq_quantmap__16c1_s_p9_2,
  125073. 21,
  125074. 21
  125075. };
  125076. static static_codebook _16c1_s_p9_2 = {
  125077. 2, 441,
  125078. _vq_lengthlist__16c1_s_p9_2,
  125079. 1, -529268736, 1611661312, 5, 0,
  125080. _vq_quantlist__16c1_s_p9_2,
  125081. NULL,
  125082. &_vq_auxt__16c1_s_p9_2,
  125083. NULL,
  125084. 0
  125085. };
  125086. static long _huff_lengthlist__16c1_s_short[] = {
  125087. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  125088. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  125089. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  125090. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  125091. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  125092. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  125093. 9, 9,10,13,
  125094. };
  125095. static static_codebook _huff_book__16c1_s_short = {
  125096. 2, 100,
  125097. _huff_lengthlist__16c1_s_short,
  125098. 0, 0, 0, 0, 0,
  125099. NULL,
  125100. NULL,
  125101. NULL,
  125102. NULL,
  125103. 0
  125104. };
  125105. static long _huff_lengthlist__16c2_s_long[] = {
  125106. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  125107. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  125108. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  125109. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  125110. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  125111. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  125112. 14,14,16,18,
  125113. };
  125114. static static_codebook _huff_book__16c2_s_long = {
  125115. 2, 100,
  125116. _huff_lengthlist__16c2_s_long,
  125117. 0, 0, 0, 0, 0,
  125118. NULL,
  125119. NULL,
  125120. NULL,
  125121. NULL,
  125122. 0
  125123. };
  125124. static long _vq_quantlist__16c2_s_p1_0[] = {
  125125. 1,
  125126. 0,
  125127. 2,
  125128. };
  125129. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125130. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125131. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125135. 0,
  125136. };
  125137. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125138. -0.5, 0.5,
  125139. };
  125140. static long _vq_quantmap__16c2_s_p1_0[] = {
  125141. 1, 0, 2,
  125142. };
  125143. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125144. _vq_quantthresh__16c2_s_p1_0,
  125145. _vq_quantmap__16c2_s_p1_0,
  125146. 3,
  125147. 3
  125148. };
  125149. static static_codebook _16c2_s_p1_0 = {
  125150. 4, 81,
  125151. _vq_lengthlist__16c2_s_p1_0,
  125152. 1, -535822336, 1611661312, 2, 0,
  125153. _vq_quantlist__16c2_s_p1_0,
  125154. NULL,
  125155. &_vq_auxt__16c2_s_p1_0,
  125156. NULL,
  125157. 0
  125158. };
  125159. static long _vq_quantlist__16c2_s_p2_0[] = {
  125160. 2,
  125161. 1,
  125162. 3,
  125163. 0,
  125164. 4,
  125165. };
  125166. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125167. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125168. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125169. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125170. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125171. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125172. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125173. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125174. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  125180. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125181. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125182. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125188. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125189. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125190. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125195. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125196. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125197. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125198. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  125203. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125204. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125205. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125206. 13,
  125207. };
  125208. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125209. -1.5, -0.5, 0.5, 1.5,
  125210. };
  125211. static long _vq_quantmap__16c2_s_p2_0[] = {
  125212. 3, 1, 0, 2, 4,
  125213. };
  125214. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125215. _vq_quantthresh__16c2_s_p2_0,
  125216. _vq_quantmap__16c2_s_p2_0,
  125217. 5,
  125218. 5
  125219. };
  125220. static static_codebook _16c2_s_p2_0 = {
  125221. 4, 625,
  125222. _vq_lengthlist__16c2_s_p2_0,
  125223. 1, -533725184, 1611661312, 3, 0,
  125224. _vq_quantlist__16c2_s_p2_0,
  125225. NULL,
  125226. &_vq_auxt__16c2_s_p2_0,
  125227. NULL,
  125228. 0
  125229. };
  125230. static long _vq_quantlist__16c2_s_p3_0[] = {
  125231. 4,
  125232. 3,
  125233. 5,
  125234. 2,
  125235. 6,
  125236. 1,
  125237. 7,
  125238. 0,
  125239. 8,
  125240. };
  125241. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125242. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125243. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125244. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125245. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125247. 0,
  125248. };
  125249. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125250. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125251. };
  125252. static long _vq_quantmap__16c2_s_p3_0[] = {
  125253. 7, 5, 3, 1, 0, 2, 4, 6,
  125254. 8,
  125255. };
  125256. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125257. _vq_quantthresh__16c2_s_p3_0,
  125258. _vq_quantmap__16c2_s_p3_0,
  125259. 9,
  125260. 9
  125261. };
  125262. static static_codebook _16c2_s_p3_0 = {
  125263. 2, 81,
  125264. _vq_lengthlist__16c2_s_p3_0,
  125265. 1, -531628032, 1611661312, 4, 0,
  125266. _vq_quantlist__16c2_s_p3_0,
  125267. NULL,
  125268. &_vq_auxt__16c2_s_p3_0,
  125269. NULL,
  125270. 0
  125271. };
  125272. static long _vq_quantlist__16c2_s_p4_0[] = {
  125273. 8,
  125274. 7,
  125275. 9,
  125276. 6,
  125277. 10,
  125278. 5,
  125279. 11,
  125280. 4,
  125281. 12,
  125282. 3,
  125283. 13,
  125284. 2,
  125285. 14,
  125286. 1,
  125287. 15,
  125288. 0,
  125289. 16,
  125290. };
  125291. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125292. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125293. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125294. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125295. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125296. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125297. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125298. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125299. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125300. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125301. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125310. 0,
  125311. };
  125312. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125313. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125314. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125315. };
  125316. static long _vq_quantmap__16c2_s_p4_0[] = {
  125317. 15, 13, 11, 9, 7, 5, 3, 1,
  125318. 0, 2, 4, 6, 8, 10, 12, 14,
  125319. 16,
  125320. };
  125321. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125322. _vq_quantthresh__16c2_s_p4_0,
  125323. _vq_quantmap__16c2_s_p4_0,
  125324. 17,
  125325. 17
  125326. };
  125327. static static_codebook _16c2_s_p4_0 = {
  125328. 2, 289,
  125329. _vq_lengthlist__16c2_s_p4_0,
  125330. 1, -529530880, 1611661312, 5, 0,
  125331. _vq_quantlist__16c2_s_p4_0,
  125332. NULL,
  125333. &_vq_auxt__16c2_s_p4_0,
  125334. NULL,
  125335. 0
  125336. };
  125337. static long _vq_quantlist__16c2_s_p5_0[] = {
  125338. 1,
  125339. 0,
  125340. 2,
  125341. };
  125342. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125343. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125344. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125345. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125346. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125347. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125348. 12,
  125349. };
  125350. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125351. -5.5, 5.5,
  125352. };
  125353. static long _vq_quantmap__16c2_s_p5_0[] = {
  125354. 1, 0, 2,
  125355. };
  125356. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125357. _vq_quantthresh__16c2_s_p5_0,
  125358. _vq_quantmap__16c2_s_p5_0,
  125359. 3,
  125360. 3
  125361. };
  125362. static static_codebook _16c2_s_p5_0 = {
  125363. 4, 81,
  125364. _vq_lengthlist__16c2_s_p5_0,
  125365. 1, -529137664, 1618345984, 2, 0,
  125366. _vq_quantlist__16c2_s_p5_0,
  125367. NULL,
  125368. &_vq_auxt__16c2_s_p5_0,
  125369. NULL,
  125370. 0
  125371. };
  125372. static long _vq_quantlist__16c2_s_p5_1[] = {
  125373. 5,
  125374. 4,
  125375. 6,
  125376. 3,
  125377. 7,
  125378. 2,
  125379. 8,
  125380. 1,
  125381. 9,
  125382. 0,
  125383. 10,
  125384. };
  125385. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125386. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125387. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125388. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125389. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125390. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125391. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125392. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125393. 11,11,11, 7, 7, 8, 8, 8, 8,
  125394. };
  125395. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125396. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125397. 3.5, 4.5,
  125398. };
  125399. static long _vq_quantmap__16c2_s_p5_1[] = {
  125400. 9, 7, 5, 3, 1, 0, 2, 4,
  125401. 6, 8, 10,
  125402. };
  125403. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125404. _vq_quantthresh__16c2_s_p5_1,
  125405. _vq_quantmap__16c2_s_p5_1,
  125406. 11,
  125407. 11
  125408. };
  125409. static static_codebook _16c2_s_p5_1 = {
  125410. 2, 121,
  125411. _vq_lengthlist__16c2_s_p5_1,
  125412. 1, -531365888, 1611661312, 4, 0,
  125413. _vq_quantlist__16c2_s_p5_1,
  125414. NULL,
  125415. &_vq_auxt__16c2_s_p5_1,
  125416. NULL,
  125417. 0
  125418. };
  125419. static long _vq_quantlist__16c2_s_p6_0[] = {
  125420. 6,
  125421. 5,
  125422. 7,
  125423. 4,
  125424. 8,
  125425. 3,
  125426. 9,
  125427. 2,
  125428. 10,
  125429. 1,
  125430. 11,
  125431. 0,
  125432. 12,
  125433. };
  125434. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125435. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125436. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125437. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125438. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125439. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125440. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. };
  125447. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125448. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125449. 12.5, 17.5, 22.5, 27.5,
  125450. };
  125451. static long _vq_quantmap__16c2_s_p6_0[] = {
  125452. 11, 9, 7, 5, 3, 1, 0, 2,
  125453. 4, 6, 8, 10, 12,
  125454. };
  125455. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125456. _vq_quantthresh__16c2_s_p6_0,
  125457. _vq_quantmap__16c2_s_p6_0,
  125458. 13,
  125459. 13
  125460. };
  125461. static static_codebook _16c2_s_p6_0 = {
  125462. 2, 169,
  125463. _vq_lengthlist__16c2_s_p6_0,
  125464. 1, -526516224, 1616117760, 4, 0,
  125465. _vq_quantlist__16c2_s_p6_0,
  125466. NULL,
  125467. &_vq_auxt__16c2_s_p6_0,
  125468. NULL,
  125469. 0
  125470. };
  125471. static long _vq_quantlist__16c2_s_p6_1[] = {
  125472. 2,
  125473. 1,
  125474. 3,
  125475. 0,
  125476. 4,
  125477. };
  125478. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125479. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125480. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125481. };
  125482. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125483. -1.5, -0.5, 0.5, 1.5,
  125484. };
  125485. static long _vq_quantmap__16c2_s_p6_1[] = {
  125486. 3, 1, 0, 2, 4,
  125487. };
  125488. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125489. _vq_quantthresh__16c2_s_p6_1,
  125490. _vq_quantmap__16c2_s_p6_1,
  125491. 5,
  125492. 5
  125493. };
  125494. static static_codebook _16c2_s_p6_1 = {
  125495. 2, 25,
  125496. _vq_lengthlist__16c2_s_p6_1,
  125497. 1, -533725184, 1611661312, 3, 0,
  125498. _vq_quantlist__16c2_s_p6_1,
  125499. NULL,
  125500. &_vq_auxt__16c2_s_p6_1,
  125501. NULL,
  125502. 0
  125503. };
  125504. static long _vq_quantlist__16c2_s_p7_0[] = {
  125505. 6,
  125506. 5,
  125507. 7,
  125508. 4,
  125509. 8,
  125510. 3,
  125511. 9,
  125512. 2,
  125513. 10,
  125514. 1,
  125515. 11,
  125516. 0,
  125517. 12,
  125518. };
  125519. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125520. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125521. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125522. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125523. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125524. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125525. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125526. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125527. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125528. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125529. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125530. 18,13,14,13,13,14,13,15,14,
  125531. };
  125532. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125533. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125534. 27.5, 38.5, 49.5, 60.5,
  125535. };
  125536. static long _vq_quantmap__16c2_s_p7_0[] = {
  125537. 11, 9, 7, 5, 3, 1, 0, 2,
  125538. 4, 6, 8, 10, 12,
  125539. };
  125540. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125541. _vq_quantthresh__16c2_s_p7_0,
  125542. _vq_quantmap__16c2_s_p7_0,
  125543. 13,
  125544. 13
  125545. };
  125546. static static_codebook _16c2_s_p7_0 = {
  125547. 2, 169,
  125548. _vq_lengthlist__16c2_s_p7_0,
  125549. 1, -523206656, 1618345984, 4, 0,
  125550. _vq_quantlist__16c2_s_p7_0,
  125551. NULL,
  125552. &_vq_auxt__16c2_s_p7_0,
  125553. NULL,
  125554. 0
  125555. };
  125556. static long _vq_quantlist__16c2_s_p7_1[] = {
  125557. 5,
  125558. 4,
  125559. 6,
  125560. 3,
  125561. 7,
  125562. 2,
  125563. 8,
  125564. 1,
  125565. 9,
  125566. 0,
  125567. 10,
  125568. };
  125569. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125570. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125571. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125572. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125573. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125574. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125575. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125576. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125577. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125578. };
  125579. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125580. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125581. 3.5, 4.5,
  125582. };
  125583. static long _vq_quantmap__16c2_s_p7_1[] = {
  125584. 9, 7, 5, 3, 1, 0, 2, 4,
  125585. 6, 8, 10,
  125586. };
  125587. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125588. _vq_quantthresh__16c2_s_p7_1,
  125589. _vq_quantmap__16c2_s_p7_1,
  125590. 11,
  125591. 11
  125592. };
  125593. static static_codebook _16c2_s_p7_1 = {
  125594. 2, 121,
  125595. _vq_lengthlist__16c2_s_p7_1,
  125596. 1, -531365888, 1611661312, 4, 0,
  125597. _vq_quantlist__16c2_s_p7_1,
  125598. NULL,
  125599. &_vq_auxt__16c2_s_p7_1,
  125600. NULL,
  125601. 0
  125602. };
  125603. static long _vq_quantlist__16c2_s_p8_0[] = {
  125604. 7,
  125605. 6,
  125606. 8,
  125607. 5,
  125608. 9,
  125609. 4,
  125610. 10,
  125611. 3,
  125612. 11,
  125613. 2,
  125614. 12,
  125615. 1,
  125616. 13,
  125617. 0,
  125618. 14,
  125619. };
  125620. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125621. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125622. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125623. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125624. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125625. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125626. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125627. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125628. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125629. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125630. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125631. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125632. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125633. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125634. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125635. 13,
  125636. };
  125637. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125638. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125639. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125640. };
  125641. static long _vq_quantmap__16c2_s_p8_0[] = {
  125642. 13, 11, 9, 7, 5, 3, 1, 0,
  125643. 2, 4, 6, 8, 10, 12, 14,
  125644. };
  125645. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125646. _vq_quantthresh__16c2_s_p8_0,
  125647. _vq_quantmap__16c2_s_p8_0,
  125648. 15,
  125649. 15
  125650. };
  125651. static static_codebook _16c2_s_p8_0 = {
  125652. 2, 225,
  125653. _vq_lengthlist__16c2_s_p8_0,
  125654. 1, -520986624, 1620377600, 4, 0,
  125655. _vq_quantlist__16c2_s_p8_0,
  125656. NULL,
  125657. &_vq_auxt__16c2_s_p8_0,
  125658. NULL,
  125659. 0
  125660. };
  125661. static long _vq_quantlist__16c2_s_p8_1[] = {
  125662. 10,
  125663. 9,
  125664. 11,
  125665. 8,
  125666. 12,
  125667. 7,
  125668. 13,
  125669. 6,
  125670. 14,
  125671. 5,
  125672. 15,
  125673. 4,
  125674. 16,
  125675. 3,
  125676. 17,
  125677. 2,
  125678. 18,
  125679. 1,
  125680. 19,
  125681. 0,
  125682. 20,
  125683. };
  125684. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125685. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125686. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125687. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125688. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125689. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125690. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125691. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125692. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125693. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125694. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125695. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125696. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125697. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125698. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125699. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125700. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125701. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125702. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125703. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125704. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125705. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125706. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125707. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125708. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125709. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125710. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125711. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125712. 10,11,10,10,10,10,10,10,10,
  125713. };
  125714. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125715. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125716. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125717. 6.5, 7.5, 8.5, 9.5,
  125718. };
  125719. static long _vq_quantmap__16c2_s_p8_1[] = {
  125720. 19, 17, 15, 13, 11, 9, 7, 5,
  125721. 3, 1, 0, 2, 4, 6, 8, 10,
  125722. 12, 14, 16, 18, 20,
  125723. };
  125724. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125725. _vq_quantthresh__16c2_s_p8_1,
  125726. _vq_quantmap__16c2_s_p8_1,
  125727. 21,
  125728. 21
  125729. };
  125730. static static_codebook _16c2_s_p8_1 = {
  125731. 2, 441,
  125732. _vq_lengthlist__16c2_s_p8_1,
  125733. 1, -529268736, 1611661312, 5, 0,
  125734. _vq_quantlist__16c2_s_p8_1,
  125735. NULL,
  125736. &_vq_auxt__16c2_s_p8_1,
  125737. NULL,
  125738. 0
  125739. };
  125740. static long _vq_quantlist__16c2_s_p9_0[] = {
  125741. 6,
  125742. 5,
  125743. 7,
  125744. 4,
  125745. 8,
  125746. 3,
  125747. 9,
  125748. 2,
  125749. 10,
  125750. 1,
  125751. 11,
  125752. 0,
  125753. 12,
  125754. };
  125755. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125756. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125757. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125758. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125759. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125760. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125761. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125762. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125763. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125764. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125765. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125766. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125767. };
  125768. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125769. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125770. 2327.5, 3258.5, 4189.5, 5120.5,
  125771. };
  125772. static long _vq_quantmap__16c2_s_p9_0[] = {
  125773. 11, 9, 7, 5, 3, 1, 0, 2,
  125774. 4, 6, 8, 10, 12,
  125775. };
  125776. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125777. _vq_quantthresh__16c2_s_p9_0,
  125778. _vq_quantmap__16c2_s_p9_0,
  125779. 13,
  125780. 13
  125781. };
  125782. static static_codebook _16c2_s_p9_0 = {
  125783. 2, 169,
  125784. _vq_lengthlist__16c2_s_p9_0,
  125785. 1, -510275072, 1631393792, 4, 0,
  125786. _vq_quantlist__16c2_s_p9_0,
  125787. NULL,
  125788. &_vq_auxt__16c2_s_p9_0,
  125789. NULL,
  125790. 0
  125791. };
  125792. static long _vq_quantlist__16c2_s_p9_1[] = {
  125793. 8,
  125794. 7,
  125795. 9,
  125796. 6,
  125797. 10,
  125798. 5,
  125799. 11,
  125800. 4,
  125801. 12,
  125802. 3,
  125803. 13,
  125804. 2,
  125805. 14,
  125806. 1,
  125807. 15,
  125808. 0,
  125809. 16,
  125810. };
  125811. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125812. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125813. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125814. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125815. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125816. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125817. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125818. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125819. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125820. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125821. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125822. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125823. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125824. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125825. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125826. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125827. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125828. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125829. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125830. 10,
  125831. };
  125832. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125833. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125834. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125835. };
  125836. static long _vq_quantmap__16c2_s_p9_1[] = {
  125837. 15, 13, 11, 9, 7, 5, 3, 1,
  125838. 0, 2, 4, 6, 8, 10, 12, 14,
  125839. 16,
  125840. };
  125841. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125842. _vq_quantthresh__16c2_s_p9_1,
  125843. _vq_quantmap__16c2_s_p9_1,
  125844. 17,
  125845. 17
  125846. };
  125847. static static_codebook _16c2_s_p9_1 = {
  125848. 2, 289,
  125849. _vq_lengthlist__16c2_s_p9_1,
  125850. 1, -518488064, 1622704128, 5, 0,
  125851. _vq_quantlist__16c2_s_p9_1,
  125852. NULL,
  125853. &_vq_auxt__16c2_s_p9_1,
  125854. NULL,
  125855. 0
  125856. };
  125857. static long _vq_quantlist__16c2_s_p9_2[] = {
  125858. 13,
  125859. 12,
  125860. 14,
  125861. 11,
  125862. 15,
  125863. 10,
  125864. 16,
  125865. 9,
  125866. 17,
  125867. 8,
  125868. 18,
  125869. 7,
  125870. 19,
  125871. 6,
  125872. 20,
  125873. 5,
  125874. 21,
  125875. 4,
  125876. 22,
  125877. 3,
  125878. 23,
  125879. 2,
  125880. 24,
  125881. 1,
  125882. 25,
  125883. 0,
  125884. 26,
  125885. };
  125886. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125887. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125888. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125889. };
  125890. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125891. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125892. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125893. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125894. 11.5, 12.5,
  125895. };
  125896. static long _vq_quantmap__16c2_s_p9_2[] = {
  125897. 25, 23, 21, 19, 17, 15, 13, 11,
  125898. 9, 7, 5, 3, 1, 0, 2, 4,
  125899. 6, 8, 10, 12, 14, 16, 18, 20,
  125900. 22, 24, 26,
  125901. };
  125902. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125903. _vq_quantthresh__16c2_s_p9_2,
  125904. _vq_quantmap__16c2_s_p9_2,
  125905. 27,
  125906. 27
  125907. };
  125908. static static_codebook _16c2_s_p9_2 = {
  125909. 1, 27,
  125910. _vq_lengthlist__16c2_s_p9_2,
  125911. 1, -528875520, 1611661312, 5, 0,
  125912. _vq_quantlist__16c2_s_p9_2,
  125913. NULL,
  125914. &_vq_auxt__16c2_s_p9_2,
  125915. NULL,
  125916. 0
  125917. };
  125918. static long _huff_lengthlist__16c2_s_short[] = {
  125919. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125920. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125921. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125922. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125923. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125924. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125925. 15,12,14,14,
  125926. };
  125927. static static_codebook _huff_book__16c2_s_short = {
  125928. 2, 100,
  125929. _huff_lengthlist__16c2_s_short,
  125930. 0, 0, 0, 0, 0,
  125931. NULL,
  125932. NULL,
  125933. NULL,
  125934. NULL,
  125935. 0
  125936. };
  125937. static long _vq_quantlist__8c0_s_p1_0[] = {
  125938. 1,
  125939. 0,
  125940. 2,
  125941. };
  125942. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125943. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125944. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125949. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125954. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  125989. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125994. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125999. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126035. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  126040. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  126045. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126353. 0,
  126354. };
  126355. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126356. -0.5, 0.5,
  126357. };
  126358. static long _vq_quantmap__8c0_s_p1_0[] = {
  126359. 1, 0, 2,
  126360. };
  126361. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126362. _vq_quantthresh__8c0_s_p1_0,
  126363. _vq_quantmap__8c0_s_p1_0,
  126364. 3,
  126365. 3
  126366. };
  126367. static static_codebook _8c0_s_p1_0 = {
  126368. 8, 6561,
  126369. _vq_lengthlist__8c0_s_p1_0,
  126370. 1, -535822336, 1611661312, 2, 0,
  126371. _vq_quantlist__8c0_s_p1_0,
  126372. NULL,
  126373. &_vq_auxt__8c0_s_p1_0,
  126374. NULL,
  126375. 0
  126376. };
  126377. static long _vq_quantlist__8c0_s_p2_0[] = {
  126378. 2,
  126379. 1,
  126380. 3,
  126381. 0,
  126382. 4,
  126383. };
  126384. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126424. 0,
  126425. };
  126426. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126427. -1.5, -0.5, 0.5, 1.5,
  126428. };
  126429. static long _vq_quantmap__8c0_s_p2_0[] = {
  126430. 3, 1, 0, 2, 4,
  126431. };
  126432. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126433. _vq_quantthresh__8c0_s_p2_0,
  126434. _vq_quantmap__8c0_s_p2_0,
  126435. 5,
  126436. 5
  126437. };
  126438. static static_codebook _8c0_s_p2_0 = {
  126439. 4, 625,
  126440. _vq_lengthlist__8c0_s_p2_0,
  126441. 1, -533725184, 1611661312, 3, 0,
  126442. _vq_quantlist__8c0_s_p2_0,
  126443. NULL,
  126444. &_vq_auxt__8c0_s_p2_0,
  126445. NULL,
  126446. 0
  126447. };
  126448. static long _vq_quantlist__8c0_s_p3_0[] = {
  126449. 2,
  126450. 1,
  126451. 3,
  126452. 0,
  126453. 4,
  126454. };
  126455. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126456. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0,
  126496. };
  126497. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126498. -1.5, -0.5, 0.5, 1.5,
  126499. };
  126500. static long _vq_quantmap__8c0_s_p3_0[] = {
  126501. 3, 1, 0, 2, 4,
  126502. };
  126503. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126504. _vq_quantthresh__8c0_s_p3_0,
  126505. _vq_quantmap__8c0_s_p3_0,
  126506. 5,
  126507. 5
  126508. };
  126509. static static_codebook _8c0_s_p3_0 = {
  126510. 4, 625,
  126511. _vq_lengthlist__8c0_s_p3_0,
  126512. 1, -533725184, 1611661312, 3, 0,
  126513. _vq_quantlist__8c0_s_p3_0,
  126514. NULL,
  126515. &_vq_auxt__8c0_s_p3_0,
  126516. NULL,
  126517. 0
  126518. };
  126519. static long _vq_quantlist__8c0_s_p4_0[] = {
  126520. 4,
  126521. 3,
  126522. 5,
  126523. 2,
  126524. 6,
  126525. 1,
  126526. 7,
  126527. 0,
  126528. 8,
  126529. };
  126530. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126531. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126532. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126533. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126534. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126535. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0,
  126537. };
  126538. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126539. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126540. };
  126541. static long _vq_quantmap__8c0_s_p4_0[] = {
  126542. 7, 5, 3, 1, 0, 2, 4, 6,
  126543. 8,
  126544. };
  126545. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126546. _vq_quantthresh__8c0_s_p4_0,
  126547. _vq_quantmap__8c0_s_p4_0,
  126548. 9,
  126549. 9
  126550. };
  126551. static static_codebook _8c0_s_p4_0 = {
  126552. 2, 81,
  126553. _vq_lengthlist__8c0_s_p4_0,
  126554. 1, -531628032, 1611661312, 4, 0,
  126555. _vq_quantlist__8c0_s_p4_0,
  126556. NULL,
  126557. &_vq_auxt__8c0_s_p4_0,
  126558. NULL,
  126559. 0
  126560. };
  126561. static long _vq_quantlist__8c0_s_p5_0[] = {
  126562. 4,
  126563. 3,
  126564. 5,
  126565. 2,
  126566. 6,
  126567. 1,
  126568. 7,
  126569. 0,
  126570. 8,
  126571. };
  126572. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126573. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126574. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126575. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126576. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126577. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126578. 10,
  126579. };
  126580. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126581. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126582. };
  126583. static long _vq_quantmap__8c0_s_p5_0[] = {
  126584. 7, 5, 3, 1, 0, 2, 4, 6,
  126585. 8,
  126586. };
  126587. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126588. _vq_quantthresh__8c0_s_p5_0,
  126589. _vq_quantmap__8c0_s_p5_0,
  126590. 9,
  126591. 9
  126592. };
  126593. static static_codebook _8c0_s_p5_0 = {
  126594. 2, 81,
  126595. _vq_lengthlist__8c0_s_p5_0,
  126596. 1, -531628032, 1611661312, 4, 0,
  126597. _vq_quantlist__8c0_s_p5_0,
  126598. NULL,
  126599. &_vq_auxt__8c0_s_p5_0,
  126600. NULL,
  126601. 0
  126602. };
  126603. static long _vq_quantlist__8c0_s_p6_0[] = {
  126604. 8,
  126605. 7,
  126606. 9,
  126607. 6,
  126608. 10,
  126609. 5,
  126610. 11,
  126611. 4,
  126612. 12,
  126613. 3,
  126614. 13,
  126615. 2,
  126616. 14,
  126617. 1,
  126618. 15,
  126619. 0,
  126620. 16,
  126621. };
  126622. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126623. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126624. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126625. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126626. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126627. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126628. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126629. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126630. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126631. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126632. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126633. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126634. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126635. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126636. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126637. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126638. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126639. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126641. 14,
  126642. };
  126643. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126644. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126645. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126646. };
  126647. static long _vq_quantmap__8c0_s_p6_0[] = {
  126648. 15, 13, 11, 9, 7, 5, 3, 1,
  126649. 0, 2, 4, 6, 8, 10, 12, 14,
  126650. 16,
  126651. };
  126652. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126653. _vq_quantthresh__8c0_s_p6_0,
  126654. _vq_quantmap__8c0_s_p6_0,
  126655. 17,
  126656. 17
  126657. };
  126658. static static_codebook _8c0_s_p6_0 = {
  126659. 2, 289,
  126660. _vq_lengthlist__8c0_s_p6_0,
  126661. 1, -529530880, 1611661312, 5, 0,
  126662. _vq_quantlist__8c0_s_p6_0,
  126663. NULL,
  126664. &_vq_auxt__8c0_s_p6_0,
  126665. NULL,
  126666. 0
  126667. };
  126668. static long _vq_quantlist__8c0_s_p7_0[] = {
  126669. 1,
  126670. 0,
  126671. 2,
  126672. };
  126673. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126674. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126675. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126676. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126677. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126678. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126679. 10,
  126680. };
  126681. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126682. -5.5, 5.5,
  126683. };
  126684. static long _vq_quantmap__8c0_s_p7_0[] = {
  126685. 1, 0, 2,
  126686. };
  126687. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126688. _vq_quantthresh__8c0_s_p7_0,
  126689. _vq_quantmap__8c0_s_p7_0,
  126690. 3,
  126691. 3
  126692. };
  126693. static static_codebook _8c0_s_p7_0 = {
  126694. 4, 81,
  126695. _vq_lengthlist__8c0_s_p7_0,
  126696. 1, -529137664, 1618345984, 2, 0,
  126697. _vq_quantlist__8c0_s_p7_0,
  126698. NULL,
  126699. &_vq_auxt__8c0_s_p7_0,
  126700. NULL,
  126701. 0
  126702. };
  126703. static long _vq_quantlist__8c0_s_p7_1[] = {
  126704. 5,
  126705. 4,
  126706. 6,
  126707. 3,
  126708. 7,
  126709. 2,
  126710. 8,
  126711. 1,
  126712. 9,
  126713. 0,
  126714. 10,
  126715. };
  126716. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126717. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126718. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126719. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126720. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126721. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126722. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126723. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126724. 10,10,10, 9, 9, 9,10,10,10,
  126725. };
  126726. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126727. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126728. 3.5, 4.5,
  126729. };
  126730. static long _vq_quantmap__8c0_s_p7_1[] = {
  126731. 9, 7, 5, 3, 1, 0, 2, 4,
  126732. 6, 8, 10,
  126733. };
  126734. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126735. _vq_quantthresh__8c0_s_p7_1,
  126736. _vq_quantmap__8c0_s_p7_1,
  126737. 11,
  126738. 11
  126739. };
  126740. static static_codebook _8c0_s_p7_1 = {
  126741. 2, 121,
  126742. _vq_lengthlist__8c0_s_p7_1,
  126743. 1, -531365888, 1611661312, 4, 0,
  126744. _vq_quantlist__8c0_s_p7_1,
  126745. NULL,
  126746. &_vq_auxt__8c0_s_p7_1,
  126747. NULL,
  126748. 0
  126749. };
  126750. static long _vq_quantlist__8c0_s_p8_0[] = {
  126751. 6,
  126752. 5,
  126753. 7,
  126754. 4,
  126755. 8,
  126756. 3,
  126757. 9,
  126758. 2,
  126759. 10,
  126760. 1,
  126761. 11,
  126762. 0,
  126763. 12,
  126764. };
  126765. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126766. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126767. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126768. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126769. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126770. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126771. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126772. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126773. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126774. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126775. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126776. 0, 0,13,13,11,13,13,11,12,
  126777. };
  126778. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126779. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126780. 12.5, 17.5, 22.5, 27.5,
  126781. };
  126782. static long _vq_quantmap__8c0_s_p8_0[] = {
  126783. 11, 9, 7, 5, 3, 1, 0, 2,
  126784. 4, 6, 8, 10, 12,
  126785. };
  126786. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126787. _vq_quantthresh__8c0_s_p8_0,
  126788. _vq_quantmap__8c0_s_p8_0,
  126789. 13,
  126790. 13
  126791. };
  126792. static static_codebook _8c0_s_p8_0 = {
  126793. 2, 169,
  126794. _vq_lengthlist__8c0_s_p8_0,
  126795. 1, -526516224, 1616117760, 4, 0,
  126796. _vq_quantlist__8c0_s_p8_0,
  126797. NULL,
  126798. &_vq_auxt__8c0_s_p8_0,
  126799. NULL,
  126800. 0
  126801. };
  126802. static long _vq_quantlist__8c0_s_p8_1[] = {
  126803. 2,
  126804. 1,
  126805. 3,
  126806. 0,
  126807. 4,
  126808. };
  126809. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126810. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126811. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126812. };
  126813. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126814. -1.5, -0.5, 0.5, 1.5,
  126815. };
  126816. static long _vq_quantmap__8c0_s_p8_1[] = {
  126817. 3, 1, 0, 2, 4,
  126818. };
  126819. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126820. _vq_quantthresh__8c0_s_p8_1,
  126821. _vq_quantmap__8c0_s_p8_1,
  126822. 5,
  126823. 5
  126824. };
  126825. static static_codebook _8c0_s_p8_1 = {
  126826. 2, 25,
  126827. _vq_lengthlist__8c0_s_p8_1,
  126828. 1, -533725184, 1611661312, 3, 0,
  126829. _vq_quantlist__8c0_s_p8_1,
  126830. NULL,
  126831. &_vq_auxt__8c0_s_p8_1,
  126832. NULL,
  126833. 0
  126834. };
  126835. static long _vq_quantlist__8c0_s_p9_0[] = {
  126836. 1,
  126837. 0,
  126838. 2,
  126839. };
  126840. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126841. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126842. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126843. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126844. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126845. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126846. 7,
  126847. };
  126848. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126849. -157.5, 157.5,
  126850. };
  126851. static long _vq_quantmap__8c0_s_p9_0[] = {
  126852. 1, 0, 2,
  126853. };
  126854. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126855. _vq_quantthresh__8c0_s_p9_0,
  126856. _vq_quantmap__8c0_s_p9_0,
  126857. 3,
  126858. 3
  126859. };
  126860. static static_codebook _8c0_s_p9_0 = {
  126861. 4, 81,
  126862. _vq_lengthlist__8c0_s_p9_0,
  126863. 1, -518803456, 1628680192, 2, 0,
  126864. _vq_quantlist__8c0_s_p9_0,
  126865. NULL,
  126866. &_vq_auxt__8c0_s_p9_0,
  126867. NULL,
  126868. 0
  126869. };
  126870. static long _vq_quantlist__8c0_s_p9_1[] = {
  126871. 7,
  126872. 6,
  126873. 8,
  126874. 5,
  126875. 9,
  126876. 4,
  126877. 10,
  126878. 3,
  126879. 11,
  126880. 2,
  126881. 12,
  126882. 1,
  126883. 13,
  126884. 0,
  126885. 14,
  126886. };
  126887. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126888. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126889. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126890. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126891. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126892. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126893. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126896. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126897. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126898. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126899. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126900. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126901. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126902. 11,
  126903. };
  126904. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126905. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126906. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126907. };
  126908. static long _vq_quantmap__8c0_s_p9_1[] = {
  126909. 13, 11, 9, 7, 5, 3, 1, 0,
  126910. 2, 4, 6, 8, 10, 12, 14,
  126911. };
  126912. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126913. _vq_quantthresh__8c0_s_p9_1,
  126914. _vq_quantmap__8c0_s_p9_1,
  126915. 15,
  126916. 15
  126917. };
  126918. static static_codebook _8c0_s_p9_1 = {
  126919. 2, 225,
  126920. _vq_lengthlist__8c0_s_p9_1,
  126921. 1, -520986624, 1620377600, 4, 0,
  126922. _vq_quantlist__8c0_s_p9_1,
  126923. NULL,
  126924. &_vq_auxt__8c0_s_p9_1,
  126925. NULL,
  126926. 0
  126927. };
  126928. static long _vq_quantlist__8c0_s_p9_2[] = {
  126929. 10,
  126930. 9,
  126931. 11,
  126932. 8,
  126933. 12,
  126934. 7,
  126935. 13,
  126936. 6,
  126937. 14,
  126938. 5,
  126939. 15,
  126940. 4,
  126941. 16,
  126942. 3,
  126943. 17,
  126944. 2,
  126945. 18,
  126946. 1,
  126947. 19,
  126948. 0,
  126949. 20,
  126950. };
  126951. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126952. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126953. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126954. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126955. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126956. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126957. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126958. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126959. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126960. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126961. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126962. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126963. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126964. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126965. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126966. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126967. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126968. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126969. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126970. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126971. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126972. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126973. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126974. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126975. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126976. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126977. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126978. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126979. 10,11, 9,11,10, 9,10, 9,10,
  126980. };
  126981. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126982. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126983. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126984. 6.5, 7.5, 8.5, 9.5,
  126985. };
  126986. static long _vq_quantmap__8c0_s_p9_2[] = {
  126987. 19, 17, 15, 13, 11, 9, 7, 5,
  126988. 3, 1, 0, 2, 4, 6, 8, 10,
  126989. 12, 14, 16, 18, 20,
  126990. };
  126991. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126992. _vq_quantthresh__8c0_s_p9_2,
  126993. _vq_quantmap__8c0_s_p9_2,
  126994. 21,
  126995. 21
  126996. };
  126997. static static_codebook _8c0_s_p9_2 = {
  126998. 2, 441,
  126999. _vq_lengthlist__8c0_s_p9_2,
  127000. 1, -529268736, 1611661312, 5, 0,
  127001. _vq_quantlist__8c0_s_p9_2,
  127002. NULL,
  127003. &_vq_auxt__8c0_s_p9_2,
  127004. NULL,
  127005. 0
  127006. };
  127007. static long _huff_lengthlist__8c0_s_single[] = {
  127008. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  127009. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  127010. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  127011. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  127012. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  127013. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  127014. 17,16,17,17,
  127015. };
  127016. static static_codebook _huff_book__8c0_s_single = {
  127017. 2, 100,
  127018. _huff_lengthlist__8c0_s_single,
  127019. 0, 0, 0, 0, 0,
  127020. NULL,
  127021. NULL,
  127022. NULL,
  127023. NULL,
  127024. 0
  127025. };
  127026. static long _vq_quantlist__8c1_s_p1_0[] = {
  127027. 1,
  127028. 0,
  127029. 2,
  127030. };
  127031. static long _vq_lengthlist__8c1_s_p1_0[] = {
  127032. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127033. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  127038. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  127043. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  127078. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  127083. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  127088. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127124. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127129. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127134. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127442. 0,
  127443. };
  127444. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127445. -0.5, 0.5,
  127446. };
  127447. static long _vq_quantmap__8c1_s_p1_0[] = {
  127448. 1, 0, 2,
  127449. };
  127450. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127451. _vq_quantthresh__8c1_s_p1_0,
  127452. _vq_quantmap__8c1_s_p1_0,
  127453. 3,
  127454. 3
  127455. };
  127456. static static_codebook _8c1_s_p1_0 = {
  127457. 8, 6561,
  127458. _vq_lengthlist__8c1_s_p1_0,
  127459. 1, -535822336, 1611661312, 2, 0,
  127460. _vq_quantlist__8c1_s_p1_0,
  127461. NULL,
  127462. &_vq_auxt__8c1_s_p1_0,
  127463. NULL,
  127464. 0
  127465. };
  127466. static long _vq_quantlist__8c1_s_p2_0[] = {
  127467. 2,
  127468. 1,
  127469. 3,
  127470. 0,
  127471. 4,
  127472. };
  127473. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0,
  127514. };
  127515. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127516. -1.5, -0.5, 0.5, 1.5,
  127517. };
  127518. static long _vq_quantmap__8c1_s_p2_0[] = {
  127519. 3, 1, 0, 2, 4,
  127520. };
  127521. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127522. _vq_quantthresh__8c1_s_p2_0,
  127523. _vq_quantmap__8c1_s_p2_0,
  127524. 5,
  127525. 5
  127526. };
  127527. static static_codebook _8c1_s_p2_0 = {
  127528. 4, 625,
  127529. _vq_lengthlist__8c1_s_p2_0,
  127530. 1, -533725184, 1611661312, 3, 0,
  127531. _vq_quantlist__8c1_s_p2_0,
  127532. NULL,
  127533. &_vq_auxt__8c1_s_p2_0,
  127534. NULL,
  127535. 0
  127536. };
  127537. static long _vq_quantlist__8c1_s_p3_0[] = {
  127538. 2,
  127539. 1,
  127540. 3,
  127541. 0,
  127542. 4,
  127543. };
  127544. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127545. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127548. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127551. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0,
  127585. };
  127586. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127587. -1.5, -0.5, 0.5, 1.5,
  127588. };
  127589. static long _vq_quantmap__8c1_s_p3_0[] = {
  127590. 3, 1, 0, 2, 4,
  127591. };
  127592. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127593. _vq_quantthresh__8c1_s_p3_0,
  127594. _vq_quantmap__8c1_s_p3_0,
  127595. 5,
  127596. 5
  127597. };
  127598. static static_codebook _8c1_s_p3_0 = {
  127599. 4, 625,
  127600. _vq_lengthlist__8c1_s_p3_0,
  127601. 1, -533725184, 1611661312, 3, 0,
  127602. _vq_quantlist__8c1_s_p3_0,
  127603. NULL,
  127604. &_vq_auxt__8c1_s_p3_0,
  127605. NULL,
  127606. 0
  127607. };
  127608. static long _vq_quantlist__8c1_s_p4_0[] = {
  127609. 4,
  127610. 3,
  127611. 5,
  127612. 2,
  127613. 6,
  127614. 1,
  127615. 7,
  127616. 0,
  127617. 8,
  127618. };
  127619. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127620. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127621. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127622. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127623. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127624. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0,
  127626. };
  127627. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127628. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127629. };
  127630. static long _vq_quantmap__8c1_s_p4_0[] = {
  127631. 7, 5, 3, 1, 0, 2, 4, 6,
  127632. 8,
  127633. };
  127634. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127635. _vq_quantthresh__8c1_s_p4_0,
  127636. _vq_quantmap__8c1_s_p4_0,
  127637. 9,
  127638. 9
  127639. };
  127640. static static_codebook _8c1_s_p4_0 = {
  127641. 2, 81,
  127642. _vq_lengthlist__8c1_s_p4_0,
  127643. 1, -531628032, 1611661312, 4, 0,
  127644. _vq_quantlist__8c1_s_p4_0,
  127645. NULL,
  127646. &_vq_auxt__8c1_s_p4_0,
  127647. NULL,
  127648. 0
  127649. };
  127650. static long _vq_quantlist__8c1_s_p5_0[] = {
  127651. 4,
  127652. 3,
  127653. 5,
  127654. 2,
  127655. 6,
  127656. 1,
  127657. 7,
  127658. 0,
  127659. 8,
  127660. };
  127661. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127662. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127663. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127664. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127665. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127666. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127667. 10,
  127668. };
  127669. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127670. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127671. };
  127672. static long _vq_quantmap__8c1_s_p5_0[] = {
  127673. 7, 5, 3, 1, 0, 2, 4, 6,
  127674. 8,
  127675. };
  127676. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127677. _vq_quantthresh__8c1_s_p5_0,
  127678. _vq_quantmap__8c1_s_p5_0,
  127679. 9,
  127680. 9
  127681. };
  127682. static static_codebook _8c1_s_p5_0 = {
  127683. 2, 81,
  127684. _vq_lengthlist__8c1_s_p5_0,
  127685. 1, -531628032, 1611661312, 4, 0,
  127686. _vq_quantlist__8c1_s_p5_0,
  127687. NULL,
  127688. &_vq_auxt__8c1_s_p5_0,
  127689. NULL,
  127690. 0
  127691. };
  127692. static long _vq_quantlist__8c1_s_p6_0[] = {
  127693. 8,
  127694. 7,
  127695. 9,
  127696. 6,
  127697. 10,
  127698. 5,
  127699. 11,
  127700. 4,
  127701. 12,
  127702. 3,
  127703. 13,
  127704. 2,
  127705. 14,
  127706. 1,
  127707. 15,
  127708. 0,
  127709. 16,
  127710. };
  127711. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127712. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127713. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127714. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127715. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127716. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127717. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127718. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127719. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127720. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127721. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127722. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127723. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127724. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127725. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127726. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127727. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127728. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127729. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127730. 14,
  127731. };
  127732. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127733. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127734. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127735. };
  127736. static long _vq_quantmap__8c1_s_p6_0[] = {
  127737. 15, 13, 11, 9, 7, 5, 3, 1,
  127738. 0, 2, 4, 6, 8, 10, 12, 14,
  127739. 16,
  127740. };
  127741. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127742. _vq_quantthresh__8c1_s_p6_0,
  127743. _vq_quantmap__8c1_s_p6_0,
  127744. 17,
  127745. 17
  127746. };
  127747. static static_codebook _8c1_s_p6_0 = {
  127748. 2, 289,
  127749. _vq_lengthlist__8c1_s_p6_0,
  127750. 1, -529530880, 1611661312, 5, 0,
  127751. _vq_quantlist__8c1_s_p6_0,
  127752. NULL,
  127753. &_vq_auxt__8c1_s_p6_0,
  127754. NULL,
  127755. 0
  127756. };
  127757. static long _vq_quantlist__8c1_s_p7_0[] = {
  127758. 1,
  127759. 0,
  127760. 2,
  127761. };
  127762. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127763. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127764. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127765. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127766. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127767. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127768. 9,
  127769. };
  127770. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127771. -5.5, 5.5,
  127772. };
  127773. static long _vq_quantmap__8c1_s_p7_0[] = {
  127774. 1, 0, 2,
  127775. };
  127776. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127777. _vq_quantthresh__8c1_s_p7_0,
  127778. _vq_quantmap__8c1_s_p7_0,
  127779. 3,
  127780. 3
  127781. };
  127782. static static_codebook _8c1_s_p7_0 = {
  127783. 4, 81,
  127784. _vq_lengthlist__8c1_s_p7_0,
  127785. 1, -529137664, 1618345984, 2, 0,
  127786. _vq_quantlist__8c1_s_p7_0,
  127787. NULL,
  127788. &_vq_auxt__8c1_s_p7_0,
  127789. NULL,
  127790. 0
  127791. };
  127792. static long _vq_quantlist__8c1_s_p7_1[] = {
  127793. 5,
  127794. 4,
  127795. 6,
  127796. 3,
  127797. 7,
  127798. 2,
  127799. 8,
  127800. 1,
  127801. 9,
  127802. 0,
  127803. 10,
  127804. };
  127805. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127806. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127807. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127808. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127809. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127810. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127811. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127812. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127813. 10,10,10, 8, 8, 8, 8, 8, 8,
  127814. };
  127815. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127816. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127817. 3.5, 4.5,
  127818. };
  127819. static long _vq_quantmap__8c1_s_p7_1[] = {
  127820. 9, 7, 5, 3, 1, 0, 2, 4,
  127821. 6, 8, 10,
  127822. };
  127823. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127824. _vq_quantthresh__8c1_s_p7_1,
  127825. _vq_quantmap__8c1_s_p7_1,
  127826. 11,
  127827. 11
  127828. };
  127829. static static_codebook _8c1_s_p7_1 = {
  127830. 2, 121,
  127831. _vq_lengthlist__8c1_s_p7_1,
  127832. 1, -531365888, 1611661312, 4, 0,
  127833. _vq_quantlist__8c1_s_p7_1,
  127834. NULL,
  127835. &_vq_auxt__8c1_s_p7_1,
  127836. NULL,
  127837. 0
  127838. };
  127839. static long _vq_quantlist__8c1_s_p8_0[] = {
  127840. 6,
  127841. 5,
  127842. 7,
  127843. 4,
  127844. 8,
  127845. 3,
  127846. 9,
  127847. 2,
  127848. 10,
  127849. 1,
  127850. 11,
  127851. 0,
  127852. 12,
  127853. };
  127854. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127855. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127856. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127857. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127858. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127859. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127860. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127861. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127862. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127863. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127864. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127865. 0,12,12,11,10,12,11,13,12,
  127866. };
  127867. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127868. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127869. 12.5, 17.5, 22.5, 27.5,
  127870. };
  127871. static long _vq_quantmap__8c1_s_p8_0[] = {
  127872. 11, 9, 7, 5, 3, 1, 0, 2,
  127873. 4, 6, 8, 10, 12,
  127874. };
  127875. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127876. _vq_quantthresh__8c1_s_p8_0,
  127877. _vq_quantmap__8c1_s_p8_0,
  127878. 13,
  127879. 13
  127880. };
  127881. static static_codebook _8c1_s_p8_0 = {
  127882. 2, 169,
  127883. _vq_lengthlist__8c1_s_p8_0,
  127884. 1, -526516224, 1616117760, 4, 0,
  127885. _vq_quantlist__8c1_s_p8_0,
  127886. NULL,
  127887. &_vq_auxt__8c1_s_p8_0,
  127888. NULL,
  127889. 0
  127890. };
  127891. static long _vq_quantlist__8c1_s_p8_1[] = {
  127892. 2,
  127893. 1,
  127894. 3,
  127895. 0,
  127896. 4,
  127897. };
  127898. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127899. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127900. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127901. };
  127902. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127903. -1.5, -0.5, 0.5, 1.5,
  127904. };
  127905. static long _vq_quantmap__8c1_s_p8_1[] = {
  127906. 3, 1, 0, 2, 4,
  127907. };
  127908. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127909. _vq_quantthresh__8c1_s_p8_1,
  127910. _vq_quantmap__8c1_s_p8_1,
  127911. 5,
  127912. 5
  127913. };
  127914. static static_codebook _8c1_s_p8_1 = {
  127915. 2, 25,
  127916. _vq_lengthlist__8c1_s_p8_1,
  127917. 1, -533725184, 1611661312, 3, 0,
  127918. _vq_quantlist__8c1_s_p8_1,
  127919. NULL,
  127920. &_vq_auxt__8c1_s_p8_1,
  127921. NULL,
  127922. 0
  127923. };
  127924. static long _vq_quantlist__8c1_s_p9_0[] = {
  127925. 6,
  127926. 5,
  127927. 7,
  127928. 4,
  127929. 8,
  127930. 3,
  127931. 9,
  127932. 2,
  127933. 10,
  127934. 1,
  127935. 11,
  127936. 0,
  127937. 12,
  127938. };
  127939. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127940. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127941. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127942. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127943. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127944. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127945. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127946. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127947. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127948. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127949. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127950. 10,10,10,10,10, 9, 9, 9, 9,
  127951. };
  127952. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127953. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127954. 787.5, 1102.5, 1417.5, 1732.5,
  127955. };
  127956. static long _vq_quantmap__8c1_s_p9_0[] = {
  127957. 11, 9, 7, 5, 3, 1, 0, 2,
  127958. 4, 6, 8, 10, 12,
  127959. };
  127960. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127961. _vq_quantthresh__8c1_s_p9_0,
  127962. _vq_quantmap__8c1_s_p9_0,
  127963. 13,
  127964. 13
  127965. };
  127966. static static_codebook _8c1_s_p9_0 = {
  127967. 2, 169,
  127968. _vq_lengthlist__8c1_s_p9_0,
  127969. 1, -513964032, 1628680192, 4, 0,
  127970. _vq_quantlist__8c1_s_p9_0,
  127971. NULL,
  127972. &_vq_auxt__8c1_s_p9_0,
  127973. NULL,
  127974. 0
  127975. };
  127976. static long _vq_quantlist__8c1_s_p9_1[] = {
  127977. 7,
  127978. 6,
  127979. 8,
  127980. 5,
  127981. 9,
  127982. 4,
  127983. 10,
  127984. 3,
  127985. 11,
  127986. 2,
  127987. 12,
  127988. 1,
  127989. 13,
  127990. 0,
  127991. 14,
  127992. };
  127993. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127994. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127995. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127996. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127997. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127998. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127999. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  128000. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  128001. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  128002. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  128003. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  128004. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  128005. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  128006. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  128007. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  128008. 15,
  128009. };
  128010. static float _vq_quantthresh__8c1_s_p9_1[] = {
  128011. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128012. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128013. };
  128014. static long _vq_quantmap__8c1_s_p9_1[] = {
  128015. 13, 11, 9, 7, 5, 3, 1, 0,
  128016. 2, 4, 6, 8, 10, 12, 14,
  128017. };
  128018. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  128019. _vq_quantthresh__8c1_s_p9_1,
  128020. _vq_quantmap__8c1_s_p9_1,
  128021. 15,
  128022. 15
  128023. };
  128024. static static_codebook _8c1_s_p9_1 = {
  128025. 2, 225,
  128026. _vq_lengthlist__8c1_s_p9_1,
  128027. 1, -520986624, 1620377600, 4, 0,
  128028. _vq_quantlist__8c1_s_p9_1,
  128029. NULL,
  128030. &_vq_auxt__8c1_s_p9_1,
  128031. NULL,
  128032. 0
  128033. };
  128034. static long _vq_quantlist__8c1_s_p9_2[] = {
  128035. 10,
  128036. 9,
  128037. 11,
  128038. 8,
  128039. 12,
  128040. 7,
  128041. 13,
  128042. 6,
  128043. 14,
  128044. 5,
  128045. 15,
  128046. 4,
  128047. 16,
  128048. 3,
  128049. 17,
  128050. 2,
  128051. 18,
  128052. 1,
  128053. 19,
  128054. 0,
  128055. 20,
  128056. };
  128057. static long _vq_lengthlist__8c1_s_p9_2[] = {
  128058. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  128059. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  128060. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  128061. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  128062. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128063. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128064. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  128065. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  128066. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  128067. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  128068. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  128069. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  128070. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  128071. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  128072. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  128073. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  128074. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128075. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  128076. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  128077. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  128078. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128079. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  128080. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  128081. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128082. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  128083. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  128084. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  128085. 10,10,10,10,10,10,10,10,10,
  128086. };
  128087. static float _vq_quantthresh__8c1_s_p9_2[] = {
  128088. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128089. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128090. 6.5, 7.5, 8.5, 9.5,
  128091. };
  128092. static long _vq_quantmap__8c1_s_p9_2[] = {
  128093. 19, 17, 15, 13, 11, 9, 7, 5,
  128094. 3, 1, 0, 2, 4, 6, 8, 10,
  128095. 12, 14, 16, 18, 20,
  128096. };
  128097. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  128098. _vq_quantthresh__8c1_s_p9_2,
  128099. _vq_quantmap__8c1_s_p9_2,
  128100. 21,
  128101. 21
  128102. };
  128103. static static_codebook _8c1_s_p9_2 = {
  128104. 2, 441,
  128105. _vq_lengthlist__8c1_s_p9_2,
  128106. 1, -529268736, 1611661312, 5, 0,
  128107. _vq_quantlist__8c1_s_p9_2,
  128108. NULL,
  128109. &_vq_auxt__8c1_s_p9_2,
  128110. NULL,
  128111. 0
  128112. };
  128113. static long _huff_lengthlist__8c1_s_single[] = {
  128114. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128115. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128116. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128117. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128118. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128119. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128120. 9, 7, 7, 8,
  128121. };
  128122. static static_codebook _huff_book__8c1_s_single = {
  128123. 2, 100,
  128124. _huff_lengthlist__8c1_s_single,
  128125. 0, 0, 0, 0, 0,
  128126. NULL,
  128127. NULL,
  128128. NULL,
  128129. NULL,
  128130. 0
  128131. };
  128132. static long _huff_lengthlist__44c2_s_long[] = {
  128133. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128134. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128135. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128136. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128137. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128138. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128139. 10, 8, 8, 9,
  128140. };
  128141. static static_codebook _huff_book__44c2_s_long = {
  128142. 2, 100,
  128143. _huff_lengthlist__44c2_s_long,
  128144. 0, 0, 0, 0, 0,
  128145. NULL,
  128146. NULL,
  128147. NULL,
  128148. NULL,
  128149. 0
  128150. };
  128151. static long _vq_quantlist__44c2_s_p1_0[] = {
  128152. 1,
  128153. 0,
  128154. 2,
  128155. };
  128156. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128157. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128158. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128163. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128168. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  128203. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128208. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128213. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128249. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128254. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128259. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128567. 0,
  128568. };
  128569. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128570. -0.5, 0.5,
  128571. };
  128572. static long _vq_quantmap__44c2_s_p1_0[] = {
  128573. 1, 0, 2,
  128574. };
  128575. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128576. _vq_quantthresh__44c2_s_p1_0,
  128577. _vq_quantmap__44c2_s_p1_0,
  128578. 3,
  128579. 3
  128580. };
  128581. static static_codebook _44c2_s_p1_0 = {
  128582. 8, 6561,
  128583. _vq_lengthlist__44c2_s_p1_0,
  128584. 1, -535822336, 1611661312, 2, 0,
  128585. _vq_quantlist__44c2_s_p1_0,
  128586. NULL,
  128587. &_vq_auxt__44c2_s_p1_0,
  128588. NULL,
  128589. 0
  128590. };
  128591. static long _vq_quantlist__44c2_s_p2_0[] = {
  128592. 2,
  128593. 1,
  128594. 3,
  128595. 0,
  128596. 4,
  128597. };
  128598. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128599. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128600. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128601. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128602. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128603. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128609. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128610. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128611. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128617. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128618. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128625. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128626. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0,
  128639. };
  128640. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128641. -1.5, -0.5, 0.5, 1.5,
  128642. };
  128643. static long _vq_quantmap__44c2_s_p2_0[] = {
  128644. 3, 1, 0, 2, 4,
  128645. };
  128646. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128647. _vq_quantthresh__44c2_s_p2_0,
  128648. _vq_quantmap__44c2_s_p2_0,
  128649. 5,
  128650. 5
  128651. };
  128652. static static_codebook _44c2_s_p2_0 = {
  128653. 4, 625,
  128654. _vq_lengthlist__44c2_s_p2_0,
  128655. 1, -533725184, 1611661312, 3, 0,
  128656. _vq_quantlist__44c2_s_p2_0,
  128657. NULL,
  128658. &_vq_auxt__44c2_s_p2_0,
  128659. NULL,
  128660. 0
  128661. };
  128662. static long _vq_quantlist__44c2_s_p3_0[] = {
  128663. 2,
  128664. 1,
  128665. 3,
  128666. 0,
  128667. 4,
  128668. };
  128669. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128670. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128673. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0,
  128710. };
  128711. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128712. -1.5, -0.5, 0.5, 1.5,
  128713. };
  128714. static long _vq_quantmap__44c2_s_p3_0[] = {
  128715. 3, 1, 0, 2, 4,
  128716. };
  128717. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128718. _vq_quantthresh__44c2_s_p3_0,
  128719. _vq_quantmap__44c2_s_p3_0,
  128720. 5,
  128721. 5
  128722. };
  128723. static static_codebook _44c2_s_p3_0 = {
  128724. 4, 625,
  128725. _vq_lengthlist__44c2_s_p3_0,
  128726. 1, -533725184, 1611661312, 3, 0,
  128727. _vq_quantlist__44c2_s_p3_0,
  128728. NULL,
  128729. &_vq_auxt__44c2_s_p3_0,
  128730. NULL,
  128731. 0
  128732. };
  128733. static long _vq_quantlist__44c2_s_p4_0[] = {
  128734. 4,
  128735. 3,
  128736. 5,
  128737. 2,
  128738. 6,
  128739. 1,
  128740. 7,
  128741. 0,
  128742. 8,
  128743. };
  128744. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128745. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128746. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128747. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128748. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128749. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0,
  128751. };
  128752. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128753. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128754. };
  128755. static long _vq_quantmap__44c2_s_p4_0[] = {
  128756. 7, 5, 3, 1, 0, 2, 4, 6,
  128757. 8,
  128758. };
  128759. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128760. _vq_quantthresh__44c2_s_p4_0,
  128761. _vq_quantmap__44c2_s_p4_0,
  128762. 9,
  128763. 9
  128764. };
  128765. static static_codebook _44c2_s_p4_0 = {
  128766. 2, 81,
  128767. _vq_lengthlist__44c2_s_p4_0,
  128768. 1, -531628032, 1611661312, 4, 0,
  128769. _vq_quantlist__44c2_s_p4_0,
  128770. NULL,
  128771. &_vq_auxt__44c2_s_p4_0,
  128772. NULL,
  128773. 0
  128774. };
  128775. static long _vq_quantlist__44c2_s_p5_0[] = {
  128776. 4,
  128777. 3,
  128778. 5,
  128779. 2,
  128780. 6,
  128781. 1,
  128782. 7,
  128783. 0,
  128784. 8,
  128785. };
  128786. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128787. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128788. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128789. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128790. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128791. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128792. 11,
  128793. };
  128794. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128795. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128796. };
  128797. static long _vq_quantmap__44c2_s_p5_0[] = {
  128798. 7, 5, 3, 1, 0, 2, 4, 6,
  128799. 8,
  128800. };
  128801. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128802. _vq_quantthresh__44c2_s_p5_0,
  128803. _vq_quantmap__44c2_s_p5_0,
  128804. 9,
  128805. 9
  128806. };
  128807. static static_codebook _44c2_s_p5_0 = {
  128808. 2, 81,
  128809. _vq_lengthlist__44c2_s_p5_0,
  128810. 1, -531628032, 1611661312, 4, 0,
  128811. _vq_quantlist__44c2_s_p5_0,
  128812. NULL,
  128813. &_vq_auxt__44c2_s_p5_0,
  128814. NULL,
  128815. 0
  128816. };
  128817. static long _vq_quantlist__44c2_s_p6_0[] = {
  128818. 8,
  128819. 7,
  128820. 9,
  128821. 6,
  128822. 10,
  128823. 5,
  128824. 11,
  128825. 4,
  128826. 12,
  128827. 3,
  128828. 13,
  128829. 2,
  128830. 14,
  128831. 1,
  128832. 15,
  128833. 0,
  128834. 16,
  128835. };
  128836. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128837. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128838. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128839. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128840. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128841. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128842. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128843. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128844. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128845. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128846. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128847. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128848. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128849. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128850. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128851. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128852. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128853. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128854. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128855. 14,
  128856. };
  128857. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128858. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128859. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128860. };
  128861. static long _vq_quantmap__44c2_s_p6_0[] = {
  128862. 15, 13, 11, 9, 7, 5, 3, 1,
  128863. 0, 2, 4, 6, 8, 10, 12, 14,
  128864. 16,
  128865. };
  128866. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128867. _vq_quantthresh__44c2_s_p6_0,
  128868. _vq_quantmap__44c2_s_p6_0,
  128869. 17,
  128870. 17
  128871. };
  128872. static static_codebook _44c2_s_p6_0 = {
  128873. 2, 289,
  128874. _vq_lengthlist__44c2_s_p6_0,
  128875. 1, -529530880, 1611661312, 5, 0,
  128876. _vq_quantlist__44c2_s_p6_0,
  128877. NULL,
  128878. &_vq_auxt__44c2_s_p6_0,
  128879. NULL,
  128880. 0
  128881. };
  128882. static long _vq_quantlist__44c2_s_p7_0[] = {
  128883. 1,
  128884. 0,
  128885. 2,
  128886. };
  128887. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128888. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128889. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128890. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128891. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128892. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128893. 11,
  128894. };
  128895. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128896. -5.5, 5.5,
  128897. };
  128898. static long _vq_quantmap__44c2_s_p7_0[] = {
  128899. 1, 0, 2,
  128900. };
  128901. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128902. _vq_quantthresh__44c2_s_p7_0,
  128903. _vq_quantmap__44c2_s_p7_0,
  128904. 3,
  128905. 3
  128906. };
  128907. static static_codebook _44c2_s_p7_0 = {
  128908. 4, 81,
  128909. _vq_lengthlist__44c2_s_p7_0,
  128910. 1, -529137664, 1618345984, 2, 0,
  128911. _vq_quantlist__44c2_s_p7_0,
  128912. NULL,
  128913. &_vq_auxt__44c2_s_p7_0,
  128914. NULL,
  128915. 0
  128916. };
  128917. static long _vq_quantlist__44c2_s_p7_1[] = {
  128918. 5,
  128919. 4,
  128920. 6,
  128921. 3,
  128922. 7,
  128923. 2,
  128924. 8,
  128925. 1,
  128926. 9,
  128927. 0,
  128928. 10,
  128929. };
  128930. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128931. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128932. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128933. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128934. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128935. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128936. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128937. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128938. 10,10,10, 8, 8, 8, 8, 8, 8,
  128939. };
  128940. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128941. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128942. 3.5, 4.5,
  128943. };
  128944. static long _vq_quantmap__44c2_s_p7_1[] = {
  128945. 9, 7, 5, 3, 1, 0, 2, 4,
  128946. 6, 8, 10,
  128947. };
  128948. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128949. _vq_quantthresh__44c2_s_p7_1,
  128950. _vq_quantmap__44c2_s_p7_1,
  128951. 11,
  128952. 11
  128953. };
  128954. static static_codebook _44c2_s_p7_1 = {
  128955. 2, 121,
  128956. _vq_lengthlist__44c2_s_p7_1,
  128957. 1, -531365888, 1611661312, 4, 0,
  128958. _vq_quantlist__44c2_s_p7_1,
  128959. NULL,
  128960. &_vq_auxt__44c2_s_p7_1,
  128961. NULL,
  128962. 0
  128963. };
  128964. static long _vq_quantlist__44c2_s_p8_0[] = {
  128965. 6,
  128966. 5,
  128967. 7,
  128968. 4,
  128969. 8,
  128970. 3,
  128971. 9,
  128972. 2,
  128973. 10,
  128974. 1,
  128975. 11,
  128976. 0,
  128977. 12,
  128978. };
  128979. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128980. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128981. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128982. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128983. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128984. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128985. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128986. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128987. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128988. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128989. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128990. 0,12,12,12,12,13,12,14,14,
  128991. };
  128992. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128993. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128994. 12.5, 17.5, 22.5, 27.5,
  128995. };
  128996. static long _vq_quantmap__44c2_s_p8_0[] = {
  128997. 11, 9, 7, 5, 3, 1, 0, 2,
  128998. 4, 6, 8, 10, 12,
  128999. };
  129000. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  129001. _vq_quantthresh__44c2_s_p8_0,
  129002. _vq_quantmap__44c2_s_p8_0,
  129003. 13,
  129004. 13
  129005. };
  129006. static static_codebook _44c2_s_p8_0 = {
  129007. 2, 169,
  129008. _vq_lengthlist__44c2_s_p8_0,
  129009. 1, -526516224, 1616117760, 4, 0,
  129010. _vq_quantlist__44c2_s_p8_0,
  129011. NULL,
  129012. &_vq_auxt__44c2_s_p8_0,
  129013. NULL,
  129014. 0
  129015. };
  129016. static long _vq_quantlist__44c2_s_p8_1[] = {
  129017. 2,
  129018. 1,
  129019. 3,
  129020. 0,
  129021. 4,
  129022. };
  129023. static long _vq_lengthlist__44c2_s_p8_1[] = {
  129024. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  129025. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129026. };
  129027. static float _vq_quantthresh__44c2_s_p8_1[] = {
  129028. -1.5, -0.5, 0.5, 1.5,
  129029. };
  129030. static long _vq_quantmap__44c2_s_p8_1[] = {
  129031. 3, 1, 0, 2, 4,
  129032. };
  129033. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  129034. _vq_quantthresh__44c2_s_p8_1,
  129035. _vq_quantmap__44c2_s_p8_1,
  129036. 5,
  129037. 5
  129038. };
  129039. static static_codebook _44c2_s_p8_1 = {
  129040. 2, 25,
  129041. _vq_lengthlist__44c2_s_p8_1,
  129042. 1, -533725184, 1611661312, 3, 0,
  129043. _vq_quantlist__44c2_s_p8_1,
  129044. NULL,
  129045. &_vq_auxt__44c2_s_p8_1,
  129046. NULL,
  129047. 0
  129048. };
  129049. static long _vq_quantlist__44c2_s_p9_0[] = {
  129050. 6,
  129051. 5,
  129052. 7,
  129053. 4,
  129054. 8,
  129055. 3,
  129056. 9,
  129057. 2,
  129058. 10,
  129059. 1,
  129060. 11,
  129061. 0,
  129062. 12,
  129063. };
  129064. static long _vq_lengthlist__44c2_s_p9_0[] = {
  129065. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129066. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  129067. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129068. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  129069. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129070. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129071. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129072. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129073. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129075. 11,11,11,11,11,11,11,11,11,
  129076. };
  129077. static float _vq_quantthresh__44c2_s_p9_0[] = {
  129078. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  129079. 552.5, 773.5, 994.5, 1215.5,
  129080. };
  129081. static long _vq_quantmap__44c2_s_p9_0[] = {
  129082. 11, 9, 7, 5, 3, 1, 0, 2,
  129083. 4, 6, 8, 10, 12,
  129084. };
  129085. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  129086. _vq_quantthresh__44c2_s_p9_0,
  129087. _vq_quantmap__44c2_s_p9_0,
  129088. 13,
  129089. 13
  129090. };
  129091. static static_codebook _44c2_s_p9_0 = {
  129092. 2, 169,
  129093. _vq_lengthlist__44c2_s_p9_0,
  129094. 1, -514541568, 1627103232, 4, 0,
  129095. _vq_quantlist__44c2_s_p9_0,
  129096. NULL,
  129097. &_vq_auxt__44c2_s_p9_0,
  129098. NULL,
  129099. 0
  129100. };
  129101. static long _vq_quantlist__44c2_s_p9_1[] = {
  129102. 6,
  129103. 5,
  129104. 7,
  129105. 4,
  129106. 8,
  129107. 3,
  129108. 9,
  129109. 2,
  129110. 10,
  129111. 1,
  129112. 11,
  129113. 0,
  129114. 12,
  129115. };
  129116. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129117. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129118. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129119. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129120. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129121. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129122. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129123. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129124. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129125. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129126. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129127. 17,13,12,12,10,13,11,14,14,
  129128. };
  129129. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129130. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129131. 42.5, 59.5, 76.5, 93.5,
  129132. };
  129133. static long _vq_quantmap__44c2_s_p9_1[] = {
  129134. 11, 9, 7, 5, 3, 1, 0, 2,
  129135. 4, 6, 8, 10, 12,
  129136. };
  129137. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129138. _vq_quantthresh__44c2_s_p9_1,
  129139. _vq_quantmap__44c2_s_p9_1,
  129140. 13,
  129141. 13
  129142. };
  129143. static static_codebook _44c2_s_p9_1 = {
  129144. 2, 169,
  129145. _vq_lengthlist__44c2_s_p9_1,
  129146. 1, -522616832, 1620115456, 4, 0,
  129147. _vq_quantlist__44c2_s_p9_1,
  129148. NULL,
  129149. &_vq_auxt__44c2_s_p9_1,
  129150. NULL,
  129151. 0
  129152. };
  129153. static long _vq_quantlist__44c2_s_p9_2[] = {
  129154. 8,
  129155. 7,
  129156. 9,
  129157. 6,
  129158. 10,
  129159. 5,
  129160. 11,
  129161. 4,
  129162. 12,
  129163. 3,
  129164. 13,
  129165. 2,
  129166. 14,
  129167. 1,
  129168. 15,
  129169. 0,
  129170. 16,
  129171. };
  129172. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129173. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129174. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129175. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129176. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129177. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129178. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129179. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129180. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129181. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129182. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129183. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129184. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129185. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129186. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129187. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129188. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129189. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129190. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129191. 10,
  129192. };
  129193. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129194. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129195. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129196. };
  129197. static long _vq_quantmap__44c2_s_p9_2[] = {
  129198. 15, 13, 11, 9, 7, 5, 3, 1,
  129199. 0, 2, 4, 6, 8, 10, 12, 14,
  129200. 16,
  129201. };
  129202. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129203. _vq_quantthresh__44c2_s_p9_2,
  129204. _vq_quantmap__44c2_s_p9_2,
  129205. 17,
  129206. 17
  129207. };
  129208. static static_codebook _44c2_s_p9_2 = {
  129209. 2, 289,
  129210. _vq_lengthlist__44c2_s_p9_2,
  129211. 1, -529530880, 1611661312, 5, 0,
  129212. _vq_quantlist__44c2_s_p9_2,
  129213. NULL,
  129214. &_vq_auxt__44c2_s_p9_2,
  129215. NULL,
  129216. 0
  129217. };
  129218. static long _huff_lengthlist__44c2_s_short[] = {
  129219. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129220. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129221. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129222. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129223. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129224. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129225. 6, 8, 9,12,
  129226. };
  129227. static static_codebook _huff_book__44c2_s_short = {
  129228. 2, 100,
  129229. _huff_lengthlist__44c2_s_short,
  129230. 0, 0, 0, 0, 0,
  129231. NULL,
  129232. NULL,
  129233. NULL,
  129234. NULL,
  129235. 0
  129236. };
  129237. static long _huff_lengthlist__44c3_s_long[] = {
  129238. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129239. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129240. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129241. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129242. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129243. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129244. 9, 8, 8, 8,
  129245. };
  129246. static static_codebook _huff_book__44c3_s_long = {
  129247. 2, 100,
  129248. _huff_lengthlist__44c3_s_long,
  129249. 0, 0, 0, 0, 0,
  129250. NULL,
  129251. NULL,
  129252. NULL,
  129253. NULL,
  129254. 0
  129255. };
  129256. static long _vq_quantlist__44c3_s_p1_0[] = {
  129257. 1,
  129258. 0,
  129259. 2,
  129260. };
  129261. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129262. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129263. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129268. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129273. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  129308. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129313. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129318. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129354. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129359. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129364. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129672. 0,
  129673. };
  129674. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129675. -0.5, 0.5,
  129676. };
  129677. static long _vq_quantmap__44c3_s_p1_0[] = {
  129678. 1, 0, 2,
  129679. };
  129680. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129681. _vq_quantthresh__44c3_s_p1_0,
  129682. _vq_quantmap__44c3_s_p1_0,
  129683. 3,
  129684. 3
  129685. };
  129686. static static_codebook _44c3_s_p1_0 = {
  129687. 8, 6561,
  129688. _vq_lengthlist__44c3_s_p1_0,
  129689. 1, -535822336, 1611661312, 2, 0,
  129690. _vq_quantlist__44c3_s_p1_0,
  129691. NULL,
  129692. &_vq_auxt__44c3_s_p1_0,
  129693. NULL,
  129694. 0
  129695. };
  129696. static long _vq_quantlist__44c3_s_p2_0[] = {
  129697. 2,
  129698. 1,
  129699. 3,
  129700. 0,
  129701. 4,
  129702. };
  129703. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129704. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129705. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129706. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129707. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129708. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129714. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129715. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129716. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129722. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129723. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129730. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129731. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0,
  129744. };
  129745. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129746. -1.5, -0.5, 0.5, 1.5,
  129747. };
  129748. static long _vq_quantmap__44c3_s_p2_0[] = {
  129749. 3, 1, 0, 2, 4,
  129750. };
  129751. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129752. _vq_quantthresh__44c3_s_p2_0,
  129753. _vq_quantmap__44c3_s_p2_0,
  129754. 5,
  129755. 5
  129756. };
  129757. static static_codebook _44c3_s_p2_0 = {
  129758. 4, 625,
  129759. _vq_lengthlist__44c3_s_p2_0,
  129760. 1, -533725184, 1611661312, 3, 0,
  129761. _vq_quantlist__44c3_s_p2_0,
  129762. NULL,
  129763. &_vq_auxt__44c3_s_p2_0,
  129764. NULL,
  129765. 0
  129766. };
  129767. static long _vq_quantlist__44c3_s_p3_0[] = {
  129768. 2,
  129769. 1,
  129770. 3,
  129771. 0,
  129772. 4,
  129773. };
  129774. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129775. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129778. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0,
  129815. };
  129816. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129817. -1.5, -0.5, 0.5, 1.5,
  129818. };
  129819. static long _vq_quantmap__44c3_s_p3_0[] = {
  129820. 3, 1, 0, 2, 4,
  129821. };
  129822. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129823. _vq_quantthresh__44c3_s_p3_0,
  129824. _vq_quantmap__44c3_s_p3_0,
  129825. 5,
  129826. 5
  129827. };
  129828. static static_codebook _44c3_s_p3_0 = {
  129829. 4, 625,
  129830. _vq_lengthlist__44c3_s_p3_0,
  129831. 1, -533725184, 1611661312, 3, 0,
  129832. _vq_quantlist__44c3_s_p3_0,
  129833. NULL,
  129834. &_vq_auxt__44c3_s_p3_0,
  129835. NULL,
  129836. 0
  129837. };
  129838. static long _vq_quantlist__44c3_s_p4_0[] = {
  129839. 4,
  129840. 3,
  129841. 5,
  129842. 2,
  129843. 6,
  129844. 1,
  129845. 7,
  129846. 0,
  129847. 8,
  129848. };
  129849. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129850. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129851. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129852. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129853. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129854. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0,
  129856. };
  129857. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129858. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129859. };
  129860. static long _vq_quantmap__44c3_s_p4_0[] = {
  129861. 7, 5, 3, 1, 0, 2, 4, 6,
  129862. 8,
  129863. };
  129864. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129865. _vq_quantthresh__44c3_s_p4_0,
  129866. _vq_quantmap__44c3_s_p4_0,
  129867. 9,
  129868. 9
  129869. };
  129870. static static_codebook _44c3_s_p4_0 = {
  129871. 2, 81,
  129872. _vq_lengthlist__44c3_s_p4_0,
  129873. 1, -531628032, 1611661312, 4, 0,
  129874. _vq_quantlist__44c3_s_p4_0,
  129875. NULL,
  129876. &_vq_auxt__44c3_s_p4_0,
  129877. NULL,
  129878. 0
  129879. };
  129880. static long _vq_quantlist__44c3_s_p5_0[] = {
  129881. 4,
  129882. 3,
  129883. 5,
  129884. 2,
  129885. 6,
  129886. 1,
  129887. 7,
  129888. 0,
  129889. 8,
  129890. };
  129891. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129892. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129893. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129894. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129895. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129896. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129897. 11,
  129898. };
  129899. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129900. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129901. };
  129902. static long _vq_quantmap__44c3_s_p5_0[] = {
  129903. 7, 5, 3, 1, 0, 2, 4, 6,
  129904. 8,
  129905. };
  129906. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129907. _vq_quantthresh__44c3_s_p5_0,
  129908. _vq_quantmap__44c3_s_p5_0,
  129909. 9,
  129910. 9
  129911. };
  129912. static static_codebook _44c3_s_p5_0 = {
  129913. 2, 81,
  129914. _vq_lengthlist__44c3_s_p5_0,
  129915. 1, -531628032, 1611661312, 4, 0,
  129916. _vq_quantlist__44c3_s_p5_0,
  129917. NULL,
  129918. &_vq_auxt__44c3_s_p5_0,
  129919. NULL,
  129920. 0
  129921. };
  129922. static long _vq_quantlist__44c3_s_p6_0[] = {
  129923. 8,
  129924. 7,
  129925. 9,
  129926. 6,
  129927. 10,
  129928. 5,
  129929. 11,
  129930. 4,
  129931. 12,
  129932. 3,
  129933. 13,
  129934. 2,
  129935. 14,
  129936. 1,
  129937. 15,
  129938. 0,
  129939. 16,
  129940. };
  129941. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129942. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129943. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129944. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129945. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129946. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129947. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129948. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129949. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129950. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129951. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129952. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129953. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129954. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129955. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129956. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129957. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129958. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129959. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129960. 13,
  129961. };
  129962. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129963. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129964. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129965. };
  129966. static long _vq_quantmap__44c3_s_p6_0[] = {
  129967. 15, 13, 11, 9, 7, 5, 3, 1,
  129968. 0, 2, 4, 6, 8, 10, 12, 14,
  129969. 16,
  129970. };
  129971. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129972. _vq_quantthresh__44c3_s_p6_0,
  129973. _vq_quantmap__44c3_s_p6_0,
  129974. 17,
  129975. 17
  129976. };
  129977. static static_codebook _44c3_s_p6_0 = {
  129978. 2, 289,
  129979. _vq_lengthlist__44c3_s_p6_0,
  129980. 1, -529530880, 1611661312, 5, 0,
  129981. _vq_quantlist__44c3_s_p6_0,
  129982. NULL,
  129983. &_vq_auxt__44c3_s_p6_0,
  129984. NULL,
  129985. 0
  129986. };
  129987. static long _vq_quantlist__44c3_s_p7_0[] = {
  129988. 1,
  129989. 0,
  129990. 2,
  129991. };
  129992. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129993. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129994. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129995. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129996. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129997. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129998. 10,
  129999. };
  130000. static float _vq_quantthresh__44c3_s_p7_0[] = {
  130001. -5.5, 5.5,
  130002. };
  130003. static long _vq_quantmap__44c3_s_p7_0[] = {
  130004. 1, 0, 2,
  130005. };
  130006. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  130007. _vq_quantthresh__44c3_s_p7_0,
  130008. _vq_quantmap__44c3_s_p7_0,
  130009. 3,
  130010. 3
  130011. };
  130012. static static_codebook _44c3_s_p7_0 = {
  130013. 4, 81,
  130014. _vq_lengthlist__44c3_s_p7_0,
  130015. 1, -529137664, 1618345984, 2, 0,
  130016. _vq_quantlist__44c3_s_p7_0,
  130017. NULL,
  130018. &_vq_auxt__44c3_s_p7_0,
  130019. NULL,
  130020. 0
  130021. };
  130022. static long _vq_quantlist__44c3_s_p7_1[] = {
  130023. 5,
  130024. 4,
  130025. 6,
  130026. 3,
  130027. 7,
  130028. 2,
  130029. 8,
  130030. 1,
  130031. 9,
  130032. 0,
  130033. 10,
  130034. };
  130035. static long _vq_lengthlist__44c3_s_p7_1[] = {
  130036. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130037. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130038. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130039. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  130040. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  130041. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130042. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130043. 10,10,10, 8, 8, 8, 8, 8, 8,
  130044. };
  130045. static float _vq_quantthresh__44c3_s_p7_1[] = {
  130046. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130047. 3.5, 4.5,
  130048. };
  130049. static long _vq_quantmap__44c3_s_p7_1[] = {
  130050. 9, 7, 5, 3, 1, 0, 2, 4,
  130051. 6, 8, 10,
  130052. };
  130053. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  130054. _vq_quantthresh__44c3_s_p7_1,
  130055. _vq_quantmap__44c3_s_p7_1,
  130056. 11,
  130057. 11
  130058. };
  130059. static static_codebook _44c3_s_p7_1 = {
  130060. 2, 121,
  130061. _vq_lengthlist__44c3_s_p7_1,
  130062. 1, -531365888, 1611661312, 4, 0,
  130063. _vq_quantlist__44c3_s_p7_1,
  130064. NULL,
  130065. &_vq_auxt__44c3_s_p7_1,
  130066. NULL,
  130067. 0
  130068. };
  130069. static long _vq_quantlist__44c3_s_p8_0[] = {
  130070. 6,
  130071. 5,
  130072. 7,
  130073. 4,
  130074. 8,
  130075. 3,
  130076. 9,
  130077. 2,
  130078. 10,
  130079. 1,
  130080. 11,
  130081. 0,
  130082. 12,
  130083. };
  130084. static long _vq_lengthlist__44c3_s_p8_0[] = {
  130085. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130086. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  130087. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130088. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130089. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  130090. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  130091. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  130092. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130093. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  130094. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  130095. 0,13,13,12,12,13,12,14,13,
  130096. };
  130097. static float _vq_quantthresh__44c3_s_p8_0[] = {
  130098. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130099. 12.5, 17.5, 22.5, 27.5,
  130100. };
  130101. static long _vq_quantmap__44c3_s_p8_0[] = {
  130102. 11, 9, 7, 5, 3, 1, 0, 2,
  130103. 4, 6, 8, 10, 12,
  130104. };
  130105. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  130106. _vq_quantthresh__44c3_s_p8_0,
  130107. _vq_quantmap__44c3_s_p8_0,
  130108. 13,
  130109. 13
  130110. };
  130111. static static_codebook _44c3_s_p8_0 = {
  130112. 2, 169,
  130113. _vq_lengthlist__44c3_s_p8_0,
  130114. 1, -526516224, 1616117760, 4, 0,
  130115. _vq_quantlist__44c3_s_p8_0,
  130116. NULL,
  130117. &_vq_auxt__44c3_s_p8_0,
  130118. NULL,
  130119. 0
  130120. };
  130121. static long _vq_quantlist__44c3_s_p8_1[] = {
  130122. 2,
  130123. 1,
  130124. 3,
  130125. 0,
  130126. 4,
  130127. };
  130128. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130129. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130130. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130131. };
  130132. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130133. -1.5, -0.5, 0.5, 1.5,
  130134. };
  130135. static long _vq_quantmap__44c3_s_p8_1[] = {
  130136. 3, 1, 0, 2, 4,
  130137. };
  130138. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130139. _vq_quantthresh__44c3_s_p8_1,
  130140. _vq_quantmap__44c3_s_p8_1,
  130141. 5,
  130142. 5
  130143. };
  130144. static static_codebook _44c3_s_p8_1 = {
  130145. 2, 25,
  130146. _vq_lengthlist__44c3_s_p8_1,
  130147. 1, -533725184, 1611661312, 3, 0,
  130148. _vq_quantlist__44c3_s_p8_1,
  130149. NULL,
  130150. &_vq_auxt__44c3_s_p8_1,
  130151. NULL,
  130152. 0
  130153. };
  130154. static long _vq_quantlist__44c3_s_p9_0[] = {
  130155. 6,
  130156. 5,
  130157. 7,
  130158. 4,
  130159. 8,
  130160. 3,
  130161. 9,
  130162. 2,
  130163. 10,
  130164. 1,
  130165. 11,
  130166. 0,
  130167. 12,
  130168. };
  130169. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130170. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130171. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130172. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130173. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130174. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130175. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130176. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130177. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130178. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130179. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130180. 11,11,11,11,11,11,11,11,11,
  130181. };
  130182. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130183. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130184. 637.5, 892.5, 1147.5, 1402.5,
  130185. };
  130186. static long _vq_quantmap__44c3_s_p9_0[] = {
  130187. 11, 9, 7, 5, 3, 1, 0, 2,
  130188. 4, 6, 8, 10, 12,
  130189. };
  130190. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130191. _vq_quantthresh__44c3_s_p9_0,
  130192. _vq_quantmap__44c3_s_p9_0,
  130193. 13,
  130194. 13
  130195. };
  130196. static static_codebook _44c3_s_p9_0 = {
  130197. 2, 169,
  130198. _vq_lengthlist__44c3_s_p9_0,
  130199. 1, -514332672, 1627381760, 4, 0,
  130200. _vq_quantlist__44c3_s_p9_0,
  130201. NULL,
  130202. &_vq_auxt__44c3_s_p9_0,
  130203. NULL,
  130204. 0
  130205. };
  130206. static long _vq_quantlist__44c3_s_p9_1[] = {
  130207. 7,
  130208. 6,
  130209. 8,
  130210. 5,
  130211. 9,
  130212. 4,
  130213. 10,
  130214. 3,
  130215. 11,
  130216. 2,
  130217. 12,
  130218. 1,
  130219. 13,
  130220. 0,
  130221. 14,
  130222. };
  130223. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130224. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130225. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130226. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130227. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130228. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130229. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130230. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130231. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130232. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130233. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130234. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130235. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130236. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130237. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130238. 15,
  130239. };
  130240. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130241. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130242. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130243. };
  130244. static long _vq_quantmap__44c3_s_p9_1[] = {
  130245. 13, 11, 9, 7, 5, 3, 1, 0,
  130246. 2, 4, 6, 8, 10, 12, 14,
  130247. };
  130248. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130249. _vq_quantthresh__44c3_s_p9_1,
  130250. _vq_quantmap__44c3_s_p9_1,
  130251. 15,
  130252. 15
  130253. };
  130254. static static_codebook _44c3_s_p9_1 = {
  130255. 2, 225,
  130256. _vq_lengthlist__44c3_s_p9_1,
  130257. 1, -522338304, 1620115456, 4, 0,
  130258. _vq_quantlist__44c3_s_p9_1,
  130259. NULL,
  130260. &_vq_auxt__44c3_s_p9_1,
  130261. NULL,
  130262. 0
  130263. };
  130264. static long _vq_quantlist__44c3_s_p9_2[] = {
  130265. 8,
  130266. 7,
  130267. 9,
  130268. 6,
  130269. 10,
  130270. 5,
  130271. 11,
  130272. 4,
  130273. 12,
  130274. 3,
  130275. 13,
  130276. 2,
  130277. 14,
  130278. 1,
  130279. 15,
  130280. 0,
  130281. 16,
  130282. };
  130283. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130284. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130285. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130286. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130287. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130288. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130289. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130290. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130291. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130292. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130293. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130294. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130295. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130296. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130297. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130298. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130299. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130300. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130301. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130302. 10,
  130303. };
  130304. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130305. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130306. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130307. };
  130308. static long _vq_quantmap__44c3_s_p9_2[] = {
  130309. 15, 13, 11, 9, 7, 5, 3, 1,
  130310. 0, 2, 4, 6, 8, 10, 12, 14,
  130311. 16,
  130312. };
  130313. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130314. _vq_quantthresh__44c3_s_p9_2,
  130315. _vq_quantmap__44c3_s_p9_2,
  130316. 17,
  130317. 17
  130318. };
  130319. static static_codebook _44c3_s_p9_2 = {
  130320. 2, 289,
  130321. _vq_lengthlist__44c3_s_p9_2,
  130322. 1, -529530880, 1611661312, 5, 0,
  130323. _vq_quantlist__44c3_s_p9_2,
  130324. NULL,
  130325. &_vq_auxt__44c3_s_p9_2,
  130326. NULL,
  130327. 0
  130328. };
  130329. static long _huff_lengthlist__44c3_s_short[] = {
  130330. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130331. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130332. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130333. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130334. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130335. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130336. 6, 8, 9,11,
  130337. };
  130338. static static_codebook _huff_book__44c3_s_short = {
  130339. 2, 100,
  130340. _huff_lengthlist__44c3_s_short,
  130341. 0, 0, 0, 0, 0,
  130342. NULL,
  130343. NULL,
  130344. NULL,
  130345. NULL,
  130346. 0
  130347. };
  130348. static long _huff_lengthlist__44c4_s_long[] = {
  130349. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130350. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130351. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130352. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130353. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130354. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130355. 9, 8, 7, 7,
  130356. };
  130357. static static_codebook _huff_book__44c4_s_long = {
  130358. 2, 100,
  130359. _huff_lengthlist__44c4_s_long,
  130360. 0, 0, 0, 0, 0,
  130361. NULL,
  130362. NULL,
  130363. NULL,
  130364. NULL,
  130365. 0
  130366. };
  130367. static long _vq_quantlist__44c4_s_p1_0[] = {
  130368. 1,
  130369. 0,
  130370. 2,
  130371. };
  130372. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130373. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130374. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130379. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130384. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  130419. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130424. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130429. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130465. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130470. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130475. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130783. 0,
  130784. };
  130785. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130786. -0.5, 0.5,
  130787. };
  130788. static long _vq_quantmap__44c4_s_p1_0[] = {
  130789. 1, 0, 2,
  130790. };
  130791. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130792. _vq_quantthresh__44c4_s_p1_0,
  130793. _vq_quantmap__44c4_s_p1_0,
  130794. 3,
  130795. 3
  130796. };
  130797. static static_codebook _44c4_s_p1_0 = {
  130798. 8, 6561,
  130799. _vq_lengthlist__44c4_s_p1_0,
  130800. 1, -535822336, 1611661312, 2, 0,
  130801. _vq_quantlist__44c4_s_p1_0,
  130802. NULL,
  130803. &_vq_auxt__44c4_s_p1_0,
  130804. NULL,
  130805. 0
  130806. };
  130807. static long _vq_quantlist__44c4_s_p2_0[] = {
  130808. 2,
  130809. 1,
  130810. 3,
  130811. 0,
  130812. 4,
  130813. };
  130814. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130815. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130816. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130817. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130818. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130819. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130825. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130826. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130827. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130833. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130834. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130841. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130842. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0,
  130855. };
  130856. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130857. -1.5, -0.5, 0.5, 1.5,
  130858. };
  130859. static long _vq_quantmap__44c4_s_p2_0[] = {
  130860. 3, 1, 0, 2, 4,
  130861. };
  130862. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130863. _vq_quantthresh__44c4_s_p2_0,
  130864. _vq_quantmap__44c4_s_p2_0,
  130865. 5,
  130866. 5
  130867. };
  130868. static static_codebook _44c4_s_p2_0 = {
  130869. 4, 625,
  130870. _vq_lengthlist__44c4_s_p2_0,
  130871. 1, -533725184, 1611661312, 3, 0,
  130872. _vq_quantlist__44c4_s_p2_0,
  130873. NULL,
  130874. &_vq_auxt__44c4_s_p2_0,
  130875. NULL,
  130876. 0
  130877. };
  130878. static long _vq_quantlist__44c4_s_p3_0[] = {
  130879. 2,
  130880. 1,
  130881. 3,
  130882. 0,
  130883. 4,
  130884. };
  130885. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130886. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130889. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0,
  130926. };
  130927. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130928. -1.5, -0.5, 0.5, 1.5,
  130929. };
  130930. static long _vq_quantmap__44c4_s_p3_0[] = {
  130931. 3, 1, 0, 2, 4,
  130932. };
  130933. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130934. _vq_quantthresh__44c4_s_p3_0,
  130935. _vq_quantmap__44c4_s_p3_0,
  130936. 5,
  130937. 5
  130938. };
  130939. static static_codebook _44c4_s_p3_0 = {
  130940. 4, 625,
  130941. _vq_lengthlist__44c4_s_p3_0,
  130942. 1, -533725184, 1611661312, 3, 0,
  130943. _vq_quantlist__44c4_s_p3_0,
  130944. NULL,
  130945. &_vq_auxt__44c4_s_p3_0,
  130946. NULL,
  130947. 0
  130948. };
  130949. static long _vq_quantlist__44c4_s_p4_0[] = {
  130950. 4,
  130951. 3,
  130952. 5,
  130953. 2,
  130954. 6,
  130955. 1,
  130956. 7,
  130957. 0,
  130958. 8,
  130959. };
  130960. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130961. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130962. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130963. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130964. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130965. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0,
  130967. };
  130968. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130969. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130970. };
  130971. static long _vq_quantmap__44c4_s_p4_0[] = {
  130972. 7, 5, 3, 1, 0, 2, 4, 6,
  130973. 8,
  130974. };
  130975. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130976. _vq_quantthresh__44c4_s_p4_0,
  130977. _vq_quantmap__44c4_s_p4_0,
  130978. 9,
  130979. 9
  130980. };
  130981. static static_codebook _44c4_s_p4_0 = {
  130982. 2, 81,
  130983. _vq_lengthlist__44c4_s_p4_0,
  130984. 1, -531628032, 1611661312, 4, 0,
  130985. _vq_quantlist__44c4_s_p4_0,
  130986. NULL,
  130987. &_vq_auxt__44c4_s_p4_0,
  130988. NULL,
  130989. 0
  130990. };
  130991. static long _vq_quantlist__44c4_s_p5_0[] = {
  130992. 4,
  130993. 3,
  130994. 5,
  130995. 2,
  130996. 6,
  130997. 1,
  130998. 7,
  130999. 0,
  131000. 8,
  131001. };
  131002. static long _vq_lengthlist__44c4_s_p5_0[] = {
  131003. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131004. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131005. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  131006. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131007. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  131008. 10,
  131009. };
  131010. static float _vq_quantthresh__44c4_s_p5_0[] = {
  131011. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131012. };
  131013. static long _vq_quantmap__44c4_s_p5_0[] = {
  131014. 7, 5, 3, 1, 0, 2, 4, 6,
  131015. 8,
  131016. };
  131017. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  131018. _vq_quantthresh__44c4_s_p5_0,
  131019. _vq_quantmap__44c4_s_p5_0,
  131020. 9,
  131021. 9
  131022. };
  131023. static static_codebook _44c4_s_p5_0 = {
  131024. 2, 81,
  131025. _vq_lengthlist__44c4_s_p5_0,
  131026. 1, -531628032, 1611661312, 4, 0,
  131027. _vq_quantlist__44c4_s_p5_0,
  131028. NULL,
  131029. &_vq_auxt__44c4_s_p5_0,
  131030. NULL,
  131031. 0
  131032. };
  131033. static long _vq_quantlist__44c4_s_p6_0[] = {
  131034. 8,
  131035. 7,
  131036. 9,
  131037. 6,
  131038. 10,
  131039. 5,
  131040. 11,
  131041. 4,
  131042. 12,
  131043. 3,
  131044. 13,
  131045. 2,
  131046. 14,
  131047. 1,
  131048. 15,
  131049. 0,
  131050. 16,
  131051. };
  131052. static long _vq_lengthlist__44c4_s_p6_0[] = {
  131053. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  131054. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131055. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131056. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131057. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131058. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131059. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  131060. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131061. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131062. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  131063. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  131064. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  131065. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  131066. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  131067. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  131068. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131069. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  131071. 13,
  131072. };
  131073. static float _vq_quantthresh__44c4_s_p6_0[] = {
  131074. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131075. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131076. };
  131077. static long _vq_quantmap__44c4_s_p6_0[] = {
  131078. 15, 13, 11, 9, 7, 5, 3, 1,
  131079. 0, 2, 4, 6, 8, 10, 12, 14,
  131080. 16,
  131081. };
  131082. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  131083. _vq_quantthresh__44c4_s_p6_0,
  131084. _vq_quantmap__44c4_s_p6_0,
  131085. 17,
  131086. 17
  131087. };
  131088. static static_codebook _44c4_s_p6_0 = {
  131089. 2, 289,
  131090. _vq_lengthlist__44c4_s_p6_0,
  131091. 1, -529530880, 1611661312, 5, 0,
  131092. _vq_quantlist__44c4_s_p6_0,
  131093. NULL,
  131094. &_vq_auxt__44c4_s_p6_0,
  131095. NULL,
  131096. 0
  131097. };
  131098. static long _vq_quantlist__44c4_s_p7_0[] = {
  131099. 1,
  131100. 0,
  131101. 2,
  131102. };
  131103. static long _vq_lengthlist__44c4_s_p7_0[] = {
  131104. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131105. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131106. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131107. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131108. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131109. 10,
  131110. };
  131111. static float _vq_quantthresh__44c4_s_p7_0[] = {
  131112. -5.5, 5.5,
  131113. };
  131114. static long _vq_quantmap__44c4_s_p7_0[] = {
  131115. 1, 0, 2,
  131116. };
  131117. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131118. _vq_quantthresh__44c4_s_p7_0,
  131119. _vq_quantmap__44c4_s_p7_0,
  131120. 3,
  131121. 3
  131122. };
  131123. static static_codebook _44c4_s_p7_0 = {
  131124. 4, 81,
  131125. _vq_lengthlist__44c4_s_p7_0,
  131126. 1, -529137664, 1618345984, 2, 0,
  131127. _vq_quantlist__44c4_s_p7_0,
  131128. NULL,
  131129. &_vq_auxt__44c4_s_p7_0,
  131130. NULL,
  131131. 0
  131132. };
  131133. static long _vq_quantlist__44c4_s_p7_1[] = {
  131134. 5,
  131135. 4,
  131136. 6,
  131137. 3,
  131138. 7,
  131139. 2,
  131140. 8,
  131141. 1,
  131142. 9,
  131143. 0,
  131144. 10,
  131145. };
  131146. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131147. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131148. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131149. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131150. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131151. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131152. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131153. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131154. 10,10,10, 8, 8, 8, 8, 9, 9,
  131155. };
  131156. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131157. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131158. 3.5, 4.5,
  131159. };
  131160. static long _vq_quantmap__44c4_s_p7_1[] = {
  131161. 9, 7, 5, 3, 1, 0, 2, 4,
  131162. 6, 8, 10,
  131163. };
  131164. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131165. _vq_quantthresh__44c4_s_p7_1,
  131166. _vq_quantmap__44c4_s_p7_1,
  131167. 11,
  131168. 11
  131169. };
  131170. static static_codebook _44c4_s_p7_1 = {
  131171. 2, 121,
  131172. _vq_lengthlist__44c4_s_p7_1,
  131173. 1, -531365888, 1611661312, 4, 0,
  131174. _vq_quantlist__44c4_s_p7_1,
  131175. NULL,
  131176. &_vq_auxt__44c4_s_p7_1,
  131177. NULL,
  131178. 0
  131179. };
  131180. static long _vq_quantlist__44c4_s_p8_0[] = {
  131181. 6,
  131182. 5,
  131183. 7,
  131184. 4,
  131185. 8,
  131186. 3,
  131187. 9,
  131188. 2,
  131189. 10,
  131190. 1,
  131191. 11,
  131192. 0,
  131193. 12,
  131194. };
  131195. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131196. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131197. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131198. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131199. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131200. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131201. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131202. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131203. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131204. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131205. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131206. 0,13,12,12,12,12,12,13,13,
  131207. };
  131208. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131209. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131210. 12.5, 17.5, 22.5, 27.5,
  131211. };
  131212. static long _vq_quantmap__44c4_s_p8_0[] = {
  131213. 11, 9, 7, 5, 3, 1, 0, 2,
  131214. 4, 6, 8, 10, 12,
  131215. };
  131216. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131217. _vq_quantthresh__44c4_s_p8_0,
  131218. _vq_quantmap__44c4_s_p8_0,
  131219. 13,
  131220. 13
  131221. };
  131222. static static_codebook _44c4_s_p8_0 = {
  131223. 2, 169,
  131224. _vq_lengthlist__44c4_s_p8_0,
  131225. 1, -526516224, 1616117760, 4, 0,
  131226. _vq_quantlist__44c4_s_p8_0,
  131227. NULL,
  131228. &_vq_auxt__44c4_s_p8_0,
  131229. NULL,
  131230. 0
  131231. };
  131232. static long _vq_quantlist__44c4_s_p8_1[] = {
  131233. 2,
  131234. 1,
  131235. 3,
  131236. 0,
  131237. 4,
  131238. };
  131239. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131240. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131241. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131242. };
  131243. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131244. -1.5, -0.5, 0.5, 1.5,
  131245. };
  131246. static long _vq_quantmap__44c4_s_p8_1[] = {
  131247. 3, 1, 0, 2, 4,
  131248. };
  131249. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131250. _vq_quantthresh__44c4_s_p8_1,
  131251. _vq_quantmap__44c4_s_p8_1,
  131252. 5,
  131253. 5
  131254. };
  131255. static static_codebook _44c4_s_p8_1 = {
  131256. 2, 25,
  131257. _vq_lengthlist__44c4_s_p8_1,
  131258. 1, -533725184, 1611661312, 3, 0,
  131259. _vq_quantlist__44c4_s_p8_1,
  131260. NULL,
  131261. &_vq_auxt__44c4_s_p8_1,
  131262. NULL,
  131263. 0
  131264. };
  131265. static long _vq_quantlist__44c4_s_p9_0[] = {
  131266. 6,
  131267. 5,
  131268. 7,
  131269. 4,
  131270. 8,
  131271. 3,
  131272. 9,
  131273. 2,
  131274. 10,
  131275. 1,
  131276. 11,
  131277. 0,
  131278. 12,
  131279. };
  131280. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131281. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131282. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131283. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131284. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131285. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131286. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131287. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131288. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131289. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131290. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131291. 12,12,12,12,12,12,12,12,12,
  131292. };
  131293. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131294. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131295. 787.5, 1102.5, 1417.5, 1732.5,
  131296. };
  131297. static long _vq_quantmap__44c4_s_p9_0[] = {
  131298. 11, 9, 7, 5, 3, 1, 0, 2,
  131299. 4, 6, 8, 10, 12,
  131300. };
  131301. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131302. _vq_quantthresh__44c4_s_p9_0,
  131303. _vq_quantmap__44c4_s_p9_0,
  131304. 13,
  131305. 13
  131306. };
  131307. static static_codebook _44c4_s_p9_0 = {
  131308. 2, 169,
  131309. _vq_lengthlist__44c4_s_p9_0,
  131310. 1, -513964032, 1628680192, 4, 0,
  131311. _vq_quantlist__44c4_s_p9_0,
  131312. NULL,
  131313. &_vq_auxt__44c4_s_p9_0,
  131314. NULL,
  131315. 0
  131316. };
  131317. static long _vq_quantlist__44c4_s_p9_1[] = {
  131318. 7,
  131319. 6,
  131320. 8,
  131321. 5,
  131322. 9,
  131323. 4,
  131324. 10,
  131325. 3,
  131326. 11,
  131327. 2,
  131328. 12,
  131329. 1,
  131330. 13,
  131331. 0,
  131332. 14,
  131333. };
  131334. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131335. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131336. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131337. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131338. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131339. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131340. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131341. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131342. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131343. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131344. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131345. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131346. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131347. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131348. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131349. 15,
  131350. };
  131351. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131352. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131353. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131354. };
  131355. static long _vq_quantmap__44c4_s_p9_1[] = {
  131356. 13, 11, 9, 7, 5, 3, 1, 0,
  131357. 2, 4, 6, 8, 10, 12, 14,
  131358. };
  131359. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131360. _vq_quantthresh__44c4_s_p9_1,
  131361. _vq_quantmap__44c4_s_p9_1,
  131362. 15,
  131363. 15
  131364. };
  131365. static static_codebook _44c4_s_p9_1 = {
  131366. 2, 225,
  131367. _vq_lengthlist__44c4_s_p9_1,
  131368. 1, -520986624, 1620377600, 4, 0,
  131369. _vq_quantlist__44c4_s_p9_1,
  131370. NULL,
  131371. &_vq_auxt__44c4_s_p9_1,
  131372. NULL,
  131373. 0
  131374. };
  131375. static long _vq_quantlist__44c4_s_p9_2[] = {
  131376. 10,
  131377. 9,
  131378. 11,
  131379. 8,
  131380. 12,
  131381. 7,
  131382. 13,
  131383. 6,
  131384. 14,
  131385. 5,
  131386. 15,
  131387. 4,
  131388. 16,
  131389. 3,
  131390. 17,
  131391. 2,
  131392. 18,
  131393. 1,
  131394. 19,
  131395. 0,
  131396. 20,
  131397. };
  131398. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131399. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131400. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131401. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131402. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131403. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131404. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131405. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131406. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131407. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131408. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131409. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131410. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131411. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131412. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131413. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131414. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131415. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131416. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131417. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131418. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131419. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131420. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131421. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131422. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131423. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131424. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131425. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131426. 10,10,10,10,10,10,10,10,10,
  131427. };
  131428. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131429. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131430. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131431. 6.5, 7.5, 8.5, 9.5,
  131432. };
  131433. static long _vq_quantmap__44c4_s_p9_2[] = {
  131434. 19, 17, 15, 13, 11, 9, 7, 5,
  131435. 3, 1, 0, 2, 4, 6, 8, 10,
  131436. 12, 14, 16, 18, 20,
  131437. };
  131438. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131439. _vq_quantthresh__44c4_s_p9_2,
  131440. _vq_quantmap__44c4_s_p9_2,
  131441. 21,
  131442. 21
  131443. };
  131444. static static_codebook _44c4_s_p9_2 = {
  131445. 2, 441,
  131446. _vq_lengthlist__44c4_s_p9_2,
  131447. 1, -529268736, 1611661312, 5, 0,
  131448. _vq_quantlist__44c4_s_p9_2,
  131449. NULL,
  131450. &_vq_auxt__44c4_s_p9_2,
  131451. NULL,
  131452. 0
  131453. };
  131454. static long _huff_lengthlist__44c4_s_short[] = {
  131455. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131456. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131457. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131458. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131459. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131460. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131461. 7, 9,12,17,
  131462. };
  131463. static static_codebook _huff_book__44c4_s_short = {
  131464. 2, 100,
  131465. _huff_lengthlist__44c4_s_short,
  131466. 0, 0, 0, 0, 0,
  131467. NULL,
  131468. NULL,
  131469. NULL,
  131470. NULL,
  131471. 0
  131472. };
  131473. static long _huff_lengthlist__44c5_s_long[] = {
  131474. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131475. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131476. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131477. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131478. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131479. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131480. 9, 8, 7, 7,
  131481. };
  131482. static static_codebook _huff_book__44c5_s_long = {
  131483. 2, 100,
  131484. _huff_lengthlist__44c5_s_long,
  131485. 0, 0, 0, 0, 0,
  131486. NULL,
  131487. NULL,
  131488. NULL,
  131489. NULL,
  131490. 0
  131491. };
  131492. static long _vq_quantlist__44c5_s_p1_0[] = {
  131493. 1,
  131494. 0,
  131495. 2,
  131496. };
  131497. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131498. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131499. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131504. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131509. 0, 0, 0, 0, 7, 9, 9, 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, 4, 7, 7, 0, 0, 0, 0,
  131544. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131549. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131554. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131590. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131595. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131600. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131908. 0,
  131909. };
  131910. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131911. -0.5, 0.5,
  131912. };
  131913. static long _vq_quantmap__44c5_s_p1_0[] = {
  131914. 1, 0, 2,
  131915. };
  131916. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131917. _vq_quantthresh__44c5_s_p1_0,
  131918. _vq_quantmap__44c5_s_p1_0,
  131919. 3,
  131920. 3
  131921. };
  131922. static static_codebook _44c5_s_p1_0 = {
  131923. 8, 6561,
  131924. _vq_lengthlist__44c5_s_p1_0,
  131925. 1, -535822336, 1611661312, 2, 0,
  131926. _vq_quantlist__44c5_s_p1_0,
  131927. NULL,
  131928. &_vq_auxt__44c5_s_p1_0,
  131929. NULL,
  131930. 0
  131931. };
  131932. static long _vq_quantlist__44c5_s_p2_0[] = {
  131933. 2,
  131934. 1,
  131935. 3,
  131936. 0,
  131937. 4,
  131938. };
  131939. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131940. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131941. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131942. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131943. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131944. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131950. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131951. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131952. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131958. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131959. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131966. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131967. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131979. 0,
  131980. };
  131981. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131982. -1.5, -0.5, 0.5, 1.5,
  131983. };
  131984. static long _vq_quantmap__44c5_s_p2_0[] = {
  131985. 3, 1, 0, 2, 4,
  131986. };
  131987. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131988. _vq_quantthresh__44c5_s_p2_0,
  131989. _vq_quantmap__44c5_s_p2_0,
  131990. 5,
  131991. 5
  131992. };
  131993. static static_codebook _44c5_s_p2_0 = {
  131994. 4, 625,
  131995. _vq_lengthlist__44c5_s_p2_0,
  131996. 1, -533725184, 1611661312, 3, 0,
  131997. _vq_quantlist__44c5_s_p2_0,
  131998. NULL,
  131999. &_vq_auxt__44c5_s_p2_0,
  132000. NULL,
  132001. 0
  132002. };
  132003. static long _vq_quantlist__44c5_s_p3_0[] = {
  132004. 2,
  132005. 1,
  132006. 3,
  132007. 0,
  132008. 4,
  132009. };
  132010. static long _vq_lengthlist__44c5_s_p3_0[] = {
  132011. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  132013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132014. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  132016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132017. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  132018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132050. 0,
  132051. };
  132052. static float _vq_quantthresh__44c5_s_p3_0[] = {
  132053. -1.5, -0.5, 0.5, 1.5,
  132054. };
  132055. static long _vq_quantmap__44c5_s_p3_0[] = {
  132056. 3, 1, 0, 2, 4,
  132057. };
  132058. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  132059. _vq_quantthresh__44c5_s_p3_0,
  132060. _vq_quantmap__44c5_s_p3_0,
  132061. 5,
  132062. 5
  132063. };
  132064. static static_codebook _44c5_s_p3_0 = {
  132065. 4, 625,
  132066. _vq_lengthlist__44c5_s_p3_0,
  132067. 1, -533725184, 1611661312, 3, 0,
  132068. _vq_quantlist__44c5_s_p3_0,
  132069. NULL,
  132070. &_vq_auxt__44c5_s_p3_0,
  132071. NULL,
  132072. 0
  132073. };
  132074. static long _vq_quantlist__44c5_s_p4_0[] = {
  132075. 4,
  132076. 3,
  132077. 5,
  132078. 2,
  132079. 6,
  132080. 1,
  132081. 7,
  132082. 0,
  132083. 8,
  132084. };
  132085. static long _vq_lengthlist__44c5_s_p4_0[] = {
  132086. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  132087. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  132088. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  132089. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  132090. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132091. 0,
  132092. };
  132093. static float _vq_quantthresh__44c5_s_p4_0[] = {
  132094. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132095. };
  132096. static long _vq_quantmap__44c5_s_p4_0[] = {
  132097. 7, 5, 3, 1, 0, 2, 4, 6,
  132098. 8,
  132099. };
  132100. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  132101. _vq_quantthresh__44c5_s_p4_0,
  132102. _vq_quantmap__44c5_s_p4_0,
  132103. 9,
  132104. 9
  132105. };
  132106. static static_codebook _44c5_s_p4_0 = {
  132107. 2, 81,
  132108. _vq_lengthlist__44c5_s_p4_0,
  132109. 1, -531628032, 1611661312, 4, 0,
  132110. _vq_quantlist__44c5_s_p4_0,
  132111. NULL,
  132112. &_vq_auxt__44c5_s_p4_0,
  132113. NULL,
  132114. 0
  132115. };
  132116. static long _vq_quantlist__44c5_s_p5_0[] = {
  132117. 4,
  132118. 3,
  132119. 5,
  132120. 2,
  132121. 6,
  132122. 1,
  132123. 7,
  132124. 0,
  132125. 8,
  132126. };
  132127. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132128. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132129. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132130. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132131. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132132. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132133. 10,
  132134. };
  132135. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132136. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132137. };
  132138. static long _vq_quantmap__44c5_s_p5_0[] = {
  132139. 7, 5, 3, 1, 0, 2, 4, 6,
  132140. 8,
  132141. };
  132142. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132143. _vq_quantthresh__44c5_s_p5_0,
  132144. _vq_quantmap__44c5_s_p5_0,
  132145. 9,
  132146. 9
  132147. };
  132148. static static_codebook _44c5_s_p5_0 = {
  132149. 2, 81,
  132150. _vq_lengthlist__44c5_s_p5_0,
  132151. 1, -531628032, 1611661312, 4, 0,
  132152. _vq_quantlist__44c5_s_p5_0,
  132153. NULL,
  132154. &_vq_auxt__44c5_s_p5_0,
  132155. NULL,
  132156. 0
  132157. };
  132158. static long _vq_quantlist__44c5_s_p6_0[] = {
  132159. 8,
  132160. 7,
  132161. 9,
  132162. 6,
  132163. 10,
  132164. 5,
  132165. 11,
  132166. 4,
  132167. 12,
  132168. 3,
  132169. 13,
  132170. 2,
  132171. 14,
  132172. 1,
  132173. 15,
  132174. 0,
  132175. 16,
  132176. };
  132177. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132178. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132179. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132180. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132181. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132182. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132183. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132184. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132185. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132186. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132187. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132188. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132189. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132190. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132191. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132192. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132193. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132194. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132195. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132196. 13,
  132197. };
  132198. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132199. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132200. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132201. };
  132202. static long _vq_quantmap__44c5_s_p6_0[] = {
  132203. 15, 13, 11, 9, 7, 5, 3, 1,
  132204. 0, 2, 4, 6, 8, 10, 12, 14,
  132205. 16,
  132206. };
  132207. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132208. _vq_quantthresh__44c5_s_p6_0,
  132209. _vq_quantmap__44c5_s_p6_0,
  132210. 17,
  132211. 17
  132212. };
  132213. static static_codebook _44c5_s_p6_0 = {
  132214. 2, 289,
  132215. _vq_lengthlist__44c5_s_p6_0,
  132216. 1, -529530880, 1611661312, 5, 0,
  132217. _vq_quantlist__44c5_s_p6_0,
  132218. NULL,
  132219. &_vq_auxt__44c5_s_p6_0,
  132220. NULL,
  132221. 0
  132222. };
  132223. static long _vq_quantlist__44c5_s_p7_0[] = {
  132224. 1,
  132225. 0,
  132226. 2,
  132227. };
  132228. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132229. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132230. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132231. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132232. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132233. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132234. 10,
  132235. };
  132236. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132237. -5.5, 5.5,
  132238. };
  132239. static long _vq_quantmap__44c5_s_p7_0[] = {
  132240. 1, 0, 2,
  132241. };
  132242. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132243. _vq_quantthresh__44c5_s_p7_0,
  132244. _vq_quantmap__44c5_s_p7_0,
  132245. 3,
  132246. 3
  132247. };
  132248. static static_codebook _44c5_s_p7_0 = {
  132249. 4, 81,
  132250. _vq_lengthlist__44c5_s_p7_0,
  132251. 1, -529137664, 1618345984, 2, 0,
  132252. _vq_quantlist__44c5_s_p7_0,
  132253. NULL,
  132254. &_vq_auxt__44c5_s_p7_0,
  132255. NULL,
  132256. 0
  132257. };
  132258. static long _vq_quantlist__44c5_s_p7_1[] = {
  132259. 5,
  132260. 4,
  132261. 6,
  132262. 3,
  132263. 7,
  132264. 2,
  132265. 8,
  132266. 1,
  132267. 9,
  132268. 0,
  132269. 10,
  132270. };
  132271. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132272. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132273. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132274. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132275. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132276. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132277. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132278. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132279. 10,10,10, 8, 8, 8, 8, 8, 8,
  132280. };
  132281. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132282. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132283. 3.5, 4.5,
  132284. };
  132285. static long _vq_quantmap__44c5_s_p7_1[] = {
  132286. 9, 7, 5, 3, 1, 0, 2, 4,
  132287. 6, 8, 10,
  132288. };
  132289. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132290. _vq_quantthresh__44c5_s_p7_1,
  132291. _vq_quantmap__44c5_s_p7_1,
  132292. 11,
  132293. 11
  132294. };
  132295. static static_codebook _44c5_s_p7_1 = {
  132296. 2, 121,
  132297. _vq_lengthlist__44c5_s_p7_1,
  132298. 1, -531365888, 1611661312, 4, 0,
  132299. _vq_quantlist__44c5_s_p7_1,
  132300. NULL,
  132301. &_vq_auxt__44c5_s_p7_1,
  132302. NULL,
  132303. 0
  132304. };
  132305. static long _vq_quantlist__44c5_s_p8_0[] = {
  132306. 6,
  132307. 5,
  132308. 7,
  132309. 4,
  132310. 8,
  132311. 3,
  132312. 9,
  132313. 2,
  132314. 10,
  132315. 1,
  132316. 11,
  132317. 0,
  132318. 12,
  132319. };
  132320. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132321. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132322. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132323. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132324. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132325. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132326. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132327. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132328. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132329. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132330. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132331. 0,12,12,12,12,12,12,13,13,
  132332. };
  132333. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132334. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132335. 12.5, 17.5, 22.5, 27.5,
  132336. };
  132337. static long _vq_quantmap__44c5_s_p8_0[] = {
  132338. 11, 9, 7, 5, 3, 1, 0, 2,
  132339. 4, 6, 8, 10, 12,
  132340. };
  132341. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132342. _vq_quantthresh__44c5_s_p8_0,
  132343. _vq_quantmap__44c5_s_p8_0,
  132344. 13,
  132345. 13
  132346. };
  132347. static static_codebook _44c5_s_p8_0 = {
  132348. 2, 169,
  132349. _vq_lengthlist__44c5_s_p8_0,
  132350. 1, -526516224, 1616117760, 4, 0,
  132351. _vq_quantlist__44c5_s_p8_0,
  132352. NULL,
  132353. &_vq_auxt__44c5_s_p8_0,
  132354. NULL,
  132355. 0
  132356. };
  132357. static long _vq_quantlist__44c5_s_p8_1[] = {
  132358. 2,
  132359. 1,
  132360. 3,
  132361. 0,
  132362. 4,
  132363. };
  132364. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132365. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132366. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132367. };
  132368. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132369. -1.5, -0.5, 0.5, 1.5,
  132370. };
  132371. static long _vq_quantmap__44c5_s_p8_1[] = {
  132372. 3, 1, 0, 2, 4,
  132373. };
  132374. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132375. _vq_quantthresh__44c5_s_p8_1,
  132376. _vq_quantmap__44c5_s_p8_1,
  132377. 5,
  132378. 5
  132379. };
  132380. static static_codebook _44c5_s_p8_1 = {
  132381. 2, 25,
  132382. _vq_lengthlist__44c5_s_p8_1,
  132383. 1, -533725184, 1611661312, 3, 0,
  132384. _vq_quantlist__44c5_s_p8_1,
  132385. NULL,
  132386. &_vq_auxt__44c5_s_p8_1,
  132387. NULL,
  132388. 0
  132389. };
  132390. static long _vq_quantlist__44c5_s_p9_0[] = {
  132391. 7,
  132392. 6,
  132393. 8,
  132394. 5,
  132395. 9,
  132396. 4,
  132397. 10,
  132398. 3,
  132399. 11,
  132400. 2,
  132401. 12,
  132402. 1,
  132403. 13,
  132404. 0,
  132405. 14,
  132406. };
  132407. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132408. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132409. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132410. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132411. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132412. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132413. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132414. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132415. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132416. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132417. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132418. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132419. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132420. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132421. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132422. 12,
  132423. };
  132424. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132425. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132426. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132427. };
  132428. static long _vq_quantmap__44c5_s_p9_0[] = {
  132429. 13, 11, 9, 7, 5, 3, 1, 0,
  132430. 2, 4, 6, 8, 10, 12, 14,
  132431. };
  132432. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132433. _vq_quantthresh__44c5_s_p9_0,
  132434. _vq_quantmap__44c5_s_p9_0,
  132435. 15,
  132436. 15
  132437. };
  132438. static static_codebook _44c5_s_p9_0 = {
  132439. 2, 225,
  132440. _vq_lengthlist__44c5_s_p9_0,
  132441. 1, -512522752, 1628852224, 4, 0,
  132442. _vq_quantlist__44c5_s_p9_0,
  132443. NULL,
  132444. &_vq_auxt__44c5_s_p9_0,
  132445. NULL,
  132446. 0
  132447. };
  132448. static long _vq_quantlist__44c5_s_p9_1[] = {
  132449. 8,
  132450. 7,
  132451. 9,
  132452. 6,
  132453. 10,
  132454. 5,
  132455. 11,
  132456. 4,
  132457. 12,
  132458. 3,
  132459. 13,
  132460. 2,
  132461. 14,
  132462. 1,
  132463. 15,
  132464. 0,
  132465. 16,
  132466. };
  132467. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132468. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132469. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132470. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132471. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132472. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132473. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132474. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132475. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132476. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132477. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132478. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132479. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132480. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132481. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132482. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132483. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132484. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132485. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132486. 15,
  132487. };
  132488. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132489. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132490. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132491. };
  132492. static long _vq_quantmap__44c5_s_p9_1[] = {
  132493. 15, 13, 11, 9, 7, 5, 3, 1,
  132494. 0, 2, 4, 6, 8, 10, 12, 14,
  132495. 16,
  132496. };
  132497. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132498. _vq_quantthresh__44c5_s_p9_1,
  132499. _vq_quantmap__44c5_s_p9_1,
  132500. 17,
  132501. 17
  132502. };
  132503. static static_codebook _44c5_s_p9_1 = {
  132504. 2, 289,
  132505. _vq_lengthlist__44c5_s_p9_1,
  132506. 1, -520814592, 1620377600, 5, 0,
  132507. _vq_quantlist__44c5_s_p9_1,
  132508. NULL,
  132509. &_vq_auxt__44c5_s_p9_1,
  132510. NULL,
  132511. 0
  132512. };
  132513. static long _vq_quantlist__44c5_s_p9_2[] = {
  132514. 10,
  132515. 9,
  132516. 11,
  132517. 8,
  132518. 12,
  132519. 7,
  132520. 13,
  132521. 6,
  132522. 14,
  132523. 5,
  132524. 15,
  132525. 4,
  132526. 16,
  132527. 3,
  132528. 17,
  132529. 2,
  132530. 18,
  132531. 1,
  132532. 19,
  132533. 0,
  132534. 20,
  132535. };
  132536. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132537. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132538. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132539. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132540. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132541. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132542. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132543. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132544. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132545. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132546. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132547. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132548. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132549. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132550. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132551. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132552. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132553. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132554. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132555. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132556. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132557. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132558. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132559. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132560. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132561. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132562. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132563. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132564. 10,10,10,10,10,10,10,10,10,
  132565. };
  132566. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132567. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132568. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132569. 6.5, 7.5, 8.5, 9.5,
  132570. };
  132571. static long _vq_quantmap__44c5_s_p9_2[] = {
  132572. 19, 17, 15, 13, 11, 9, 7, 5,
  132573. 3, 1, 0, 2, 4, 6, 8, 10,
  132574. 12, 14, 16, 18, 20,
  132575. };
  132576. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132577. _vq_quantthresh__44c5_s_p9_2,
  132578. _vq_quantmap__44c5_s_p9_2,
  132579. 21,
  132580. 21
  132581. };
  132582. static static_codebook _44c5_s_p9_2 = {
  132583. 2, 441,
  132584. _vq_lengthlist__44c5_s_p9_2,
  132585. 1, -529268736, 1611661312, 5, 0,
  132586. _vq_quantlist__44c5_s_p9_2,
  132587. NULL,
  132588. &_vq_auxt__44c5_s_p9_2,
  132589. NULL,
  132590. 0
  132591. };
  132592. static long _huff_lengthlist__44c5_s_short[] = {
  132593. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132594. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132595. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132596. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132597. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132598. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132599. 6, 8,11,16,
  132600. };
  132601. static static_codebook _huff_book__44c5_s_short = {
  132602. 2, 100,
  132603. _huff_lengthlist__44c5_s_short,
  132604. 0, 0, 0, 0, 0,
  132605. NULL,
  132606. NULL,
  132607. NULL,
  132608. NULL,
  132609. 0
  132610. };
  132611. static long _huff_lengthlist__44c6_s_long[] = {
  132612. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132613. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132614. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132615. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132616. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132617. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132618. 11,10,10,12,
  132619. };
  132620. static static_codebook _huff_book__44c6_s_long = {
  132621. 2, 100,
  132622. _huff_lengthlist__44c6_s_long,
  132623. 0, 0, 0, 0, 0,
  132624. NULL,
  132625. NULL,
  132626. NULL,
  132627. NULL,
  132628. 0
  132629. };
  132630. static long _vq_quantlist__44c6_s_p1_0[] = {
  132631. 1,
  132632. 0,
  132633. 2,
  132634. };
  132635. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132636. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132637. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132638. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132639. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132640. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132641. 8,
  132642. };
  132643. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132644. -0.5, 0.5,
  132645. };
  132646. static long _vq_quantmap__44c6_s_p1_0[] = {
  132647. 1, 0, 2,
  132648. };
  132649. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132650. _vq_quantthresh__44c6_s_p1_0,
  132651. _vq_quantmap__44c6_s_p1_0,
  132652. 3,
  132653. 3
  132654. };
  132655. static static_codebook _44c6_s_p1_0 = {
  132656. 4, 81,
  132657. _vq_lengthlist__44c6_s_p1_0,
  132658. 1, -535822336, 1611661312, 2, 0,
  132659. _vq_quantlist__44c6_s_p1_0,
  132660. NULL,
  132661. &_vq_auxt__44c6_s_p1_0,
  132662. NULL,
  132663. 0
  132664. };
  132665. static long _vq_quantlist__44c6_s_p2_0[] = {
  132666. 2,
  132667. 1,
  132668. 3,
  132669. 0,
  132670. 4,
  132671. };
  132672. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132673. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132674. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132675. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132676. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132677. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132678. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132679. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132680. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132682. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132683. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132684. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132685. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132686. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132687. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132688. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132690. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132691. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132692. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132693. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132694. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132695. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132696. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132698. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132699. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132700. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132701. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132702. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132703. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132704. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132709. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132710. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132711. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132712. 13,
  132713. };
  132714. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132715. -1.5, -0.5, 0.5, 1.5,
  132716. };
  132717. static long _vq_quantmap__44c6_s_p2_0[] = {
  132718. 3, 1, 0, 2, 4,
  132719. };
  132720. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132721. _vq_quantthresh__44c6_s_p2_0,
  132722. _vq_quantmap__44c6_s_p2_0,
  132723. 5,
  132724. 5
  132725. };
  132726. static static_codebook _44c6_s_p2_0 = {
  132727. 4, 625,
  132728. _vq_lengthlist__44c6_s_p2_0,
  132729. 1, -533725184, 1611661312, 3, 0,
  132730. _vq_quantlist__44c6_s_p2_0,
  132731. NULL,
  132732. &_vq_auxt__44c6_s_p2_0,
  132733. NULL,
  132734. 0
  132735. };
  132736. static long _vq_quantlist__44c6_s_p3_0[] = {
  132737. 4,
  132738. 3,
  132739. 5,
  132740. 2,
  132741. 6,
  132742. 1,
  132743. 7,
  132744. 0,
  132745. 8,
  132746. };
  132747. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132748. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132749. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132750. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132751. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132753. 0,
  132754. };
  132755. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132756. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132757. };
  132758. static long _vq_quantmap__44c6_s_p3_0[] = {
  132759. 7, 5, 3, 1, 0, 2, 4, 6,
  132760. 8,
  132761. };
  132762. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132763. _vq_quantthresh__44c6_s_p3_0,
  132764. _vq_quantmap__44c6_s_p3_0,
  132765. 9,
  132766. 9
  132767. };
  132768. static static_codebook _44c6_s_p3_0 = {
  132769. 2, 81,
  132770. _vq_lengthlist__44c6_s_p3_0,
  132771. 1, -531628032, 1611661312, 4, 0,
  132772. _vq_quantlist__44c6_s_p3_0,
  132773. NULL,
  132774. &_vq_auxt__44c6_s_p3_0,
  132775. NULL,
  132776. 0
  132777. };
  132778. static long _vq_quantlist__44c6_s_p4_0[] = {
  132779. 8,
  132780. 7,
  132781. 9,
  132782. 6,
  132783. 10,
  132784. 5,
  132785. 11,
  132786. 4,
  132787. 12,
  132788. 3,
  132789. 13,
  132790. 2,
  132791. 14,
  132792. 1,
  132793. 15,
  132794. 0,
  132795. 16,
  132796. };
  132797. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132798. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132799. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132800. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132801. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132802. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132803. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132804. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132805. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132806. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132807. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132816. 0,
  132817. };
  132818. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132819. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132820. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132821. };
  132822. static long _vq_quantmap__44c6_s_p4_0[] = {
  132823. 15, 13, 11, 9, 7, 5, 3, 1,
  132824. 0, 2, 4, 6, 8, 10, 12, 14,
  132825. 16,
  132826. };
  132827. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132828. _vq_quantthresh__44c6_s_p4_0,
  132829. _vq_quantmap__44c6_s_p4_0,
  132830. 17,
  132831. 17
  132832. };
  132833. static static_codebook _44c6_s_p4_0 = {
  132834. 2, 289,
  132835. _vq_lengthlist__44c6_s_p4_0,
  132836. 1, -529530880, 1611661312, 5, 0,
  132837. _vq_quantlist__44c6_s_p4_0,
  132838. NULL,
  132839. &_vq_auxt__44c6_s_p4_0,
  132840. NULL,
  132841. 0
  132842. };
  132843. static long _vq_quantlist__44c6_s_p5_0[] = {
  132844. 1,
  132845. 0,
  132846. 2,
  132847. };
  132848. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132849. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132850. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132851. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132852. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132853. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132854. 12,
  132855. };
  132856. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132857. -5.5, 5.5,
  132858. };
  132859. static long _vq_quantmap__44c6_s_p5_0[] = {
  132860. 1, 0, 2,
  132861. };
  132862. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132863. _vq_quantthresh__44c6_s_p5_0,
  132864. _vq_quantmap__44c6_s_p5_0,
  132865. 3,
  132866. 3
  132867. };
  132868. static static_codebook _44c6_s_p5_0 = {
  132869. 4, 81,
  132870. _vq_lengthlist__44c6_s_p5_0,
  132871. 1, -529137664, 1618345984, 2, 0,
  132872. _vq_quantlist__44c6_s_p5_0,
  132873. NULL,
  132874. &_vq_auxt__44c6_s_p5_0,
  132875. NULL,
  132876. 0
  132877. };
  132878. static long _vq_quantlist__44c6_s_p5_1[] = {
  132879. 5,
  132880. 4,
  132881. 6,
  132882. 3,
  132883. 7,
  132884. 2,
  132885. 8,
  132886. 1,
  132887. 9,
  132888. 0,
  132889. 10,
  132890. };
  132891. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132892. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132893. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132894. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132895. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132896. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132897. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132898. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132899. 11,10,10, 7, 7, 8, 8, 8, 8,
  132900. };
  132901. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132902. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132903. 3.5, 4.5,
  132904. };
  132905. static long _vq_quantmap__44c6_s_p5_1[] = {
  132906. 9, 7, 5, 3, 1, 0, 2, 4,
  132907. 6, 8, 10,
  132908. };
  132909. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132910. _vq_quantthresh__44c6_s_p5_1,
  132911. _vq_quantmap__44c6_s_p5_1,
  132912. 11,
  132913. 11
  132914. };
  132915. static static_codebook _44c6_s_p5_1 = {
  132916. 2, 121,
  132917. _vq_lengthlist__44c6_s_p5_1,
  132918. 1, -531365888, 1611661312, 4, 0,
  132919. _vq_quantlist__44c6_s_p5_1,
  132920. NULL,
  132921. &_vq_auxt__44c6_s_p5_1,
  132922. NULL,
  132923. 0
  132924. };
  132925. static long _vq_quantlist__44c6_s_p6_0[] = {
  132926. 6,
  132927. 5,
  132928. 7,
  132929. 4,
  132930. 8,
  132931. 3,
  132932. 9,
  132933. 2,
  132934. 10,
  132935. 1,
  132936. 11,
  132937. 0,
  132938. 12,
  132939. };
  132940. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132941. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132942. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132943. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132944. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132945. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132946. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132951. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132952. };
  132953. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132954. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132955. 12.5, 17.5, 22.5, 27.5,
  132956. };
  132957. static long _vq_quantmap__44c6_s_p6_0[] = {
  132958. 11, 9, 7, 5, 3, 1, 0, 2,
  132959. 4, 6, 8, 10, 12,
  132960. };
  132961. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132962. _vq_quantthresh__44c6_s_p6_0,
  132963. _vq_quantmap__44c6_s_p6_0,
  132964. 13,
  132965. 13
  132966. };
  132967. static static_codebook _44c6_s_p6_0 = {
  132968. 2, 169,
  132969. _vq_lengthlist__44c6_s_p6_0,
  132970. 1, -526516224, 1616117760, 4, 0,
  132971. _vq_quantlist__44c6_s_p6_0,
  132972. NULL,
  132973. &_vq_auxt__44c6_s_p6_0,
  132974. NULL,
  132975. 0
  132976. };
  132977. static long _vq_quantlist__44c6_s_p6_1[] = {
  132978. 2,
  132979. 1,
  132980. 3,
  132981. 0,
  132982. 4,
  132983. };
  132984. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132985. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132986. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132987. };
  132988. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132989. -1.5, -0.5, 0.5, 1.5,
  132990. };
  132991. static long _vq_quantmap__44c6_s_p6_1[] = {
  132992. 3, 1, 0, 2, 4,
  132993. };
  132994. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132995. _vq_quantthresh__44c6_s_p6_1,
  132996. _vq_quantmap__44c6_s_p6_1,
  132997. 5,
  132998. 5
  132999. };
  133000. static static_codebook _44c6_s_p6_1 = {
  133001. 2, 25,
  133002. _vq_lengthlist__44c6_s_p6_1,
  133003. 1, -533725184, 1611661312, 3, 0,
  133004. _vq_quantlist__44c6_s_p6_1,
  133005. NULL,
  133006. &_vq_auxt__44c6_s_p6_1,
  133007. NULL,
  133008. 0
  133009. };
  133010. static long _vq_quantlist__44c6_s_p7_0[] = {
  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_p7_0[] = {
  133026. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  133027. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  133028. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  133029. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  133030. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  133031. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  133032. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  133033. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  133034. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  133035. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  133036. 20,13,13,13,13,13,13,14,14,
  133037. };
  133038. static float _vq_quantthresh__44c6_s_p7_0[] = {
  133039. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133040. 27.5, 38.5, 49.5, 60.5,
  133041. };
  133042. static long _vq_quantmap__44c6_s_p7_0[] = {
  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_p7_0 = {
  133047. _vq_quantthresh__44c6_s_p7_0,
  133048. _vq_quantmap__44c6_s_p7_0,
  133049. 13,
  133050. 13
  133051. };
  133052. static static_codebook _44c6_s_p7_0 = {
  133053. 2, 169,
  133054. _vq_lengthlist__44c6_s_p7_0,
  133055. 1, -523206656, 1618345984, 4, 0,
  133056. _vq_quantlist__44c6_s_p7_0,
  133057. NULL,
  133058. &_vq_auxt__44c6_s_p7_0,
  133059. NULL,
  133060. 0
  133061. };
  133062. static long _vq_quantlist__44c6_s_p7_1[] = {
  133063. 5,
  133064. 4,
  133065. 6,
  133066. 3,
  133067. 7,
  133068. 2,
  133069. 8,
  133070. 1,
  133071. 9,
  133072. 0,
  133073. 10,
  133074. };
  133075. static long _vq_lengthlist__44c6_s_p7_1[] = {
  133076. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  133077. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  133078. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  133079. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  133080. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  133081. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  133082. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  133083. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  133084. };
  133085. static float _vq_quantthresh__44c6_s_p7_1[] = {
  133086. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133087. 3.5, 4.5,
  133088. };
  133089. static long _vq_quantmap__44c6_s_p7_1[] = {
  133090. 9, 7, 5, 3, 1, 0, 2, 4,
  133091. 6, 8, 10,
  133092. };
  133093. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  133094. _vq_quantthresh__44c6_s_p7_1,
  133095. _vq_quantmap__44c6_s_p7_1,
  133096. 11,
  133097. 11
  133098. };
  133099. static static_codebook _44c6_s_p7_1 = {
  133100. 2, 121,
  133101. _vq_lengthlist__44c6_s_p7_1,
  133102. 1, -531365888, 1611661312, 4, 0,
  133103. _vq_quantlist__44c6_s_p7_1,
  133104. NULL,
  133105. &_vq_auxt__44c6_s_p7_1,
  133106. NULL,
  133107. 0
  133108. };
  133109. static long _vq_quantlist__44c6_s_p8_0[] = {
  133110. 7,
  133111. 6,
  133112. 8,
  133113. 5,
  133114. 9,
  133115. 4,
  133116. 10,
  133117. 3,
  133118. 11,
  133119. 2,
  133120. 12,
  133121. 1,
  133122. 13,
  133123. 0,
  133124. 14,
  133125. };
  133126. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133127. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133128. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133129. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133130. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133131. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133132. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133133. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133134. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133135. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133136. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133137. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133138. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133139. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133140. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133141. 14,
  133142. };
  133143. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133144. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133145. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133146. };
  133147. static long _vq_quantmap__44c6_s_p8_0[] = {
  133148. 13, 11, 9, 7, 5, 3, 1, 0,
  133149. 2, 4, 6, 8, 10, 12, 14,
  133150. };
  133151. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133152. _vq_quantthresh__44c6_s_p8_0,
  133153. _vq_quantmap__44c6_s_p8_0,
  133154. 15,
  133155. 15
  133156. };
  133157. static static_codebook _44c6_s_p8_0 = {
  133158. 2, 225,
  133159. _vq_lengthlist__44c6_s_p8_0,
  133160. 1, -520986624, 1620377600, 4, 0,
  133161. _vq_quantlist__44c6_s_p8_0,
  133162. NULL,
  133163. &_vq_auxt__44c6_s_p8_0,
  133164. NULL,
  133165. 0
  133166. };
  133167. static long _vq_quantlist__44c6_s_p8_1[] = {
  133168. 10,
  133169. 9,
  133170. 11,
  133171. 8,
  133172. 12,
  133173. 7,
  133174. 13,
  133175. 6,
  133176. 14,
  133177. 5,
  133178. 15,
  133179. 4,
  133180. 16,
  133181. 3,
  133182. 17,
  133183. 2,
  133184. 18,
  133185. 1,
  133186. 19,
  133187. 0,
  133188. 20,
  133189. };
  133190. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133191. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133192. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133193. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133194. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133195. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133196. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133197. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133198. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133199. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133200. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133201. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133202. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133203. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133204. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133205. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133206. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133207. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133208. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133209. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133210. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133211. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133212. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133213. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133214. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133215. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133216. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133217. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133218. 10,10,10,10,10,10,10,10,10,
  133219. };
  133220. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133221. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133222. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133223. 6.5, 7.5, 8.5, 9.5,
  133224. };
  133225. static long _vq_quantmap__44c6_s_p8_1[] = {
  133226. 19, 17, 15, 13, 11, 9, 7, 5,
  133227. 3, 1, 0, 2, 4, 6, 8, 10,
  133228. 12, 14, 16, 18, 20,
  133229. };
  133230. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133231. _vq_quantthresh__44c6_s_p8_1,
  133232. _vq_quantmap__44c6_s_p8_1,
  133233. 21,
  133234. 21
  133235. };
  133236. static static_codebook _44c6_s_p8_1 = {
  133237. 2, 441,
  133238. _vq_lengthlist__44c6_s_p8_1,
  133239. 1, -529268736, 1611661312, 5, 0,
  133240. _vq_quantlist__44c6_s_p8_1,
  133241. NULL,
  133242. &_vq_auxt__44c6_s_p8_1,
  133243. NULL,
  133244. 0
  133245. };
  133246. static long _vq_quantlist__44c6_s_p9_0[] = {
  133247. 6,
  133248. 5,
  133249. 7,
  133250. 4,
  133251. 8,
  133252. 3,
  133253. 9,
  133254. 2,
  133255. 10,
  133256. 1,
  133257. 11,
  133258. 0,
  133259. 12,
  133260. };
  133261. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133262. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133263. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133265. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133266. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133267. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133268. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133269. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133270. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133271. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133272. 10,10,10,10,10,10,10,10,10,
  133273. };
  133274. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133275. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133276. 1592.5, 2229.5, 2866.5, 3503.5,
  133277. };
  133278. static long _vq_quantmap__44c6_s_p9_0[] = {
  133279. 11, 9, 7, 5, 3, 1, 0, 2,
  133280. 4, 6, 8, 10, 12,
  133281. };
  133282. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133283. _vq_quantthresh__44c6_s_p9_0,
  133284. _vq_quantmap__44c6_s_p9_0,
  133285. 13,
  133286. 13
  133287. };
  133288. static static_codebook _44c6_s_p9_0 = {
  133289. 2, 169,
  133290. _vq_lengthlist__44c6_s_p9_0,
  133291. 1, -511845376, 1630791680, 4, 0,
  133292. _vq_quantlist__44c6_s_p9_0,
  133293. NULL,
  133294. &_vq_auxt__44c6_s_p9_0,
  133295. NULL,
  133296. 0
  133297. };
  133298. static long _vq_quantlist__44c6_s_p9_1[] = {
  133299. 6,
  133300. 5,
  133301. 7,
  133302. 4,
  133303. 8,
  133304. 3,
  133305. 9,
  133306. 2,
  133307. 10,
  133308. 1,
  133309. 11,
  133310. 0,
  133311. 12,
  133312. };
  133313. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133314. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133315. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133316. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133317. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133318. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133319. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133320. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133321. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133322. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133323. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133324. 15,12,10,11,11,13,11,12,13,
  133325. };
  133326. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133327. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133328. 122.5, 171.5, 220.5, 269.5,
  133329. };
  133330. static long _vq_quantmap__44c6_s_p9_1[] = {
  133331. 11, 9, 7, 5, 3, 1, 0, 2,
  133332. 4, 6, 8, 10, 12,
  133333. };
  133334. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133335. _vq_quantthresh__44c6_s_p9_1,
  133336. _vq_quantmap__44c6_s_p9_1,
  133337. 13,
  133338. 13
  133339. };
  133340. static static_codebook _44c6_s_p9_1 = {
  133341. 2, 169,
  133342. _vq_lengthlist__44c6_s_p9_1,
  133343. 1, -518889472, 1622704128, 4, 0,
  133344. _vq_quantlist__44c6_s_p9_1,
  133345. NULL,
  133346. &_vq_auxt__44c6_s_p9_1,
  133347. NULL,
  133348. 0
  133349. };
  133350. static long _vq_quantlist__44c6_s_p9_2[] = {
  133351. 24,
  133352. 23,
  133353. 25,
  133354. 22,
  133355. 26,
  133356. 21,
  133357. 27,
  133358. 20,
  133359. 28,
  133360. 19,
  133361. 29,
  133362. 18,
  133363. 30,
  133364. 17,
  133365. 31,
  133366. 16,
  133367. 32,
  133368. 15,
  133369. 33,
  133370. 14,
  133371. 34,
  133372. 13,
  133373. 35,
  133374. 12,
  133375. 36,
  133376. 11,
  133377. 37,
  133378. 10,
  133379. 38,
  133380. 9,
  133381. 39,
  133382. 8,
  133383. 40,
  133384. 7,
  133385. 41,
  133386. 6,
  133387. 42,
  133388. 5,
  133389. 43,
  133390. 4,
  133391. 44,
  133392. 3,
  133393. 45,
  133394. 2,
  133395. 46,
  133396. 1,
  133397. 47,
  133398. 0,
  133399. 48,
  133400. };
  133401. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133402. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133403. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133404. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133405. 7,
  133406. };
  133407. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133408. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133409. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133410. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133411. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133412. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133413. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133414. };
  133415. static long _vq_quantmap__44c6_s_p9_2[] = {
  133416. 47, 45, 43, 41, 39, 37, 35, 33,
  133417. 31, 29, 27, 25, 23, 21, 19, 17,
  133418. 15, 13, 11, 9, 7, 5, 3, 1,
  133419. 0, 2, 4, 6, 8, 10, 12, 14,
  133420. 16, 18, 20, 22, 24, 26, 28, 30,
  133421. 32, 34, 36, 38, 40, 42, 44, 46,
  133422. 48,
  133423. };
  133424. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133425. _vq_quantthresh__44c6_s_p9_2,
  133426. _vq_quantmap__44c6_s_p9_2,
  133427. 49,
  133428. 49
  133429. };
  133430. static static_codebook _44c6_s_p9_2 = {
  133431. 1, 49,
  133432. _vq_lengthlist__44c6_s_p9_2,
  133433. 1, -526909440, 1611661312, 6, 0,
  133434. _vq_quantlist__44c6_s_p9_2,
  133435. NULL,
  133436. &_vq_auxt__44c6_s_p9_2,
  133437. NULL,
  133438. 0
  133439. };
  133440. static long _huff_lengthlist__44c6_s_short[] = {
  133441. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133442. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133443. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133444. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133445. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133446. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133447. 9,10,17,18,
  133448. };
  133449. static static_codebook _huff_book__44c6_s_short = {
  133450. 2, 100,
  133451. _huff_lengthlist__44c6_s_short,
  133452. 0, 0, 0, 0, 0,
  133453. NULL,
  133454. NULL,
  133455. NULL,
  133456. NULL,
  133457. 0
  133458. };
  133459. static long _huff_lengthlist__44c7_s_long[] = {
  133460. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133461. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133462. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133463. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133464. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133465. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133466. 11,10,10,12,
  133467. };
  133468. static static_codebook _huff_book__44c7_s_long = {
  133469. 2, 100,
  133470. _huff_lengthlist__44c7_s_long,
  133471. 0, 0, 0, 0, 0,
  133472. NULL,
  133473. NULL,
  133474. NULL,
  133475. NULL,
  133476. 0
  133477. };
  133478. static long _vq_quantlist__44c7_s_p1_0[] = {
  133479. 1,
  133480. 0,
  133481. 2,
  133482. };
  133483. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133484. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133485. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133486. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133487. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133488. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133489. 8,
  133490. };
  133491. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133492. -0.5, 0.5,
  133493. };
  133494. static long _vq_quantmap__44c7_s_p1_0[] = {
  133495. 1, 0, 2,
  133496. };
  133497. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133498. _vq_quantthresh__44c7_s_p1_0,
  133499. _vq_quantmap__44c7_s_p1_0,
  133500. 3,
  133501. 3
  133502. };
  133503. static static_codebook _44c7_s_p1_0 = {
  133504. 4, 81,
  133505. _vq_lengthlist__44c7_s_p1_0,
  133506. 1, -535822336, 1611661312, 2, 0,
  133507. _vq_quantlist__44c7_s_p1_0,
  133508. NULL,
  133509. &_vq_auxt__44c7_s_p1_0,
  133510. NULL,
  133511. 0
  133512. };
  133513. static long _vq_quantlist__44c7_s_p2_0[] = {
  133514. 2,
  133515. 1,
  133516. 3,
  133517. 0,
  133518. 4,
  133519. };
  133520. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133521. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133522. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133523. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133524. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133525. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133526. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133527. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133528. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133530. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133531. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133532. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133533. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133534. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133535. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133536. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133538. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133539. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133540. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133541. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133542. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133543. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133544. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133546. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133547. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133548. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133549. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133550. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133551. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133552. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133557. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133558. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133559. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133560. 13,
  133561. };
  133562. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133563. -1.5, -0.5, 0.5, 1.5,
  133564. };
  133565. static long _vq_quantmap__44c7_s_p2_0[] = {
  133566. 3, 1, 0, 2, 4,
  133567. };
  133568. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133569. _vq_quantthresh__44c7_s_p2_0,
  133570. _vq_quantmap__44c7_s_p2_0,
  133571. 5,
  133572. 5
  133573. };
  133574. static static_codebook _44c7_s_p2_0 = {
  133575. 4, 625,
  133576. _vq_lengthlist__44c7_s_p2_0,
  133577. 1, -533725184, 1611661312, 3, 0,
  133578. _vq_quantlist__44c7_s_p2_0,
  133579. NULL,
  133580. &_vq_auxt__44c7_s_p2_0,
  133581. NULL,
  133582. 0
  133583. };
  133584. static long _vq_quantlist__44c7_s_p3_0[] = {
  133585. 4,
  133586. 3,
  133587. 5,
  133588. 2,
  133589. 6,
  133590. 1,
  133591. 7,
  133592. 0,
  133593. 8,
  133594. };
  133595. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133596. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133597. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133598. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133599. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133601. 0,
  133602. };
  133603. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133604. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133605. };
  133606. static long _vq_quantmap__44c7_s_p3_0[] = {
  133607. 7, 5, 3, 1, 0, 2, 4, 6,
  133608. 8,
  133609. };
  133610. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133611. _vq_quantthresh__44c7_s_p3_0,
  133612. _vq_quantmap__44c7_s_p3_0,
  133613. 9,
  133614. 9
  133615. };
  133616. static static_codebook _44c7_s_p3_0 = {
  133617. 2, 81,
  133618. _vq_lengthlist__44c7_s_p3_0,
  133619. 1, -531628032, 1611661312, 4, 0,
  133620. _vq_quantlist__44c7_s_p3_0,
  133621. NULL,
  133622. &_vq_auxt__44c7_s_p3_0,
  133623. NULL,
  133624. 0
  133625. };
  133626. static long _vq_quantlist__44c7_s_p4_0[] = {
  133627. 8,
  133628. 7,
  133629. 9,
  133630. 6,
  133631. 10,
  133632. 5,
  133633. 11,
  133634. 4,
  133635. 12,
  133636. 3,
  133637. 13,
  133638. 2,
  133639. 14,
  133640. 1,
  133641. 15,
  133642. 0,
  133643. 16,
  133644. };
  133645. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133646. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133647. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133648. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133649. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133650. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133651. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133652. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133653. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133654. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133655. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133664. 0,
  133665. };
  133666. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133667. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133668. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133669. };
  133670. static long _vq_quantmap__44c7_s_p4_0[] = {
  133671. 15, 13, 11, 9, 7, 5, 3, 1,
  133672. 0, 2, 4, 6, 8, 10, 12, 14,
  133673. 16,
  133674. };
  133675. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133676. _vq_quantthresh__44c7_s_p4_0,
  133677. _vq_quantmap__44c7_s_p4_0,
  133678. 17,
  133679. 17
  133680. };
  133681. static static_codebook _44c7_s_p4_0 = {
  133682. 2, 289,
  133683. _vq_lengthlist__44c7_s_p4_0,
  133684. 1, -529530880, 1611661312, 5, 0,
  133685. _vq_quantlist__44c7_s_p4_0,
  133686. NULL,
  133687. &_vq_auxt__44c7_s_p4_0,
  133688. NULL,
  133689. 0
  133690. };
  133691. static long _vq_quantlist__44c7_s_p5_0[] = {
  133692. 1,
  133693. 0,
  133694. 2,
  133695. };
  133696. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133697. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133698. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133699. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133700. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133701. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133702. 12,
  133703. };
  133704. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133705. -5.5, 5.5,
  133706. };
  133707. static long _vq_quantmap__44c7_s_p5_0[] = {
  133708. 1, 0, 2,
  133709. };
  133710. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133711. _vq_quantthresh__44c7_s_p5_0,
  133712. _vq_quantmap__44c7_s_p5_0,
  133713. 3,
  133714. 3
  133715. };
  133716. static static_codebook _44c7_s_p5_0 = {
  133717. 4, 81,
  133718. _vq_lengthlist__44c7_s_p5_0,
  133719. 1, -529137664, 1618345984, 2, 0,
  133720. _vq_quantlist__44c7_s_p5_0,
  133721. NULL,
  133722. &_vq_auxt__44c7_s_p5_0,
  133723. NULL,
  133724. 0
  133725. };
  133726. static long _vq_quantlist__44c7_s_p5_1[] = {
  133727. 5,
  133728. 4,
  133729. 6,
  133730. 3,
  133731. 7,
  133732. 2,
  133733. 8,
  133734. 1,
  133735. 9,
  133736. 0,
  133737. 10,
  133738. };
  133739. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133740. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133741. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133742. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133743. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133744. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133745. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133746. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133747. 11,11,11, 7, 7, 8, 8, 8, 8,
  133748. };
  133749. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133750. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133751. 3.5, 4.5,
  133752. };
  133753. static long _vq_quantmap__44c7_s_p5_1[] = {
  133754. 9, 7, 5, 3, 1, 0, 2, 4,
  133755. 6, 8, 10,
  133756. };
  133757. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133758. _vq_quantthresh__44c7_s_p5_1,
  133759. _vq_quantmap__44c7_s_p5_1,
  133760. 11,
  133761. 11
  133762. };
  133763. static static_codebook _44c7_s_p5_1 = {
  133764. 2, 121,
  133765. _vq_lengthlist__44c7_s_p5_1,
  133766. 1, -531365888, 1611661312, 4, 0,
  133767. _vq_quantlist__44c7_s_p5_1,
  133768. NULL,
  133769. &_vq_auxt__44c7_s_p5_1,
  133770. NULL,
  133771. 0
  133772. };
  133773. static long _vq_quantlist__44c7_s_p6_0[] = {
  133774. 6,
  133775. 5,
  133776. 7,
  133777. 4,
  133778. 8,
  133779. 3,
  133780. 9,
  133781. 2,
  133782. 10,
  133783. 1,
  133784. 11,
  133785. 0,
  133786. 12,
  133787. };
  133788. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133789. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133790. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133791. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133792. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133793. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133794. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133799. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133800. };
  133801. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133802. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133803. 12.5, 17.5, 22.5, 27.5,
  133804. };
  133805. static long _vq_quantmap__44c7_s_p6_0[] = {
  133806. 11, 9, 7, 5, 3, 1, 0, 2,
  133807. 4, 6, 8, 10, 12,
  133808. };
  133809. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133810. _vq_quantthresh__44c7_s_p6_0,
  133811. _vq_quantmap__44c7_s_p6_0,
  133812. 13,
  133813. 13
  133814. };
  133815. static static_codebook _44c7_s_p6_0 = {
  133816. 2, 169,
  133817. _vq_lengthlist__44c7_s_p6_0,
  133818. 1, -526516224, 1616117760, 4, 0,
  133819. _vq_quantlist__44c7_s_p6_0,
  133820. NULL,
  133821. &_vq_auxt__44c7_s_p6_0,
  133822. NULL,
  133823. 0
  133824. };
  133825. static long _vq_quantlist__44c7_s_p6_1[] = {
  133826. 2,
  133827. 1,
  133828. 3,
  133829. 0,
  133830. 4,
  133831. };
  133832. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133833. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133834. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133835. };
  133836. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133837. -1.5, -0.5, 0.5, 1.5,
  133838. };
  133839. static long _vq_quantmap__44c7_s_p6_1[] = {
  133840. 3, 1, 0, 2, 4,
  133841. };
  133842. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133843. _vq_quantthresh__44c7_s_p6_1,
  133844. _vq_quantmap__44c7_s_p6_1,
  133845. 5,
  133846. 5
  133847. };
  133848. static static_codebook _44c7_s_p6_1 = {
  133849. 2, 25,
  133850. _vq_lengthlist__44c7_s_p6_1,
  133851. 1, -533725184, 1611661312, 3, 0,
  133852. _vq_quantlist__44c7_s_p6_1,
  133853. NULL,
  133854. &_vq_auxt__44c7_s_p6_1,
  133855. NULL,
  133856. 0
  133857. };
  133858. static long _vq_quantlist__44c7_s_p7_0[] = {
  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_p7_0[] = {
  133874. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133875. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133876. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133877. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133878. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133879. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133880. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133881. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133882. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133883. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133884. 19,13,13,13,13,14,14,15,15,
  133885. };
  133886. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133887. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133888. 27.5, 38.5, 49.5, 60.5,
  133889. };
  133890. static long _vq_quantmap__44c7_s_p7_0[] = {
  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_p7_0 = {
  133895. _vq_quantthresh__44c7_s_p7_0,
  133896. _vq_quantmap__44c7_s_p7_0,
  133897. 13,
  133898. 13
  133899. };
  133900. static static_codebook _44c7_s_p7_0 = {
  133901. 2, 169,
  133902. _vq_lengthlist__44c7_s_p7_0,
  133903. 1, -523206656, 1618345984, 4, 0,
  133904. _vq_quantlist__44c7_s_p7_0,
  133905. NULL,
  133906. &_vq_auxt__44c7_s_p7_0,
  133907. NULL,
  133908. 0
  133909. };
  133910. static long _vq_quantlist__44c7_s_p7_1[] = {
  133911. 5,
  133912. 4,
  133913. 6,
  133914. 3,
  133915. 7,
  133916. 2,
  133917. 8,
  133918. 1,
  133919. 9,
  133920. 0,
  133921. 10,
  133922. };
  133923. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133924. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133925. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133926. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133927. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133928. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133929. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133930. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133931. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133932. };
  133933. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133934. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133935. 3.5, 4.5,
  133936. };
  133937. static long _vq_quantmap__44c7_s_p7_1[] = {
  133938. 9, 7, 5, 3, 1, 0, 2, 4,
  133939. 6, 8, 10,
  133940. };
  133941. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133942. _vq_quantthresh__44c7_s_p7_1,
  133943. _vq_quantmap__44c7_s_p7_1,
  133944. 11,
  133945. 11
  133946. };
  133947. static static_codebook _44c7_s_p7_1 = {
  133948. 2, 121,
  133949. _vq_lengthlist__44c7_s_p7_1,
  133950. 1, -531365888, 1611661312, 4, 0,
  133951. _vq_quantlist__44c7_s_p7_1,
  133952. NULL,
  133953. &_vq_auxt__44c7_s_p7_1,
  133954. NULL,
  133955. 0
  133956. };
  133957. static long _vq_quantlist__44c7_s_p8_0[] = {
  133958. 7,
  133959. 6,
  133960. 8,
  133961. 5,
  133962. 9,
  133963. 4,
  133964. 10,
  133965. 3,
  133966. 11,
  133967. 2,
  133968. 12,
  133969. 1,
  133970. 13,
  133971. 0,
  133972. 14,
  133973. };
  133974. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133975. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133976. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133977. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133978. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133979. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133980. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133981. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133982. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133983. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133984. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133985. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133986. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133987. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133988. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133989. 14,
  133990. };
  133991. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133992. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133993. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133994. };
  133995. static long _vq_quantmap__44c7_s_p8_0[] = {
  133996. 13, 11, 9, 7, 5, 3, 1, 0,
  133997. 2, 4, 6, 8, 10, 12, 14,
  133998. };
  133999. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  134000. _vq_quantthresh__44c7_s_p8_0,
  134001. _vq_quantmap__44c7_s_p8_0,
  134002. 15,
  134003. 15
  134004. };
  134005. static static_codebook _44c7_s_p8_0 = {
  134006. 2, 225,
  134007. _vq_lengthlist__44c7_s_p8_0,
  134008. 1, -520986624, 1620377600, 4, 0,
  134009. _vq_quantlist__44c7_s_p8_0,
  134010. NULL,
  134011. &_vq_auxt__44c7_s_p8_0,
  134012. NULL,
  134013. 0
  134014. };
  134015. static long _vq_quantlist__44c7_s_p8_1[] = {
  134016. 10,
  134017. 9,
  134018. 11,
  134019. 8,
  134020. 12,
  134021. 7,
  134022. 13,
  134023. 6,
  134024. 14,
  134025. 5,
  134026. 15,
  134027. 4,
  134028. 16,
  134029. 3,
  134030. 17,
  134031. 2,
  134032. 18,
  134033. 1,
  134034. 19,
  134035. 0,
  134036. 20,
  134037. };
  134038. static long _vq_lengthlist__44c7_s_p8_1[] = {
  134039. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134040. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134041. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134042. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134043. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134044. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134045. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134046. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134047. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134048. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134049. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  134050. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  134051. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  134052. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  134053. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  134054. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  134055. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  134056. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  134057. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  134058. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  134059. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  134060. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  134061. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  134062. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  134063. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  134064. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  134065. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  134066. 10,10,10,10,10,10,10,10,10,
  134067. };
  134068. static float _vq_quantthresh__44c7_s_p8_1[] = {
  134069. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134070. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134071. 6.5, 7.5, 8.5, 9.5,
  134072. };
  134073. static long _vq_quantmap__44c7_s_p8_1[] = {
  134074. 19, 17, 15, 13, 11, 9, 7, 5,
  134075. 3, 1, 0, 2, 4, 6, 8, 10,
  134076. 12, 14, 16, 18, 20,
  134077. };
  134078. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  134079. _vq_quantthresh__44c7_s_p8_1,
  134080. _vq_quantmap__44c7_s_p8_1,
  134081. 21,
  134082. 21
  134083. };
  134084. static static_codebook _44c7_s_p8_1 = {
  134085. 2, 441,
  134086. _vq_lengthlist__44c7_s_p8_1,
  134087. 1, -529268736, 1611661312, 5, 0,
  134088. _vq_quantlist__44c7_s_p8_1,
  134089. NULL,
  134090. &_vq_auxt__44c7_s_p8_1,
  134091. NULL,
  134092. 0
  134093. };
  134094. static long _vq_quantlist__44c7_s_p9_0[] = {
  134095. 6,
  134096. 5,
  134097. 7,
  134098. 4,
  134099. 8,
  134100. 3,
  134101. 9,
  134102. 2,
  134103. 10,
  134104. 1,
  134105. 11,
  134106. 0,
  134107. 12,
  134108. };
  134109. static long _vq_lengthlist__44c7_s_p9_0[] = {
  134110. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  134111. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  134112. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134113. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134114. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134116. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134117. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134118. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134119. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134120. 11,11,11,11,11,11,11,11,11,
  134121. };
  134122. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134123. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134124. 1592.5, 2229.5, 2866.5, 3503.5,
  134125. };
  134126. static long _vq_quantmap__44c7_s_p9_0[] = {
  134127. 11, 9, 7, 5, 3, 1, 0, 2,
  134128. 4, 6, 8, 10, 12,
  134129. };
  134130. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134131. _vq_quantthresh__44c7_s_p9_0,
  134132. _vq_quantmap__44c7_s_p9_0,
  134133. 13,
  134134. 13
  134135. };
  134136. static static_codebook _44c7_s_p9_0 = {
  134137. 2, 169,
  134138. _vq_lengthlist__44c7_s_p9_0,
  134139. 1, -511845376, 1630791680, 4, 0,
  134140. _vq_quantlist__44c7_s_p9_0,
  134141. NULL,
  134142. &_vq_auxt__44c7_s_p9_0,
  134143. NULL,
  134144. 0
  134145. };
  134146. static long _vq_quantlist__44c7_s_p9_1[] = {
  134147. 6,
  134148. 5,
  134149. 7,
  134150. 4,
  134151. 8,
  134152. 3,
  134153. 9,
  134154. 2,
  134155. 10,
  134156. 1,
  134157. 11,
  134158. 0,
  134159. 12,
  134160. };
  134161. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134162. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134163. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134164. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134165. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134166. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134167. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134168. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134169. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134170. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134171. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134172. 15,11,11,10,10,12,12,12,12,
  134173. };
  134174. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134175. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134176. 122.5, 171.5, 220.5, 269.5,
  134177. };
  134178. static long _vq_quantmap__44c7_s_p9_1[] = {
  134179. 11, 9, 7, 5, 3, 1, 0, 2,
  134180. 4, 6, 8, 10, 12,
  134181. };
  134182. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134183. _vq_quantthresh__44c7_s_p9_1,
  134184. _vq_quantmap__44c7_s_p9_1,
  134185. 13,
  134186. 13
  134187. };
  134188. static static_codebook _44c7_s_p9_1 = {
  134189. 2, 169,
  134190. _vq_lengthlist__44c7_s_p9_1,
  134191. 1, -518889472, 1622704128, 4, 0,
  134192. _vq_quantlist__44c7_s_p9_1,
  134193. NULL,
  134194. &_vq_auxt__44c7_s_p9_1,
  134195. NULL,
  134196. 0
  134197. };
  134198. static long _vq_quantlist__44c7_s_p9_2[] = {
  134199. 24,
  134200. 23,
  134201. 25,
  134202. 22,
  134203. 26,
  134204. 21,
  134205. 27,
  134206. 20,
  134207. 28,
  134208. 19,
  134209. 29,
  134210. 18,
  134211. 30,
  134212. 17,
  134213. 31,
  134214. 16,
  134215. 32,
  134216. 15,
  134217. 33,
  134218. 14,
  134219. 34,
  134220. 13,
  134221. 35,
  134222. 12,
  134223. 36,
  134224. 11,
  134225. 37,
  134226. 10,
  134227. 38,
  134228. 9,
  134229. 39,
  134230. 8,
  134231. 40,
  134232. 7,
  134233. 41,
  134234. 6,
  134235. 42,
  134236. 5,
  134237. 43,
  134238. 4,
  134239. 44,
  134240. 3,
  134241. 45,
  134242. 2,
  134243. 46,
  134244. 1,
  134245. 47,
  134246. 0,
  134247. 48,
  134248. };
  134249. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134250. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134251. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134252. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134253. 7,
  134254. };
  134255. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134256. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134257. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134258. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134259. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134260. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134261. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134262. };
  134263. static long _vq_quantmap__44c7_s_p9_2[] = {
  134264. 47, 45, 43, 41, 39, 37, 35, 33,
  134265. 31, 29, 27, 25, 23, 21, 19, 17,
  134266. 15, 13, 11, 9, 7, 5, 3, 1,
  134267. 0, 2, 4, 6, 8, 10, 12, 14,
  134268. 16, 18, 20, 22, 24, 26, 28, 30,
  134269. 32, 34, 36, 38, 40, 42, 44, 46,
  134270. 48,
  134271. };
  134272. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134273. _vq_quantthresh__44c7_s_p9_2,
  134274. _vq_quantmap__44c7_s_p9_2,
  134275. 49,
  134276. 49
  134277. };
  134278. static static_codebook _44c7_s_p9_2 = {
  134279. 1, 49,
  134280. _vq_lengthlist__44c7_s_p9_2,
  134281. 1, -526909440, 1611661312, 6, 0,
  134282. _vq_quantlist__44c7_s_p9_2,
  134283. NULL,
  134284. &_vq_auxt__44c7_s_p9_2,
  134285. NULL,
  134286. 0
  134287. };
  134288. static long _huff_lengthlist__44c7_s_short[] = {
  134289. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134290. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134291. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134292. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134293. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134294. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134295. 10, 9,11,14,
  134296. };
  134297. static static_codebook _huff_book__44c7_s_short = {
  134298. 2, 100,
  134299. _huff_lengthlist__44c7_s_short,
  134300. 0, 0, 0, 0, 0,
  134301. NULL,
  134302. NULL,
  134303. NULL,
  134304. NULL,
  134305. 0
  134306. };
  134307. static long _huff_lengthlist__44c8_s_long[] = {
  134308. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134309. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134310. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134311. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134312. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134313. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134314. 11, 9, 9,10,
  134315. };
  134316. static static_codebook _huff_book__44c8_s_long = {
  134317. 2, 100,
  134318. _huff_lengthlist__44c8_s_long,
  134319. 0, 0, 0, 0, 0,
  134320. NULL,
  134321. NULL,
  134322. NULL,
  134323. NULL,
  134324. 0
  134325. };
  134326. static long _vq_quantlist__44c8_s_p1_0[] = {
  134327. 1,
  134328. 0,
  134329. 2,
  134330. };
  134331. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134332. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134333. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134334. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134335. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134336. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134337. 8,
  134338. };
  134339. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134340. -0.5, 0.5,
  134341. };
  134342. static long _vq_quantmap__44c8_s_p1_0[] = {
  134343. 1, 0, 2,
  134344. };
  134345. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134346. _vq_quantthresh__44c8_s_p1_0,
  134347. _vq_quantmap__44c8_s_p1_0,
  134348. 3,
  134349. 3
  134350. };
  134351. static static_codebook _44c8_s_p1_0 = {
  134352. 4, 81,
  134353. _vq_lengthlist__44c8_s_p1_0,
  134354. 1, -535822336, 1611661312, 2, 0,
  134355. _vq_quantlist__44c8_s_p1_0,
  134356. NULL,
  134357. &_vq_auxt__44c8_s_p1_0,
  134358. NULL,
  134359. 0
  134360. };
  134361. static long _vq_quantlist__44c8_s_p2_0[] = {
  134362. 2,
  134363. 1,
  134364. 3,
  134365. 0,
  134366. 4,
  134367. };
  134368. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134369. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134370. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134371. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134372. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134373. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134374. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134375. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134376. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134378. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134379. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134380. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134381. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134382. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134383. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134384. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134386. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134387. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134388. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134389. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134390. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134391. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134392. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134394. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134395. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134396. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134397. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134398. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134399. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134400. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134405. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134406. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134407. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134408. 13,
  134409. };
  134410. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134411. -1.5, -0.5, 0.5, 1.5,
  134412. };
  134413. static long _vq_quantmap__44c8_s_p2_0[] = {
  134414. 3, 1, 0, 2, 4,
  134415. };
  134416. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134417. _vq_quantthresh__44c8_s_p2_0,
  134418. _vq_quantmap__44c8_s_p2_0,
  134419. 5,
  134420. 5
  134421. };
  134422. static static_codebook _44c8_s_p2_0 = {
  134423. 4, 625,
  134424. _vq_lengthlist__44c8_s_p2_0,
  134425. 1, -533725184, 1611661312, 3, 0,
  134426. _vq_quantlist__44c8_s_p2_0,
  134427. NULL,
  134428. &_vq_auxt__44c8_s_p2_0,
  134429. NULL,
  134430. 0
  134431. };
  134432. static long _vq_quantlist__44c8_s_p3_0[] = {
  134433. 4,
  134434. 3,
  134435. 5,
  134436. 2,
  134437. 6,
  134438. 1,
  134439. 7,
  134440. 0,
  134441. 8,
  134442. };
  134443. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134444. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134445. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134446. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134447. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134449. 0,
  134450. };
  134451. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134452. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134453. };
  134454. static long _vq_quantmap__44c8_s_p3_0[] = {
  134455. 7, 5, 3, 1, 0, 2, 4, 6,
  134456. 8,
  134457. };
  134458. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134459. _vq_quantthresh__44c8_s_p3_0,
  134460. _vq_quantmap__44c8_s_p3_0,
  134461. 9,
  134462. 9
  134463. };
  134464. static static_codebook _44c8_s_p3_0 = {
  134465. 2, 81,
  134466. _vq_lengthlist__44c8_s_p3_0,
  134467. 1, -531628032, 1611661312, 4, 0,
  134468. _vq_quantlist__44c8_s_p3_0,
  134469. NULL,
  134470. &_vq_auxt__44c8_s_p3_0,
  134471. NULL,
  134472. 0
  134473. };
  134474. static long _vq_quantlist__44c8_s_p4_0[] = {
  134475. 8,
  134476. 7,
  134477. 9,
  134478. 6,
  134479. 10,
  134480. 5,
  134481. 11,
  134482. 4,
  134483. 12,
  134484. 3,
  134485. 13,
  134486. 2,
  134487. 14,
  134488. 1,
  134489. 15,
  134490. 0,
  134491. 16,
  134492. };
  134493. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134494. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134495. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134496. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134497. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134498. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134499. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134500. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134501. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134502. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134503. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134512. 0,
  134513. };
  134514. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134515. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134516. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134517. };
  134518. static long _vq_quantmap__44c8_s_p4_0[] = {
  134519. 15, 13, 11, 9, 7, 5, 3, 1,
  134520. 0, 2, 4, 6, 8, 10, 12, 14,
  134521. 16,
  134522. };
  134523. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134524. _vq_quantthresh__44c8_s_p4_0,
  134525. _vq_quantmap__44c8_s_p4_0,
  134526. 17,
  134527. 17
  134528. };
  134529. static static_codebook _44c8_s_p4_0 = {
  134530. 2, 289,
  134531. _vq_lengthlist__44c8_s_p4_0,
  134532. 1, -529530880, 1611661312, 5, 0,
  134533. _vq_quantlist__44c8_s_p4_0,
  134534. NULL,
  134535. &_vq_auxt__44c8_s_p4_0,
  134536. NULL,
  134537. 0
  134538. };
  134539. static long _vq_quantlist__44c8_s_p5_0[] = {
  134540. 1,
  134541. 0,
  134542. 2,
  134543. };
  134544. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134545. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134546. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134547. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134548. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134549. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134550. 12,
  134551. };
  134552. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134553. -5.5, 5.5,
  134554. };
  134555. static long _vq_quantmap__44c8_s_p5_0[] = {
  134556. 1, 0, 2,
  134557. };
  134558. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134559. _vq_quantthresh__44c8_s_p5_0,
  134560. _vq_quantmap__44c8_s_p5_0,
  134561. 3,
  134562. 3
  134563. };
  134564. static static_codebook _44c8_s_p5_0 = {
  134565. 4, 81,
  134566. _vq_lengthlist__44c8_s_p5_0,
  134567. 1, -529137664, 1618345984, 2, 0,
  134568. _vq_quantlist__44c8_s_p5_0,
  134569. NULL,
  134570. &_vq_auxt__44c8_s_p5_0,
  134571. NULL,
  134572. 0
  134573. };
  134574. static long _vq_quantlist__44c8_s_p5_1[] = {
  134575. 5,
  134576. 4,
  134577. 6,
  134578. 3,
  134579. 7,
  134580. 2,
  134581. 8,
  134582. 1,
  134583. 9,
  134584. 0,
  134585. 10,
  134586. };
  134587. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134588. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134589. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134590. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134591. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134592. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134593. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134594. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134595. 11,11,11, 7, 7, 7, 7, 8, 8,
  134596. };
  134597. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134598. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134599. 3.5, 4.5,
  134600. };
  134601. static long _vq_quantmap__44c8_s_p5_1[] = {
  134602. 9, 7, 5, 3, 1, 0, 2, 4,
  134603. 6, 8, 10,
  134604. };
  134605. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134606. _vq_quantthresh__44c8_s_p5_1,
  134607. _vq_quantmap__44c8_s_p5_1,
  134608. 11,
  134609. 11
  134610. };
  134611. static static_codebook _44c8_s_p5_1 = {
  134612. 2, 121,
  134613. _vq_lengthlist__44c8_s_p5_1,
  134614. 1, -531365888, 1611661312, 4, 0,
  134615. _vq_quantlist__44c8_s_p5_1,
  134616. NULL,
  134617. &_vq_auxt__44c8_s_p5_1,
  134618. NULL,
  134619. 0
  134620. };
  134621. static long _vq_quantlist__44c8_s_p6_0[] = {
  134622. 6,
  134623. 5,
  134624. 7,
  134625. 4,
  134626. 8,
  134627. 3,
  134628. 9,
  134629. 2,
  134630. 10,
  134631. 1,
  134632. 11,
  134633. 0,
  134634. 12,
  134635. };
  134636. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134637. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134638. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134639. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134640. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134641. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134642. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134647. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134648. };
  134649. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134650. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134651. 12.5, 17.5, 22.5, 27.5,
  134652. };
  134653. static long _vq_quantmap__44c8_s_p6_0[] = {
  134654. 11, 9, 7, 5, 3, 1, 0, 2,
  134655. 4, 6, 8, 10, 12,
  134656. };
  134657. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134658. _vq_quantthresh__44c8_s_p6_0,
  134659. _vq_quantmap__44c8_s_p6_0,
  134660. 13,
  134661. 13
  134662. };
  134663. static static_codebook _44c8_s_p6_0 = {
  134664. 2, 169,
  134665. _vq_lengthlist__44c8_s_p6_0,
  134666. 1, -526516224, 1616117760, 4, 0,
  134667. _vq_quantlist__44c8_s_p6_0,
  134668. NULL,
  134669. &_vq_auxt__44c8_s_p6_0,
  134670. NULL,
  134671. 0
  134672. };
  134673. static long _vq_quantlist__44c8_s_p6_1[] = {
  134674. 2,
  134675. 1,
  134676. 3,
  134677. 0,
  134678. 4,
  134679. };
  134680. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134681. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134682. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134683. };
  134684. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134685. -1.5, -0.5, 0.5, 1.5,
  134686. };
  134687. static long _vq_quantmap__44c8_s_p6_1[] = {
  134688. 3, 1, 0, 2, 4,
  134689. };
  134690. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134691. _vq_quantthresh__44c8_s_p6_1,
  134692. _vq_quantmap__44c8_s_p6_1,
  134693. 5,
  134694. 5
  134695. };
  134696. static static_codebook _44c8_s_p6_1 = {
  134697. 2, 25,
  134698. _vq_lengthlist__44c8_s_p6_1,
  134699. 1, -533725184, 1611661312, 3, 0,
  134700. _vq_quantlist__44c8_s_p6_1,
  134701. NULL,
  134702. &_vq_auxt__44c8_s_p6_1,
  134703. NULL,
  134704. 0
  134705. };
  134706. static long _vq_quantlist__44c8_s_p7_0[] = {
  134707. 6,
  134708. 5,
  134709. 7,
  134710. 4,
  134711. 8,
  134712. 3,
  134713. 9,
  134714. 2,
  134715. 10,
  134716. 1,
  134717. 11,
  134718. 0,
  134719. 12,
  134720. };
  134721. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134722. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134723. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134724. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134725. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134726. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134727. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134728. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134729. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134730. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134731. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134732. 20,13,13,13,13,14,13,15,15,
  134733. };
  134734. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134735. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134736. 27.5, 38.5, 49.5, 60.5,
  134737. };
  134738. static long _vq_quantmap__44c8_s_p7_0[] = {
  134739. 11, 9, 7, 5, 3, 1, 0, 2,
  134740. 4, 6, 8, 10, 12,
  134741. };
  134742. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134743. _vq_quantthresh__44c8_s_p7_0,
  134744. _vq_quantmap__44c8_s_p7_0,
  134745. 13,
  134746. 13
  134747. };
  134748. static static_codebook _44c8_s_p7_0 = {
  134749. 2, 169,
  134750. _vq_lengthlist__44c8_s_p7_0,
  134751. 1, -523206656, 1618345984, 4, 0,
  134752. _vq_quantlist__44c8_s_p7_0,
  134753. NULL,
  134754. &_vq_auxt__44c8_s_p7_0,
  134755. NULL,
  134756. 0
  134757. };
  134758. static long _vq_quantlist__44c8_s_p7_1[] = {
  134759. 5,
  134760. 4,
  134761. 6,
  134762. 3,
  134763. 7,
  134764. 2,
  134765. 8,
  134766. 1,
  134767. 9,
  134768. 0,
  134769. 10,
  134770. };
  134771. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134772. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134773. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134774. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134775. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134776. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134777. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134778. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134779. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134780. };
  134781. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134782. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134783. 3.5, 4.5,
  134784. };
  134785. static long _vq_quantmap__44c8_s_p7_1[] = {
  134786. 9, 7, 5, 3, 1, 0, 2, 4,
  134787. 6, 8, 10,
  134788. };
  134789. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134790. _vq_quantthresh__44c8_s_p7_1,
  134791. _vq_quantmap__44c8_s_p7_1,
  134792. 11,
  134793. 11
  134794. };
  134795. static static_codebook _44c8_s_p7_1 = {
  134796. 2, 121,
  134797. _vq_lengthlist__44c8_s_p7_1,
  134798. 1, -531365888, 1611661312, 4, 0,
  134799. _vq_quantlist__44c8_s_p7_1,
  134800. NULL,
  134801. &_vq_auxt__44c8_s_p7_1,
  134802. NULL,
  134803. 0
  134804. };
  134805. static long _vq_quantlist__44c8_s_p8_0[] = {
  134806. 7,
  134807. 6,
  134808. 8,
  134809. 5,
  134810. 9,
  134811. 4,
  134812. 10,
  134813. 3,
  134814. 11,
  134815. 2,
  134816. 12,
  134817. 1,
  134818. 13,
  134819. 0,
  134820. 14,
  134821. };
  134822. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134823. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134824. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134825. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134826. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134827. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134828. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134829. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134830. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134831. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134832. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134833. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134834. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134835. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134836. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134837. 15,
  134838. };
  134839. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134840. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134841. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134842. };
  134843. static long _vq_quantmap__44c8_s_p8_0[] = {
  134844. 13, 11, 9, 7, 5, 3, 1, 0,
  134845. 2, 4, 6, 8, 10, 12, 14,
  134846. };
  134847. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134848. _vq_quantthresh__44c8_s_p8_0,
  134849. _vq_quantmap__44c8_s_p8_0,
  134850. 15,
  134851. 15
  134852. };
  134853. static static_codebook _44c8_s_p8_0 = {
  134854. 2, 225,
  134855. _vq_lengthlist__44c8_s_p8_0,
  134856. 1, -520986624, 1620377600, 4, 0,
  134857. _vq_quantlist__44c8_s_p8_0,
  134858. NULL,
  134859. &_vq_auxt__44c8_s_p8_0,
  134860. NULL,
  134861. 0
  134862. };
  134863. static long _vq_quantlist__44c8_s_p8_1[] = {
  134864. 10,
  134865. 9,
  134866. 11,
  134867. 8,
  134868. 12,
  134869. 7,
  134870. 13,
  134871. 6,
  134872. 14,
  134873. 5,
  134874. 15,
  134875. 4,
  134876. 16,
  134877. 3,
  134878. 17,
  134879. 2,
  134880. 18,
  134881. 1,
  134882. 19,
  134883. 0,
  134884. 20,
  134885. };
  134886. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134887. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134888. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134889. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134890. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134891. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134892. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134893. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134894. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134895. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134896. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134897. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134898. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134899. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134900. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134901. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134902. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134903. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134904. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134905. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134906. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134907. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134908. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134909. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134910. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134911. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134912. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134913. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134914. 10, 9, 9,10,10, 9,10, 9, 9,
  134915. };
  134916. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134917. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134918. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134919. 6.5, 7.5, 8.5, 9.5,
  134920. };
  134921. static long _vq_quantmap__44c8_s_p8_1[] = {
  134922. 19, 17, 15, 13, 11, 9, 7, 5,
  134923. 3, 1, 0, 2, 4, 6, 8, 10,
  134924. 12, 14, 16, 18, 20,
  134925. };
  134926. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134927. _vq_quantthresh__44c8_s_p8_1,
  134928. _vq_quantmap__44c8_s_p8_1,
  134929. 21,
  134930. 21
  134931. };
  134932. static static_codebook _44c8_s_p8_1 = {
  134933. 2, 441,
  134934. _vq_lengthlist__44c8_s_p8_1,
  134935. 1, -529268736, 1611661312, 5, 0,
  134936. _vq_quantlist__44c8_s_p8_1,
  134937. NULL,
  134938. &_vq_auxt__44c8_s_p8_1,
  134939. NULL,
  134940. 0
  134941. };
  134942. static long _vq_quantlist__44c8_s_p9_0[] = {
  134943. 8,
  134944. 7,
  134945. 9,
  134946. 6,
  134947. 10,
  134948. 5,
  134949. 11,
  134950. 4,
  134951. 12,
  134952. 3,
  134953. 13,
  134954. 2,
  134955. 14,
  134956. 1,
  134957. 15,
  134958. 0,
  134959. 16,
  134960. };
  134961. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134962. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134963. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134964. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134965. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134966. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134967. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134968. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134969. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134970. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134971. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134972. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134973. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134974. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134975. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134976. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134977. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134978. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134979. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134980. 10,
  134981. };
  134982. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134983. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134984. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134985. };
  134986. static long _vq_quantmap__44c8_s_p9_0[] = {
  134987. 15, 13, 11, 9, 7, 5, 3, 1,
  134988. 0, 2, 4, 6, 8, 10, 12, 14,
  134989. 16,
  134990. };
  134991. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134992. _vq_quantthresh__44c8_s_p9_0,
  134993. _vq_quantmap__44c8_s_p9_0,
  134994. 17,
  134995. 17
  134996. };
  134997. static static_codebook _44c8_s_p9_0 = {
  134998. 2, 289,
  134999. _vq_lengthlist__44c8_s_p9_0,
  135000. 1, -509798400, 1631393792, 5, 0,
  135001. _vq_quantlist__44c8_s_p9_0,
  135002. NULL,
  135003. &_vq_auxt__44c8_s_p9_0,
  135004. NULL,
  135005. 0
  135006. };
  135007. static long _vq_quantlist__44c8_s_p9_1[] = {
  135008. 9,
  135009. 8,
  135010. 10,
  135011. 7,
  135012. 11,
  135013. 6,
  135014. 12,
  135015. 5,
  135016. 13,
  135017. 4,
  135018. 14,
  135019. 3,
  135020. 15,
  135021. 2,
  135022. 16,
  135023. 1,
  135024. 17,
  135025. 0,
  135026. 18,
  135027. };
  135028. static long _vq_lengthlist__44c8_s_p9_1[] = {
  135029. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  135030. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  135031. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  135032. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  135033. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  135034. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  135035. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  135036. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  135037. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  135038. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  135039. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  135040. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  135041. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  135042. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  135043. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  135044. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  135045. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  135046. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  135047. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  135048. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  135049. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  135050. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  135051. 14,13,13,14,14,15,14,15,14,
  135052. };
  135053. static float _vq_quantthresh__44c8_s_p9_1[] = {
  135054. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135055. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135056. 367.5, 416.5,
  135057. };
  135058. static long _vq_quantmap__44c8_s_p9_1[] = {
  135059. 17, 15, 13, 11, 9, 7, 5, 3,
  135060. 1, 0, 2, 4, 6, 8, 10, 12,
  135061. 14, 16, 18,
  135062. };
  135063. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  135064. _vq_quantthresh__44c8_s_p9_1,
  135065. _vq_quantmap__44c8_s_p9_1,
  135066. 19,
  135067. 19
  135068. };
  135069. static static_codebook _44c8_s_p9_1 = {
  135070. 2, 361,
  135071. _vq_lengthlist__44c8_s_p9_1,
  135072. 1, -518287360, 1622704128, 5, 0,
  135073. _vq_quantlist__44c8_s_p9_1,
  135074. NULL,
  135075. &_vq_auxt__44c8_s_p9_1,
  135076. NULL,
  135077. 0
  135078. };
  135079. static long _vq_quantlist__44c8_s_p9_2[] = {
  135080. 24,
  135081. 23,
  135082. 25,
  135083. 22,
  135084. 26,
  135085. 21,
  135086. 27,
  135087. 20,
  135088. 28,
  135089. 19,
  135090. 29,
  135091. 18,
  135092. 30,
  135093. 17,
  135094. 31,
  135095. 16,
  135096. 32,
  135097. 15,
  135098. 33,
  135099. 14,
  135100. 34,
  135101. 13,
  135102. 35,
  135103. 12,
  135104. 36,
  135105. 11,
  135106. 37,
  135107. 10,
  135108. 38,
  135109. 9,
  135110. 39,
  135111. 8,
  135112. 40,
  135113. 7,
  135114. 41,
  135115. 6,
  135116. 42,
  135117. 5,
  135118. 43,
  135119. 4,
  135120. 44,
  135121. 3,
  135122. 45,
  135123. 2,
  135124. 46,
  135125. 1,
  135126. 47,
  135127. 0,
  135128. 48,
  135129. };
  135130. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135131. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135132. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135133. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135134. 7,
  135135. };
  135136. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135137. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135138. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135139. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135140. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135141. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135142. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135143. };
  135144. static long _vq_quantmap__44c8_s_p9_2[] = {
  135145. 47, 45, 43, 41, 39, 37, 35, 33,
  135146. 31, 29, 27, 25, 23, 21, 19, 17,
  135147. 15, 13, 11, 9, 7, 5, 3, 1,
  135148. 0, 2, 4, 6, 8, 10, 12, 14,
  135149. 16, 18, 20, 22, 24, 26, 28, 30,
  135150. 32, 34, 36, 38, 40, 42, 44, 46,
  135151. 48,
  135152. };
  135153. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135154. _vq_quantthresh__44c8_s_p9_2,
  135155. _vq_quantmap__44c8_s_p9_2,
  135156. 49,
  135157. 49
  135158. };
  135159. static static_codebook _44c8_s_p9_2 = {
  135160. 1, 49,
  135161. _vq_lengthlist__44c8_s_p9_2,
  135162. 1, -526909440, 1611661312, 6, 0,
  135163. _vq_quantlist__44c8_s_p9_2,
  135164. NULL,
  135165. &_vq_auxt__44c8_s_p9_2,
  135166. NULL,
  135167. 0
  135168. };
  135169. static long _huff_lengthlist__44c8_s_short[] = {
  135170. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135171. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135172. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135173. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135174. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135175. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135176. 10, 9,11,14,
  135177. };
  135178. static static_codebook _huff_book__44c8_s_short = {
  135179. 2, 100,
  135180. _huff_lengthlist__44c8_s_short,
  135181. 0, 0, 0, 0, 0,
  135182. NULL,
  135183. NULL,
  135184. NULL,
  135185. NULL,
  135186. 0
  135187. };
  135188. static long _huff_lengthlist__44c9_s_long[] = {
  135189. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135190. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135191. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135192. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135193. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135194. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135195. 10, 9, 8, 9,
  135196. };
  135197. static static_codebook _huff_book__44c9_s_long = {
  135198. 2, 100,
  135199. _huff_lengthlist__44c9_s_long,
  135200. 0, 0, 0, 0, 0,
  135201. NULL,
  135202. NULL,
  135203. NULL,
  135204. NULL,
  135205. 0
  135206. };
  135207. static long _vq_quantlist__44c9_s_p1_0[] = {
  135208. 1,
  135209. 0,
  135210. 2,
  135211. };
  135212. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135213. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135214. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135215. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135216. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135217. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135218. 7,
  135219. };
  135220. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135221. -0.5, 0.5,
  135222. };
  135223. static long _vq_quantmap__44c9_s_p1_0[] = {
  135224. 1, 0, 2,
  135225. };
  135226. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135227. _vq_quantthresh__44c9_s_p1_0,
  135228. _vq_quantmap__44c9_s_p1_0,
  135229. 3,
  135230. 3
  135231. };
  135232. static static_codebook _44c9_s_p1_0 = {
  135233. 4, 81,
  135234. _vq_lengthlist__44c9_s_p1_0,
  135235. 1, -535822336, 1611661312, 2, 0,
  135236. _vq_quantlist__44c9_s_p1_0,
  135237. NULL,
  135238. &_vq_auxt__44c9_s_p1_0,
  135239. NULL,
  135240. 0
  135241. };
  135242. static long _vq_quantlist__44c9_s_p2_0[] = {
  135243. 2,
  135244. 1,
  135245. 3,
  135246. 0,
  135247. 4,
  135248. };
  135249. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135250. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135251. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135252. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135253. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135254. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135255. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135256. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135257. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135259. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135260. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135261. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135262. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135263. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135264. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135265. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135267. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135268. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135269. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135270. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135271. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135272. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135273. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135276. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135277. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135278. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135279. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135280. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135281. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135286. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135287. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135288. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135289. 12,
  135290. };
  135291. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135292. -1.5, -0.5, 0.5, 1.5,
  135293. };
  135294. static long _vq_quantmap__44c9_s_p2_0[] = {
  135295. 3, 1, 0, 2, 4,
  135296. };
  135297. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135298. _vq_quantthresh__44c9_s_p2_0,
  135299. _vq_quantmap__44c9_s_p2_0,
  135300. 5,
  135301. 5
  135302. };
  135303. static static_codebook _44c9_s_p2_0 = {
  135304. 4, 625,
  135305. _vq_lengthlist__44c9_s_p2_0,
  135306. 1, -533725184, 1611661312, 3, 0,
  135307. _vq_quantlist__44c9_s_p2_0,
  135308. NULL,
  135309. &_vq_auxt__44c9_s_p2_0,
  135310. NULL,
  135311. 0
  135312. };
  135313. static long _vq_quantlist__44c9_s_p3_0[] = {
  135314. 4,
  135315. 3,
  135316. 5,
  135317. 2,
  135318. 6,
  135319. 1,
  135320. 7,
  135321. 0,
  135322. 8,
  135323. };
  135324. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135325. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135326. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135327. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135328. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0,
  135331. };
  135332. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135333. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135334. };
  135335. static long _vq_quantmap__44c9_s_p3_0[] = {
  135336. 7, 5, 3, 1, 0, 2, 4, 6,
  135337. 8,
  135338. };
  135339. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135340. _vq_quantthresh__44c9_s_p3_0,
  135341. _vq_quantmap__44c9_s_p3_0,
  135342. 9,
  135343. 9
  135344. };
  135345. static static_codebook _44c9_s_p3_0 = {
  135346. 2, 81,
  135347. _vq_lengthlist__44c9_s_p3_0,
  135348. 1, -531628032, 1611661312, 4, 0,
  135349. _vq_quantlist__44c9_s_p3_0,
  135350. NULL,
  135351. &_vq_auxt__44c9_s_p3_0,
  135352. NULL,
  135353. 0
  135354. };
  135355. static long _vq_quantlist__44c9_s_p4_0[] = {
  135356. 8,
  135357. 7,
  135358. 9,
  135359. 6,
  135360. 10,
  135361. 5,
  135362. 11,
  135363. 4,
  135364. 12,
  135365. 3,
  135366. 13,
  135367. 2,
  135368. 14,
  135369. 1,
  135370. 15,
  135371. 0,
  135372. 16,
  135373. };
  135374. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135375. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135376. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135377. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135378. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135379. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135380. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135381. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135382. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135383. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135384. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135393. 0,
  135394. };
  135395. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135396. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135397. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135398. };
  135399. static long _vq_quantmap__44c9_s_p4_0[] = {
  135400. 15, 13, 11, 9, 7, 5, 3, 1,
  135401. 0, 2, 4, 6, 8, 10, 12, 14,
  135402. 16,
  135403. };
  135404. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135405. _vq_quantthresh__44c9_s_p4_0,
  135406. _vq_quantmap__44c9_s_p4_0,
  135407. 17,
  135408. 17
  135409. };
  135410. static static_codebook _44c9_s_p4_0 = {
  135411. 2, 289,
  135412. _vq_lengthlist__44c9_s_p4_0,
  135413. 1, -529530880, 1611661312, 5, 0,
  135414. _vq_quantlist__44c9_s_p4_0,
  135415. NULL,
  135416. &_vq_auxt__44c9_s_p4_0,
  135417. NULL,
  135418. 0
  135419. };
  135420. static long _vq_quantlist__44c9_s_p5_0[] = {
  135421. 1,
  135422. 0,
  135423. 2,
  135424. };
  135425. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135426. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135427. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135428. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135429. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135430. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135431. 12,
  135432. };
  135433. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135434. -5.5, 5.5,
  135435. };
  135436. static long _vq_quantmap__44c9_s_p5_0[] = {
  135437. 1, 0, 2,
  135438. };
  135439. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135440. _vq_quantthresh__44c9_s_p5_0,
  135441. _vq_quantmap__44c9_s_p5_0,
  135442. 3,
  135443. 3
  135444. };
  135445. static static_codebook _44c9_s_p5_0 = {
  135446. 4, 81,
  135447. _vq_lengthlist__44c9_s_p5_0,
  135448. 1, -529137664, 1618345984, 2, 0,
  135449. _vq_quantlist__44c9_s_p5_0,
  135450. NULL,
  135451. &_vq_auxt__44c9_s_p5_0,
  135452. NULL,
  135453. 0
  135454. };
  135455. static long _vq_quantlist__44c9_s_p5_1[] = {
  135456. 5,
  135457. 4,
  135458. 6,
  135459. 3,
  135460. 7,
  135461. 2,
  135462. 8,
  135463. 1,
  135464. 9,
  135465. 0,
  135466. 10,
  135467. };
  135468. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135469. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135470. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135471. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135472. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135473. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135474. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135475. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135476. 11,11,11, 7, 7, 7, 7, 7, 7,
  135477. };
  135478. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135479. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135480. 3.5, 4.5,
  135481. };
  135482. static long _vq_quantmap__44c9_s_p5_1[] = {
  135483. 9, 7, 5, 3, 1, 0, 2, 4,
  135484. 6, 8, 10,
  135485. };
  135486. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135487. _vq_quantthresh__44c9_s_p5_1,
  135488. _vq_quantmap__44c9_s_p5_1,
  135489. 11,
  135490. 11
  135491. };
  135492. static static_codebook _44c9_s_p5_1 = {
  135493. 2, 121,
  135494. _vq_lengthlist__44c9_s_p5_1,
  135495. 1, -531365888, 1611661312, 4, 0,
  135496. _vq_quantlist__44c9_s_p5_1,
  135497. NULL,
  135498. &_vq_auxt__44c9_s_p5_1,
  135499. NULL,
  135500. 0
  135501. };
  135502. static long _vq_quantlist__44c9_s_p6_0[] = {
  135503. 6,
  135504. 5,
  135505. 7,
  135506. 4,
  135507. 8,
  135508. 3,
  135509. 9,
  135510. 2,
  135511. 10,
  135512. 1,
  135513. 11,
  135514. 0,
  135515. 12,
  135516. };
  135517. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135518. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135519. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135520. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135521. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135522. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135523. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. };
  135530. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135531. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135532. 12.5, 17.5, 22.5, 27.5,
  135533. };
  135534. static long _vq_quantmap__44c9_s_p6_0[] = {
  135535. 11, 9, 7, 5, 3, 1, 0, 2,
  135536. 4, 6, 8, 10, 12,
  135537. };
  135538. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135539. _vq_quantthresh__44c9_s_p6_0,
  135540. _vq_quantmap__44c9_s_p6_0,
  135541. 13,
  135542. 13
  135543. };
  135544. static static_codebook _44c9_s_p6_0 = {
  135545. 2, 169,
  135546. _vq_lengthlist__44c9_s_p6_0,
  135547. 1, -526516224, 1616117760, 4, 0,
  135548. _vq_quantlist__44c9_s_p6_0,
  135549. NULL,
  135550. &_vq_auxt__44c9_s_p6_0,
  135551. NULL,
  135552. 0
  135553. };
  135554. static long _vq_quantlist__44c9_s_p6_1[] = {
  135555. 2,
  135556. 1,
  135557. 3,
  135558. 0,
  135559. 4,
  135560. };
  135561. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135562. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135563. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135564. };
  135565. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135566. -1.5, -0.5, 0.5, 1.5,
  135567. };
  135568. static long _vq_quantmap__44c9_s_p6_1[] = {
  135569. 3, 1, 0, 2, 4,
  135570. };
  135571. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135572. _vq_quantthresh__44c9_s_p6_1,
  135573. _vq_quantmap__44c9_s_p6_1,
  135574. 5,
  135575. 5
  135576. };
  135577. static static_codebook _44c9_s_p6_1 = {
  135578. 2, 25,
  135579. _vq_lengthlist__44c9_s_p6_1,
  135580. 1, -533725184, 1611661312, 3, 0,
  135581. _vq_quantlist__44c9_s_p6_1,
  135582. NULL,
  135583. &_vq_auxt__44c9_s_p6_1,
  135584. NULL,
  135585. 0
  135586. };
  135587. static long _vq_quantlist__44c9_s_p7_0[] = {
  135588. 6,
  135589. 5,
  135590. 7,
  135591. 4,
  135592. 8,
  135593. 3,
  135594. 9,
  135595. 2,
  135596. 10,
  135597. 1,
  135598. 11,
  135599. 0,
  135600. 12,
  135601. };
  135602. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135603. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135604. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135605. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135606. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135607. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135608. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135609. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135610. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135611. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135612. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135613. 19,12,12,12,12,13,13,14,14,
  135614. };
  135615. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135616. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135617. 27.5, 38.5, 49.5, 60.5,
  135618. };
  135619. static long _vq_quantmap__44c9_s_p7_0[] = {
  135620. 11, 9, 7, 5, 3, 1, 0, 2,
  135621. 4, 6, 8, 10, 12,
  135622. };
  135623. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135624. _vq_quantthresh__44c9_s_p7_0,
  135625. _vq_quantmap__44c9_s_p7_0,
  135626. 13,
  135627. 13
  135628. };
  135629. static static_codebook _44c9_s_p7_0 = {
  135630. 2, 169,
  135631. _vq_lengthlist__44c9_s_p7_0,
  135632. 1, -523206656, 1618345984, 4, 0,
  135633. _vq_quantlist__44c9_s_p7_0,
  135634. NULL,
  135635. &_vq_auxt__44c9_s_p7_0,
  135636. NULL,
  135637. 0
  135638. };
  135639. static long _vq_quantlist__44c9_s_p7_1[] = {
  135640. 5,
  135641. 4,
  135642. 6,
  135643. 3,
  135644. 7,
  135645. 2,
  135646. 8,
  135647. 1,
  135648. 9,
  135649. 0,
  135650. 10,
  135651. };
  135652. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135653. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135654. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135655. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135656. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135657. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135658. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135659. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135660. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135661. };
  135662. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135663. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135664. 3.5, 4.5,
  135665. };
  135666. static long _vq_quantmap__44c9_s_p7_1[] = {
  135667. 9, 7, 5, 3, 1, 0, 2, 4,
  135668. 6, 8, 10,
  135669. };
  135670. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135671. _vq_quantthresh__44c9_s_p7_1,
  135672. _vq_quantmap__44c9_s_p7_1,
  135673. 11,
  135674. 11
  135675. };
  135676. static static_codebook _44c9_s_p7_1 = {
  135677. 2, 121,
  135678. _vq_lengthlist__44c9_s_p7_1,
  135679. 1, -531365888, 1611661312, 4, 0,
  135680. _vq_quantlist__44c9_s_p7_1,
  135681. NULL,
  135682. &_vq_auxt__44c9_s_p7_1,
  135683. NULL,
  135684. 0
  135685. };
  135686. static long _vq_quantlist__44c9_s_p8_0[] = {
  135687. 7,
  135688. 6,
  135689. 8,
  135690. 5,
  135691. 9,
  135692. 4,
  135693. 10,
  135694. 3,
  135695. 11,
  135696. 2,
  135697. 12,
  135698. 1,
  135699. 13,
  135700. 0,
  135701. 14,
  135702. };
  135703. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135704. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135705. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135706. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135707. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135708. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135709. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135710. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135711. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135712. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135713. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135714. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135715. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135716. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135717. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135718. 14,
  135719. };
  135720. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135721. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135722. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135723. };
  135724. static long _vq_quantmap__44c9_s_p8_0[] = {
  135725. 13, 11, 9, 7, 5, 3, 1, 0,
  135726. 2, 4, 6, 8, 10, 12, 14,
  135727. };
  135728. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135729. _vq_quantthresh__44c9_s_p8_0,
  135730. _vq_quantmap__44c9_s_p8_0,
  135731. 15,
  135732. 15
  135733. };
  135734. static static_codebook _44c9_s_p8_0 = {
  135735. 2, 225,
  135736. _vq_lengthlist__44c9_s_p8_0,
  135737. 1, -520986624, 1620377600, 4, 0,
  135738. _vq_quantlist__44c9_s_p8_0,
  135739. NULL,
  135740. &_vq_auxt__44c9_s_p8_0,
  135741. NULL,
  135742. 0
  135743. };
  135744. static long _vq_quantlist__44c9_s_p8_1[] = {
  135745. 10,
  135746. 9,
  135747. 11,
  135748. 8,
  135749. 12,
  135750. 7,
  135751. 13,
  135752. 6,
  135753. 14,
  135754. 5,
  135755. 15,
  135756. 4,
  135757. 16,
  135758. 3,
  135759. 17,
  135760. 2,
  135761. 18,
  135762. 1,
  135763. 19,
  135764. 0,
  135765. 20,
  135766. };
  135767. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135768. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135769. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135770. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135771. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135772. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135773. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135774. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135775. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135776. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135777. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135778. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135779. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135780. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135781. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135782. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135783. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135784. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135785. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135786. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135787. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135788. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135789. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135790. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135791. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135792. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135793. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135794. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135795. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135796. };
  135797. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135798. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135799. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135800. 6.5, 7.5, 8.5, 9.5,
  135801. };
  135802. static long _vq_quantmap__44c9_s_p8_1[] = {
  135803. 19, 17, 15, 13, 11, 9, 7, 5,
  135804. 3, 1, 0, 2, 4, 6, 8, 10,
  135805. 12, 14, 16, 18, 20,
  135806. };
  135807. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135808. _vq_quantthresh__44c9_s_p8_1,
  135809. _vq_quantmap__44c9_s_p8_1,
  135810. 21,
  135811. 21
  135812. };
  135813. static static_codebook _44c9_s_p8_1 = {
  135814. 2, 441,
  135815. _vq_lengthlist__44c9_s_p8_1,
  135816. 1, -529268736, 1611661312, 5, 0,
  135817. _vq_quantlist__44c9_s_p8_1,
  135818. NULL,
  135819. &_vq_auxt__44c9_s_p8_1,
  135820. NULL,
  135821. 0
  135822. };
  135823. static long _vq_quantlist__44c9_s_p9_0[] = {
  135824. 9,
  135825. 8,
  135826. 10,
  135827. 7,
  135828. 11,
  135829. 6,
  135830. 12,
  135831. 5,
  135832. 13,
  135833. 4,
  135834. 14,
  135835. 3,
  135836. 15,
  135837. 2,
  135838. 16,
  135839. 1,
  135840. 17,
  135841. 0,
  135842. 18,
  135843. };
  135844. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135845. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135846. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135847. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135848. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135849. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135850. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135851. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135852. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135853. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135854. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135855. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135856. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135857. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135858. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135859. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135860. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135861. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135867. 11,11,11,11,11,11,11,11,11,
  135868. };
  135869. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135870. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135871. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135872. 6982.5, 7913.5,
  135873. };
  135874. static long _vq_quantmap__44c9_s_p9_0[] = {
  135875. 17, 15, 13, 11, 9, 7, 5, 3,
  135876. 1, 0, 2, 4, 6, 8, 10, 12,
  135877. 14, 16, 18,
  135878. };
  135879. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135880. _vq_quantthresh__44c9_s_p9_0,
  135881. _vq_quantmap__44c9_s_p9_0,
  135882. 19,
  135883. 19
  135884. };
  135885. static static_codebook _44c9_s_p9_0 = {
  135886. 2, 361,
  135887. _vq_lengthlist__44c9_s_p9_0,
  135888. 1, -508535424, 1631393792, 5, 0,
  135889. _vq_quantlist__44c9_s_p9_0,
  135890. NULL,
  135891. &_vq_auxt__44c9_s_p9_0,
  135892. NULL,
  135893. 0
  135894. };
  135895. static long _vq_quantlist__44c9_s_p9_1[] = {
  135896. 9,
  135897. 8,
  135898. 10,
  135899. 7,
  135900. 11,
  135901. 6,
  135902. 12,
  135903. 5,
  135904. 13,
  135905. 4,
  135906. 14,
  135907. 3,
  135908. 15,
  135909. 2,
  135910. 16,
  135911. 1,
  135912. 17,
  135913. 0,
  135914. 18,
  135915. };
  135916. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135917. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135918. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135919. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135920. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135921. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135922. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135923. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135924. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135925. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135926. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135927. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135928. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135929. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135930. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135931. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135932. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135933. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135934. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135935. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135936. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135937. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135938. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135939. 13,13,13,14,13,14,15,15,15,
  135940. };
  135941. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135942. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135943. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135944. 367.5, 416.5,
  135945. };
  135946. static long _vq_quantmap__44c9_s_p9_1[] = {
  135947. 17, 15, 13, 11, 9, 7, 5, 3,
  135948. 1, 0, 2, 4, 6, 8, 10, 12,
  135949. 14, 16, 18,
  135950. };
  135951. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135952. _vq_quantthresh__44c9_s_p9_1,
  135953. _vq_quantmap__44c9_s_p9_1,
  135954. 19,
  135955. 19
  135956. };
  135957. static static_codebook _44c9_s_p9_1 = {
  135958. 2, 361,
  135959. _vq_lengthlist__44c9_s_p9_1,
  135960. 1, -518287360, 1622704128, 5, 0,
  135961. _vq_quantlist__44c9_s_p9_1,
  135962. NULL,
  135963. &_vq_auxt__44c9_s_p9_1,
  135964. NULL,
  135965. 0
  135966. };
  135967. static long _vq_quantlist__44c9_s_p9_2[] = {
  135968. 24,
  135969. 23,
  135970. 25,
  135971. 22,
  135972. 26,
  135973. 21,
  135974. 27,
  135975. 20,
  135976. 28,
  135977. 19,
  135978. 29,
  135979. 18,
  135980. 30,
  135981. 17,
  135982. 31,
  135983. 16,
  135984. 32,
  135985. 15,
  135986. 33,
  135987. 14,
  135988. 34,
  135989. 13,
  135990. 35,
  135991. 12,
  135992. 36,
  135993. 11,
  135994. 37,
  135995. 10,
  135996. 38,
  135997. 9,
  135998. 39,
  135999. 8,
  136000. 40,
  136001. 7,
  136002. 41,
  136003. 6,
  136004. 42,
  136005. 5,
  136006. 43,
  136007. 4,
  136008. 44,
  136009. 3,
  136010. 45,
  136011. 2,
  136012. 46,
  136013. 1,
  136014. 47,
  136015. 0,
  136016. 48,
  136017. };
  136018. static long _vq_lengthlist__44c9_s_p9_2[] = {
  136019. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  136020. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  136021. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  136022. 7,
  136023. };
  136024. static float _vq_quantthresh__44c9_s_p9_2[] = {
  136025. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  136026. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  136027. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136028. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136029. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  136030. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  136031. };
  136032. static long _vq_quantmap__44c9_s_p9_2[] = {
  136033. 47, 45, 43, 41, 39, 37, 35, 33,
  136034. 31, 29, 27, 25, 23, 21, 19, 17,
  136035. 15, 13, 11, 9, 7, 5, 3, 1,
  136036. 0, 2, 4, 6, 8, 10, 12, 14,
  136037. 16, 18, 20, 22, 24, 26, 28, 30,
  136038. 32, 34, 36, 38, 40, 42, 44, 46,
  136039. 48,
  136040. };
  136041. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  136042. _vq_quantthresh__44c9_s_p9_2,
  136043. _vq_quantmap__44c9_s_p9_2,
  136044. 49,
  136045. 49
  136046. };
  136047. static static_codebook _44c9_s_p9_2 = {
  136048. 1, 49,
  136049. _vq_lengthlist__44c9_s_p9_2,
  136050. 1, -526909440, 1611661312, 6, 0,
  136051. _vq_quantlist__44c9_s_p9_2,
  136052. NULL,
  136053. &_vq_auxt__44c9_s_p9_2,
  136054. NULL,
  136055. 0
  136056. };
  136057. static long _huff_lengthlist__44c9_s_short[] = {
  136058. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  136059. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  136060. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  136061. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  136062. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  136063. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  136064. 9, 8,10,13,
  136065. };
  136066. static static_codebook _huff_book__44c9_s_short = {
  136067. 2, 100,
  136068. _huff_lengthlist__44c9_s_short,
  136069. 0, 0, 0, 0, 0,
  136070. NULL,
  136071. NULL,
  136072. NULL,
  136073. NULL,
  136074. 0
  136075. };
  136076. static long _huff_lengthlist__44c0_s_long[] = {
  136077. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  136078. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  136079. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  136080. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  136081. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  136082. 12,
  136083. };
  136084. static static_codebook _huff_book__44c0_s_long = {
  136085. 2, 81,
  136086. _huff_lengthlist__44c0_s_long,
  136087. 0, 0, 0, 0, 0,
  136088. NULL,
  136089. NULL,
  136090. NULL,
  136091. NULL,
  136092. 0
  136093. };
  136094. static long _vq_quantlist__44c0_s_p1_0[] = {
  136095. 1,
  136096. 0,
  136097. 2,
  136098. };
  136099. static long _vq_lengthlist__44c0_s_p1_0[] = {
  136100. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136101. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136106. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136111. 0, 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0,
  136146. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136151. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  136156. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136192. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136197. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136202. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0,
  136511. };
  136512. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136513. -0.5, 0.5,
  136514. };
  136515. static long _vq_quantmap__44c0_s_p1_0[] = {
  136516. 1, 0, 2,
  136517. };
  136518. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136519. _vq_quantthresh__44c0_s_p1_0,
  136520. _vq_quantmap__44c0_s_p1_0,
  136521. 3,
  136522. 3
  136523. };
  136524. static static_codebook _44c0_s_p1_0 = {
  136525. 8, 6561,
  136526. _vq_lengthlist__44c0_s_p1_0,
  136527. 1, -535822336, 1611661312, 2, 0,
  136528. _vq_quantlist__44c0_s_p1_0,
  136529. NULL,
  136530. &_vq_auxt__44c0_s_p1_0,
  136531. NULL,
  136532. 0
  136533. };
  136534. static long _vq_quantlist__44c0_s_p2_0[] = {
  136535. 2,
  136536. 1,
  136537. 3,
  136538. 0,
  136539. 4,
  136540. };
  136541. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136542. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136545. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0,
  136582. };
  136583. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136584. -1.5, -0.5, 0.5, 1.5,
  136585. };
  136586. static long _vq_quantmap__44c0_s_p2_0[] = {
  136587. 3, 1, 0, 2, 4,
  136588. };
  136589. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136590. _vq_quantthresh__44c0_s_p2_0,
  136591. _vq_quantmap__44c0_s_p2_0,
  136592. 5,
  136593. 5
  136594. };
  136595. static static_codebook _44c0_s_p2_0 = {
  136596. 4, 625,
  136597. _vq_lengthlist__44c0_s_p2_0,
  136598. 1, -533725184, 1611661312, 3, 0,
  136599. _vq_quantlist__44c0_s_p2_0,
  136600. NULL,
  136601. &_vq_auxt__44c0_s_p2_0,
  136602. NULL,
  136603. 0
  136604. };
  136605. static long _vq_quantlist__44c0_s_p3_0[] = {
  136606. 4,
  136607. 3,
  136608. 5,
  136609. 2,
  136610. 6,
  136611. 1,
  136612. 7,
  136613. 0,
  136614. 8,
  136615. };
  136616. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136617. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136618. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136619. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136620. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136621. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0,
  136623. };
  136624. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136625. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136626. };
  136627. static long _vq_quantmap__44c0_s_p3_0[] = {
  136628. 7, 5, 3, 1, 0, 2, 4, 6,
  136629. 8,
  136630. };
  136631. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136632. _vq_quantthresh__44c0_s_p3_0,
  136633. _vq_quantmap__44c0_s_p3_0,
  136634. 9,
  136635. 9
  136636. };
  136637. static static_codebook _44c0_s_p3_0 = {
  136638. 2, 81,
  136639. _vq_lengthlist__44c0_s_p3_0,
  136640. 1, -531628032, 1611661312, 4, 0,
  136641. _vq_quantlist__44c0_s_p3_0,
  136642. NULL,
  136643. &_vq_auxt__44c0_s_p3_0,
  136644. NULL,
  136645. 0
  136646. };
  136647. static long _vq_quantlist__44c0_s_p4_0[] = {
  136648. 4,
  136649. 3,
  136650. 5,
  136651. 2,
  136652. 6,
  136653. 1,
  136654. 7,
  136655. 0,
  136656. 8,
  136657. };
  136658. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136659. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136660. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136661. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136662. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136663. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136664. 10,
  136665. };
  136666. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136667. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136668. };
  136669. static long _vq_quantmap__44c0_s_p4_0[] = {
  136670. 7, 5, 3, 1, 0, 2, 4, 6,
  136671. 8,
  136672. };
  136673. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136674. _vq_quantthresh__44c0_s_p4_0,
  136675. _vq_quantmap__44c0_s_p4_0,
  136676. 9,
  136677. 9
  136678. };
  136679. static static_codebook _44c0_s_p4_0 = {
  136680. 2, 81,
  136681. _vq_lengthlist__44c0_s_p4_0,
  136682. 1, -531628032, 1611661312, 4, 0,
  136683. _vq_quantlist__44c0_s_p4_0,
  136684. NULL,
  136685. &_vq_auxt__44c0_s_p4_0,
  136686. NULL,
  136687. 0
  136688. };
  136689. static long _vq_quantlist__44c0_s_p5_0[] = {
  136690. 8,
  136691. 7,
  136692. 9,
  136693. 6,
  136694. 10,
  136695. 5,
  136696. 11,
  136697. 4,
  136698. 12,
  136699. 3,
  136700. 13,
  136701. 2,
  136702. 14,
  136703. 1,
  136704. 15,
  136705. 0,
  136706. 16,
  136707. };
  136708. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136709. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136710. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136711. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136712. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136713. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136714. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136715. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136716. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136717. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136718. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136719. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136720. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136721. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136722. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136723. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136724. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136725. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136727. 14,
  136728. };
  136729. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136730. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136731. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136732. };
  136733. static long _vq_quantmap__44c0_s_p5_0[] = {
  136734. 15, 13, 11, 9, 7, 5, 3, 1,
  136735. 0, 2, 4, 6, 8, 10, 12, 14,
  136736. 16,
  136737. };
  136738. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136739. _vq_quantthresh__44c0_s_p5_0,
  136740. _vq_quantmap__44c0_s_p5_0,
  136741. 17,
  136742. 17
  136743. };
  136744. static static_codebook _44c0_s_p5_0 = {
  136745. 2, 289,
  136746. _vq_lengthlist__44c0_s_p5_0,
  136747. 1, -529530880, 1611661312, 5, 0,
  136748. _vq_quantlist__44c0_s_p5_0,
  136749. NULL,
  136750. &_vq_auxt__44c0_s_p5_0,
  136751. NULL,
  136752. 0
  136753. };
  136754. static long _vq_quantlist__44c0_s_p6_0[] = {
  136755. 1,
  136756. 0,
  136757. 2,
  136758. };
  136759. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136760. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136761. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136762. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136763. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136764. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136765. 10,
  136766. };
  136767. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136768. -5.5, 5.5,
  136769. };
  136770. static long _vq_quantmap__44c0_s_p6_0[] = {
  136771. 1, 0, 2,
  136772. };
  136773. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136774. _vq_quantthresh__44c0_s_p6_0,
  136775. _vq_quantmap__44c0_s_p6_0,
  136776. 3,
  136777. 3
  136778. };
  136779. static static_codebook _44c0_s_p6_0 = {
  136780. 4, 81,
  136781. _vq_lengthlist__44c0_s_p6_0,
  136782. 1, -529137664, 1618345984, 2, 0,
  136783. _vq_quantlist__44c0_s_p6_0,
  136784. NULL,
  136785. &_vq_auxt__44c0_s_p6_0,
  136786. NULL,
  136787. 0
  136788. };
  136789. static long _vq_quantlist__44c0_s_p6_1[] = {
  136790. 5,
  136791. 4,
  136792. 6,
  136793. 3,
  136794. 7,
  136795. 2,
  136796. 8,
  136797. 1,
  136798. 9,
  136799. 0,
  136800. 10,
  136801. };
  136802. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136803. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136804. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136805. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136806. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136807. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136808. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136809. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136810. 10,10,10, 8, 8, 8, 8, 8, 8,
  136811. };
  136812. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136813. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136814. 3.5, 4.5,
  136815. };
  136816. static long _vq_quantmap__44c0_s_p6_1[] = {
  136817. 9, 7, 5, 3, 1, 0, 2, 4,
  136818. 6, 8, 10,
  136819. };
  136820. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136821. _vq_quantthresh__44c0_s_p6_1,
  136822. _vq_quantmap__44c0_s_p6_1,
  136823. 11,
  136824. 11
  136825. };
  136826. static static_codebook _44c0_s_p6_1 = {
  136827. 2, 121,
  136828. _vq_lengthlist__44c0_s_p6_1,
  136829. 1, -531365888, 1611661312, 4, 0,
  136830. _vq_quantlist__44c0_s_p6_1,
  136831. NULL,
  136832. &_vq_auxt__44c0_s_p6_1,
  136833. NULL,
  136834. 0
  136835. };
  136836. static long _vq_quantlist__44c0_s_p7_0[] = {
  136837. 6,
  136838. 5,
  136839. 7,
  136840. 4,
  136841. 8,
  136842. 3,
  136843. 9,
  136844. 2,
  136845. 10,
  136846. 1,
  136847. 11,
  136848. 0,
  136849. 12,
  136850. };
  136851. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136852. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136853. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136854. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136855. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136856. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136857. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136858. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136859. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136860. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136861. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136862. 0,12,12,11,11,12,12,13,13,
  136863. };
  136864. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136865. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136866. 12.5, 17.5, 22.5, 27.5,
  136867. };
  136868. static long _vq_quantmap__44c0_s_p7_0[] = {
  136869. 11, 9, 7, 5, 3, 1, 0, 2,
  136870. 4, 6, 8, 10, 12,
  136871. };
  136872. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136873. _vq_quantthresh__44c0_s_p7_0,
  136874. _vq_quantmap__44c0_s_p7_0,
  136875. 13,
  136876. 13
  136877. };
  136878. static static_codebook _44c0_s_p7_0 = {
  136879. 2, 169,
  136880. _vq_lengthlist__44c0_s_p7_0,
  136881. 1, -526516224, 1616117760, 4, 0,
  136882. _vq_quantlist__44c0_s_p7_0,
  136883. NULL,
  136884. &_vq_auxt__44c0_s_p7_0,
  136885. NULL,
  136886. 0
  136887. };
  136888. static long _vq_quantlist__44c0_s_p7_1[] = {
  136889. 2,
  136890. 1,
  136891. 3,
  136892. 0,
  136893. 4,
  136894. };
  136895. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136896. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136897. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136898. };
  136899. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136900. -1.5, -0.5, 0.5, 1.5,
  136901. };
  136902. static long _vq_quantmap__44c0_s_p7_1[] = {
  136903. 3, 1, 0, 2, 4,
  136904. };
  136905. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136906. _vq_quantthresh__44c0_s_p7_1,
  136907. _vq_quantmap__44c0_s_p7_1,
  136908. 5,
  136909. 5
  136910. };
  136911. static static_codebook _44c0_s_p7_1 = {
  136912. 2, 25,
  136913. _vq_lengthlist__44c0_s_p7_1,
  136914. 1, -533725184, 1611661312, 3, 0,
  136915. _vq_quantlist__44c0_s_p7_1,
  136916. NULL,
  136917. &_vq_auxt__44c0_s_p7_1,
  136918. NULL,
  136919. 0
  136920. };
  136921. static long _vq_quantlist__44c0_s_p8_0[] = {
  136922. 2,
  136923. 1,
  136924. 3,
  136925. 0,
  136926. 4,
  136927. };
  136928. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136929. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136930. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136931. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136932. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136933. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136934. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136935. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136936. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136937. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136938. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136940. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136941. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136943. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136944. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136945. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136946. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136947. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136948. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136949. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136950. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136951. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136952. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136959. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136960. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136961. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136962. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136963. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136964. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136965. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136966. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136967. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136968. 11,
  136969. };
  136970. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136971. -331.5, -110.5, 110.5, 331.5,
  136972. };
  136973. static long _vq_quantmap__44c0_s_p8_0[] = {
  136974. 3, 1, 0, 2, 4,
  136975. };
  136976. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136977. _vq_quantthresh__44c0_s_p8_0,
  136978. _vq_quantmap__44c0_s_p8_0,
  136979. 5,
  136980. 5
  136981. };
  136982. static static_codebook _44c0_s_p8_0 = {
  136983. 4, 625,
  136984. _vq_lengthlist__44c0_s_p8_0,
  136985. 1, -518283264, 1627103232, 3, 0,
  136986. _vq_quantlist__44c0_s_p8_0,
  136987. NULL,
  136988. &_vq_auxt__44c0_s_p8_0,
  136989. NULL,
  136990. 0
  136991. };
  136992. static long _vq_quantlist__44c0_s_p8_1[] = {
  136993. 6,
  136994. 5,
  136995. 7,
  136996. 4,
  136997. 8,
  136998. 3,
  136999. 9,
  137000. 2,
  137001. 10,
  137002. 1,
  137003. 11,
  137004. 0,
  137005. 12,
  137006. };
  137007. static long _vq_lengthlist__44c0_s_p8_1[] = {
  137008. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  137009. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  137010. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  137011. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  137012. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  137013. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  137014. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  137015. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  137016. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  137017. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  137018. 16,13,13,12,12,14,14,15,13,
  137019. };
  137020. static float _vq_quantthresh__44c0_s_p8_1[] = {
  137021. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137022. 42.5, 59.5, 76.5, 93.5,
  137023. };
  137024. static long _vq_quantmap__44c0_s_p8_1[] = {
  137025. 11, 9, 7, 5, 3, 1, 0, 2,
  137026. 4, 6, 8, 10, 12,
  137027. };
  137028. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  137029. _vq_quantthresh__44c0_s_p8_1,
  137030. _vq_quantmap__44c0_s_p8_1,
  137031. 13,
  137032. 13
  137033. };
  137034. static static_codebook _44c0_s_p8_1 = {
  137035. 2, 169,
  137036. _vq_lengthlist__44c0_s_p8_1,
  137037. 1, -522616832, 1620115456, 4, 0,
  137038. _vq_quantlist__44c0_s_p8_1,
  137039. NULL,
  137040. &_vq_auxt__44c0_s_p8_1,
  137041. NULL,
  137042. 0
  137043. };
  137044. static long _vq_quantlist__44c0_s_p8_2[] = {
  137045. 8,
  137046. 7,
  137047. 9,
  137048. 6,
  137049. 10,
  137050. 5,
  137051. 11,
  137052. 4,
  137053. 12,
  137054. 3,
  137055. 13,
  137056. 2,
  137057. 14,
  137058. 1,
  137059. 15,
  137060. 0,
  137061. 16,
  137062. };
  137063. static long _vq_lengthlist__44c0_s_p8_2[] = {
  137064. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137065. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  137066. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  137067. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  137068. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137069. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  137070. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  137071. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  137072. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  137073. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  137074. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  137075. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137076. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  137077. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  137078. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  137079. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  137080. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  137081. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  137082. 10,
  137083. };
  137084. static float _vq_quantthresh__44c0_s_p8_2[] = {
  137085. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137086. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137087. };
  137088. static long _vq_quantmap__44c0_s_p8_2[] = {
  137089. 15, 13, 11, 9, 7, 5, 3, 1,
  137090. 0, 2, 4, 6, 8, 10, 12, 14,
  137091. 16,
  137092. };
  137093. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  137094. _vq_quantthresh__44c0_s_p8_2,
  137095. _vq_quantmap__44c0_s_p8_2,
  137096. 17,
  137097. 17
  137098. };
  137099. static static_codebook _44c0_s_p8_2 = {
  137100. 2, 289,
  137101. _vq_lengthlist__44c0_s_p8_2,
  137102. 1, -529530880, 1611661312, 5, 0,
  137103. _vq_quantlist__44c0_s_p8_2,
  137104. NULL,
  137105. &_vq_auxt__44c0_s_p8_2,
  137106. NULL,
  137107. 0
  137108. };
  137109. static long _huff_lengthlist__44c0_s_short[] = {
  137110. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  137111. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  137112. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  137113. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  137114. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137115. 12,
  137116. };
  137117. static static_codebook _huff_book__44c0_s_short = {
  137118. 2, 81,
  137119. _huff_lengthlist__44c0_s_short,
  137120. 0, 0, 0, 0, 0,
  137121. NULL,
  137122. NULL,
  137123. NULL,
  137124. NULL,
  137125. 0
  137126. };
  137127. static long _huff_lengthlist__44c0_sm_long[] = {
  137128. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137129. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137130. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137131. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137132. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137133. 13,
  137134. };
  137135. static static_codebook _huff_book__44c0_sm_long = {
  137136. 2, 81,
  137137. _huff_lengthlist__44c0_sm_long,
  137138. 0, 0, 0, 0, 0,
  137139. NULL,
  137140. NULL,
  137141. NULL,
  137142. NULL,
  137143. 0
  137144. };
  137145. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137146. 1,
  137147. 0,
  137148. 2,
  137149. };
  137150. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137151. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137152. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137157. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137162. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  137197. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  137202. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137207. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137243. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137248. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137253. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137561. 0,
  137562. };
  137563. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137564. -0.5, 0.5,
  137565. };
  137566. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137567. 1, 0, 2,
  137568. };
  137569. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137570. _vq_quantthresh__44c0_sm_p1_0,
  137571. _vq_quantmap__44c0_sm_p1_0,
  137572. 3,
  137573. 3
  137574. };
  137575. static static_codebook _44c0_sm_p1_0 = {
  137576. 8, 6561,
  137577. _vq_lengthlist__44c0_sm_p1_0,
  137578. 1, -535822336, 1611661312, 2, 0,
  137579. _vq_quantlist__44c0_sm_p1_0,
  137580. NULL,
  137581. &_vq_auxt__44c0_sm_p1_0,
  137582. NULL,
  137583. 0
  137584. };
  137585. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137586. 2,
  137587. 1,
  137588. 3,
  137589. 0,
  137590. 4,
  137591. };
  137592. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137593. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0,
  137633. };
  137634. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137635. -1.5, -0.5, 0.5, 1.5,
  137636. };
  137637. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137638. 3, 1, 0, 2, 4,
  137639. };
  137640. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137641. _vq_quantthresh__44c0_sm_p2_0,
  137642. _vq_quantmap__44c0_sm_p2_0,
  137643. 5,
  137644. 5
  137645. };
  137646. static static_codebook _44c0_sm_p2_0 = {
  137647. 4, 625,
  137648. _vq_lengthlist__44c0_sm_p2_0,
  137649. 1, -533725184, 1611661312, 3, 0,
  137650. _vq_quantlist__44c0_sm_p2_0,
  137651. NULL,
  137652. &_vq_auxt__44c0_sm_p2_0,
  137653. NULL,
  137654. 0
  137655. };
  137656. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137657. 4,
  137658. 3,
  137659. 5,
  137660. 2,
  137661. 6,
  137662. 1,
  137663. 7,
  137664. 0,
  137665. 8,
  137666. };
  137667. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137668. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137669. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137670. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137671. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137672. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0,
  137674. };
  137675. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137676. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137677. };
  137678. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137679. 7, 5, 3, 1, 0, 2, 4, 6,
  137680. 8,
  137681. };
  137682. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137683. _vq_quantthresh__44c0_sm_p3_0,
  137684. _vq_quantmap__44c0_sm_p3_0,
  137685. 9,
  137686. 9
  137687. };
  137688. static static_codebook _44c0_sm_p3_0 = {
  137689. 2, 81,
  137690. _vq_lengthlist__44c0_sm_p3_0,
  137691. 1, -531628032, 1611661312, 4, 0,
  137692. _vq_quantlist__44c0_sm_p3_0,
  137693. NULL,
  137694. &_vq_auxt__44c0_sm_p3_0,
  137695. NULL,
  137696. 0
  137697. };
  137698. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137699. 4,
  137700. 3,
  137701. 5,
  137702. 2,
  137703. 6,
  137704. 1,
  137705. 7,
  137706. 0,
  137707. 8,
  137708. };
  137709. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137710. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137711. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137712. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137713. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137714. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137715. 11,
  137716. };
  137717. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137718. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137719. };
  137720. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137721. 7, 5, 3, 1, 0, 2, 4, 6,
  137722. 8,
  137723. };
  137724. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137725. _vq_quantthresh__44c0_sm_p4_0,
  137726. _vq_quantmap__44c0_sm_p4_0,
  137727. 9,
  137728. 9
  137729. };
  137730. static static_codebook _44c0_sm_p4_0 = {
  137731. 2, 81,
  137732. _vq_lengthlist__44c0_sm_p4_0,
  137733. 1, -531628032, 1611661312, 4, 0,
  137734. _vq_quantlist__44c0_sm_p4_0,
  137735. NULL,
  137736. &_vq_auxt__44c0_sm_p4_0,
  137737. NULL,
  137738. 0
  137739. };
  137740. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137741. 8,
  137742. 7,
  137743. 9,
  137744. 6,
  137745. 10,
  137746. 5,
  137747. 11,
  137748. 4,
  137749. 12,
  137750. 3,
  137751. 13,
  137752. 2,
  137753. 14,
  137754. 1,
  137755. 15,
  137756. 0,
  137757. 16,
  137758. };
  137759. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137760. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137761. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137762. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137763. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137764. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137765. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137766. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137767. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137768. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137769. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137770. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137771. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137772. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137773. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137774. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137775. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137776. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137778. 14,
  137779. };
  137780. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137781. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137782. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137783. };
  137784. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137785. 15, 13, 11, 9, 7, 5, 3, 1,
  137786. 0, 2, 4, 6, 8, 10, 12, 14,
  137787. 16,
  137788. };
  137789. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137790. _vq_quantthresh__44c0_sm_p5_0,
  137791. _vq_quantmap__44c0_sm_p5_0,
  137792. 17,
  137793. 17
  137794. };
  137795. static static_codebook _44c0_sm_p5_0 = {
  137796. 2, 289,
  137797. _vq_lengthlist__44c0_sm_p5_0,
  137798. 1, -529530880, 1611661312, 5, 0,
  137799. _vq_quantlist__44c0_sm_p5_0,
  137800. NULL,
  137801. &_vq_auxt__44c0_sm_p5_0,
  137802. NULL,
  137803. 0
  137804. };
  137805. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137806. 1,
  137807. 0,
  137808. 2,
  137809. };
  137810. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137811. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137812. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137813. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137814. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137815. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137816. 11,
  137817. };
  137818. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137819. -5.5, 5.5,
  137820. };
  137821. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137822. 1, 0, 2,
  137823. };
  137824. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137825. _vq_quantthresh__44c0_sm_p6_0,
  137826. _vq_quantmap__44c0_sm_p6_0,
  137827. 3,
  137828. 3
  137829. };
  137830. static static_codebook _44c0_sm_p6_0 = {
  137831. 4, 81,
  137832. _vq_lengthlist__44c0_sm_p6_0,
  137833. 1, -529137664, 1618345984, 2, 0,
  137834. _vq_quantlist__44c0_sm_p6_0,
  137835. NULL,
  137836. &_vq_auxt__44c0_sm_p6_0,
  137837. NULL,
  137838. 0
  137839. };
  137840. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137841. 5,
  137842. 4,
  137843. 6,
  137844. 3,
  137845. 7,
  137846. 2,
  137847. 8,
  137848. 1,
  137849. 9,
  137850. 0,
  137851. 10,
  137852. };
  137853. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137854. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137855. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137856. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137857. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137858. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137859. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137860. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137861. 10,10,10, 8, 8, 8, 8, 8, 8,
  137862. };
  137863. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137864. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137865. 3.5, 4.5,
  137866. };
  137867. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137868. 9, 7, 5, 3, 1, 0, 2, 4,
  137869. 6, 8, 10,
  137870. };
  137871. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137872. _vq_quantthresh__44c0_sm_p6_1,
  137873. _vq_quantmap__44c0_sm_p6_1,
  137874. 11,
  137875. 11
  137876. };
  137877. static static_codebook _44c0_sm_p6_1 = {
  137878. 2, 121,
  137879. _vq_lengthlist__44c0_sm_p6_1,
  137880. 1, -531365888, 1611661312, 4, 0,
  137881. _vq_quantlist__44c0_sm_p6_1,
  137882. NULL,
  137883. &_vq_auxt__44c0_sm_p6_1,
  137884. NULL,
  137885. 0
  137886. };
  137887. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137888. 6,
  137889. 5,
  137890. 7,
  137891. 4,
  137892. 8,
  137893. 3,
  137894. 9,
  137895. 2,
  137896. 10,
  137897. 1,
  137898. 11,
  137899. 0,
  137900. 12,
  137901. };
  137902. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137903. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137904. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137905. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137906. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137907. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137908. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137909. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137910. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137911. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137912. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137913. 0,12,12,11,11,13,12,14,14,
  137914. };
  137915. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137916. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137917. 12.5, 17.5, 22.5, 27.5,
  137918. };
  137919. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137920. 11, 9, 7, 5, 3, 1, 0, 2,
  137921. 4, 6, 8, 10, 12,
  137922. };
  137923. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137924. _vq_quantthresh__44c0_sm_p7_0,
  137925. _vq_quantmap__44c0_sm_p7_0,
  137926. 13,
  137927. 13
  137928. };
  137929. static static_codebook _44c0_sm_p7_0 = {
  137930. 2, 169,
  137931. _vq_lengthlist__44c0_sm_p7_0,
  137932. 1, -526516224, 1616117760, 4, 0,
  137933. _vq_quantlist__44c0_sm_p7_0,
  137934. NULL,
  137935. &_vq_auxt__44c0_sm_p7_0,
  137936. NULL,
  137937. 0
  137938. };
  137939. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137940. 2,
  137941. 1,
  137942. 3,
  137943. 0,
  137944. 4,
  137945. };
  137946. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137947. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137948. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137949. };
  137950. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137951. -1.5, -0.5, 0.5, 1.5,
  137952. };
  137953. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137954. 3, 1, 0, 2, 4,
  137955. };
  137956. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137957. _vq_quantthresh__44c0_sm_p7_1,
  137958. _vq_quantmap__44c0_sm_p7_1,
  137959. 5,
  137960. 5
  137961. };
  137962. static static_codebook _44c0_sm_p7_1 = {
  137963. 2, 25,
  137964. _vq_lengthlist__44c0_sm_p7_1,
  137965. 1, -533725184, 1611661312, 3, 0,
  137966. _vq_quantlist__44c0_sm_p7_1,
  137967. NULL,
  137968. &_vq_auxt__44c0_sm_p7_1,
  137969. NULL,
  137970. 0
  137971. };
  137972. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137973. 4,
  137974. 3,
  137975. 5,
  137976. 2,
  137977. 6,
  137978. 1,
  137979. 7,
  137980. 0,
  137981. 8,
  137982. };
  137983. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137984. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137985. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137986. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137987. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137988. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137989. 12,
  137990. };
  137991. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137992. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137993. };
  137994. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137995. 7, 5, 3, 1, 0, 2, 4, 6,
  137996. 8,
  137997. };
  137998. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137999. _vq_quantthresh__44c0_sm_p8_0,
  138000. _vq_quantmap__44c0_sm_p8_0,
  138001. 9,
  138002. 9
  138003. };
  138004. static static_codebook _44c0_sm_p8_0 = {
  138005. 2, 81,
  138006. _vq_lengthlist__44c0_sm_p8_0,
  138007. 1, -516186112, 1627103232, 4, 0,
  138008. _vq_quantlist__44c0_sm_p8_0,
  138009. NULL,
  138010. &_vq_auxt__44c0_sm_p8_0,
  138011. NULL,
  138012. 0
  138013. };
  138014. static long _vq_quantlist__44c0_sm_p8_1[] = {
  138015. 6,
  138016. 5,
  138017. 7,
  138018. 4,
  138019. 8,
  138020. 3,
  138021. 9,
  138022. 2,
  138023. 10,
  138024. 1,
  138025. 11,
  138026. 0,
  138027. 12,
  138028. };
  138029. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  138030. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  138031. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138032. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  138033. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  138034. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  138035. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  138036. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  138037. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  138038. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  138039. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  138040. 20,13,13,12,12,16,13,15,13,
  138041. };
  138042. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  138043. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138044. 42.5, 59.5, 76.5, 93.5,
  138045. };
  138046. static long _vq_quantmap__44c0_sm_p8_1[] = {
  138047. 11, 9, 7, 5, 3, 1, 0, 2,
  138048. 4, 6, 8, 10, 12,
  138049. };
  138050. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  138051. _vq_quantthresh__44c0_sm_p8_1,
  138052. _vq_quantmap__44c0_sm_p8_1,
  138053. 13,
  138054. 13
  138055. };
  138056. static static_codebook _44c0_sm_p8_1 = {
  138057. 2, 169,
  138058. _vq_lengthlist__44c0_sm_p8_1,
  138059. 1, -522616832, 1620115456, 4, 0,
  138060. _vq_quantlist__44c0_sm_p8_1,
  138061. NULL,
  138062. &_vq_auxt__44c0_sm_p8_1,
  138063. NULL,
  138064. 0
  138065. };
  138066. static long _vq_quantlist__44c0_sm_p8_2[] = {
  138067. 8,
  138068. 7,
  138069. 9,
  138070. 6,
  138071. 10,
  138072. 5,
  138073. 11,
  138074. 4,
  138075. 12,
  138076. 3,
  138077. 13,
  138078. 2,
  138079. 14,
  138080. 1,
  138081. 15,
  138082. 0,
  138083. 16,
  138084. };
  138085. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  138086. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138087. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138088. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138089. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138090. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138091. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138092. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138093. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138094. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  138095. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  138096. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  138097. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  138098. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  138099. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  138100. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138101. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138102. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138103. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138104. 9,
  138105. };
  138106. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  138107. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138108. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138109. };
  138110. static long _vq_quantmap__44c0_sm_p8_2[] = {
  138111. 15, 13, 11, 9, 7, 5, 3, 1,
  138112. 0, 2, 4, 6, 8, 10, 12, 14,
  138113. 16,
  138114. };
  138115. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138116. _vq_quantthresh__44c0_sm_p8_2,
  138117. _vq_quantmap__44c0_sm_p8_2,
  138118. 17,
  138119. 17
  138120. };
  138121. static static_codebook _44c0_sm_p8_2 = {
  138122. 2, 289,
  138123. _vq_lengthlist__44c0_sm_p8_2,
  138124. 1, -529530880, 1611661312, 5, 0,
  138125. _vq_quantlist__44c0_sm_p8_2,
  138126. NULL,
  138127. &_vq_auxt__44c0_sm_p8_2,
  138128. NULL,
  138129. 0
  138130. };
  138131. static long _huff_lengthlist__44c0_sm_short[] = {
  138132. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138133. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138134. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138135. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138136. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138137. 12,
  138138. };
  138139. static static_codebook _huff_book__44c0_sm_short = {
  138140. 2, 81,
  138141. _huff_lengthlist__44c0_sm_short,
  138142. 0, 0, 0, 0, 0,
  138143. NULL,
  138144. NULL,
  138145. NULL,
  138146. NULL,
  138147. 0
  138148. };
  138149. static long _huff_lengthlist__44c1_s_long[] = {
  138150. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138151. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138152. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138153. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138154. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138155. 11,
  138156. };
  138157. static static_codebook _huff_book__44c1_s_long = {
  138158. 2, 81,
  138159. _huff_lengthlist__44c1_s_long,
  138160. 0, 0, 0, 0, 0,
  138161. NULL,
  138162. NULL,
  138163. NULL,
  138164. NULL,
  138165. 0
  138166. };
  138167. static long _vq_quantlist__44c1_s_p1_0[] = {
  138168. 1,
  138169. 0,
  138170. 2,
  138171. };
  138172. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138173. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138174. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138179. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138184. 0, 0, 0, 0, 7, 8, 8, 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, 4, 7, 7, 0, 0, 0, 0,
  138219. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  138224. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  138229. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138265. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138270. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138275. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0,
  138584. };
  138585. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138586. -0.5, 0.5,
  138587. };
  138588. static long _vq_quantmap__44c1_s_p1_0[] = {
  138589. 1, 0, 2,
  138590. };
  138591. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138592. _vq_quantthresh__44c1_s_p1_0,
  138593. _vq_quantmap__44c1_s_p1_0,
  138594. 3,
  138595. 3
  138596. };
  138597. static static_codebook _44c1_s_p1_0 = {
  138598. 8, 6561,
  138599. _vq_lengthlist__44c1_s_p1_0,
  138600. 1, -535822336, 1611661312, 2, 0,
  138601. _vq_quantlist__44c1_s_p1_0,
  138602. NULL,
  138603. &_vq_auxt__44c1_s_p1_0,
  138604. NULL,
  138605. 0
  138606. };
  138607. static long _vq_quantlist__44c1_s_p2_0[] = {
  138608. 2,
  138609. 1,
  138610. 3,
  138611. 0,
  138612. 4,
  138613. };
  138614. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138615. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138618. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0,
  138655. };
  138656. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138657. -1.5, -0.5, 0.5, 1.5,
  138658. };
  138659. static long _vq_quantmap__44c1_s_p2_0[] = {
  138660. 3, 1, 0, 2, 4,
  138661. };
  138662. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138663. _vq_quantthresh__44c1_s_p2_0,
  138664. _vq_quantmap__44c1_s_p2_0,
  138665. 5,
  138666. 5
  138667. };
  138668. static static_codebook _44c1_s_p2_0 = {
  138669. 4, 625,
  138670. _vq_lengthlist__44c1_s_p2_0,
  138671. 1, -533725184, 1611661312, 3, 0,
  138672. _vq_quantlist__44c1_s_p2_0,
  138673. NULL,
  138674. &_vq_auxt__44c1_s_p2_0,
  138675. NULL,
  138676. 0
  138677. };
  138678. static long _vq_quantlist__44c1_s_p3_0[] = {
  138679. 4,
  138680. 3,
  138681. 5,
  138682. 2,
  138683. 6,
  138684. 1,
  138685. 7,
  138686. 0,
  138687. 8,
  138688. };
  138689. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138690. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138691. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138692. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138693. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138694. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0,
  138696. };
  138697. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138698. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138699. };
  138700. static long _vq_quantmap__44c1_s_p3_0[] = {
  138701. 7, 5, 3, 1, 0, 2, 4, 6,
  138702. 8,
  138703. };
  138704. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138705. _vq_quantthresh__44c1_s_p3_0,
  138706. _vq_quantmap__44c1_s_p3_0,
  138707. 9,
  138708. 9
  138709. };
  138710. static static_codebook _44c1_s_p3_0 = {
  138711. 2, 81,
  138712. _vq_lengthlist__44c1_s_p3_0,
  138713. 1, -531628032, 1611661312, 4, 0,
  138714. _vq_quantlist__44c1_s_p3_0,
  138715. NULL,
  138716. &_vq_auxt__44c1_s_p3_0,
  138717. NULL,
  138718. 0
  138719. };
  138720. static long _vq_quantlist__44c1_s_p4_0[] = {
  138721. 4,
  138722. 3,
  138723. 5,
  138724. 2,
  138725. 6,
  138726. 1,
  138727. 7,
  138728. 0,
  138729. 8,
  138730. };
  138731. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138732. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138733. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138734. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138735. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138736. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138737. 11,
  138738. };
  138739. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138740. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138741. };
  138742. static long _vq_quantmap__44c1_s_p4_0[] = {
  138743. 7, 5, 3, 1, 0, 2, 4, 6,
  138744. 8,
  138745. };
  138746. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138747. _vq_quantthresh__44c1_s_p4_0,
  138748. _vq_quantmap__44c1_s_p4_0,
  138749. 9,
  138750. 9
  138751. };
  138752. static static_codebook _44c1_s_p4_0 = {
  138753. 2, 81,
  138754. _vq_lengthlist__44c1_s_p4_0,
  138755. 1, -531628032, 1611661312, 4, 0,
  138756. _vq_quantlist__44c1_s_p4_0,
  138757. NULL,
  138758. &_vq_auxt__44c1_s_p4_0,
  138759. NULL,
  138760. 0
  138761. };
  138762. static long _vq_quantlist__44c1_s_p5_0[] = {
  138763. 8,
  138764. 7,
  138765. 9,
  138766. 6,
  138767. 10,
  138768. 5,
  138769. 11,
  138770. 4,
  138771. 12,
  138772. 3,
  138773. 13,
  138774. 2,
  138775. 14,
  138776. 1,
  138777. 15,
  138778. 0,
  138779. 16,
  138780. };
  138781. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138782. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138783. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138784. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138785. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138786. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138787. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138788. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138789. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138790. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138791. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138792. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138793. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138794. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138795. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138796. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138797. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138798. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138800. 14,
  138801. };
  138802. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138803. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138804. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138805. };
  138806. static long _vq_quantmap__44c1_s_p5_0[] = {
  138807. 15, 13, 11, 9, 7, 5, 3, 1,
  138808. 0, 2, 4, 6, 8, 10, 12, 14,
  138809. 16,
  138810. };
  138811. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138812. _vq_quantthresh__44c1_s_p5_0,
  138813. _vq_quantmap__44c1_s_p5_0,
  138814. 17,
  138815. 17
  138816. };
  138817. static static_codebook _44c1_s_p5_0 = {
  138818. 2, 289,
  138819. _vq_lengthlist__44c1_s_p5_0,
  138820. 1, -529530880, 1611661312, 5, 0,
  138821. _vq_quantlist__44c1_s_p5_0,
  138822. NULL,
  138823. &_vq_auxt__44c1_s_p5_0,
  138824. NULL,
  138825. 0
  138826. };
  138827. static long _vq_quantlist__44c1_s_p6_0[] = {
  138828. 1,
  138829. 0,
  138830. 2,
  138831. };
  138832. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138833. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138834. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138835. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138836. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138837. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138838. 11,
  138839. };
  138840. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138841. -5.5, 5.5,
  138842. };
  138843. static long _vq_quantmap__44c1_s_p6_0[] = {
  138844. 1, 0, 2,
  138845. };
  138846. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138847. _vq_quantthresh__44c1_s_p6_0,
  138848. _vq_quantmap__44c1_s_p6_0,
  138849. 3,
  138850. 3
  138851. };
  138852. static static_codebook _44c1_s_p6_0 = {
  138853. 4, 81,
  138854. _vq_lengthlist__44c1_s_p6_0,
  138855. 1, -529137664, 1618345984, 2, 0,
  138856. _vq_quantlist__44c1_s_p6_0,
  138857. NULL,
  138858. &_vq_auxt__44c1_s_p6_0,
  138859. NULL,
  138860. 0
  138861. };
  138862. static long _vq_quantlist__44c1_s_p6_1[] = {
  138863. 5,
  138864. 4,
  138865. 6,
  138866. 3,
  138867. 7,
  138868. 2,
  138869. 8,
  138870. 1,
  138871. 9,
  138872. 0,
  138873. 10,
  138874. };
  138875. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138876. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138877. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138878. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138879. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138880. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138881. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138882. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138883. 10,10,10, 8, 8, 8, 8, 8, 8,
  138884. };
  138885. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138886. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138887. 3.5, 4.5,
  138888. };
  138889. static long _vq_quantmap__44c1_s_p6_1[] = {
  138890. 9, 7, 5, 3, 1, 0, 2, 4,
  138891. 6, 8, 10,
  138892. };
  138893. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138894. _vq_quantthresh__44c1_s_p6_1,
  138895. _vq_quantmap__44c1_s_p6_1,
  138896. 11,
  138897. 11
  138898. };
  138899. static static_codebook _44c1_s_p6_1 = {
  138900. 2, 121,
  138901. _vq_lengthlist__44c1_s_p6_1,
  138902. 1, -531365888, 1611661312, 4, 0,
  138903. _vq_quantlist__44c1_s_p6_1,
  138904. NULL,
  138905. &_vq_auxt__44c1_s_p6_1,
  138906. NULL,
  138907. 0
  138908. };
  138909. static long _vq_quantlist__44c1_s_p7_0[] = {
  138910. 6,
  138911. 5,
  138912. 7,
  138913. 4,
  138914. 8,
  138915. 3,
  138916. 9,
  138917. 2,
  138918. 10,
  138919. 1,
  138920. 11,
  138921. 0,
  138922. 12,
  138923. };
  138924. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138925. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138926. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138927. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138928. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138929. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138930. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138931. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138932. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138933. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138934. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138935. 0,12,11,11,11,13,10,14,13,
  138936. };
  138937. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138938. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138939. 12.5, 17.5, 22.5, 27.5,
  138940. };
  138941. static long _vq_quantmap__44c1_s_p7_0[] = {
  138942. 11, 9, 7, 5, 3, 1, 0, 2,
  138943. 4, 6, 8, 10, 12,
  138944. };
  138945. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138946. _vq_quantthresh__44c1_s_p7_0,
  138947. _vq_quantmap__44c1_s_p7_0,
  138948. 13,
  138949. 13
  138950. };
  138951. static static_codebook _44c1_s_p7_0 = {
  138952. 2, 169,
  138953. _vq_lengthlist__44c1_s_p7_0,
  138954. 1, -526516224, 1616117760, 4, 0,
  138955. _vq_quantlist__44c1_s_p7_0,
  138956. NULL,
  138957. &_vq_auxt__44c1_s_p7_0,
  138958. NULL,
  138959. 0
  138960. };
  138961. static long _vq_quantlist__44c1_s_p7_1[] = {
  138962. 2,
  138963. 1,
  138964. 3,
  138965. 0,
  138966. 4,
  138967. };
  138968. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138969. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138970. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138971. };
  138972. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138973. -1.5, -0.5, 0.5, 1.5,
  138974. };
  138975. static long _vq_quantmap__44c1_s_p7_1[] = {
  138976. 3, 1, 0, 2, 4,
  138977. };
  138978. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138979. _vq_quantthresh__44c1_s_p7_1,
  138980. _vq_quantmap__44c1_s_p7_1,
  138981. 5,
  138982. 5
  138983. };
  138984. static static_codebook _44c1_s_p7_1 = {
  138985. 2, 25,
  138986. _vq_lengthlist__44c1_s_p7_1,
  138987. 1, -533725184, 1611661312, 3, 0,
  138988. _vq_quantlist__44c1_s_p7_1,
  138989. NULL,
  138990. &_vq_auxt__44c1_s_p7_1,
  138991. NULL,
  138992. 0
  138993. };
  138994. static long _vq_quantlist__44c1_s_p8_0[] = {
  138995. 6,
  138996. 5,
  138997. 7,
  138998. 4,
  138999. 8,
  139000. 3,
  139001. 9,
  139002. 2,
  139003. 10,
  139004. 1,
  139005. 11,
  139006. 0,
  139007. 12,
  139008. };
  139009. static long _vq_lengthlist__44c1_s_p8_0[] = {
  139010. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  139011. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  139012. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139013. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139014. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139015. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139016. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139017. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139018. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139019. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139020. 10,10,10,10,10,10,10,10,10,
  139021. };
  139022. static float _vq_quantthresh__44c1_s_p8_0[] = {
  139023. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139024. 552.5, 773.5, 994.5, 1215.5,
  139025. };
  139026. static long _vq_quantmap__44c1_s_p8_0[] = {
  139027. 11, 9, 7, 5, 3, 1, 0, 2,
  139028. 4, 6, 8, 10, 12,
  139029. };
  139030. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  139031. _vq_quantthresh__44c1_s_p8_0,
  139032. _vq_quantmap__44c1_s_p8_0,
  139033. 13,
  139034. 13
  139035. };
  139036. static static_codebook _44c1_s_p8_0 = {
  139037. 2, 169,
  139038. _vq_lengthlist__44c1_s_p8_0,
  139039. 1, -514541568, 1627103232, 4, 0,
  139040. _vq_quantlist__44c1_s_p8_0,
  139041. NULL,
  139042. &_vq_auxt__44c1_s_p8_0,
  139043. NULL,
  139044. 0
  139045. };
  139046. static long _vq_quantlist__44c1_s_p8_1[] = {
  139047. 6,
  139048. 5,
  139049. 7,
  139050. 4,
  139051. 8,
  139052. 3,
  139053. 9,
  139054. 2,
  139055. 10,
  139056. 1,
  139057. 11,
  139058. 0,
  139059. 12,
  139060. };
  139061. static long _vq_lengthlist__44c1_s_p8_1[] = {
  139062. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  139063. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  139064. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  139065. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  139066. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  139067. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  139068. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  139069. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  139070. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  139071. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  139072. 16,13,12,12,11,14,12,15,13,
  139073. };
  139074. static float _vq_quantthresh__44c1_s_p8_1[] = {
  139075. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139076. 42.5, 59.5, 76.5, 93.5,
  139077. };
  139078. static long _vq_quantmap__44c1_s_p8_1[] = {
  139079. 11, 9, 7, 5, 3, 1, 0, 2,
  139080. 4, 6, 8, 10, 12,
  139081. };
  139082. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  139083. _vq_quantthresh__44c1_s_p8_1,
  139084. _vq_quantmap__44c1_s_p8_1,
  139085. 13,
  139086. 13
  139087. };
  139088. static static_codebook _44c1_s_p8_1 = {
  139089. 2, 169,
  139090. _vq_lengthlist__44c1_s_p8_1,
  139091. 1, -522616832, 1620115456, 4, 0,
  139092. _vq_quantlist__44c1_s_p8_1,
  139093. NULL,
  139094. &_vq_auxt__44c1_s_p8_1,
  139095. NULL,
  139096. 0
  139097. };
  139098. static long _vq_quantlist__44c1_s_p8_2[] = {
  139099. 8,
  139100. 7,
  139101. 9,
  139102. 6,
  139103. 10,
  139104. 5,
  139105. 11,
  139106. 4,
  139107. 12,
  139108. 3,
  139109. 13,
  139110. 2,
  139111. 14,
  139112. 1,
  139113. 15,
  139114. 0,
  139115. 16,
  139116. };
  139117. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139118. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139119. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139120. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139121. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139122. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139123. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139124. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139125. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139126. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139127. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139128. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139129. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139130. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139131. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139132. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139133. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139134. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139135. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139136. 9,
  139137. };
  139138. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139139. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139140. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139141. };
  139142. static long _vq_quantmap__44c1_s_p8_2[] = {
  139143. 15, 13, 11, 9, 7, 5, 3, 1,
  139144. 0, 2, 4, 6, 8, 10, 12, 14,
  139145. 16,
  139146. };
  139147. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139148. _vq_quantthresh__44c1_s_p8_2,
  139149. _vq_quantmap__44c1_s_p8_2,
  139150. 17,
  139151. 17
  139152. };
  139153. static static_codebook _44c1_s_p8_2 = {
  139154. 2, 289,
  139155. _vq_lengthlist__44c1_s_p8_2,
  139156. 1, -529530880, 1611661312, 5, 0,
  139157. _vq_quantlist__44c1_s_p8_2,
  139158. NULL,
  139159. &_vq_auxt__44c1_s_p8_2,
  139160. NULL,
  139161. 0
  139162. };
  139163. static long _huff_lengthlist__44c1_s_short[] = {
  139164. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139165. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139166. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139167. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139168. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139169. 11,
  139170. };
  139171. static static_codebook _huff_book__44c1_s_short = {
  139172. 2, 81,
  139173. _huff_lengthlist__44c1_s_short,
  139174. 0, 0, 0, 0, 0,
  139175. NULL,
  139176. NULL,
  139177. NULL,
  139178. NULL,
  139179. 0
  139180. };
  139181. static long _huff_lengthlist__44c1_sm_long[] = {
  139182. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139183. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139184. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139185. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139186. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139187. 11,
  139188. };
  139189. static static_codebook _huff_book__44c1_sm_long = {
  139190. 2, 81,
  139191. _huff_lengthlist__44c1_sm_long,
  139192. 0, 0, 0, 0, 0,
  139193. NULL,
  139194. NULL,
  139195. NULL,
  139196. NULL,
  139197. 0
  139198. };
  139199. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139200. 1,
  139201. 0,
  139202. 2,
  139203. };
  139204. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139205. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139206. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139211. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139216. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  139251. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  139256. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  139261. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139297. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139302. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139307. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139615. 0,
  139616. };
  139617. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139618. -0.5, 0.5,
  139619. };
  139620. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139621. 1, 0, 2,
  139622. };
  139623. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139624. _vq_quantthresh__44c1_sm_p1_0,
  139625. _vq_quantmap__44c1_sm_p1_0,
  139626. 3,
  139627. 3
  139628. };
  139629. static static_codebook _44c1_sm_p1_0 = {
  139630. 8, 6561,
  139631. _vq_lengthlist__44c1_sm_p1_0,
  139632. 1, -535822336, 1611661312, 2, 0,
  139633. _vq_quantlist__44c1_sm_p1_0,
  139634. NULL,
  139635. &_vq_auxt__44c1_sm_p1_0,
  139636. NULL,
  139637. 0
  139638. };
  139639. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139640. 2,
  139641. 1,
  139642. 3,
  139643. 0,
  139644. 4,
  139645. };
  139646. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139647. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139650. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0,
  139687. };
  139688. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139689. -1.5, -0.5, 0.5, 1.5,
  139690. };
  139691. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139692. 3, 1, 0, 2, 4,
  139693. };
  139694. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139695. _vq_quantthresh__44c1_sm_p2_0,
  139696. _vq_quantmap__44c1_sm_p2_0,
  139697. 5,
  139698. 5
  139699. };
  139700. static static_codebook _44c1_sm_p2_0 = {
  139701. 4, 625,
  139702. _vq_lengthlist__44c1_sm_p2_0,
  139703. 1, -533725184, 1611661312, 3, 0,
  139704. _vq_quantlist__44c1_sm_p2_0,
  139705. NULL,
  139706. &_vq_auxt__44c1_sm_p2_0,
  139707. NULL,
  139708. 0
  139709. };
  139710. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139711. 4,
  139712. 3,
  139713. 5,
  139714. 2,
  139715. 6,
  139716. 1,
  139717. 7,
  139718. 0,
  139719. 8,
  139720. };
  139721. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139722. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139723. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139724. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139725. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139726. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0,
  139728. };
  139729. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139730. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139731. };
  139732. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139733. 7, 5, 3, 1, 0, 2, 4, 6,
  139734. 8,
  139735. };
  139736. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139737. _vq_quantthresh__44c1_sm_p3_0,
  139738. _vq_quantmap__44c1_sm_p3_0,
  139739. 9,
  139740. 9
  139741. };
  139742. static static_codebook _44c1_sm_p3_0 = {
  139743. 2, 81,
  139744. _vq_lengthlist__44c1_sm_p3_0,
  139745. 1, -531628032, 1611661312, 4, 0,
  139746. _vq_quantlist__44c1_sm_p3_0,
  139747. NULL,
  139748. &_vq_auxt__44c1_sm_p3_0,
  139749. NULL,
  139750. 0
  139751. };
  139752. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139753. 4,
  139754. 3,
  139755. 5,
  139756. 2,
  139757. 6,
  139758. 1,
  139759. 7,
  139760. 0,
  139761. 8,
  139762. };
  139763. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139764. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139765. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139766. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139767. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139768. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139769. 11,
  139770. };
  139771. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139772. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139773. };
  139774. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139775. 7, 5, 3, 1, 0, 2, 4, 6,
  139776. 8,
  139777. };
  139778. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139779. _vq_quantthresh__44c1_sm_p4_0,
  139780. _vq_quantmap__44c1_sm_p4_0,
  139781. 9,
  139782. 9
  139783. };
  139784. static static_codebook _44c1_sm_p4_0 = {
  139785. 2, 81,
  139786. _vq_lengthlist__44c1_sm_p4_0,
  139787. 1, -531628032, 1611661312, 4, 0,
  139788. _vq_quantlist__44c1_sm_p4_0,
  139789. NULL,
  139790. &_vq_auxt__44c1_sm_p4_0,
  139791. NULL,
  139792. 0
  139793. };
  139794. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139795. 8,
  139796. 7,
  139797. 9,
  139798. 6,
  139799. 10,
  139800. 5,
  139801. 11,
  139802. 4,
  139803. 12,
  139804. 3,
  139805. 13,
  139806. 2,
  139807. 14,
  139808. 1,
  139809. 15,
  139810. 0,
  139811. 16,
  139812. };
  139813. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139814. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139815. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139816. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139817. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139818. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139819. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139820. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139821. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139822. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139823. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139824. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139825. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139826. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139827. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139828. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139829. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139830. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139831. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139832. 14,
  139833. };
  139834. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139835. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139836. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139837. };
  139838. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139839. 15, 13, 11, 9, 7, 5, 3, 1,
  139840. 0, 2, 4, 6, 8, 10, 12, 14,
  139841. 16,
  139842. };
  139843. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139844. _vq_quantthresh__44c1_sm_p5_0,
  139845. _vq_quantmap__44c1_sm_p5_0,
  139846. 17,
  139847. 17
  139848. };
  139849. static static_codebook _44c1_sm_p5_0 = {
  139850. 2, 289,
  139851. _vq_lengthlist__44c1_sm_p5_0,
  139852. 1, -529530880, 1611661312, 5, 0,
  139853. _vq_quantlist__44c1_sm_p5_0,
  139854. NULL,
  139855. &_vq_auxt__44c1_sm_p5_0,
  139856. NULL,
  139857. 0
  139858. };
  139859. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139860. 1,
  139861. 0,
  139862. 2,
  139863. };
  139864. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139865. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139866. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139867. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139868. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139869. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139870. 11,
  139871. };
  139872. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139873. -5.5, 5.5,
  139874. };
  139875. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139876. 1, 0, 2,
  139877. };
  139878. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139879. _vq_quantthresh__44c1_sm_p6_0,
  139880. _vq_quantmap__44c1_sm_p6_0,
  139881. 3,
  139882. 3
  139883. };
  139884. static static_codebook _44c1_sm_p6_0 = {
  139885. 4, 81,
  139886. _vq_lengthlist__44c1_sm_p6_0,
  139887. 1, -529137664, 1618345984, 2, 0,
  139888. _vq_quantlist__44c1_sm_p6_0,
  139889. NULL,
  139890. &_vq_auxt__44c1_sm_p6_0,
  139891. NULL,
  139892. 0
  139893. };
  139894. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139895. 5,
  139896. 4,
  139897. 6,
  139898. 3,
  139899. 7,
  139900. 2,
  139901. 8,
  139902. 1,
  139903. 9,
  139904. 0,
  139905. 10,
  139906. };
  139907. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139908. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139909. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139910. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139911. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139912. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139913. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139914. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139915. 10,10,10, 8, 8, 8, 8, 8, 8,
  139916. };
  139917. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139918. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139919. 3.5, 4.5,
  139920. };
  139921. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139922. 9, 7, 5, 3, 1, 0, 2, 4,
  139923. 6, 8, 10,
  139924. };
  139925. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139926. _vq_quantthresh__44c1_sm_p6_1,
  139927. _vq_quantmap__44c1_sm_p6_1,
  139928. 11,
  139929. 11
  139930. };
  139931. static static_codebook _44c1_sm_p6_1 = {
  139932. 2, 121,
  139933. _vq_lengthlist__44c1_sm_p6_1,
  139934. 1, -531365888, 1611661312, 4, 0,
  139935. _vq_quantlist__44c1_sm_p6_1,
  139936. NULL,
  139937. &_vq_auxt__44c1_sm_p6_1,
  139938. NULL,
  139939. 0
  139940. };
  139941. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139942. 6,
  139943. 5,
  139944. 7,
  139945. 4,
  139946. 8,
  139947. 3,
  139948. 9,
  139949. 2,
  139950. 10,
  139951. 1,
  139952. 11,
  139953. 0,
  139954. 12,
  139955. };
  139956. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139957. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139958. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139959. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139960. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139961. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139962. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139963. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139964. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139965. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139966. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139967. 0,12,12,11,11,13,12,14,13,
  139968. };
  139969. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139970. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139971. 12.5, 17.5, 22.5, 27.5,
  139972. };
  139973. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139974. 11, 9, 7, 5, 3, 1, 0, 2,
  139975. 4, 6, 8, 10, 12,
  139976. };
  139977. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139978. _vq_quantthresh__44c1_sm_p7_0,
  139979. _vq_quantmap__44c1_sm_p7_0,
  139980. 13,
  139981. 13
  139982. };
  139983. static static_codebook _44c1_sm_p7_0 = {
  139984. 2, 169,
  139985. _vq_lengthlist__44c1_sm_p7_0,
  139986. 1, -526516224, 1616117760, 4, 0,
  139987. _vq_quantlist__44c1_sm_p7_0,
  139988. NULL,
  139989. &_vq_auxt__44c1_sm_p7_0,
  139990. NULL,
  139991. 0
  139992. };
  139993. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139994. 2,
  139995. 1,
  139996. 3,
  139997. 0,
  139998. 4,
  139999. };
  140000. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  140001. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  140002. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  140003. };
  140004. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  140005. -1.5, -0.5, 0.5, 1.5,
  140006. };
  140007. static long _vq_quantmap__44c1_sm_p7_1[] = {
  140008. 3, 1, 0, 2, 4,
  140009. };
  140010. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  140011. _vq_quantthresh__44c1_sm_p7_1,
  140012. _vq_quantmap__44c1_sm_p7_1,
  140013. 5,
  140014. 5
  140015. };
  140016. static static_codebook _44c1_sm_p7_1 = {
  140017. 2, 25,
  140018. _vq_lengthlist__44c1_sm_p7_1,
  140019. 1, -533725184, 1611661312, 3, 0,
  140020. _vq_quantlist__44c1_sm_p7_1,
  140021. NULL,
  140022. &_vq_auxt__44c1_sm_p7_1,
  140023. NULL,
  140024. 0
  140025. };
  140026. static long _vq_quantlist__44c1_sm_p8_0[] = {
  140027. 6,
  140028. 5,
  140029. 7,
  140030. 4,
  140031. 8,
  140032. 3,
  140033. 9,
  140034. 2,
  140035. 10,
  140036. 1,
  140037. 11,
  140038. 0,
  140039. 12,
  140040. };
  140041. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  140042. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  140043. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  140044. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140045. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140046. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140047. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140048. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140049. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140050. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140051. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140052. 13,13,13,13,13,13,13,13,13,
  140053. };
  140054. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  140055. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  140056. 552.5, 773.5, 994.5, 1215.5,
  140057. };
  140058. static long _vq_quantmap__44c1_sm_p8_0[] = {
  140059. 11, 9, 7, 5, 3, 1, 0, 2,
  140060. 4, 6, 8, 10, 12,
  140061. };
  140062. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  140063. _vq_quantthresh__44c1_sm_p8_0,
  140064. _vq_quantmap__44c1_sm_p8_0,
  140065. 13,
  140066. 13
  140067. };
  140068. static static_codebook _44c1_sm_p8_0 = {
  140069. 2, 169,
  140070. _vq_lengthlist__44c1_sm_p8_0,
  140071. 1, -514541568, 1627103232, 4, 0,
  140072. _vq_quantlist__44c1_sm_p8_0,
  140073. NULL,
  140074. &_vq_auxt__44c1_sm_p8_0,
  140075. NULL,
  140076. 0
  140077. };
  140078. static long _vq_quantlist__44c1_sm_p8_1[] = {
  140079. 6,
  140080. 5,
  140081. 7,
  140082. 4,
  140083. 8,
  140084. 3,
  140085. 9,
  140086. 2,
  140087. 10,
  140088. 1,
  140089. 11,
  140090. 0,
  140091. 12,
  140092. };
  140093. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  140094. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  140095. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  140096. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  140097. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  140098. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  140099. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  140100. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  140101. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  140102. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  140103. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  140104. 20,13,12,12,12,14,12,14,13,
  140105. };
  140106. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  140107. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140108. 42.5, 59.5, 76.5, 93.5,
  140109. };
  140110. static long _vq_quantmap__44c1_sm_p8_1[] = {
  140111. 11, 9, 7, 5, 3, 1, 0, 2,
  140112. 4, 6, 8, 10, 12,
  140113. };
  140114. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140115. _vq_quantthresh__44c1_sm_p8_1,
  140116. _vq_quantmap__44c1_sm_p8_1,
  140117. 13,
  140118. 13
  140119. };
  140120. static static_codebook _44c1_sm_p8_1 = {
  140121. 2, 169,
  140122. _vq_lengthlist__44c1_sm_p8_1,
  140123. 1, -522616832, 1620115456, 4, 0,
  140124. _vq_quantlist__44c1_sm_p8_1,
  140125. NULL,
  140126. &_vq_auxt__44c1_sm_p8_1,
  140127. NULL,
  140128. 0
  140129. };
  140130. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140131. 8,
  140132. 7,
  140133. 9,
  140134. 6,
  140135. 10,
  140136. 5,
  140137. 11,
  140138. 4,
  140139. 12,
  140140. 3,
  140141. 13,
  140142. 2,
  140143. 14,
  140144. 1,
  140145. 15,
  140146. 0,
  140147. 16,
  140148. };
  140149. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140150. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140151. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140152. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140153. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140154. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140155. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140156. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140157. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140158. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140159. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140160. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140161. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140162. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140163. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140164. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140165. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140166. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140167. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140168. 9,
  140169. };
  140170. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140171. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140172. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140173. };
  140174. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140175. 15, 13, 11, 9, 7, 5, 3, 1,
  140176. 0, 2, 4, 6, 8, 10, 12, 14,
  140177. 16,
  140178. };
  140179. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140180. _vq_quantthresh__44c1_sm_p8_2,
  140181. _vq_quantmap__44c1_sm_p8_2,
  140182. 17,
  140183. 17
  140184. };
  140185. static static_codebook _44c1_sm_p8_2 = {
  140186. 2, 289,
  140187. _vq_lengthlist__44c1_sm_p8_2,
  140188. 1, -529530880, 1611661312, 5, 0,
  140189. _vq_quantlist__44c1_sm_p8_2,
  140190. NULL,
  140191. &_vq_auxt__44c1_sm_p8_2,
  140192. NULL,
  140193. 0
  140194. };
  140195. static long _huff_lengthlist__44c1_sm_short[] = {
  140196. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140197. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140198. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140199. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140200. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140201. 11,
  140202. };
  140203. static static_codebook _huff_book__44c1_sm_short = {
  140204. 2, 81,
  140205. _huff_lengthlist__44c1_sm_short,
  140206. 0, 0, 0, 0, 0,
  140207. NULL,
  140208. NULL,
  140209. NULL,
  140210. NULL,
  140211. 0
  140212. };
  140213. static long _huff_lengthlist__44cn1_s_long[] = {
  140214. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140215. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140216. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140217. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140218. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140219. 20,
  140220. };
  140221. static static_codebook _huff_book__44cn1_s_long = {
  140222. 2, 81,
  140223. _huff_lengthlist__44cn1_s_long,
  140224. 0, 0, 0, 0, 0,
  140225. NULL,
  140226. NULL,
  140227. NULL,
  140228. NULL,
  140229. 0
  140230. };
  140231. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140232. 1,
  140233. 0,
  140234. 2,
  140235. };
  140236. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140237. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140238. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140243. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140248. 0, 0, 0, 0, 8,10, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  140283. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  140288. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  140293. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140329. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140334. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140339. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140647. 0,
  140648. };
  140649. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140650. -0.5, 0.5,
  140651. };
  140652. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140653. 1, 0, 2,
  140654. };
  140655. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140656. _vq_quantthresh__44cn1_s_p1_0,
  140657. _vq_quantmap__44cn1_s_p1_0,
  140658. 3,
  140659. 3
  140660. };
  140661. static static_codebook _44cn1_s_p1_0 = {
  140662. 8, 6561,
  140663. _vq_lengthlist__44cn1_s_p1_0,
  140664. 1, -535822336, 1611661312, 2, 0,
  140665. _vq_quantlist__44cn1_s_p1_0,
  140666. NULL,
  140667. &_vq_auxt__44cn1_s_p1_0,
  140668. NULL,
  140669. 0
  140670. };
  140671. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140672. 2,
  140673. 1,
  140674. 3,
  140675. 0,
  140676. 4,
  140677. };
  140678. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140679. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140682. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140685. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0,
  140719. };
  140720. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140721. -1.5, -0.5, 0.5, 1.5,
  140722. };
  140723. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140724. 3, 1, 0, 2, 4,
  140725. };
  140726. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140727. _vq_quantthresh__44cn1_s_p2_0,
  140728. _vq_quantmap__44cn1_s_p2_0,
  140729. 5,
  140730. 5
  140731. };
  140732. static static_codebook _44cn1_s_p2_0 = {
  140733. 4, 625,
  140734. _vq_lengthlist__44cn1_s_p2_0,
  140735. 1, -533725184, 1611661312, 3, 0,
  140736. _vq_quantlist__44cn1_s_p2_0,
  140737. NULL,
  140738. &_vq_auxt__44cn1_s_p2_0,
  140739. NULL,
  140740. 0
  140741. };
  140742. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140743. 4,
  140744. 3,
  140745. 5,
  140746. 2,
  140747. 6,
  140748. 1,
  140749. 7,
  140750. 0,
  140751. 8,
  140752. };
  140753. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140754. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140755. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140756. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140757. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140758. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140759. 0,
  140760. };
  140761. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140762. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140763. };
  140764. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140765. 7, 5, 3, 1, 0, 2, 4, 6,
  140766. 8,
  140767. };
  140768. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140769. _vq_quantthresh__44cn1_s_p3_0,
  140770. _vq_quantmap__44cn1_s_p3_0,
  140771. 9,
  140772. 9
  140773. };
  140774. static static_codebook _44cn1_s_p3_0 = {
  140775. 2, 81,
  140776. _vq_lengthlist__44cn1_s_p3_0,
  140777. 1, -531628032, 1611661312, 4, 0,
  140778. _vq_quantlist__44cn1_s_p3_0,
  140779. NULL,
  140780. &_vq_auxt__44cn1_s_p3_0,
  140781. NULL,
  140782. 0
  140783. };
  140784. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140785. 4,
  140786. 3,
  140787. 5,
  140788. 2,
  140789. 6,
  140790. 1,
  140791. 7,
  140792. 0,
  140793. 8,
  140794. };
  140795. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140796. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140797. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140798. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140799. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140800. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140801. 11,
  140802. };
  140803. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140804. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140805. };
  140806. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140807. 7, 5, 3, 1, 0, 2, 4, 6,
  140808. 8,
  140809. };
  140810. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140811. _vq_quantthresh__44cn1_s_p4_0,
  140812. _vq_quantmap__44cn1_s_p4_0,
  140813. 9,
  140814. 9
  140815. };
  140816. static static_codebook _44cn1_s_p4_0 = {
  140817. 2, 81,
  140818. _vq_lengthlist__44cn1_s_p4_0,
  140819. 1, -531628032, 1611661312, 4, 0,
  140820. _vq_quantlist__44cn1_s_p4_0,
  140821. NULL,
  140822. &_vq_auxt__44cn1_s_p4_0,
  140823. NULL,
  140824. 0
  140825. };
  140826. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140827. 8,
  140828. 7,
  140829. 9,
  140830. 6,
  140831. 10,
  140832. 5,
  140833. 11,
  140834. 4,
  140835. 12,
  140836. 3,
  140837. 13,
  140838. 2,
  140839. 14,
  140840. 1,
  140841. 15,
  140842. 0,
  140843. 16,
  140844. };
  140845. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140846. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140847. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140848. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140849. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140850. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140851. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140852. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140853. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140854. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140855. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140856. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140857. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140858. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140859. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140860. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140861. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140862. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140863. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140864. 14,
  140865. };
  140866. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140867. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140868. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140869. };
  140870. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140871. 15, 13, 11, 9, 7, 5, 3, 1,
  140872. 0, 2, 4, 6, 8, 10, 12, 14,
  140873. 16,
  140874. };
  140875. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140876. _vq_quantthresh__44cn1_s_p5_0,
  140877. _vq_quantmap__44cn1_s_p5_0,
  140878. 17,
  140879. 17
  140880. };
  140881. static static_codebook _44cn1_s_p5_0 = {
  140882. 2, 289,
  140883. _vq_lengthlist__44cn1_s_p5_0,
  140884. 1, -529530880, 1611661312, 5, 0,
  140885. _vq_quantlist__44cn1_s_p5_0,
  140886. NULL,
  140887. &_vq_auxt__44cn1_s_p5_0,
  140888. NULL,
  140889. 0
  140890. };
  140891. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140892. 1,
  140893. 0,
  140894. 2,
  140895. };
  140896. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140897. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140898. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140899. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140900. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140901. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140902. 10,
  140903. };
  140904. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140905. -5.5, 5.5,
  140906. };
  140907. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140908. 1, 0, 2,
  140909. };
  140910. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140911. _vq_quantthresh__44cn1_s_p6_0,
  140912. _vq_quantmap__44cn1_s_p6_0,
  140913. 3,
  140914. 3
  140915. };
  140916. static static_codebook _44cn1_s_p6_0 = {
  140917. 4, 81,
  140918. _vq_lengthlist__44cn1_s_p6_0,
  140919. 1, -529137664, 1618345984, 2, 0,
  140920. _vq_quantlist__44cn1_s_p6_0,
  140921. NULL,
  140922. &_vq_auxt__44cn1_s_p6_0,
  140923. NULL,
  140924. 0
  140925. };
  140926. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140927. 5,
  140928. 4,
  140929. 6,
  140930. 3,
  140931. 7,
  140932. 2,
  140933. 8,
  140934. 1,
  140935. 9,
  140936. 0,
  140937. 10,
  140938. };
  140939. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140940. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140941. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140942. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140943. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140944. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140945. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140946. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140947. 10,10,10, 9, 9, 9, 9, 9, 9,
  140948. };
  140949. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140950. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140951. 3.5, 4.5,
  140952. };
  140953. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140954. 9, 7, 5, 3, 1, 0, 2, 4,
  140955. 6, 8, 10,
  140956. };
  140957. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140958. _vq_quantthresh__44cn1_s_p6_1,
  140959. _vq_quantmap__44cn1_s_p6_1,
  140960. 11,
  140961. 11
  140962. };
  140963. static static_codebook _44cn1_s_p6_1 = {
  140964. 2, 121,
  140965. _vq_lengthlist__44cn1_s_p6_1,
  140966. 1, -531365888, 1611661312, 4, 0,
  140967. _vq_quantlist__44cn1_s_p6_1,
  140968. NULL,
  140969. &_vq_auxt__44cn1_s_p6_1,
  140970. NULL,
  140971. 0
  140972. };
  140973. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140974. 6,
  140975. 5,
  140976. 7,
  140977. 4,
  140978. 8,
  140979. 3,
  140980. 9,
  140981. 2,
  140982. 10,
  140983. 1,
  140984. 11,
  140985. 0,
  140986. 12,
  140987. };
  140988. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140989. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140990. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140991. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140992. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140993. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140994. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140995. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140996. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140997. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140998. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140999. 0,13,13,12,12,13,13,13,14,
  141000. };
  141001. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  141002. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141003. 12.5, 17.5, 22.5, 27.5,
  141004. };
  141005. static long _vq_quantmap__44cn1_s_p7_0[] = {
  141006. 11, 9, 7, 5, 3, 1, 0, 2,
  141007. 4, 6, 8, 10, 12,
  141008. };
  141009. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  141010. _vq_quantthresh__44cn1_s_p7_0,
  141011. _vq_quantmap__44cn1_s_p7_0,
  141012. 13,
  141013. 13
  141014. };
  141015. static static_codebook _44cn1_s_p7_0 = {
  141016. 2, 169,
  141017. _vq_lengthlist__44cn1_s_p7_0,
  141018. 1, -526516224, 1616117760, 4, 0,
  141019. _vq_quantlist__44cn1_s_p7_0,
  141020. NULL,
  141021. &_vq_auxt__44cn1_s_p7_0,
  141022. NULL,
  141023. 0
  141024. };
  141025. static long _vq_quantlist__44cn1_s_p7_1[] = {
  141026. 2,
  141027. 1,
  141028. 3,
  141029. 0,
  141030. 4,
  141031. };
  141032. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  141033. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  141034. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  141035. };
  141036. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  141037. -1.5, -0.5, 0.5, 1.5,
  141038. };
  141039. static long _vq_quantmap__44cn1_s_p7_1[] = {
  141040. 3, 1, 0, 2, 4,
  141041. };
  141042. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  141043. _vq_quantthresh__44cn1_s_p7_1,
  141044. _vq_quantmap__44cn1_s_p7_1,
  141045. 5,
  141046. 5
  141047. };
  141048. static static_codebook _44cn1_s_p7_1 = {
  141049. 2, 25,
  141050. _vq_lengthlist__44cn1_s_p7_1,
  141051. 1, -533725184, 1611661312, 3, 0,
  141052. _vq_quantlist__44cn1_s_p7_1,
  141053. NULL,
  141054. &_vq_auxt__44cn1_s_p7_1,
  141055. NULL,
  141056. 0
  141057. };
  141058. static long _vq_quantlist__44cn1_s_p8_0[] = {
  141059. 2,
  141060. 1,
  141061. 3,
  141062. 0,
  141063. 4,
  141064. };
  141065. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  141066. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  141067. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  141068. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141069. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  141070. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141071. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141072. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141073. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  141074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141075. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  141076. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141078. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141080. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141081. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  141082. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141083. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141084. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141098. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141099. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  141100. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141101. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141102. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141103. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141104. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141105. 12,
  141106. };
  141107. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  141108. -331.5, -110.5, 110.5, 331.5,
  141109. };
  141110. static long _vq_quantmap__44cn1_s_p8_0[] = {
  141111. 3, 1, 0, 2, 4,
  141112. };
  141113. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  141114. _vq_quantthresh__44cn1_s_p8_0,
  141115. _vq_quantmap__44cn1_s_p8_0,
  141116. 5,
  141117. 5
  141118. };
  141119. static static_codebook _44cn1_s_p8_0 = {
  141120. 4, 625,
  141121. _vq_lengthlist__44cn1_s_p8_0,
  141122. 1, -518283264, 1627103232, 3, 0,
  141123. _vq_quantlist__44cn1_s_p8_0,
  141124. NULL,
  141125. &_vq_auxt__44cn1_s_p8_0,
  141126. NULL,
  141127. 0
  141128. };
  141129. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141130. 6,
  141131. 5,
  141132. 7,
  141133. 4,
  141134. 8,
  141135. 3,
  141136. 9,
  141137. 2,
  141138. 10,
  141139. 1,
  141140. 11,
  141141. 0,
  141142. 12,
  141143. };
  141144. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141145. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141146. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141147. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141148. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141149. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141150. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141151. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141152. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141153. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141154. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141155. 15,12,12,11,11,14,12,13,14,
  141156. };
  141157. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141158. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141159. 42.5, 59.5, 76.5, 93.5,
  141160. };
  141161. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141162. 11, 9, 7, 5, 3, 1, 0, 2,
  141163. 4, 6, 8, 10, 12,
  141164. };
  141165. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141166. _vq_quantthresh__44cn1_s_p8_1,
  141167. _vq_quantmap__44cn1_s_p8_1,
  141168. 13,
  141169. 13
  141170. };
  141171. static static_codebook _44cn1_s_p8_1 = {
  141172. 2, 169,
  141173. _vq_lengthlist__44cn1_s_p8_1,
  141174. 1, -522616832, 1620115456, 4, 0,
  141175. _vq_quantlist__44cn1_s_p8_1,
  141176. NULL,
  141177. &_vq_auxt__44cn1_s_p8_1,
  141178. NULL,
  141179. 0
  141180. };
  141181. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141182. 8,
  141183. 7,
  141184. 9,
  141185. 6,
  141186. 10,
  141187. 5,
  141188. 11,
  141189. 4,
  141190. 12,
  141191. 3,
  141192. 13,
  141193. 2,
  141194. 14,
  141195. 1,
  141196. 15,
  141197. 0,
  141198. 16,
  141199. };
  141200. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141201. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141202. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141203. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141204. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141205. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141206. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141207. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141208. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141209. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141210. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141211. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141212. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141213. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141214. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141215. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141216. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141217. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141218. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141219. 9,
  141220. };
  141221. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141222. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141223. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141224. };
  141225. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141226. 15, 13, 11, 9, 7, 5, 3, 1,
  141227. 0, 2, 4, 6, 8, 10, 12, 14,
  141228. 16,
  141229. };
  141230. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141231. _vq_quantthresh__44cn1_s_p8_2,
  141232. _vq_quantmap__44cn1_s_p8_2,
  141233. 17,
  141234. 17
  141235. };
  141236. static static_codebook _44cn1_s_p8_2 = {
  141237. 2, 289,
  141238. _vq_lengthlist__44cn1_s_p8_2,
  141239. 1, -529530880, 1611661312, 5, 0,
  141240. _vq_quantlist__44cn1_s_p8_2,
  141241. NULL,
  141242. &_vq_auxt__44cn1_s_p8_2,
  141243. NULL,
  141244. 0
  141245. };
  141246. static long _huff_lengthlist__44cn1_s_short[] = {
  141247. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141248. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141249. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141250. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141251. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141252. 10,
  141253. };
  141254. static static_codebook _huff_book__44cn1_s_short = {
  141255. 2, 81,
  141256. _huff_lengthlist__44cn1_s_short,
  141257. 0, 0, 0, 0, 0,
  141258. NULL,
  141259. NULL,
  141260. NULL,
  141261. NULL,
  141262. 0
  141263. };
  141264. static long _huff_lengthlist__44cn1_sm_long[] = {
  141265. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141266. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141267. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141268. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141269. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141270. 17,
  141271. };
  141272. static static_codebook _huff_book__44cn1_sm_long = {
  141273. 2, 81,
  141274. _huff_lengthlist__44cn1_sm_long,
  141275. 0, 0, 0, 0, 0,
  141276. NULL,
  141277. NULL,
  141278. NULL,
  141279. NULL,
  141280. 0
  141281. };
  141282. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141283. 1,
  141284. 0,
  141285. 2,
  141286. };
  141287. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141288. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141289. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141294. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141299. 0, 0, 0, 0, 8, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  141334. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  141339. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  141344. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141380. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141385. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141390. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141698. 0,
  141699. };
  141700. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141701. -0.5, 0.5,
  141702. };
  141703. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141704. 1, 0, 2,
  141705. };
  141706. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141707. _vq_quantthresh__44cn1_sm_p1_0,
  141708. _vq_quantmap__44cn1_sm_p1_0,
  141709. 3,
  141710. 3
  141711. };
  141712. static static_codebook _44cn1_sm_p1_0 = {
  141713. 8, 6561,
  141714. _vq_lengthlist__44cn1_sm_p1_0,
  141715. 1, -535822336, 1611661312, 2, 0,
  141716. _vq_quantlist__44cn1_sm_p1_0,
  141717. NULL,
  141718. &_vq_auxt__44cn1_sm_p1_0,
  141719. NULL,
  141720. 0
  141721. };
  141722. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141723. 2,
  141724. 1,
  141725. 3,
  141726. 0,
  141727. 4,
  141728. };
  141729. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141730. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141733. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141736. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141769. 0,
  141770. };
  141771. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141772. -1.5, -0.5, 0.5, 1.5,
  141773. };
  141774. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141775. 3, 1, 0, 2, 4,
  141776. };
  141777. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141778. _vq_quantthresh__44cn1_sm_p2_0,
  141779. _vq_quantmap__44cn1_sm_p2_0,
  141780. 5,
  141781. 5
  141782. };
  141783. static static_codebook _44cn1_sm_p2_0 = {
  141784. 4, 625,
  141785. _vq_lengthlist__44cn1_sm_p2_0,
  141786. 1, -533725184, 1611661312, 3, 0,
  141787. _vq_quantlist__44cn1_sm_p2_0,
  141788. NULL,
  141789. &_vq_auxt__44cn1_sm_p2_0,
  141790. NULL,
  141791. 0
  141792. };
  141793. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141794. 4,
  141795. 3,
  141796. 5,
  141797. 2,
  141798. 6,
  141799. 1,
  141800. 7,
  141801. 0,
  141802. 8,
  141803. };
  141804. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141805. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141806. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141807. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141808. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141809. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141810. 0,
  141811. };
  141812. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141813. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141814. };
  141815. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141816. 7, 5, 3, 1, 0, 2, 4, 6,
  141817. 8,
  141818. };
  141819. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141820. _vq_quantthresh__44cn1_sm_p3_0,
  141821. _vq_quantmap__44cn1_sm_p3_0,
  141822. 9,
  141823. 9
  141824. };
  141825. static static_codebook _44cn1_sm_p3_0 = {
  141826. 2, 81,
  141827. _vq_lengthlist__44cn1_sm_p3_0,
  141828. 1, -531628032, 1611661312, 4, 0,
  141829. _vq_quantlist__44cn1_sm_p3_0,
  141830. NULL,
  141831. &_vq_auxt__44cn1_sm_p3_0,
  141832. NULL,
  141833. 0
  141834. };
  141835. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141836. 4,
  141837. 3,
  141838. 5,
  141839. 2,
  141840. 6,
  141841. 1,
  141842. 7,
  141843. 0,
  141844. 8,
  141845. };
  141846. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141847. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141848. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141849. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141850. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141851. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141852. 11,
  141853. };
  141854. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141855. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141856. };
  141857. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141858. 7, 5, 3, 1, 0, 2, 4, 6,
  141859. 8,
  141860. };
  141861. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141862. _vq_quantthresh__44cn1_sm_p4_0,
  141863. _vq_quantmap__44cn1_sm_p4_0,
  141864. 9,
  141865. 9
  141866. };
  141867. static static_codebook _44cn1_sm_p4_0 = {
  141868. 2, 81,
  141869. _vq_lengthlist__44cn1_sm_p4_0,
  141870. 1, -531628032, 1611661312, 4, 0,
  141871. _vq_quantlist__44cn1_sm_p4_0,
  141872. NULL,
  141873. &_vq_auxt__44cn1_sm_p4_0,
  141874. NULL,
  141875. 0
  141876. };
  141877. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141878. 8,
  141879. 7,
  141880. 9,
  141881. 6,
  141882. 10,
  141883. 5,
  141884. 11,
  141885. 4,
  141886. 12,
  141887. 3,
  141888. 13,
  141889. 2,
  141890. 14,
  141891. 1,
  141892. 15,
  141893. 0,
  141894. 16,
  141895. };
  141896. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141897. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141898. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141899. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141900. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141901. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141902. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141903. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141904. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141905. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141906. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141907. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141908. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141909. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141910. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141911. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141912. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141913. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141914. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141915. 14,
  141916. };
  141917. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141918. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141919. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141920. };
  141921. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141922. 15, 13, 11, 9, 7, 5, 3, 1,
  141923. 0, 2, 4, 6, 8, 10, 12, 14,
  141924. 16,
  141925. };
  141926. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141927. _vq_quantthresh__44cn1_sm_p5_0,
  141928. _vq_quantmap__44cn1_sm_p5_0,
  141929. 17,
  141930. 17
  141931. };
  141932. static static_codebook _44cn1_sm_p5_0 = {
  141933. 2, 289,
  141934. _vq_lengthlist__44cn1_sm_p5_0,
  141935. 1, -529530880, 1611661312, 5, 0,
  141936. _vq_quantlist__44cn1_sm_p5_0,
  141937. NULL,
  141938. &_vq_auxt__44cn1_sm_p5_0,
  141939. NULL,
  141940. 0
  141941. };
  141942. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141943. 1,
  141944. 0,
  141945. 2,
  141946. };
  141947. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141948. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141949. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141950. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141951. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141952. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141953. 10,
  141954. };
  141955. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141956. -5.5, 5.5,
  141957. };
  141958. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141959. 1, 0, 2,
  141960. };
  141961. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141962. _vq_quantthresh__44cn1_sm_p6_0,
  141963. _vq_quantmap__44cn1_sm_p6_0,
  141964. 3,
  141965. 3
  141966. };
  141967. static static_codebook _44cn1_sm_p6_0 = {
  141968. 4, 81,
  141969. _vq_lengthlist__44cn1_sm_p6_0,
  141970. 1, -529137664, 1618345984, 2, 0,
  141971. _vq_quantlist__44cn1_sm_p6_0,
  141972. NULL,
  141973. &_vq_auxt__44cn1_sm_p6_0,
  141974. NULL,
  141975. 0
  141976. };
  141977. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141978. 5,
  141979. 4,
  141980. 6,
  141981. 3,
  141982. 7,
  141983. 2,
  141984. 8,
  141985. 1,
  141986. 9,
  141987. 0,
  141988. 10,
  141989. };
  141990. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141991. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141992. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141993. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141994. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141995. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141996. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141997. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141998. 10,10,10, 8, 9, 8, 8, 9, 8,
  141999. };
  142000. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  142001. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142002. 3.5, 4.5,
  142003. };
  142004. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  142005. 9, 7, 5, 3, 1, 0, 2, 4,
  142006. 6, 8, 10,
  142007. };
  142008. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  142009. _vq_quantthresh__44cn1_sm_p6_1,
  142010. _vq_quantmap__44cn1_sm_p6_1,
  142011. 11,
  142012. 11
  142013. };
  142014. static static_codebook _44cn1_sm_p6_1 = {
  142015. 2, 121,
  142016. _vq_lengthlist__44cn1_sm_p6_1,
  142017. 1, -531365888, 1611661312, 4, 0,
  142018. _vq_quantlist__44cn1_sm_p6_1,
  142019. NULL,
  142020. &_vq_auxt__44cn1_sm_p6_1,
  142021. NULL,
  142022. 0
  142023. };
  142024. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  142025. 6,
  142026. 5,
  142027. 7,
  142028. 4,
  142029. 8,
  142030. 3,
  142031. 9,
  142032. 2,
  142033. 10,
  142034. 1,
  142035. 11,
  142036. 0,
  142037. 12,
  142038. };
  142039. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  142040. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  142041. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  142042. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  142043. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  142044. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  142045. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  142046. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  142047. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  142048. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  142049. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  142050. 0,13,12,12,12,13,13,13,14,
  142051. };
  142052. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  142053. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142054. 12.5, 17.5, 22.5, 27.5,
  142055. };
  142056. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  142057. 11, 9, 7, 5, 3, 1, 0, 2,
  142058. 4, 6, 8, 10, 12,
  142059. };
  142060. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  142061. _vq_quantthresh__44cn1_sm_p7_0,
  142062. _vq_quantmap__44cn1_sm_p7_0,
  142063. 13,
  142064. 13
  142065. };
  142066. static static_codebook _44cn1_sm_p7_0 = {
  142067. 2, 169,
  142068. _vq_lengthlist__44cn1_sm_p7_0,
  142069. 1, -526516224, 1616117760, 4, 0,
  142070. _vq_quantlist__44cn1_sm_p7_0,
  142071. NULL,
  142072. &_vq_auxt__44cn1_sm_p7_0,
  142073. NULL,
  142074. 0
  142075. };
  142076. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  142077. 2,
  142078. 1,
  142079. 3,
  142080. 0,
  142081. 4,
  142082. };
  142083. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  142084. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  142085. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  142086. };
  142087. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  142088. -1.5, -0.5, 0.5, 1.5,
  142089. };
  142090. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  142091. 3, 1, 0, 2, 4,
  142092. };
  142093. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  142094. _vq_quantthresh__44cn1_sm_p7_1,
  142095. _vq_quantmap__44cn1_sm_p7_1,
  142096. 5,
  142097. 5
  142098. };
  142099. static static_codebook _44cn1_sm_p7_1 = {
  142100. 2, 25,
  142101. _vq_lengthlist__44cn1_sm_p7_1,
  142102. 1, -533725184, 1611661312, 3, 0,
  142103. _vq_quantlist__44cn1_sm_p7_1,
  142104. NULL,
  142105. &_vq_auxt__44cn1_sm_p7_1,
  142106. NULL,
  142107. 0
  142108. };
  142109. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  142110. 4,
  142111. 3,
  142112. 5,
  142113. 2,
  142114. 6,
  142115. 1,
  142116. 7,
  142117. 0,
  142118. 8,
  142119. };
  142120. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142121. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142122. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142123. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142124. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142125. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142126. 14,
  142127. };
  142128. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142129. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142130. };
  142131. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142132. 7, 5, 3, 1, 0, 2, 4, 6,
  142133. 8,
  142134. };
  142135. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142136. _vq_quantthresh__44cn1_sm_p8_0,
  142137. _vq_quantmap__44cn1_sm_p8_0,
  142138. 9,
  142139. 9
  142140. };
  142141. static static_codebook _44cn1_sm_p8_0 = {
  142142. 2, 81,
  142143. _vq_lengthlist__44cn1_sm_p8_0,
  142144. 1, -516186112, 1627103232, 4, 0,
  142145. _vq_quantlist__44cn1_sm_p8_0,
  142146. NULL,
  142147. &_vq_auxt__44cn1_sm_p8_0,
  142148. NULL,
  142149. 0
  142150. };
  142151. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142152. 6,
  142153. 5,
  142154. 7,
  142155. 4,
  142156. 8,
  142157. 3,
  142158. 9,
  142159. 2,
  142160. 10,
  142161. 1,
  142162. 11,
  142163. 0,
  142164. 12,
  142165. };
  142166. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142167. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142168. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142169. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142170. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142171. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142172. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142173. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142174. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142175. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142176. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142177. 17,12,12,11,10,13,11,13,13,
  142178. };
  142179. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142180. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142181. 42.5, 59.5, 76.5, 93.5,
  142182. };
  142183. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142184. 11, 9, 7, 5, 3, 1, 0, 2,
  142185. 4, 6, 8, 10, 12,
  142186. };
  142187. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142188. _vq_quantthresh__44cn1_sm_p8_1,
  142189. _vq_quantmap__44cn1_sm_p8_1,
  142190. 13,
  142191. 13
  142192. };
  142193. static static_codebook _44cn1_sm_p8_1 = {
  142194. 2, 169,
  142195. _vq_lengthlist__44cn1_sm_p8_1,
  142196. 1, -522616832, 1620115456, 4, 0,
  142197. _vq_quantlist__44cn1_sm_p8_1,
  142198. NULL,
  142199. &_vq_auxt__44cn1_sm_p8_1,
  142200. NULL,
  142201. 0
  142202. };
  142203. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142204. 8,
  142205. 7,
  142206. 9,
  142207. 6,
  142208. 10,
  142209. 5,
  142210. 11,
  142211. 4,
  142212. 12,
  142213. 3,
  142214. 13,
  142215. 2,
  142216. 14,
  142217. 1,
  142218. 15,
  142219. 0,
  142220. 16,
  142221. };
  142222. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142223. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142224. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142225. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142226. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142227. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142228. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142229. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142230. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142231. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142232. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142233. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142234. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142235. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142236. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142237. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142238. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142239. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142240. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142241. 9,
  142242. };
  142243. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142244. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142245. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142246. };
  142247. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142248. 15, 13, 11, 9, 7, 5, 3, 1,
  142249. 0, 2, 4, 6, 8, 10, 12, 14,
  142250. 16,
  142251. };
  142252. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142253. _vq_quantthresh__44cn1_sm_p8_2,
  142254. _vq_quantmap__44cn1_sm_p8_2,
  142255. 17,
  142256. 17
  142257. };
  142258. static static_codebook _44cn1_sm_p8_2 = {
  142259. 2, 289,
  142260. _vq_lengthlist__44cn1_sm_p8_2,
  142261. 1, -529530880, 1611661312, 5, 0,
  142262. _vq_quantlist__44cn1_sm_p8_2,
  142263. NULL,
  142264. &_vq_auxt__44cn1_sm_p8_2,
  142265. NULL,
  142266. 0
  142267. };
  142268. static long _huff_lengthlist__44cn1_sm_short[] = {
  142269. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142270. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142271. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142272. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142273. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142274. 9,
  142275. };
  142276. static static_codebook _huff_book__44cn1_sm_short = {
  142277. 2, 81,
  142278. _huff_lengthlist__44cn1_sm_short,
  142279. 0, 0, 0, 0, 0,
  142280. NULL,
  142281. NULL,
  142282. NULL,
  142283. NULL,
  142284. 0
  142285. };
  142286. /*** End of inlined file: res_books_stereo.h ***/
  142287. /***** residue backends *********************************************/
  142288. static vorbis_info_residue0 _residue_44_low={
  142289. 0,-1, -1, 9,-1,
  142290. /* 0 1 2 3 4 5 6 7 */
  142291. {0},
  142292. {-1},
  142293. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142294. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142295. };
  142296. static vorbis_info_residue0 _residue_44_mid={
  142297. 0,-1, -1, 10,-1,
  142298. /* 0 1 2 3 4 5 6 7 8 */
  142299. {0},
  142300. {-1},
  142301. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142302. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142303. };
  142304. static vorbis_info_residue0 _residue_44_high={
  142305. 0,-1, -1, 10,-1,
  142306. /* 0 1 2 3 4 5 6 7 8 */
  142307. {0},
  142308. {-1},
  142309. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142310. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142311. };
  142312. static static_bookblock _resbook_44s_n1={
  142313. {
  142314. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142315. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142316. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142317. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142318. }
  142319. };
  142320. static static_bookblock _resbook_44sm_n1={
  142321. {
  142322. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142323. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142324. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142325. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142326. }
  142327. };
  142328. static static_bookblock _resbook_44s_0={
  142329. {
  142330. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142331. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142332. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142333. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142334. }
  142335. };
  142336. static static_bookblock _resbook_44sm_0={
  142337. {
  142338. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142339. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142340. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142341. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142342. }
  142343. };
  142344. static static_bookblock _resbook_44s_1={
  142345. {
  142346. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142347. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142348. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142349. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142350. }
  142351. };
  142352. static static_bookblock _resbook_44sm_1={
  142353. {
  142354. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142355. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142356. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142357. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142358. }
  142359. };
  142360. static static_bookblock _resbook_44s_2={
  142361. {
  142362. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142363. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142364. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142365. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142366. }
  142367. };
  142368. static static_bookblock _resbook_44s_3={
  142369. {
  142370. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142371. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142372. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142373. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142374. }
  142375. };
  142376. static static_bookblock _resbook_44s_4={
  142377. {
  142378. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142379. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142380. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142381. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142382. }
  142383. };
  142384. static static_bookblock _resbook_44s_5={
  142385. {
  142386. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142387. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142388. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142389. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142390. }
  142391. };
  142392. static static_bookblock _resbook_44s_6={
  142393. {
  142394. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142395. {0,0,&_44c6_s_p4_0},
  142396. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142397. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142398. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142399. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142400. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142401. }
  142402. };
  142403. static static_bookblock _resbook_44s_7={
  142404. {
  142405. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142406. {0,0,&_44c7_s_p4_0},
  142407. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142408. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142409. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142410. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142411. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142412. }
  142413. };
  142414. static static_bookblock _resbook_44s_8={
  142415. {
  142416. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142417. {0,0,&_44c8_s_p4_0},
  142418. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142419. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142420. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142421. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142422. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142423. }
  142424. };
  142425. static static_bookblock _resbook_44s_9={
  142426. {
  142427. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142428. {0,0,&_44c9_s_p4_0},
  142429. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142430. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142431. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142432. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142433. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142434. }
  142435. };
  142436. static vorbis_residue_template _res_44s_n1[]={
  142437. {2,0, &_residue_44_low,
  142438. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142439. &_resbook_44s_n1,&_resbook_44sm_n1},
  142440. {2,0, &_residue_44_low,
  142441. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142442. &_resbook_44s_n1,&_resbook_44sm_n1}
  142443. };
  142444. static vorbis_residue_template _res_44s_0[]={
  142445. {2,0, &_residue_44_low,
  142446. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142447. &_resbook_44s_0,&_resbook_44sm_0},
  142448. {2,0, &_residue_44_low,
  142449. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142450. &_resbook_44s_0,&_resbook_44sm_0}
  142451. };
  142452. static vorbis_residue_template _res_44s_1[]={
  142453. {2,0, &_residue_44_low,
  142454. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142455. &_resbook_44s_1,&_resbook_44sm_1},
  142456. {2,0, &_residue_44_low,
  142457. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142458. &_resbook_44s_1,&_resbook_44sm_1}
  142459. };
  142460. static vorbis_residue_template _res_44s_2[]={
  142461. {2,0, &_residue_44_mid,
  142462. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142463. &_resbook_44s_2,&_resbook_44s_2},
  142464. {2,0, &_residue_44_mid,
  142465. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142466. &_resbook_44s_2,&_resbook_44s_2}
  142467. };
  142468. static vorbis_residue_template _res_44s_3[]={
  142469. {2,0, &_residue_44_mid,
  142470. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142471. &_resbook_44s_3,&_resbook_44s_3},
  142472. {2,0, &_residue_44_mid,
  142473. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142474. &_resbook_44s_3,&_resbook_44s_3}
  142475. };
  142476. static vorbis_residue_template _res_44s_4[]={
  142477. {2,0, &_residue_44_mid,
  142478. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142479. &_resbook_44s_4,&_resbook_44s_4},
  142480. {2,0, &_residue_44_mid,
  142481. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142482. &_resbook_44s_4,&_resbook_44s_4}
  142483. };
  142484. static vorbis_residue_template _res_44s_5[]={
  142485. {2,0, &_residue_44_mid,
  142486. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142487. &_resbook_44s_5,&_resbook_44s_5},
  142488. {2,0, &_residue_44_mid,
  142489. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142490. &_resbook_44s_5,&_resbook_44s_5}
  142491. };
  142492. static vorbis_residue_template _res_44s_6[]={
  142493. {2,0, &_residue_44_high,
  142494. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142495. &_resbook_44s_6,&_resbook_44s_6},
  142496. {2,0, &_residue_44_high,
  142497. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142498. &_resbook_44s_6,&_resbook_44s_6}
  142499. };
  142500. static vorbis_residue_template _res_44s_7[]={
  142501. {2,0, &_residue_44_high,
  142502. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142503. &_resbook_44s_7,&_resbook_44s_7},
  142504. {2,0, &_residue_44_high,
  142505. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142506. &_resbook_44s_7,&_resbook_44s_7}
  142507. };
  142508. static vorbis_residue_template _res_44s_8[]={
  142509. {2,0, &_residue_44_high,
  142510. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142511. &_resbook_44s_8,&_resbook_44s_8},
  142512. {2,0, &_residue_44_high,
  142513. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142514. &_resbook_44s_8,&_resbook_44s_8}
  142515. };
  142516. static vorbis_residue_template _res_44s_9[]={
  142517. {2,0, &_residue_44_high,
  142518. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142519. &_resbook_44s_9,&_resbook_44s_9},
  142520. {2,0, &_residue_44_high,
  142521. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142522. &_resbook_44s_9,&_resbook_44s_9}
  142523. };
  142524. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142525. { _map_nominal, _res_44s_n1 }, /* -1 */
  142526. { _map_nominal, _res_44s_0 }, /* 0 */
  142527. { _map_nominal, _res_44s_1 }, /* 1 */
  142528. { _map_nominal, _res_44s_2 }, /* 2 */
  142529. { _map_nominal, _res_44s_3 }, /* 3 */
  142530. { _map_nominal, _res_44s_4 }, /* 4 */
  142531. { _map_nominal, _res_44s_5 }, /* 5 */
  142532. { _map_nominal, _res_44s_6 }, /* 6 */
  142533. { _map_nominal, _res_44s_7 }, /* 7 */
  142534. { _map_nominal, _res_44s_8 }, /* 8 */
  142535. { _map_nominal, _res_44s_9 }, /* 9 */
  142536. };
  142537. /*** End of inlined file: residue_44.h ***/
  142538. /*** Start of inlined file: psych_44.h ***/
  142539. /* preecho trigger settings *****************************************/
  142540. static vorbis_info_psy_global _psy_global_44[5]={
  142541. {8, /* lines per eighth octave */
  142542. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142543. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142544. -6.f,
  142545. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142546. },
  142547. {8, /* lines per eighth octave */
  142548. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142549. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142550. -6.f,
  142551. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142552. },
  142553. {8, /* lines per eighth octave */
  142554. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142555. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142556. -6.f,
  142557. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142558. },
  142559. {8, /* lines per eighth octave */
  142560. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142561. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142562. -6.f,
  142563. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142564. },
  142565. {8, /* lines per eighth octave */
  142566. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142567. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142568. -6.f,
  142569. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142570. },
  142571. };
  142572. /* noise compander lookups * low, mid, high quality ****************/
  142573. static compandblock _psy_compand_44[6]={
  142574. /* sub-mode Z short */
  142575. {{
  142576. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142577. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142578. 16,17,18,19,20,21,22, 23, /* 23dB */
  142579. 24,25,26,27,28,29,30, 31, /* 31dB */
  142580. 32,33,34,35,36,37,38, 39, /* 39dB */
  142581. }},
  142582. /* mode_Z nominal short */
  142583. {{
  142584. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142585. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142586. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142587. 15,16,17,17,17,18,18, 19, /* 31dB */
  142588. 19,19,20,21,22,23,24, 25, /* 39dB */
  142589. }},
  142590. /* mode A short */
  142591. {{
  142592. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142593. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142594. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142595. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142596. 11,12,13,14,15,16,17, 18, /* 39dB */
  142597. }},
  142598. /* sub-mode Z long */
  142599. {{
  142600. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142601. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142602. 16,17,18,19,20,21,22, 23, /* 23dB */
  142603. 24,25,26,27,28,29,30, 31, /* 31dB */
  142604. 32,33,34,35,36,37,38, 39, /* 39dB */
  142605. }},
  142606. /* mode_Z nominal long */
  142607. {{
  142608. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142609. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142610. 13,14,14,14,15,15,15, 15, /* 23dB */
  142611. 16,16,17,17,17,18,18, 19, /* 31dB */
  142612. 19,19,20,21,22,23,24, 25, /* 39dB */
  142613. }},
  142614. /* mode A long */
  142615. {{
  142616. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142617. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142618. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142619. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142620. 11,12,13,14,15,16,17, 18, /* 39dB */
  142621. }}
  142622. };
  142623. /* tonal masking curve level adjustments *************************/
  142624. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142625. /* 63 125 250 500 1 2 4 8 16 */
  142626. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142627. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142628. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142629. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142630. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142631. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142632. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142633. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142634. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142635. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142636. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142637. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142638. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142639. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142640. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142641. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142642. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142643. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142644. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142645. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142646. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142647. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142648. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142649. };
  142650. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142651. /* 63 125 250 500 1 2 4 8 16 */
  142652. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142653. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142654. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142655. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142656. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142657. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142658. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142659. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142660. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142661. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142662. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142663. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142664. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142665. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142666. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142667. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142668. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142669. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142670. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142671. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142672. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142673. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142674. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142675. };
  142676. /* noise bias (transition block) */
  142677. static noise3 _psy_noisebias_trans[12]={
  142678. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142679. /* -1 */
  142680. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142681. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142682. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142683. /* 0
  142684. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142685. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142686. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142687. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142688. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142689. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142690. /* 1
  142691. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142692. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142693. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142694. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142695. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142696. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142697. /* 2
  142698. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142699. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142700. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142701. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142702. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142703. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142704. /* 3
  142705. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142706. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142707. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142708. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142709. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142710. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142711. /* 4
  142712. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142713. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142714. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142715. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142716. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142717. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142718. /* 5
  142719. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142720. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142721. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142722. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142723. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142724. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142725. /* 6
  142726. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142727. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142728. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142729. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142730. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142731. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142732. /* 7
  142733. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142734. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142735. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142736. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142737. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142738. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142739. /* 8
  142740. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142741. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142742. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142743. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142744. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142745. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142746. /* 9
  142747. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142748. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142749. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142750. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142751. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142752. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142753. /* 10 */
  142754. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142755. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142756. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142757. };
  142758. /* noise bias (long block) */
  142759. static noise3 _psy_noisebias_long[12]={
  142760. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142761. /* -1 */
  142762. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142763. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142764. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142765. /* 0 */
  142766. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142767. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142768. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142769. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142770. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142771. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142772. /* 1 */
  142773. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142774. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142775. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142776. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142777. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142778. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142779. /* 2 */
  142780. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142781. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142782. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142783. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142784. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142785. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142786. /* 3 */
  142787. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142788. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142789. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142790. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142791. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142792. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142793. /* 4 */
  142794. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142795. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142796. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142797. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142798. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142799. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142800. /* 5 */
  142801. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142802. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142803. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142804. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142805. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142806. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142807. /* 6 */
  142808. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142809. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142810. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142811. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142812. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142813. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142814. /* 7 */
  142815. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142816. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142817. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142818. /* 8 */
  142819. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142820. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142821. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142822. /* 9 */
  142823. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142824. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142825. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142826. /* 10 */
  142827. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142828. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142829. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142830. };
  142831. /* noise bias (impulse block) */
  142832. static noise3 _psy_noisebias_impulse[12]={
  142833. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142834. /* -1 */
  142835. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142836. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142837. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142838. /* 0 */
  142839. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142840. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142841. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142842. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142843. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142844. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142845. /* 1 */
  142846. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142847. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142848. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142849. /* 2 */
  142850. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142851. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142852. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142853. /* 3 */
  142854. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142855. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142856. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142857. /* 4 */
  142858. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142859. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142860. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142861. /* 5 */
  142862. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142863. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142864. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142865. /* 6
  142866. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142867. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142868. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142869. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142870. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142871. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142872. /* 7 */
  142873. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142874. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142875. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142876. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142877. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142878. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142879. /* 8 */
  142880. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142881. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142882. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142883. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142884. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142885. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142886. /* 9 */
  142887. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142888. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142889. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142890. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142891. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142892. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142893. /* 10 */
  142894. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142895. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142896. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142897. };
  142898. /* noise bias (padding block) */
  142899. static noise3 _psy_noisebias_padding[12]={
  142900. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142901. /* -1 */
  142902. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142903. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142904. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142905. /* 0 */
  142906. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142907. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142908. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142909. /* 1 */
  142910. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142911. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142912. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142913. /* 2 */
  142914. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142915. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142916. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142917. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142918. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142919. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142920. /* 3 */
  142921. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142922. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142923. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142924. /* 4 */
  142925. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142926. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142927. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142928. /* 5 */
  142929. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142930. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142931. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142932. /* 6 */
  142933. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142934. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142935. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142936. /* 7 */
  142937. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142938. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142939. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142940. /* 8 */
  142941. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142942. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142943. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142944. /* 9 */
  142945. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142946. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142947. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142948. /* 10 */
  142949. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142950. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142951. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142952. };
  142953. static noiseguard _psy_noiseguards_44[4]={
  142954. {3,3,15},
  142955. {3,3,15},
  142956. {10,10,100},
  142957. {10,10,100},
  142958. };
  142959. static int _psy_tone_suppress[12]={
  142960. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142961. };
  142962. static int _psy_tone_0dB[12]={
  142963. 90,90,95,95,95,95,105,105,105,105,105,105,
  142964. };
  142965. static int _psy_noise_suppress[12]={
  142966. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142967. };
  142968. static vorbis_info_psy _psy_info_template={
  142969. /* blockflag */
  142970. -1,
  142971. /* ath_adjatt, ath_maxatt */
  142972. -140.,-140.,
  142973. /* tonemask att boost/decay,suppr,curves */
  142974. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142975. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142976. 1, -0.f, .5f, .5f, 0,0,0,
  142977. /* noiseoffset*3, noisecompand, max_curve_dB */
  142978. {{-1},{-1},{-1}},{-1},105.f,
  142979. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142980. 0,0,-1,-1,0.,
  142981. };
  142982. /* ath ****************/
  142983. static int _psy_ath_floater[12]={
  142984. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142985. };
  142986. static int _psy_ath_abs[12]={
  142987. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142988. };
  142989. /* stereo setup. These don't map directly to quality level, there's
  142990. an additional indirection as several of the below may be used in a
  142991. single bitmanaged stream
  142992. ****************/
  142993. /* various stereo possibilities */
  142994. /* stereo mode by base quality level */
  142995. static adj_stereo _psy_stereo_modes_44[12]={
  142996. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142997. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142998. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142999. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  143000. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  143001. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  143002. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  143003. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  143004. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  143005. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143006. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  143007. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  143008. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  143009. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  143010. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  143011. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  143012. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  143013. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  143014. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143015. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  143016. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  143017. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  143018. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  143019. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  143020. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  143021. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  143022. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  143023. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143024. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  143025. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  143026. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  143027. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  143028. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143029. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  143030. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143031. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  143032. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  143033. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143034. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  143035. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143036. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  143037. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143038. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143039. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143040. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  143041. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  143042. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143043. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  143044. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143045. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143046. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143047. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  143048. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143049. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143050. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143051. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143052. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  143053. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143054. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143055. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143056. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143057. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143058. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143059. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143060. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143061. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  143062. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143063. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143064. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143065. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143066. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143067. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143068. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143069. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143070. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  143071. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143072. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143073. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143074. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143075. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  143076. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143077. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143078. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143079. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143080. };
  143081. /* tone master attenuation by base quality mode and bitrate tweak */
  143082. static att3 _psy_tone_masteratt_44[12]={
  143083. {{ 35, 21, 9}, 0, 0}, /* -1 */
  143084. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  143085. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  143086. {{ 25, 12, 2}, 0, 0}, /* 1 */
  143087. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  143088. {{ 20, 9, -3}, 0, 0}, /* 2 */
  143089. {{ 20, 9, -4}, 0, 0}, /* 3 */
  143090. {{ 20, 9, -4}, 0, 0}, /* 4 */
  143091. {{ 20, 6, -6}, 0, 0}, /* 5 */
  143092. {{ 20, 3, -10}, 0, 0}, /* 6 */
  143093. {{ 18, 1, -14}, 0, 0}, /* 7 */
  143094. {{ 18, 0, -16}, 0, 0}, /* 8 */
  143095. {{ 18, -2, -16}, 0, 0}, /* 9 */
  143096. {{ 12, -2, -20}, 0, 0}, /* 10 */
  143097. };
  143098. /* lowpass by mode **************/
  143099. static double _psy_lowpass_44[12]={
  143100. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  143101. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  143102. };
  143103. /* noise normalization **********/
  143104. static int _noise_start_short_44[11]={
  143105. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  143106. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  143107. };
  143108. static int _noise_start_long_44[11]={
  143109. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  143110. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  143111. };
  143112. static int _noise_part_short_44[11]={
  143113. 8,8,8,8,8,8,8,8,8,8,8
  143114. };
  143115. static int _noise_part_long_44[11]={
  143116. 32,32,32,32,32,32,32,32,32,32,32
  143117. };
  143118. static double _noise_thresh_44[11]={
  143119. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143120. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143121. };
  143122. static double _noise_thresh_5only[2]={
  143123. .5,.5,
  143124. };
  143125. /*** End of inlined file: psych_44.h ***/
  143126. static double rate_mapping_44_stereo[12]={
  143127. 22500.,32000.,40000.,48000.,56000.,64000.,
  143128. 80000.,96000.,112000.,128000.,160000.,250001.
  143129. };
  143130. static double quality_mapping_44[12]={
  143131. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143132. };
  143133. static int blocksize_short_44[11]={
  143134. 512,256,256,256,256,256,256,256,256,256,256
  143135. };
  143136. static int blocksize_long_44[11]={
  143137. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143138. };
  143139. static double _psy_compand_short_mapping[12]={
  143140. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143141. };
  143142. static double _psy_compand_long_mapping[12]={
  143143. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143144. };
  143145. static double _global_mapping_44[12]={
  143146. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143147. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143148. };
  143149. static int _floor_short_mapping_44[11]={
  143150. 1,0,0,2,2,4,5,5,5,5,5
  143151. };
  143152. static int _floor_long_mapping_44[11]={
  143153. 8,7,7,7,7,7,7,7,7,7,7
  143154. };
  143155. ve_setup_data_template ve_setup_44_stereo={
  143156. 11,
  143157. rate_mapping_44_stereo,
  143158. quality_mapping_44,
  143159. 2,
  143160. 40000,
  143161. 50000,
  143162. blocksize_short_44,
  143163. blocksize_long_44,
  143164. _psy_tone_masteratt_44,
  143165. _psy_tone_0dB,
  143166. _psy_tone_suppress,
  143167. _vp_tonemask_adj_otherblock,
  143168. _vp_tonemask_adj_longblock,
  143169. _vp_tonemask_adj_otherblock,
  143170. _psy_noiseguards_44,
  143171. _psy_noisebias_impulse,
  143172. _psy_noisebias_padding,
  143173. _psy_noisebias_trans,
  143174. _psy_noisebias_long,
  143175. _psy_noise_suppress,
  143176. _psy_compand_44,
  143177. _psy_compand_short_mapping,
  143178. _psy_compand_long_mapping,
  143179. {_noise_start_short_44,_noise_start_long_44},
  143180. {_noise_part_short_44,_noise_part_long_44},
  143181. _noise_thresh_44,
  143182. _psy_ath_floater,
  143183. _psy_ath_abs,
  143184. _psy_lowpass_44,
  143185. _psy_global_44,
  143186. _global_mapping_44,
  143187. _psy_stereo_modes_44,
  143188. _floor_books,
  143189. _floor,
  143190. _floor_short_mapping_44,
  143191. _floor_long_mapping_44,
  143192. _mapres_template_44_stereo
  143193. };
  143194. /*** End of inlined file: setup_44.h ***/
  143195. /*** Start of inlined file: setup_44u.h ***/
  143196. /*** Start of inlined file: residue_44u.h ***/
  143197. /*** Start of inlined file: res_books_uncoupled.h ***/
  143198. static long _vq_quantlist__16u0__p1_0[] = {
  143199. 1,
  143200. 0,
  143201. 2,
  143202. };
  143203. static long _vq_lengthlist__16u0__p1_0[] = {
  143204. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143205. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143206. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143207. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143208. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143209. 12,
  143210. };
  143211. static float _vq_quantthresh__16u0__p1_0[] = {
  143212. -0.5, 0.5,
  143213. };
  143214. static long _vq_quantmap__16u0__p1_0[] = {
  143215. 1, 0, 2,
  143216. };
  143217. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143218. _vq_quantthresh__16u0__p1_0,
  143219. _vq_quantmap__16u0__p1_0,
  143220. 3,
  143221. 3
  143222. };
  143223. static static_codebook _16u0__p1_0 = {
  143224. 4, 81,
  143225. _vq_lengthlist__16u0__p1_0,
  143226. 1, -535822336, 1611661312, 2, 0,
  143227. _vq_quantlist__16u0__p1_0,
  143228. NULL,
  143229. &_vq_auxt__16u0__p1_0,
  143230. NULL,
  143231. 0
  143232. };
  143233. static long _vq_quantlist__16u0__p2_0[] = {
  143234. 1,
  143235. 0,
  143236. 2,
  143237. };
  143238. static long _vq_lengthlist__16u0__p2_0[] = {
  143239. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143240. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143241. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143242. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143243. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143244. 8,
  143245. };
  143246. static float _vq_quantthresh__16u0__p2_0[] = {
  143247. -0.5, 0.5,
  143248. };
  143249. static long _vq_quantmap__16u0__p2_0[] = {
  143250. 1, 0, 2,
  143251. };
  143252. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143253. _vq_quantthresh__16u0__p2_0,
  143254. _vq_quantmap__16u0__p2_0,
  143255. 3,
  143256. 3
  143257. };
  143258. static static_codebook _16u0__p2_0 = {
  143259. 4, 81,
  143260. _vq_lengthlist__16u0__p2_0,
  143261. 1, -535822336, 1611661312, 2, 0,
  143262. _vq_quantlist__16u0__p2_0,
  143263. NULL,
  143264. &_vq_auxt__16u0__p2_0,
  143265. NULL,
  143266. 0
  143267. };
  143268. static long _vq_quantlist__16u0__p3_0[] = {
  143269. 2,
  143270. 1,
  143271. 3,
  143272. 0,
  143273. 4,
  143274. };
  143275. static long _vq_lengthlist__16u0__p3_0[] = {
  143276. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143277. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143278. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143279. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143280. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143281. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143282. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143283. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143284. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143285. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143286. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143287. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143288. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143289. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143290. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143291. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143292. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143293. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143294. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143295. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143296. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143297. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143298. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143299. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143300. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143301. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143302. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143303. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143304. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143305. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143306. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143307. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143308. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143309. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143310. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143311. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143312. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143313. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143314. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143315. 18,
  143316. };
  143317. static float _vq_quantthresh__16u0__p3_0[] = {
  143318. -1.5, -0.5, 0.5, 1.5,
  143319. };
  143320. static long _vq_quantmap__16u0__p3_0[] = {
  143321. 3, 1, 0, 2, 4,
  143322. };
  143323. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143324. _vq_quantthresh__16u0__p3_0,
  143325. _vq_quantmap__16u0__p3_0,
  143326. 5,
  143327. 5
  143328. };
  143329. static static_codebook _16u0__p3_0 = {
  143330. 4, 625,
  143331. _vq_lengthlist__16u0__p3_0,
  143332. 1, -533725184, 1611661312, 3, 0,
  143333. _vq_quantlist__16u0__p3_0,
  143334. NULL,
  143335. &_vq_auxt__16u0__p3_0,
  143336. NULL,
  143337. 0
  143338. };
  143339. static long _vq_quantlist__16u0__p4_0[] = {
  143340. 2,
  143341. 1,
  143342. 3,
  143343. 0,
  143344. 4,
  143345. };
  143346. static long _vq_lengthlist__16u0__p4_0[] = {
  143347. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143348. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143349. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143350. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143351. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143352. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143353. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143354. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143355. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143356. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143357. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143358. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143359. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143360. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143361. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143362. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143363. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143364. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143365. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143366. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143367. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143368. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143369. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143370. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143371. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143372. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143373. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143374. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143375. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143376. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143377. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143378. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143379. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143380. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143381. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143382. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143383. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143384. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143385. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143386. 11,
  143387. };
  143388. static float _vq_quantthresh__16u0__p4_0[] = {
  143389. -1.5, -0.5, 0.5, 1.5,
  143390. };
  143391. static long _vq_quantmap__16u0__p4_0[] = {
  143392. 3, 1, 0, 2, 4,
  143393. };
  143394. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143395. _vq_quantthresh__16u0__p4_0,
  143396. _vq_quantmap__16u0__p4_0,
  143397. 5,
  143398. 5
  143399. };
  143400. static static_codebook _16u0__p4_0 = {
  143401. 4, 625,
  143402. _vq_lengthlist__16u0__p4_0,
  143403. 1, -533725184, 1611661312, 3, 0,
  143404. _vq_quantlist__16u0__p4_0,
  143405. NULL,
  143406. &_vq_auxt__16u0__p4_0,
  143407. NULL,
  143408. 0
  143409. };
  143410. static long _vq_quantlist__16u0__p5_0[] = {
  143411. 4,
  143412. 3,
  143413. 5,
  143414. 2,
  143415. 6,
  143416. 1,
  143417. 7,
  143418. 0,
  143419. 8,
  143420. };
  143421. static long _vq_lengthlist__16u0__p5_0[] = {
  143422. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143423. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143424. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143425. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143426. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143427. 12,
  143428. };
  143429. static float _vq_quantthresh__16u0__p5_0[] = {
  143430. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143431. };
  143432. static long _vq_quantmap__16u0__p5_0[] = {
  143433. 7, 5, 3, 1, 0, 2, 4, 6,
  143434. 8,
  143435. };
  143436. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143437. _vq_quantthresh__16u0__p5_0,
  143438. _vq_quantmap__16u0__p5_0,
  143439. 9,
  143440. 9
  143441. };
  143442. static static_codebook _16u0__p5_0 = {
  143443. 2, 81,
  143444. _vq_lengthlist__16u0__p5_0,
  143445. 1, -531628032, 1611661312, 4, 0,
  143446. _vq_quantlist__16u0__p5_0,
  143447. NULL,
  143448. &_vq_auxt__16u0__p5_0,
  143449. NULL,
  143450. 0
  143451. };
  143452. static long _vq_quantlist__16u0__p6_0[] = {
  143453. 6,
  143454. 5,
  143455. 7,
  143456. 4,
  143457. 8,
  143458. 3,
  143459. 9,
  143460. 2,
  143461. 10,
  143462. 1,
  143463. 11,
  143464. 0,
  143465. 12,
  143466. };
  143467. static long _vq_lengthlist__16u0__p6_0[] = {
  143468. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143469. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143470. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143471. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143472. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143473. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143474. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143475. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143476. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143477. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143478. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143479. };
  143480. static float _vq_quantthresh__16u0__p6_0[] = {
  143481. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143482. 12.5, 17.5, 22.5, 27.5,
  143483. };
  143484. static long _vq_quantmap__16u0__p6_0[] = {
  143485. 11, 9, 7, 5, 3, 1, 0, 2,
  143486. 4, 6, 8, 10, 12,
  143487. };
  143488. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143489. _vq_quantthresh__16u0__p6_0,
  143490. _vq_quantmap__16u0__p6_0,
  143491. 13,
  143492. 13
  143493. };
  143494. static static_codebook _16u0__p6_0 = {
  143495. 2, 169,
  143496. _vq_lengthlist__16u0__p6_0,
  143497. 1, -526516224, 1616117760, 4, 0,
  143498. _vq_quantlist__16u0__p6_0,
  143499. NULL,
  143500. &_vq_auxt__16u0__p6_0,
  143501. NULL,
  143502. 0
  143503. };
  143504. static long _vq_quantlist__16u0__p6_1[] = {
  143505. 2,
  143506. 1,
  143507. 3,
  143508. 0,
  143509. 4,
  143510. };
  143511. static long _vq_lengthlist__16u0__p6_1[] = {
  143512. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143513. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143514. };
  143515. static float _vq_quantthresh__16u0__p6_1[] = {
  143516. -1.5, -0.5, 0.5, 1.5,
  143517. };
  143518. static long _vq_quantmap__16u0__p6_1[] = {
  143519. 3, 1, 0, 2, 4,
  143520. };
  143521. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143522. _vq_quantthresh__16u0__p6_1,
  143523. _vq_quantmap__16u0__p6_1,
  143524. 5,
  143525. 5
  143526. };
  143527. static static_codebook _16u0__p6_1 = {
  143528. 2, 25,
  143529. _vq_lengthlist__16u0__p6_1,
  143530. 1, -533725184, 1611661312, 3, 0,
  143531. _vq_quantlist__16u0__p6_1,
  143532. NULL,
  143533. &_vq_auxt__16u0__p6_1,
  143534. NULL,
  143535. 0
  143536. };
  143537. static long _vq_quantlist__16u0__p7_0[] = {
  143538. 1,
  143539. 0,
  143540. 2,
  143541. };
  143542. static long _vq_lengthlist__16u0__p7_0[] = {
  143543. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143544. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143545. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143546. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143547. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143548. 7,
  143549. };
  143550. static float _vq_quantthresh__16u0__p7_0[] = {
  143551. -157.5, 157.5,
  143552. };
  143553. static long _vq_quantmap__16u0__p7_0[] = {
  143554. 1, 0, 2,
  143555. };
  143556. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143557. _vq_quantthresh__16u0__p7_0,
  143558. _vq_quantmap__16u0__p7_0,
  143559. 3,
  143560. 3
  143561. };
  143562. static static_codebook _16u0__p7_0 = {
  143563. 4, 81,
  143564. _vq_lengthlist__16u0__p7_0,
  143565. 1, -518803456, 1628680192, 2, 0,
  143566. _vq_quantlist__16u0__p7_0,
  143567. NULL,
  143568. &_vq_auxt__16u0__p7_0,
  143569. NULL,
  143570. 0
  143571. };
  143572. static long _vq_quantlist__16u0__p7_1[] = {
  143573. 7,
  143574. 6,
  143575. 8,
  143576. 5,
  143577. 9,
  143578. 4,
  143579. 10,
  143580. 3,
  143581. 11,
  143582. 2,
  143583. 12,
  143584. 1,
  143585. 13,
  143586. 0,
  143587. 14,
  143588. };
  143589. static long _vq_lengthlist__16u0__p7_1[] = {
  143590. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143591. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143592. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143593. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143594. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143595. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143596. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143597. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143598. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143599. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143600. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143601. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143602. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143603. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143604. 10,
  143605. };
  143606. static float _vq_quantthresh__16u0__p7_1[] = {
  143607. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143608. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143609. };
  143610. static long _vq_quantmap__16u0__p7_1[] = {
  143611. 13, 11, 9, 7, 5, 3, 1, 0,
  143612. 2, 4, 6, 8, 10, 12, 14,
  143613. };
  143614. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143615. _vq_quantthresh__16u0__p7_1,
  143616. _vq_quantmap__16u0__p7_1,
  143617. 15,
  143618. 15
  143619. };
  143620. static static_codebook _16u0__p7_1 = {
  143621. 2, 225,
  143622. _vq_lengthlist__16u0__p7_1,
  143623. 1, -520986624, 1620377600, 4, 0,
  143624. _vq_quantlist__16u0__p7_1,
  143625. NULL,
  143626. &_vq_auxt__16u0__p7_1,
  143627. NULL,
  143628. 0
  143629. };
  143630. static long _vq_quantlist__16u0__p7_2[] = {
  143631. 10,
  143632. 9,
  143633. 11,
  143634. 8,
  143635. 12,
  143636. 7,
  143637. 13,
  143638. 6,
  143639. 14,
  143640. 5,
  143641. 15,
  143642. 4,
  143643. 16,
  143644. 3,
  143645. 17,
  143646. 2,
  143647. 18,
  143648. 1,
  143649. 19,
  143650. 0,
  143651. 20,
  143652. };
  143653. static long _vq_lengthlist__16u0__p7_2[] = {
  143654. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143655. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143656. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143657. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143658. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143659. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143660. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143661. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143662. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143663. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143664. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143665. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143666. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143667. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143668. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143669. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143670. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143671. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143672. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143673. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143674. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143675. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143676. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143677. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143678. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143679. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143680. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143681. 10,10,12,11,10,11,11,11,10,
  143682. };
  143683. static float _vq_quantthresh__16u0__p7_2[] = {
  143684. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143685. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143686. 6.5, 7.5, 8.5, 9.5,
  143687. };
  143688. static long _vq_quantmap__16u0__p7_2[] = {
  143689. 19, 17, 15, 13, 11, 9, 7, 5,
  143690. 3, 1, 0, 2, 4, 6, 8, 10,
  143691. 12, 14, 16, 18, 20,
  143692. };
  143693. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143694. _vq_quantthresh__16u0__p7_2,
  143695. _vq_quantmap__16u0__p7_2,
  143696. 21,
  143697. 21
  143698. };
  143699. static static_codebook _16u0__p7_2 = {
  143700. 2, 441,
  143701. _vq_lengthlist__16u0__p7_2,
  143702. 1, -529268736, 1611661312, 5, 0,
  143703. _vq_quantlist__16u0__p7_2,
  143704. NULL,
  143705. &_vq_auxt__16u0__p7_2,
  143706. NULL,
  143707. 0
  143708. };
  143709. static long _huff_lengthlist__16u0__single[] = {
  143710. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143711. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143712. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143713. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143714. };
  143715. static static_codebook _huff_book__16u0__single = {
  143716. 2, 64,
  143717. _huff_lengthlist__16u0__single,
  143718. 0, 0, 0, 0, 0,
  143719. NULL,
  143720. NULL,
  143721. NULL,
  143722. NULL,
  143723. 0
  143724. };
  143725. static long _huff_lengthlist__16u1__long[] = {
  143726. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143727. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143728. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143729. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143730. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143731. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143732. 16,13,16,18,
  143733. };
  143734. static static_codebook _huff_book__16u1__long = {
  143735. 2, 100,
  143736. _huff_lengthlist__16u1__long,
  143737. 0, 0, 0, 0, 0,
  143738. NULL,
  143739. NULL,
  143740. NULL,
  143741. NULL,
  143742. 0
  143743. };
  143744. static long _vq_quantlist__16u1__p1_0[] = {
  143745. 1,
  143746. 0,
  143747. 2,
  143748. };
  143749. static long _vq_lengthlist__16u1__p1_0[] = {
  143750. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143751. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143752. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143753. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143754. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143755. 11,
  143756. };
  143757. static float _vq_quantthresh__16u1__p1_0[] = {
  143758. -0.5, 0.5,
  143759. };
  143760. static long _vq_quantmap__16u1__p1_0[] = {
  143761. 1, 0, 2,
  143762. };
  143763. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143764. _vq_quantthresh__16u1__p1_0,
  143765. _vq_quantmap__16u1__p1_0,
  143766. 3,
  143767. 3
  143768. };
  143769. static static_codebook _16u1__p1_0 = {
  143770. 4, 81,
  143771. _vq_lengthlist__16u1__p1_0,
  143772. 1, -535822336, 1611661312, 2, 0,
  143773. _vq_quantlist__16u1__p1_0,
  143774. NULL,
  143775. &_vq_auxt__16u1__p1_0,
  143776. NULL,
  143777. 0
  143778. };
  143779. static long _vq_quantlist__16u1__p2_0[] = {
  143780. 1,
  143781. 0,
  143782. 2,
  143783. };
  143784. static long _vq_lengthlist__16u1__p2_0[] = {
  143785. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143786. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143787. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143788. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143789. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143790. 8,
  143791. };
  143792. static float _vq_quantthresh__16u1__p2_0[] = {
  143793. -0.5, 0.5,
  143794. };
  143795. static long _vq_quantmap__16u1__p2_0[] = {
  143796. 1, 0, 2,
  143797. };
  143798. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143799. _vq_quantthresh__16u1__p2_0,
  143800. _vq_quantmap__16u1__p2_0,
  143801. 3,
  143802. 3
  143803. };
  143804. static static_codebook _16u1__p2_0 = {
  143805. 4, 81,
  143806. _vq_lengthlist__16u1__p2_0,
  143807. 1, -535822336, 1611661312, 2, 0,
  143808. _vq_quantlist__16u1__p2_0,
  143809. NULL,
  143810. &_vq_auxt__16u1__p2_0,
  143811. NULL,
  143812. 0
  143813. };
  143814. static long _vq_quantlist__16u1__p3_0[] = {
  143815. 2,
  143816. 1,
  143817. 3,
  143818. 0,
  143819. 4,
  143820. };
  143821. static long _vq_lengthlist__16u1__p3_0[] = {
  143822. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143823. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143824. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143825. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143826. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143827. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143828. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143829. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143830. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143831. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143832. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143833. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143834. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143835. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143836. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143837. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143838. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143839. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143840. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143841. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143842. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143843. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143844. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143845. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143846. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143847. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143848. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143849. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143850. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143851. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143852. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143853. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143854. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143855. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143856. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143857. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143858. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143859. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143860. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143861. 16,
  143862. };
  143863. static float _vq_quantthresh__16u1__p3_0[] = {
  143864. -1.5, -0.5, 0.5, 1.5,
  143865. };
  143866. static long _vq_quantmap__16u1__p3_0[] = {
  143867. 3, 1, 0, 2, 4,
  143868. };
  143869. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143870. _vq_quantthresh__16u1__p3_0,
  143871. _vq_quantmap__16u1__p3_0,
  143872. 5,
  143873. 5
  143874. };
  143875. static static_codebook _16u1__p3_0 = {
  143876. 4, 625,
  143877. _vq_lengthlist__16u1__p3_0,
  143878. 1, -533725184, 1611661312, 3, 0,
  143879. _vq_quantlist__16u1__p3_0,
  143880. NULL,
  143881. &_vq_auxt__16u1__p3_0,
  143882. NULL,
  143883. 0
  143884. };
  143885. static long _vq_quantlist__16u1__p4_0[] = {
  143886. 2,
  143887. 1,
  143888. 3,
  143889. 0,
  143890. 4,
  143891. };
  143892. static long _vq_lengthlist__16u1__p4_0[] = {
  143893. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143894. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143895. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143896. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143897. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143898. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143899. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143900. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143901. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143902. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143903. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143904. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143905. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143906. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143907. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143908. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143909. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143910. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143911. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143912. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143913. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143914. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143915. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143916. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143917. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143918. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143919. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143920. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143921. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143922. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143923. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143924. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143925. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143926. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143927. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143928. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143929. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143930. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143931. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143932. 11,
  143933. };
  143934. static float _vq_quantthresh__16u1__p4_0[] = {
  143935. -1.5, -0.5, 0.5, 1.5,
  143936. };
  143937. static long _vq_quantmap__16u1__p4_0[] = {
  143938. 3, 1, 0, 2, 4,
  143939. };
  143940. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143941. _vq_quantthresh__16u1__p4_0,
  143942. _vq_quantmap__16u1__p4_0,
  143943. 5,
  143944. 5
  143945. };
  143946. static static_codebook _16u1__p4_0 = {
  143947. 4, 625,
  143948. _vq_lengthlist__16u1__p4_0,
  143949. 1, -533725184, 1611661312, 3, 0,
  143950. _vq_quantlist__16u1__p4_0,
  143951. NULL,
  143952. &_vq_auxt__16u1__p4_0,
  143953. NULL,
  143954. 0
  143955. };
  143956. static long _vq_quantlist__16u1__p5_0[] = {
  143957. 4,
  143958. 3,
  143959. 5,
  143960. 2,
  143961. 6,
  143962. 1,
  143963. 7,
  143964. 0,
  143965. 8,
  143966. };
  143967. static long _vq_lengthlist__16u1__p5_0[] = {
  143968. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143969. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143970. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143971. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143972. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143973. 13,
  143974. };
  143975. static float _vq_quantthresh__16u1__p5_0[] = {
  143976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143977. };
  143978. static long _vq_quantmap__16u1__p5_0[] = {
  143979. 7, 5, 3, 1, 0, 2, 4, 6,
  143980. 8,
  143981. };
  143982. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143983. _vq_quantthresh__16u1__p5_0,
  143984. _vq_quantmap__16u1__p5_0,
  143985. 9,
  143986. 9
  143987. };
  143988. static static_codebook _16u1__p5_0 = {
  143989. 2, 81,
  143990. _vq_lengthlist__16u1__p5_0,
  143991. 1, -531628032, 1611661312, 4, 0,
  143992. _vq_quantlist__16u1__p5_0,
  143993. NULL,
  143994. &_vq_auxt__16u1__p5_0,
  143995. NULL,
  143996. 0
  143997. };
  143998. static long _vq_quantlist__16u1__p6_0[] = {
  143999. 4,
  144000. 3,
  144001. 5,
  144002. 2,
  144003. 6,
  144004. 1,
  144005. 7,
  144006. 0,
  144007. 8,
  144008. };
  144009. static long _vq_lengthlist__16u1__p6_0[] = {
  144010. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  144011. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  144012. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144013. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144014. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144015. 11,
  144016. };
  144017. static float _vq_quantthresh__16u1__p6_0[] = {
  144018. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144019. };
  144020. static long _vq_quantmap__16u1__p6_0[] = {
  144021. 7, 5, 3, 1, 0, 2, 4, 6,
  144022. 8,
  144023. };
  144024. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  144025. _vq_quantthresh__16u1__p6_0,
  144026. _vq_quantmap__16u1__p6_0,
  144027. 9,
  144028. 9
  144029. };
  144030. static static_codebook _16u1__p6_0 = {
  144031. 2, 81,
  144032. _vq_lengthlist__16u1__p6_0,
  144033. 1, -531628032, 1611661312, 4, 0,
  144034. _vq_quantlist__16u1__p6_0,
  144035. NULL,
  144036. &_vq_auxt__16u1__p6_0,
  144037. NULL,
  144038. 0
  144039. };
  144040. static long _vq_quantlist__16u1__p7_0[] = {
  144041. 1,
  144042. 0,
  144043. 2,
  144044. };
  144045. static long _vq_lengthlist__16u1__p7_0[] = {
  144046. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  144047. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  144048. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  144049. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  144050. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  144051. 13,
  144052. };
  144053. static float _vq_quantthresh__16u1__p7_0[] = {
  144054. -5.5, 5.5,
  144055. };
  144056. static long _vq_quantmap__16u1__p7_0[] = {
  144057. 1, 0, 2,
  144058. };
  144059. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  144060. _vq_quantthresh__16u1__p7_0,
  144061. _vq_quantmap__16u1__p7_0,
  144062. 3,
  144063. 3
  144064. };
  144065. static static_codebook _16u1__p7_0 = {
  144066. 4, 81,
  144067. _vq_lengthlist__16u1__p7_0,
  144068. 1, -529137664, 1618345984, 2, 0,
  144069. _vq_quantlist__16u1__p7_0,
  144070. NULL,
  144071. &_vq_auxt__16u1__p7_0,
  144072. NULL,
  144073. 0
  144074. };
  144075. static long _vq_quantlist__16u1__p7_1[] = {
  144076. 5,
  144077. 4,
  144078. 6,
  144079. 3,
  144080. 7,
  144081. 2,
  144082. 8,
  144083. 1,
  144084. 9,
  144085. 0,
  144086. 10,
  144087. };
  144088. static long _vq_lengthlist__16u1__p7_1[] = {
  144089. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  144090. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  144091. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144092. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  144093. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  144094. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  144095. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  144096. 8, 9, 9,10,10,10,10,10,10,
  144097. };
  144098. static float _vq_quantthresh__16u1__p7_1[] = {
  144099. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144100. 3.5, 4.5,
  144101. };
  144102. static long _vq_quantmap__16u1__p7_1[] = {
  144103. 9, 7, 5, 3, 1, 0, 2, 4,
  144104. 6, 8, 10,
  144105. };
  144106. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  144107. _vq_quantthresh__16u1__p7_1,
  144108. _vq_quantmap__16u1__p7_1,
  144109. 11,
  144110. 11
  144111. };
  144112. static static_codebook _16u1__p7_1 = {
  144113. 2, 121,
  144114. _vq_lengthlist__16u1__p7_1,
  144115. 1, -531365888, 1611661312, 4, 0,
  144116. _vq_quantlist__16u1__p7_1,
  144117. NULL,
  144118. &_vq_auxt__16u1__p7_1,
  144119. NULL,
  144120. 0
  144121. };
  144122. static long _vq_quantlist__16u1__p8_0[] = {
  144123. 5,
  144124. 4,
  144125. 6,
  144126. 3,
  144127. 7,
  144128. 2,
  144129. 8,
  144130. 1,
  144131. 9,
  144132. 0,
  144133. 10,
  144134. };
  144135. static long _vq_lengthlist__16u1__p8_0[] = {
  144136. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144137. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144138. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144139. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144140. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144141. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144142. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144143. 13,14,14,15,15,16,16,15,16,
  144144. };
  144145. static float _vq_quantthresh__16u1__p8_0[] = {
  144146. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144147. 38.5, 49.5,
  144148. };
  144149. static long _vq_quantmap__16u1__p8_0[] = {
  144150. 9, 7, 5, 3, 1, 0, 2, 4,
  144151. 6, 8, 10,
  144152. };
  144153. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144154. _vq_quantthresh__16u1__p8_0,
  144155. _vq_quantmap__16u1__p8_0,
  144156. 11,
  144157. 11
  144158. };
  144159. static static_codebook _16u1__p8_0 = {
  144160. 2, 121,
  144161. _vq_lengthlist__16u1__p8_0,
  144162. 1, -524582912, 1618345984, 4, 0,
  144163. _vq_quantlist__16u1__p8_0,
  144164. NULL,
  144165. &_vq_auxt__16u1__p8_0,
  144166. NULL,
  144167. 0
  144168. };
  144169. static long _vq_quantlist__16u1__p8_1[] = {
  144170. 5,
  144171. 4,
  144172. 6,
  144173. 3,
  144174. 7,
  144175. 2,
  144176. 8,
  144177. 1,
  144178. 9,
  144179. 0,
  144180. 10,
  144181. };
  144182. static long _vq_lengthlist__16u1__p8_1[] = {
  144183. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144184. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144185. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144186. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144187. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144188. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144189. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144190. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144191. };
  144192. static float _vq_quantthresh__16u1__p8_1[] = {
  144193. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144194. 3.5, 4.5,
  144195. };
  144196. static long _vq_quantmap__16u1__p8_1[] = {
  144197. 9, 7, 5, 3, 1, 0, 2, 4,
  144198. 6, 8, 10,
  144199. };
  144200. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144201. _vq_quantthresh__16u1__p8_1,
  144202. _vq_quantmap__16u1__p8_1,
  144203. 11,
  144204. 11
  144205. };
  144206. static static_codebook _16u1__p8_1 = {
  144207. 2, 121,
  144208. _vq_lengthlist__16u1__p8_1,
  144209. 1, -531365888, 1611661312, 4, 0,
  144210. _vq_quantlist__16u1__p8_1,
  144211. NULL,
  144212. &_vq_auxt__16u1__p8_1,
  144213. NULL,
  144214. 0
  144215. };
  144216. static long _vq_quantlist__16u1__p9_0[] = {
  144217. 7,
  144218. 6,
  144219. 8,
  144220. 5,
  144221. 9,
  144222. 4,
  144223. 10,
  144224. 3,
  144225. 11,
  144226. 2,
  144227. 12,
  144228. 1,
  144229. 13,
  144230. 0,
  144231. 14,
  144232. };
  144233. static long _vq_lengthlist__16u1__p9_0[] = {
  144234. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144235. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144236. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144237. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144238. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144239. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144240. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144241. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144242. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144243. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144244. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144245. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144246. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144247. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144248. 8,
  144249. };
  144250. static float _vq_quantthresh__16u1__p9_0[] = {
  144251. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144252. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144253. };
  144254. static long _vq_quantmap__16u1__p9_0[] = {
  144255. 13, 11, 9, 7, 5, 3, 1, 0,
  144256. 2, 4, 6, 8, 10, 12, 14,
  144257. };
  144258. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144259. _vq_quantthresh__16u1__p9_0,
  144260. _vq_quantmap__16u1__p9_0,
  144261. 15,
  144262. 15
  144263. };
  144264. static static_codebook _16u1__p9_0 = {
  144265. 2, 225,
  144266. _vq_lengthlist__16u1__p9_0,
  144267. 1, -514071552, 1627381760, 4, 0,
  144268. _vq_quantlist__16u1__p9_0,
  144269. NULL,
  144270. &_vq_auxt__16u1__p9_0,
  144271. NULL,
  144272. 0
  144273. };
  144274. static long _vq_quantlist__16u1__p9_1[] = {
  144275. 7,
  144276. 6,
  144277. 8,
  144278. 5,
  144279. 9,
  144280. 4,
  144281. 10,
  144282. 3,
  144283. 11,
  144284. 2,
  144285. 12,
  144286. 1,
  144287. 13,
  144288. 0,
  144289. 14,
  144290. };
  144291. static long _vq_lengthlist__16u1__p9_1[] = {
  144292. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144293. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144294. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144295. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144296. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144297. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144298. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144299. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144300. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144301. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144302. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144303. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144304. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144305. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144306. 9,
  144307. };
  144308. static float _vq_quantthresh__16u1__p9_1[] = {
  144309. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144310. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144311. };
  144312. static long _vq_quantmap__16u1__p9_1[] = {
  144313. 13, 11, 9, 7, 5, 3, 1, 0,
  144314. 2, 4, 6, 8, 10, 12, 14,
  144315. };
  144316. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144317. _vq_quantthresh__16u1__p9_1,
  144318. _vq_quantmap__16u1__p9_1,
  144319. 15,
  144320. 15
  144321. };
  144322. static static_codebook _16u1__p9_1 = {
  144323. 2, 225,
  144324. _vq_lengthlist__16u1__p9_1,
  144325. 1, -522338304, 1620115456, 4, 0,
  144326. _vq_quantlist__16u1__p9_1,
  144327. NULL,
  144328. &_vq_auxt__16u1__p9_1,
  144329. NULL,
  144330. 0
  144331. };
  144332. static long _vq_quantlist__16u1__p9_2[] = {
  144333. 8,
  144334. 7,
  144335. 9,
  144336. 6,
  144337. 10,
  144338. 5,
  144339. 11,
  144340. 4,
  144341. 12,
  144342. 3,
  144343. 13,
  144344. 2,
  144345. 14,
  144346. 1,
  144347. 15,
  144348. 0,
  144349. 16,
  144350. };
  144351. static long _vq_lengthlist__16u1__p9_2[] = {
  144352. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144353. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144354. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144355. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144356. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144357. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144358. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144359. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144360. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144361. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144362. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144363. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144364. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144365. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144366. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144367. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144368. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144369. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144370. 10,
  144371. };
  144372. static float _vq_quantthresh__16u1__p9_2[] = {
  144373. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144374. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144375. };
  144376. static long _vq_quantmap__16u1__p9_2[] = {
  144377. 15, 13, 11, 9, 7, 5, 3, 1,
  144378. 0, 2, 4, 6, 8, 10, 12, 14,
  144379. 16,
  144380. };
  144381. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144382. _vq_quantthresh__16u1__p9_2,
  144383. _vq_quantmap__16u1__p9_2,
  144384. 17,
  144385. 17
  144386. };
  144387. static static_codebook _16u1__p9_2 = {
  144388. 2, 289,
  144389. _vq_lengthlist__16u1__p9_2,
  144390. 1, -529530880, 1611661312, 5, 0,
  144391. _vq_quantlist__16u1__p9_2,
  144392. NULL,
  144393. &_vq_auxt__16u1__p9_2,
  144394. NULL,
  144395. 0
  144396. };
  144397. static long _huff_lengthlist__16u1__short[] = {
  144398. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144399. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144400. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144401. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144402. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144403. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144404. 16,16,16,16,
  144405. };
  144406. static static_codebook _huff_book__16u1__short = {
  144407. 2, 100,
  144408. _huff_lengthlist__16u1__short,
  144409. 0, 0, 0, 0, 0,
  144410. NULL,
  144411. NULL,
  144412. NULL,
  144413. NULL,
  144414. 0
  144415. };
  144416. static long _huff_lengthlist__16u2__long[] = {
  144417. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144418. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144419. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144420. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144421. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144422. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144423. 13,14,18,18,
  144424. };
  144425. static static_codebook _huff_book__16u2__long = {
  144426. 2, 100,
  144427. _huff_lengthlist__16u2__long,
  144428. 0, 0, 0, 0, 0,
  144429. NULL,
  144430. NULL,
  144431. NULL,
  144432. NULL,
  144433. 0
  144434. };
  144435. static long _huff_lengthlist__16u2__short[] = {
  144436. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144437. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144438. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144439. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144440. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144441. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144442. 16,16,16,16,
  144443. };
  144444. static static_codebook _huff_book__16u2__short = {
  144445. 2, 100,
  144446. _huff_lengthlist__16u2__short,
  144447. 0, 0, 0, 0, 0,
  144448. NULL,
  144449. NULL,
  144450. NULL,
  144451. NULL,
  144452. 0
  144453. };
  144454. static long _vq_quantlist__16u2_p1_0[] = {
  144455. 1,
  144456. 0,
  144457. 2,
  144458. };
  144459. static long _vq_lengthlist__16u2_p1_0[] = {
  144460. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144461. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144462. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144463. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144464. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144465. 10,
  144466. };
  144467. static float _vq_quantthresh__16u2_p1_0[] = {
  144468. -0.5, 0.5,
  144469. };
  144470. static long _vq_quantmap__16u2_p1_0[] = {
  144471. 1, 0, 2,
  144472. };
  144473. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144474. _vq_quantthresh__16u2_p1_0,
  144475. _vq_quantmap__16u2_p1_0,
  144476. 3,
  144477. 3
  144478. };
  144479. static static_codebook _16u2_p1_0 = {
  144480. 4, 81,
  144481. _vq_lengthlist__16u2_p1_0,
  144482. 1, -535822336, 1611661312, 2, 0,
  144483. _vq_quantlist__16u2_p1_0,
  144484. NULL,
  144485. &_vq_auxt__16u2_p1_0,
  144486. NULL,
  144487. 0
  144488. };
  144489. static long _vq_quantlist__16u2_p2_0[] = {
  144490. 2,
  144491. 1,
  144492. 3,
  144493. 0,
  144494. 4,
  144495. };
  144496. static long _vq_lengthlist__16u2_p2_0[] = {
  144497. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144498. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144499. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144500. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144501. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144502. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144503. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144504. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144505. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144506. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144507. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144508. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144509. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144510. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144511. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144512. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144513. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144514. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144515. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144516. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144517. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144518. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144519. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144520. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144521. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144522. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144523. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144524. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144525. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144526. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144527. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144528. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144529. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144530. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144531. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144532. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144533. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144534. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144535. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144536. 13,
  144537. };
  144538. static float _vq_quantthresh__16u2_p2_0[] = {
  144539. -1.5, -0.5, 0.5, 1.5,
  144540. };
  144541. static long _vq_quantmap__16u2_p2_0[] = {
  144542. 3, 1, 0, 2, 4,
  144543. };
  144544. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144545. _vq_quantthresh__16u2_p2_0,
  144546. _vq_quantmap__16u2_p2_0,
  144547. 5,
  144548. 5
  144549. };
  144550. static static_codebook _16u2_p2_0 = {
  144551. 4, 625,
  144552. _vq_lengthlist__16u2_p2_0,
  144553. 1, -533725184, 1611661312, 3, 0,
  144554. _vq_quantlist__16u2_p2_0,
  144555. NULL,
  144556. &_vq_auxt__16u2_p2_0,
  144557. NULL,
  144558. 0
  144559. };
  144560. static long _vq_quantlist__16u2_p3_0[] = {
  144561. 4,
  144562. 3,
  144563. 5,
  144564. 2,
  144565. 6,
  144566. 1,
  144567. 7,
  144568. 0,
  144569. 8,
  144570. };
  144571. static long _vq_lengthlist__16u2_p3_0[] = {
  144572. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144573. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144574. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144575. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144576. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144577. 11,
  144578. };
  144579. static float _vq_quantthresh__16u2_p3_0[] = {
  144580. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144581. };
  144582. static long _vq_quantmap__16u2_p3_0[] = {
  144583. 7, 5, 3, 1, 0, 2, 4, 6,
  144584. 8,
  144585. };
  144586. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144587. _vq_quantthresh__16u2_p3_0,
  144588. _vq_quantmap__16u2_p3_0,
  144589. 9,
  144590. 9
  144591. };
  144592. static static_codebook _16u2_p3_0 = {
  144593. 2, 81,
  144594. _vq_lengthlist__16u2_p3_0,
  144595. 1, -531628032, 1611661312, 4, 0,
  144596. _vq_quantlist__16u2_p3_0,
  144597. NULL,
  144598. &_vq_auxt__16u2_p3_0,
  144599. NULL,
  144600. 0
  144601. };
  144602. static long _vq_quantlist__16u2_p4_0[] = {
  144603. 8,
  144604. 7,
  144605. 9,
  144606. 6,
  144607. 10,
  144608. 5,
  144609. 11,
  144610. 4,
  144611. 12,
  144612. 3,
  144613. 13,
  144614. 2,
  144615. 14,
  144616. 1,
  144617. 15,
  144618. 0,
  144619. 16,
  144620. };
  144621. static long _vq_lengthlist__16u2_p4_0[] = {
  144622. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144623. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144624. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144625. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144626. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144627. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144628. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144629. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144630. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144631. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144632. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144633. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144634. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144635. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144636. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144637. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144638. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144639. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144640. 14,
  144641. };
  144642. static float _vq_quantthresh__16u2_p4_0[] = {
  144643. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144644. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144645. };
  144646. static long _vq_quantmap__16u2_p4_0[] = {
  144647. 15, 13, 11, 9, 7, 5, 3, 1,
  144648. 0, 2, 4, 6, 8, 10, 12, 14,
  144649. 16,
  144650. };
  144651. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144652. _vq_quantthresh__16u2_p4_0,
  144653. _vq_quantmap__16u2_p4_0,
  144654. 17,
  144655. 17
  144656. };
  144657. static static_codebook _16u2_p4_0 = {
  144658. 2, 289,
  144659. _vq_lengthlist__16u2_p4_0,
  144660. 1, -529530880, 1611661312, 5, 0,
  144661. _vq_quantlist__16u2_p4_0,
  144662. NULL,
  144663. &_vq_auxt__16u2_p4_0,
  144664. NULL,
  144665. 0
  144666. };
  144667. static long _vq_quantlist__16u2_p5_0[] = {
  144668. 1,
  144669. 0,
  144670. 2,
  144671. };
  144672. static long _vq_lengthlist__16u2_p5_0[] = {
  144673. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144674. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144675. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144676. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144677. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144678. 10,
  144679. };
  144680. static float _vq_quantthresh__16u2_p5_0[] = {
  144681. -5.5, 5.5,
  144682. };
  144683. static long _vq_quantmap__16u2_p5_0[] = {
  144684. 1, 0, 2,
  144685. };
  144686. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144687. _vq_quantthresh__16u2_p5_0,
  144688. _vq_quantmap__16u2_p5_0,
  144689. 3,
  144690. 3
  144691. };
  144692. static static_codebook _16u2_p5_0 = {
  144693. 4, 81,
  144694. _vq_lengthlist__16u2_p5_0,
  144695. 1, -529137664, 1618345984, 2, 0,
  144696. _vq_quantlist__16u2_p5_0,
  144697. NULL,
  144698. &_vq_auxt__16u2_p5_0,
  144699. NULL,
  144700. 0
  144701. };
  144702. static long _vq_quantlist__16u2_p5_1[] = {
  144703. 5,
  144704. 4,
  144705. 6,
  144706. 3,
  144707. 7,
  144708. 2,
  144709. 8,
  144710. 1,
  144711. 9,
  144712. 0,
  144713. 10,
  144714. };
  144715. static long _vq_lengthlist__16u2_p5_1[] = {
  144716. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144717. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144718. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144719. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144720. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144721. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144722. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144723. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144724. };
  144725. static float _vq_quantthresh__16u2_p5_1[] = {
  144726. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144727. 3.5, 4.5,
  144728. };
  144729. static long _vq_quantmap__16u2_p5_1[] = {
  144730. 9, 7, 5, 3, 1, 0, 2, 4,
  144731. 6, 8, 10,
  144732. };
  144733. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144734. _vq_quantthresh__16u2_p5_1,
  144735. _vq_quantmap__16u2_p5_1,
  144736. 11,
  144737. 11
  144738. };
  144739. static static_codebook _16u2_p5_1 = {
  144740. 2, 121,
  144741. _vq_lengthlist__16u2_p5_1,
  144742. 1, -531365888, 1611661312, 4, 0,
  144743. _vq_quantlist__16u2_p5_1,
  144744. NULL,
  144745. &_vq_auxt__16u2_p5_1,
  144746. NULL,
  144747. 0
  144748. };
  144749. static long _vq_quantlist__16u2_p6_0[] = {
  144750. 6,
  144751. 5,
  144752. 7,
  144753. 4,
  144754. 8,
  144755. 3,
  144756. 9,
  144757. 2,
  144758. 10,
  144759. 1,
  144760. 11,
  144761. 0,
  144762. 12,
  144763. };
  144764. static long _vq_lengthlist__16u2_p6_0[] = {
  144765. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144766. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144767. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144768. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144769. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144770. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144771. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144772. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144773. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144774. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144775. 12,13,13,14,14,14,14,15,15,
  144776. };
  144777. static float _vq_quantthresh__16u2_p6_0[] = {
  144778. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144779. 12.5, 17.5, 22.5, 27.5,
  144780. };
  144781. static long _vq_quantmap__16u2_p6_0[] = {
  144782. 11, 9, 7, 5, 3, 1, 0, 2,
  144783. 4, 6, 8, 10, 12,
  144784. };
  144785. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144786. _vq_quantthresh__16u2_p6_0,
  144787. _vq_quantmap__16u2_p6_0,
  144788. 13,
  144789. 13
  144790. };
  144791. static static_codebook _16u2_p6_0 = {
  144792. 2, 169,
  144793. _vq_lengthlist__16u2_p6_0,
  144794. 1, -526516224, 1616117760, 4, 0,
  144795. _vq_quantlist__16u2_p6_0,
  144796. NULL,
  144797. &_vq_auxt__16u2_p6_0,
  144798. NULL,
  144799. 0
  144800. };
  144801. static long _vq_quantlist__16u2_p6_1[] = {
  144802. 2,
  144803. 1,
  144804. 3,
  144805. 0,
  144806. 4,
  144807. };
  144808. static long _vq_lengthlist__16u2_p6_1[] = {
  144809. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144810. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144811. };
  144812. static float _vq_quantthresh__16u2_p6_1[] = {
  144813. -1.5, -0.5, 0.5, 1.5,
  144814. };
  144815. static long _vq_quantmap__16u2_p6_1[] = {
  144816. 3, 1, 0, 2, 4,
  144817. };
  144818. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144819. _vq_quantthresh__16u2_p6_1,
  144820. _vq_quantmap__16u2_p6_1,
  144821. 5,
  144822. 5
  144823. };
  144824. static static_codebook _16u2_p6_1 = {
  144825. 2, 25,
  144826. _vq_lengthlist__16u2_p6_1,
  144827. 1, -533725184, 1611661312, 3, 0,
  144828. _vq_quantlist__16u2_p6_1,
  144829. NULL,
  144830. &_vq_auxt__16u2_p6_1,
  144831. NULL,
  144832. 0
  144833. };
  144834. static long _vq_quantlist__16u2_p7_0[] = {
  144835. 6,
  144836. 5,
  144837. 7,
  144838. 4,
  144839. 8,
  144840. 3,
  144841. 9,
  144842. 2,
  144843. 10,
  144844. 1,
  144845. 11,
  144846. 0,
  144847. 12,
  144848. };
  144849. static long _vq_lengthlist__16u2_p7_0[] = {
  144850. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144851. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144852. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144853. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144854. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144855. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144856. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144857. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144858. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144859. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144860. 12,13,13,13,14,14,14,15,14,
  144861. };
  144862. static float _vq_quantthresh__16u2_p7_0[] = {
  144863. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144864. 27.5, 38.5, 49.5, 60.5,
  144865. };
  144866. static long _vq_quantmap__16u2_p7_0[] = {
  144867. 11, 9, 7, 5, 3, 1, 0, 2,
  144868. 4, 6, 8, 10, 12,
  144869. };
  144870. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144871. _vq_quantthresh__16u2_p7_0,
  144872. _vq_quantmap__16u2_p7_0,
  144873. 13,
  144874. 13
  144875. };
  144876. static static_codebook _16u2_p7_0 = {
  144877. 2, 169,
  144878. _vq_lengthlist__16u2_p7_0,
  144879. 1, -523206656, 1618345984, 4, 0,
  144880. _vq_quantlist__16u2_p7_0,
  144881. NULL,
  144882. &_vq_auxt__16u2_p7_0,
  144883. NULL,
  144884. 0
  144885. };
  144886. static long _vq_quantlist__16u2_p7_1[] = {
  144887. 5,
  144888. 4,
  144889. 6,
  144890. 3,
  144891. 7,
  144892. 2,
  144893. 8,
  144894. 1,
  144895. 9,
  144896. 0,
  144897. 10,
  144898. };
  144899. static long _vq_lengthlist__16u2_p7_1[] = {
  144900. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144901. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144902. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144903. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144904. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144905. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144906. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144907. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144908. };
  144909. static float _vq_quantthresh__16u2_p7_1[] = {
  144910. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144911. 3.5, 4.5,
  144912. };
  144913. static long _vq_quantmap__16u2_p7_1[] = {
  144914. 9, 7, 5, 3, 1, 0, 2, 4,
  144915. 6, 8, 10,
  144916. };
  144917. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144918. _vq_quantthresh__16u2_p7_1,
  144919. _vq_quantmap__16u2_p7_1,
  144920. 11,
  144921. 11
  144922. };
  144923. static static_codebook _16u2_p7_1 = {
  144924. 2, 121,
  144925. _vq_lengthlist__16u2_p7_1,
  144926. 1, -531365888, 1611661312, 4, 0,
  144927. _vq_quantlist__16u2_p7_1,
  144928. NULL,
  144929. &_vq_auxt__16u2_p7_1,
  144930. NULL,
  144931. 0
  144932. };
  144933. static long _vq_quantlist__16u2_p8_0[] = {
  144934. 7,
  144935. 6,
  144936. 8,
  144937. 5,
  144938. 9,
  144939. 4,
  144940. 10,
  144941. 3,
  144942. 11,
  144943. 2,
  144944. 12,
  144945. 1,
  144946. 13,
  144947. 0,
  144948. 14,
  144949. };
  144950. static long _vq_lengthlist__16u2_p8_0[] = {
  144951. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144952. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144953. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144954. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144955. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144956. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144957. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144958. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144959. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144960. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144961. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144962. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144963. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144964. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144965. 14,
  144966. };
  144967. static float _vq_quantthresh__16u2_p8_0[] = {
  144968. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144969. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144970. };
  144971. static long _vq_quantmap__16u2_p8_0[] = {
  144972. 13, 11, 9, 7, 5, 3, 1, 0,
  144973. 2, 4, 6, 8, 10, 12, 14,
  144974. };
  144975. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144976. _vq_quantthresh__16u2_p8_0,
  144977. _vq_quantmap__16u2_p8_0,
  144978. 15,
  144979. 15
  144980. };
  144981. static static_codebook _16u2_p8_0 = {
  144982. 2, 225,
  144983. _vq_lengthlist__16u2_p8_0,
  144984. 1, -520986624, 1620377600, 4, 0,
  144985. _vq_quantlist__16u2_p8_0,
  144986. NULL,
  144987. &_vq_auxt__16u2_p8_0,
  144988. NULL,
  144989. 0
  144990. };
  144991. static long _vq_quantlist__16u2_p8_1[] = {
  144992. 10,
  144993. 9,
  144994. 11,
  144995. 8,
  144996. 12,
  144997. 7,
  144998. 13,
  144999. 6,
  145000. 14,
  145001. 5,
  145002. 15,
  145003. 4,
  145004. 16,
  145005. 3,
  145006. 17,
  145007. 2,
  145008. 18,
  145009. 1,
  145010. 19,
  145011. 0,
  145012. 20,
  145013. };
  145014. static long _vq_lengthlist__16u2_p8_1[] = {
  145015. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  145016. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  145017. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  145018. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  145019. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  145020. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  145021. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  145022. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  145023. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  145024. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  145025. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  145026. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  145027. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  145028. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  145029. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  145030. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  145031. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  145032. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  145033. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  145034. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  145035. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  145036. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  145037. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  145038. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  145039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  145040. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  145041. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  145042. 11,11,10,11,11,11,10,11,11,
  145043. };
  145044. static float _vq_quantthresh__16u2_p8_1[] = {
  145045. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145046. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145047. 6.5, 7.5, 8.5, 9.5,
  145048. };
  145049. static long _vq_quantmap__16u2_p8_1[] = {
  145050. 19, 17, 15, 13, 11, 9, 7, 5,
  145051. 3, 1, 0, 2, 4, 6, 8, 10,
  145052. 12, 14, 16, 18, 20,
  145053. };
  145054. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  145055. _vq_quantthresh__16u2_p8_1,
  145056. _vq_quantmap__16u2_p8_1,
  145057. 21,
  145058. 21
  145059. };
  145060. static static_codebook _16u2_p8_1 = {
  145061. 2, 441,
  145062. _vq_lengthlist__16u2_p8_1,
  145063. 1, -529268736, 1611661312, 5, 0,
  145064. _vq_quantlist__16u2_p8_1,
  145065. NULL,
  145066. &_vq_auxt__16u2_p8_1,
  145067. NULL,
  145068. 0
  145069. };
  145070. static long _vq_quantlist__16u2_p9_0[] = {
  145071. 5586,
  145072. 4655,
  145073. 6517,
  145074. 3724,
  145075. 7448,
  145076. 2793,
  145077. 8379,
  145078. 1862,
  145079. 9310,
  145080. 931,
  145081. 10241,
  145082. 0,
  145083. 11172,
  145084. 5521,
  145085. 5651,
  145086. };
  145087. static long _vq_lengthlist__16u2_p9_0[] = {
  145088. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  145089. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145090. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145091. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145092. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145093. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145094. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145095. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145096. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145097. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145098. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145099. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145100. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  145101. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  145102. 5,
  145103. };
  145104. static float _vq_quantthresh__16u2_p9_0[] = {
  145105. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  145106. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  145107. };
  145108. static long _vq_quantmap__16u2_p9_0[] = {
  145109. 11, 9, 7, 5, 3, 1, 13, 0,
  145110. 14, 2, 4, 6, 8, 10, 12,
  145111. };
  145112. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  145113. _vq_quantthresh__16u2_p9_0,
  145114. _vq_quantmap__16u2_p9_0,
  145115. 15,
  145116. 15
  145117. };
  145118. static static_codebook _16u2_p9_0 = {
  145119. 2, 225,
  145120. _vq_lengthlist__16u2_p9_0,
  145121. 1, -510275072, 1611661312, 14, 0,
  145122. _vq_quantlist__16u2_p9_0,
  145123. NULL,
  145124. &_vq_auxt__16u2_p9_0,
  145125. NULL,
  145126. 0
  145127. };
  145128. static long _vq_quantlist__16u2_p9_1[] = {
  145129. 392,
  145130. 343,
  145131. 441,
  145132. 294,
  145133. 490,
  145134. 245,
  145135. 539,
  145136. 196,
  145137. 588,
  145138. 147,
  145139. 637,
  145140. 98,
  145141. 686,
  145142. 49,
  145143. 735,
  145144. 0,
  145145. 784,
  145146. 388,
  145147. 396,
  145148. };
  145149. static long _vq_lengthlist__16u2_p9_1[] = {
  145150. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145151. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145152. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145153. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145154. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145155. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145156. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145157. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145158. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145159. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145160. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145161. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145162. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145163. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145164. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145170. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145171. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145172. 11,11,11,11,11,11,11, 5, 4,
  145173. };
  145174. static float _vq_quantthresh__16u2_p9_1[] = {
  145175. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145176. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145177. 318.5, 367.5,
  145178. };
  145179. static long _vq_quantmap__16u2_p9_1[] = {
  145180. 15, 13, 11, 9, 7, 5, 3, 1,
  145181. 17, 0, 18, 2, 4, 6, 8, 10,
  145182. 12, 14, 16,
  145183. };
  145184. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145185. _vq_quantthresh__16u2_p9_1,
  145186. _vq_quantmap__16u2_p9_1,
  145187. 19,
  145188. 19
  145189. };
  145190. static static_codebook _16u2_p9_1 = {
  145191. 2, 361,
  145192. _vq_lengthlist__16u2_p9_1,
  145193. 1, -518488064, 1611661312, 10, 0,
  145194. _vq_quantlist__16u2_p9_1,
  145195. NULL,
  145196. &_vq_auxt__16u2_p9_1,
  145197. NULL,
  145198. 0
  145199. };
  145200. static long _vq_quantlist__16u2_p9_2[] = {
  145201. 24,
  145202. 23,
  145203. 25,
  145204. 22,
  145205. 26,
  145206. 21,
  145207. 27,
  145208. 20,
  145209. 28,
  145210. 19,
  145211. 29,
  145212. 18,
  145213. 30,
  145214. 17,
  145215. 31,
  145216. 16,
  145217. 32,
  145218. 15,
  145219. 33,
  145220. 14,
  145221. 34,
  145222. 13,
  145223. 35,
  145224. 12,
  145225. 36,
  145226. 11,
  145227. 37,
  145228. 10,
  145229. 38,
  145230. 9,
  145231. 39,
  145232. 8,
  145233. 40,
  145234. 7,
  145235. 41,
  145236. 6,
  145237. 42,
  145238. 5,
  145239. 43,
  145240. 4,
  145241. 44,
  145242. 3,
  145243. 45,
  145244. 2,
  145245. 46,
  145246. 1,
  145247. 47,
  145248. 0,
  145249. 48,
  145250. };
  145251. static long _vq_lengthlist__16u2_p9_2[] = {
  145252. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145253. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145254. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145255. 11,
  145256. };
  145257. static float _vq_quantthresh__16u2_p9_2[] = {
  145258. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145259. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145260. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145261. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145262. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145263. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145264. };
  145265. static long _vq_quantmap__16u2_p9_2[] = {
  145266. 47, 45, 43, 41, 39, 37, 35, 33,
  145267. 31, 29, 27, 25, 23, 21, 19, 17,
  145268. 15, 13, 11, 9, 7, 5, 3, 1,
  145269. 0, 2, 4, 6, 8, 10, 12, 14,
  145270. 16, 18, 20, 22, 24, 26, 28, 30,
  145271. 32, 34, 36, 38, 40, 42, 44, 46,
  145272. 48,
  145273. };
  145274. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145275. _vq_quantthresh__16u2_p9_2,
  145276. _vq_quantmap__16u2_p9_2,
  145277. 49,
  145278. 49
  145279. };
  145280. static static_codebook _16u2_p9_2 = {
  145281. 1, 49,
  145282. _vq_lengthlist__16u2_p9_2,
  145283. 1, -526909440, 1611661312, 6, 0,
  145284. _vq_quantlist__16u2_p9_2,
  145285. NULL,
  145286. &_vq_auxt__16u2_p9_2,
  145287. NULL,
  145288. 0
  145289. };
  145290. static long _vq_quantlist__8u0__p1_0[] = {
  145291. 1,
  145292. 0,
  145293. 2,
  145294. };
  145295. static long _vq_lengthlist__8u0__p1_0[] = {
  145296. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145297. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145298. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145299. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145300. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145301. 11,
  145302. };
  145303. static float _vq_quantthresh__8u0__p1_0[] = {
  145304. -0.5, 0.5,
  145305. };
  145306. static long _vq_quantmap__8u0__p1_0[] = {
  145307. 1, 0, 2,
  145308. };
  145309. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145310. _vq_quantthresh__8u0__p1_0,
  145311. _vq_quantmap__8u0__p1_0,
  145312. 3,
  145313. 3
  145314. };
  145315. static static_codebook _8u0__p1_0 = {
  145316. 4, 81,
  145317. _vq_lengthlist__8u0__p1_0,
  145318. 1, -535822336, 1611661312, 2, 0,
  145319. _vq_quantlist__8u0__p1_0,
  145320. NULL,
  145321. &_vq_auxt__8u0__p1_0,
  145322. NULL,
  145323. 0
  145324. };
  145325. static long _vq_quantlist__8u0__p2_0[] = {
  145326. 1,
  145327. 0,
  145328. 2,
  145329. };
  145330. static long _vq_lengthlist__8u0__p2_0[] = {
  145331. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145332. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145333. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145334. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145335. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145336. 8,
  145337. };
  145338. static float _vq_quantthresh__8u0__p2_0[] = {
  145339. -0.5, 0.5,
  145340. };
  145341. static long _vq_quantmap__8u0__p2_0[] = {
  145342. 1, 0, 2,
  145343. };
  145344. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145345. _vq_quantthresh__8u0__p2_0,
  145346. _vq_quantmap__8u0__p2_0,
  145347. 3,
  145348. 3
  145349. };
  145350. static static_codebook _8u0__p2_0 = {
  145351. 4, 81,
  145352. _vq_lengthlist__8u0__p2_0,
  145353. 1, -535822336, 1611661312, 2, 0,
  145354. _vq_quantlist__8u0__p2_0,
  145355. NULL,
  145356. &_vq_auxt__8u0__p2_0,
  145357. NULL,
  145358. 0
  145359. };
  145360. static long _vq_quantlist__8u0__p3_0[] = {
  145361. 2,
  145362. 1,
  145363. 3,
  145364. 0,
  145365. 4,
  145366. };
  145367. static long _vq_lengthlist__8u0__p3_0[] = {
  145368. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145369. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145370. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145371. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145372. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145373. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145374. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145375. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145376. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145377. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145378. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145379. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145380. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145381. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145382. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145383. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145384. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145385. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145386. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145387. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145388. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145389. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145390. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145391. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145392. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145393. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145394. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145395. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145396. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145397. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145398. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145399. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145400. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145401. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145402. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145403. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145404. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145405. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145406. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145407. 16,
  145408. };
  145409. static float _vq_quantthresh__8u0__p3_0[] = {
  145410. -1.5, -0.5, 0.5, 1.5,
  145411. };
  145412. static long _vq_quantmap__8u0__p3_0[] = {
  145413. 3, 1, 0, 2, 4,
  145414. };
  145415. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145416. _vq_quantthresh__8u0__p3_0,
  145417. _vq_quantmap__8u0__p3_0,
  145418. 5,
  145419. 5
  145420. };
  145421. static static_codebook _8u0__p3_0 = {
  145422. 4, 625,
  145423. _vq_lengthlist__8u0__p3_0,
  145424. 1, -533725184, 1611661312, 3, 0,
  145425. _vq_quantlist__8u0__p3_0,
  145426. NULL,
  145427. &_vq_auxt__8u0__p3_0,
  145428. NULL,
  145429. 0
  145430. };
  145431. static long _vq_quantlist__8u0__p4_0[] = {
  145432. 2,
  145433. 1,
  145434. 3,
  145435. 0,
  145436. 4,
  145437. };
  145438. static long _vq_lengthlist__8u0__p4_0[] = {
  145439. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145440. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145441. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145442. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145443. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145444. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145445. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145446. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145447. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145448. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145449. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145450. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145451. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145452. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145453. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145454. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145455. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145456. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145457. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145458. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145459. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145460. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145461. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145462. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145463. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145464. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145465. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145466. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145467. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145468. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145469. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145470. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145471. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145472. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145473. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145474. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145475. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145476. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145477. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145478. 12,
  145479. };
  145480. static float _vq_quantthresh__8u0__p4_0[] = {
  145481. -1.5, -0.5, 0.5, 1.5,
  145482. };
  145483. static long _vq_quantmap__8u0__p4_0[] = {
  145484. 3, 1, 0, 2, 4,
  145485. };
  145486. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145487. _vq_quantthresh__8u0__p4_0,
  145488. _vq_quantmap__8u0__p4_0,
  145489. 5,
  145490. 5
  145491. };
  145492. static static_codebook _8u0__p4_0 = {
  145493. 4, 625,
  145494. _vq_lengthlist__8u0__p4_0,
  145495. 1, -533725184, 1611661312, 3, 0,
  145496. _vq_quantlist__8u0__p4_0,
  145497. NULL,
  145498. &_vq_auxt__8u0__p4_0,
  145499. NULL,
  145500. 0
  145501. };
  145502. static long _vq_quantlist__8u0__p5_0[] = {
  145503. 4,
  145504. 3,
  145505. 5,
  145506. 2,
  145507. 6,
  145508. 1,
  145509. 7,
  145510. 0,
  145511. 8,
  145512. };
  145513. static long _vq_lengthlist__8u0__p5_0[] = {
  145514. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145515. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145516. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145517. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145518. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145519. 12,
  145520. };
  145521. static float _vq_quantthresh__8u0__p5_0[] = {
  145522. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145523. };
  145524. static long _vq_quantmap__8u0__p5_0[] = {
  145525. 7, 5, 3, 1, 0, 2, 4, 6,
  145526. 8,
  145527. };
  145528. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145529. _vq_quantthresh__8u0__p5_0,
  145530. _vq_quantmap__8u0__p5_0,
  145531. 9,
  145532. 9
  145533. };
  145534. static static_codebook _8u0__p5_0 = {
  145535. 2, 81,
  145536. _vq_lengthlist__8u0__p5_0,
  145537. 1, -531628032, 1611661312, 4, 0,
  145538. _vq_quantlist__8u0__p5_0,
  145539. NULL,
  145540. &_vq_auxt__8u0__p5_0,
  145541. NULL,
  145542. 0
  145543. };
  145544. static long _vq_quantlist__8u0__p6_0[] = {
  145545. 6,
  145546. 5,
  145547. 7,
  145548. 4,
  145549. 8,
  145550. 3,
  145551. 9,
  145552. 2,
  145553. 10,
  145554. 1,
  145555. 11,
  145556. 0,
  145557. 12,
  145558. };
  145559. static long _vq_lengthlist__8u0__p6_0[] = {
  145560. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145561. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145562. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145563. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145564. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145565. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145566. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145567. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145568. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145569. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145570. 16, 0,15, 0,17, 0, 0, 0, 0,
  145571. };
  145572. static float _vq_quantthresh__8u0__p6_0[] = {
  145573. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145574. 12.5, 17.5, 22.5, 27.5,
  145575. };
  145576. static long _vq_quantmap__8u0__p6_0[] = {
  145577. 11, 9, 7, 5, 3, 1, 0, 2,
  145578. 4, 6, 8, 10, 12,
  145579. };
  145580. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145581. _vq_quantthresh__8u0__p6_0,
  145582. _vq_quantmap__8u0__p6_0,
  145583. 13,
  145584. 13
  145585. };
  145586. static static_codebook _8u0__p6_0 = {
  145587. 2, 169,
  145588. _vq_lengthlist__8u0__p6_0,
  145589. 1, -526516224, 1616117760, 4, 0,
  145590. _vq_quantlist__8u0__p6_0,
  145591. NULL,
  145592. &_vq_auxt__8u0__p6_0,
  145593. NULL,
  145594. 0
  145595. };
  145596. static long _vq_quantlist__8u0__p6_1[] = {
  145597. 2,
  145598. 1,
  145599. 3,
  145600. 0,
  145601. 4,
  145602. };
  145603. static long _vq_lengthlist__8u0__p6_1[] = {
  145604. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145605. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145606. };
  145607. static float _vq_quantthresh__8u0__p6_1[] = {
  145608. -1.5, -0.5, 0.5, 1.5,
  145609. };
  145610. static long _vq_quantmap__8u0__p6_1[] = {
  145611. 3, 1, 0, 2, 4,
  145612. };
  145613. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145614. _vq_quantthresh__8u0__p6_1,
  145615. _vq_quantmap__8u0__p6_1,
  145616. 5,
  145617. 5
  145618. };
  145619. static static_codebook _8u0__p6_1 = {
  145620. 2, 25,
  145621. _vq_lengthlist__8u0__p6_1,
  145622. 1, -533725184, 1611661312, 3, 0,
  145623. _vq_quantlist__8u0__p6_1,
  145624. NULL,
  145625. &_vq_auxt__8u0__p6_1,
  145626. NULL,
  145627. 0
  145628. };
  145629. static long _vq_quantlist__8u0__p7_0[] = {
  145630. 1,
  145631. 0,
  145632. 2,
  145633. };
  145634. static long _vq_lengthlist__8u0__p7_0[] = {
  145635. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145636. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145637. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145638. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145639. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145640. 7,
  145641. };
  145642. static float _vq_quantthresh__8u0__p7_0[] = {
  145643. -157.5, 157.5,
  145644. };
  145645. static long _vq_quantmap__8u0__p7_0[] = {
  145646. 1, 0, 2,
  145647. };
  145648. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145649. _vq_quantthresh__8u0__p7_0,
  145650. _vq_quantmap__8u0__p7_0,
  145651. 3,
  145652. 3
  145653. };
  145654. static static_codebook _8u0__p7_0 = {
  145655. 4, 81,
  145656. _vq_lengthlist__8u0__p7_0,
  145657. 1, -518803456, 1628680192, 2, 0,
  145658. _vq_quantlist__8u0__p7_0,
  145659. NULL,
  145660. &_vq_auxt__8u0__p7_0,
  145661. NULL,
  145662. 0
  145663. };
  145664. static long _vq_quantlist__8u0__p7_1[] = {
  145665. 7,
  145666. 6,
  145667. 8,
  145668. 5,
  145669. 9,
  145670. 4,
  145671. 10,
  145672. 3,
  145673. 11,
  145674. 2,
  145675. 12,
  145676. 1,
  145677. 13,
  145678. 0,
  145679. 14,
  145680. };
  145681. static long _vq_lengthlist__8u0__p7_1[] = {
  145682. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145683. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145684. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145685. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145686. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145687. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145691. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145692. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145694. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145696. 10,
  145697. };
  145698. static float _vq_quantthresh__8u0__p7_1[] = {
  145699. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145700. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145701. };
  145702. static long _vq_quantmap__8u0__p7_1[] = {
  145703. 13, 11, 9, 7, 5, 3, 1, 0,
  145704. 2, 4, 6, 8, 10, 12, 14,
  145705. };
  145706. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145707. _vq_quantthresh__8u0__p7_1,
  145708. _vq_quantmap__8u0__p7_1,
  145709. 15,
  145710. 15
  145711. };
  145712. static static_codebook _8u0__p7_1 = {
  145713. 2, 225,
  145714. _vq_lengthlist__8u0__p7_1,
  145715. 1, -520986624, 1620377600, 4, 0,
  145716. _vq_quantlist__8u0__p7_1,
  145717. NULL,
  145718. &_vq_auxt__8u0__p7_1,
  145719. NULL,
  145720. 0
  145721. };
  145722. static long _vq_quantlist__8u0__p7_2[] = {
  145723. 10,
  145724. 9,
  145725. 11,
  145726. 8,
  145727. 12,
  145728. 7,
  145729. 13,
  145730. 6,
  145731. 14,
  145732. 5,
  145733. 15,
  145734. 4,
  145735. 16,
  145736. 3,
  145737. 17,
  145738. 2,
  145739. 18,
  145740. 1,
  145741. 19,
  145742. 0,
  145743. 20,
  145744. };
  145745. static long _vq_lengthlist__8u0__p7_2[] = {
  145746. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145747. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145748. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145749. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145750. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145751. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145752. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145753. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145754. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145755. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145756. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145757. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145758. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145759. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145760. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145761. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145762. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145763. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145764. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145765. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145766. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145767. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145768. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145769. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145770. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145771. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145772. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145773. 11,12,11,11,11,10,10,11,11,
  145774. };
  145775. static float _vq_quantthresh__8u0__p7_2[] = {
  145776. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145777. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145778. 6.5, 7.5, 8.5, 9.5,
  145779. };
  145780. static long _vq_quantmap__8u0__p7_2[] = {
  145781. 19, 17, 15, 13, 11, 9, 7, 5,
  145782. 3, 1, 0, 2, 4, 6, 8, 10,
  145783. 12, 14, 16, 18, 20,
  145784. };
  145785. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145786. _vq_quantthresh__8u0__p7_2,
  145787. _vq_quantmap__8u0__p7_2,
  145788. 21,
  145789. 21
  145790. };
  145791. static static_codebook _8u0__p7_2 = {
  145792. 2, 441,
  145793. _vq_lengthlist__8u0__p7_2,
  145794. 1, -529268736, 1611661312, 5, 0,
  145795. _vq_quantlist__8u0__p7_2,
  145796. NULL,
  145797. &_vq_auxt__8u0__p7_2,
  145798. NULL,
  145799. 0
  145800. };
  145801. static long _huff_lengthlist__8u0__single[] = {
  145802. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145803. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145804. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145805. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145806. };
  145807. static static_codebook _huff_book__8u0__single = {
  145808. 2, 64,
  145809. _huff_lengthlist__8u0__single,
  145810. 0, 0, 0, 0, 0,
  145811. NULL,
  145812. NULL,
  145813. NULL,
  145814. NULL,
  145815. 0
  145816. };
  145817. static long _vq_quantlist__8u1__p1_0[] = {
  145818. 1,
  145819. 0,
  145820. 2,
  145821. };
  145822. static long _vq_lengthlist__8u1__p1_0[] = {
  145823. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145824. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145825. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145826. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145827. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145828. 10,
  145829. };
  145830. static float _vq_quantthresh__8u1__p1_0[] = {
  145831. -0.5, 0.5,
  145832. };
  145833. static long _vq_quantmap__8u1__p1_0[] = {
  145834. 1, 0, 2,
  145835. };
  145836. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145837. _vq_quantthresh__8u1__p1_0,
  145838. _vq_quantmap__8u1__p1_0,
  145839. 3,
  145840. 3
  145841. };
  145842. static static_codebook _8u1__p1_0 = {
  145843. 4, 81,
  145844. _vq_lengthlist__8u1__p1_0,
  145845. 1, -535822336, 1611661312, 2, 0,
  145846. _vq_quantlist__8u1__p1_0,
  145847. NULL,
  145848. &_vq_auxt__8u1__p1_0,
  145849. NULL,
  145850. 0
  145851. };
  145852. static long _vq_quantlist__8u1__p2_0[] = {
  145853. 1,
  145854. 0,
  145855. 2,
  145856. };
  145857. static long _vq_lengthlist__8u1__p2_0[] = {
  145858. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145859. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145860. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145861. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145862. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145863. 7,
  145864. };
  145865. static float _vq_quantthresh__8u1__p2_0[] = {
  145866. -0.5, 0.5,
  145867. };
  145868. static long _vq_quantmap__8u1__p2_0[] = {
  145869. 1, 0, 2,
  145870. };
  145871. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145872. _vq_quantthresh__8u1__p2_0,
  145873. _vq_quantmap__8u1__p2_0,
  145874. 3,
  145875. 3
  145876. };
  145877. static static_codebook _8u1__p2_0 = {
  145878. 4, 81,
  145879. _vq_lengthlist__8u1__p2_0,
  145880. 1, -535822336, 1611661312, 2, 0,
  145881. _vq_quantlist__8u1__p2_0,
  145882. NULL,
  145883. &_vq_auxt__8u1__p2_0,
  145884. NULL,
  145885. 0
  145886. };
  145887. static long _vq_quantlist__8u1__p3_0[] = {
  145888. 2,
  145889. 1,
  145890. 3,
  145891. 0,
  145892. 4,
  145893. };
  145894. static long _vq_lengthlist__8u1__p3_0[] = {
  145895. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145896. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145897. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145898. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145899. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145900. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145901. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145902. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145903. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145904. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145905. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145906. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145907. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145908. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145909. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145910. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145911. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145912. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145913. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145914. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145915. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145916. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145917. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145918. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145919. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145920. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145921. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145922. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145923. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145924. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145925. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145926. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145927. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145928. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145929. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145930. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145931. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145932. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145933. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145934. 16,
  145935. };
  145936. static float _vq_quantthresh__8u1__p3_0[] = {
  145937. -1.5, -0.5, 0.5, 1.5,
  145938. };
  145939. static long _vq_quantmap__8u1__p3_0[] = {
  145940. 3, 1, 0, 2, 4,
  145941. };
  145942. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145943. _vq_quantthresh__8u1__p3_0,
  145944. _vq_quantmap__8u1__p3_0,
  145945. 5,
  145946. 5
  145947. };
  145948. static static_codebook _8u1__p3_0 = {
  145949. 4, 625,
  145950. _vq_lengthlist__8u1__p3_0,
  145951. 1, -533725184, 1611661312, 3, 0,
  145952. _vq_quantlist__8u1__p3_0,
  145953. NULL,
  145954. &_vq_auxt__8u1__p3_0,
  145955. NULL,
  145956. 0
  145957. };
  145958. static long _vq_quantlist__8u1__p4_0[] = {
  145959. 2,
  145960. 1,
  145961. 3,
  145962. 0,
  145963. 4,
  145964. };
  145965. static long _vq_lengthlist__8u1__p4_0[] = {
  145966. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145967. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145968. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145969. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145970. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145971. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145972. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145973. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145974. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145975. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145976. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145977. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145978. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145979. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145980. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145981. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145982. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145983. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145984. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145985. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145986. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145987. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145988. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145989. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145990. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145991. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145992. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145993. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145994. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145995. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145996. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145997. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145998. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145999. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  146000. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  146001. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  146002. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  146003. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  146004. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  146005. 10,
  146006. };
  146007. static float _vq_quantthresh__8u1__p4_0[] = {
  146008. -1.5, -0.5, 0.5, 1.5,
  146009. };
  146010. static long _vq_quantmap__8u1__p4_0[] = {
  146011. 3, 1, 0, 2, 4,
  146012. };
  146013. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  146014. _vq_quantthresh__8u1__p4_0,
  146015. _vq_quantmap__8u1__p4_0,
  146016. 5,
  146017. 5
  146018. };
  146019. static static_codebook _8u1__p4_0 = {
  146020. 4, 625,
  146021. _vq_lengthlist__8u1__p4_0,
  146022. 1, -533725184, 1611661312, 3, 0,
  146023. _vq_quantlist__8u1__p4_0,
  146024. NULL,
  146025. &_vq_auxt__8u1__p4_0,
  146026. NULL,
  146027. 0
  146028. };
  146029. static long _vq_quantlist__8u1__p5_0[] = {
  146030. 4,
  146031. 3,
  146032. 5,
  146033. 2,
  146034. 6,
  146035. 1,
  146036. 7,
  146037. 0,
  146038. 8,
  146039. };
  146040. static long _vq_lengthlist__8u1__p5_0[] = {
  146041. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  146042. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146043. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146044. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  146045. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  146046. 13,
  146047. };
  146048. static float _vq_quantthresh__8u1__p5_0[] = {
  146049. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146050. };
  146051. static long _vq_quantmap__8u1__p5_0[] = {
  146052. 7, 5, 3, 1, 0, 2, 4, 6,
  146053. 8,
  146054. };
  146055. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  146056. _vq_quantthresh__8u1__p5_0,
  146057. _vq_quantmap__8u1__p5_0,
  146058. 9,
  146059. 9
  146060. };
  146061. static static_codebook _8u1__p5_0 = {
  146062. 2, 81,
  146063. _vq_lengthlist__8u1__p5_0,
  146064. 1, -531628032, 1611661312, 4, 0,
  146065. _vq_quantlist__8u1__p5_0,
  146066. NULL,
  146067. &_vq_auxt__8u1__p5_0,
  146068. NULL,
  146069. 0
  146070. };
  146071. static long _vq_quantlist__8u1__p6_0[] = {
  146072. 4,
  146073. 3,
  146074. 5,
  146075. 2,
  146076. 6,
  146077. 1,
  146078. 7,
  146079. 0,
  146080. 8,
  146081. };
  146082. static long _vq_lengthlist__8u1__p6_0[] = {
  146083. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  146084. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  146085. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146086. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  146087. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146088. 10,
  146089. };
  146090. static float _vq_quantthresh__8u1__p6_0[] = {
  146091. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146092. };
  146093. static long _vq_quantmap__8u1__p6_0[] = {
  146094. 7, 5, 3, 1, 0, 2, 4, 6,
  146095. 8,
  146096. };
  146097. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  146098. _vq_quantthresh__8u1__p6_0,
  146099. _vq_quantmap__8u1__p6_0,
  146100. 9,
  146101. 9
  146102. };
  146103. static static_codebook _8u1__p6_0 = {
  146104. 2, 81,
  146105. _vq_lengthlist__8u1__p6_0,
  146106. 1, -531628032, 1611661312, 4, 0,
  146107. _vq_quantlist__8u1__p6_0,
  146108. NULL,
  146109. &_vq_auxt__8u1__p6_0,
  146110. NULL,
  146111. 0
  146112. };
  146113. static long _vq_quantlist__8u1__p7_0[] = {
  146114. 1,
  146115. 0,
  146116. 2,
  146117. };
  146118. static long _vq_lengthlist__8u1__p7_0[] = {
  146119. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146120. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146121. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146122. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146123. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146124. 11,
  146125. };
  146126. static float _vq_quantthresh__8u1__p7_0[] = {
  146127. -5.5, 5.5,
  146128. };
  146129. static long _vq_quantmap__8u1__p7_0[] = {
  146130. 1, 0, 2,
  146131. };
  146132. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146133. _vq_quantthresh__8u1__p7_0,
  146134. _vq_quantmap__8u1__p7_0,
  146135. 3,
  146136. 3
  146137. };
  146138. static static_codebook _8u1__p7_0 = {
  146139. 4, 81,
  146140. _vq_lengthlist__8u1__p7_0,
  146141. 1, -529137664, 1618345984, 2, 0,
  146142. _vq_quantlist__8u1__p7_0,
  146143. NULL,
  146144. &_vq_auxt__8u1__p7_0,
  146145. NULL,
  146146. 0
  146147. };
  146148. static long _vq_quantlist__8u1__p7_1[] = {
  146149. 5,
  146150. 4,
  146151. 6,
  146152. 3,
  146153. 7,
  146154. 2,
  146155. 8,
  146156. 1,
  146157. 9,
  146158. 0,
  146159. 10,
  146160. };
  146161. static long _vq_lengthlist__8u1__p7_1[] = {
  146162. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146163. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146164. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146165. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146166. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146167. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146168. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146169. 9, 9, 9, 9, 9,10,10,10,10,
  146170. };
  146171. static float _vq_quantthresh__8u1__p7_1[] = {
  146172. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146173. 3.5, 4.5,
  146174. };
  146175. static long _vq_quantmap__8u1__p7_1[] = {
  146176. 9, 7, 5, 3, 1, 0, 2, 4,
  146177. 6, 8, 10,
  146178. };
  146179. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146180. _vq_quantthresh__8u1__p7_1,
  146181. _vq_quantmap__8u1__p7_1,
  146182. 11,
  146183. 11
  146184. };
  146185. static static_codebook _8u1__p7_1 = {
  146186. 2, 121,
  146187. _vq_lengthlist__8u1__p7_1,
  146188. 1, -531365888, 1611661312, 4, 0,
  146189. _vq_quantlist__8u1__p7_1,
  146190. NULL,
  146191. &_vq_auxt__8u1__p7_1,
  146192. NULL,
  146193. 0
  146194. };
  146195. static long _vq_quantlist__8u1__p8_0[] = {
  146196. 5,
  146197. 4,
  146198. 6,
  146199. 3,
  146200. 7,
  146201. 2,
  146202. 8,
  146203. 1,
  146204. 9,
  146205. 0,
  146206. 10,
  146207. };
  146208. static long _vq_lengthlist__8u1__p8_0[] = {
  146209. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146210. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146211. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146212. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146213. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146214. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146215. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146216. 12,13,13,14,14,15,15,15,15,
  146217. };
  146218. static float _vq_quantthresh__8u1__p8_0[] = {
  146219. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146220. 38.5, 49.5,
  146221. };
  146222. static long _vq_quantmap__8u1__p8_0[] = {
  146223. 9, 7, 5, 3, 1, 0, 2, 4,
  146224. 6, 8, 10,
  146225. };
  146226. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146227. _vq_quantthresh__8u1__p8_0,
  146228. _vq_quantmap__8u1__p8_0,
  146229. 11,
  146230. 11
  146231. };
  146232. static static_codebook _8u1__p8_0 = {
  146233. 2, 121,
  146234. _vq_lengthlist__8u1__p8_0,
  146235. 1, -524582912, 1618345984, 4, 0,
  146236. _vq_quantlist__8u1__p8_0,
  146237. NULL,
  146238. &_vq_auxt__8u1__p8_0,
  146239. NULL,
  146240. 0
  146241. };
  146242. static long _vq_quantlist__8u1__p8_1[] = {
  146243. 5,
  146244. 4,
  146245. 6,
  146246. 3,
  146247. 7,
  146248. 2,
  146249. 8,
  146250. 1,
  146251. 9,
  146252. 0,
  146253. 10,
  146254. };
  146255. static long _vq_lengthlist__8u1__p8_1[] = {
  146256. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146257. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146258. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146259. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146260. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146261. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146262. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146263. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146264. };
  146265. static float _vq_quantthresh__8u1__p8_1[] = {
  146266. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146267. 3.5, 4.5,
  146268. };
  146269. static long _vq_quantmap__8u1__p8_1[] = {
  146270. 9, 7, 5, 3, 1, 0, 2, 4,
  146271. 6, 8, 10,
  146272. };
  146273. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146274. _vq_quantthresh__8u1__p8_1,
  146275. _vq_quantmap__8u1__p8_1,
  146276. 11,
  146277. 11
  146278. };
  146279. static static_codebook _8u1__p8_1 = {
  146280. 2, 121,
  146281. _vq_lengthlist__8u1__p8_1,
  146282. 1, -531365888, 1611661312, 4, 0,
  146283. _vq_quantlist__8u1__p8_1,
  146284. NULL,
  146285. &_vq_auxt__8u1__p8_1,
  146286. NULL,
  146287. 0
  146288. };
  146289. static long _vq_quantlist__8u1__p9_0[] = {
  146290. 7,
  146291. 6,
  146292. 8,
  146293. 5,
  146294. 9,
  146295. 4,
  146296. 10,
  146297. 3,
  146298. 11,
  146299. 2,
  146300. 12,
  146301. 1,
  146302. 13,
  146303. 0,
  146304. 14,
  146305. };
  146306. static long _vq_lengthlist__8u1__p9_0[] = {
  146307. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146308. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146309. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146310. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146311. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146312. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146313. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146314. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146315. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146316. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146317. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146318. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146319. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146320. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146321. 10,
  146322. };
  146323. static float _vq_quantthresh__8u1__p9_0[] = {
  146324. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146325. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146326. };
  146327. static long _vq_quantmap__8u1__p9_0[] = {
  146328. 13, 11, 9, 7, 5, 3, 1, 0,
  146329. 2, 4, 6, 8, 10, 12, 14,
  146330. };
  146331. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146332. _vq_quantthresh__8u1__p9_0,
  146333. _vq_quantmap__8u1__p9_0,
  146334. 15,
  146335. 15
  146336. };
  146337. static static_codebook _8u1__p9_0 = {
  146338. 2, 225,
  146339. _vq_lengthlist__8u1__p9_0,
  146340. 1, -514071552, 1627381760, 4, 0,
  146341. _vq_quantlist__8u1__p9_0,
  146342. NULL,
  146343. &_vq_auxt__8u1__p9_0,
  146344. NULL,
  146345. 0
  146346. };
  146347. static long _vq_quantlist__8u1__p9_1[] = {
  146348. 7,
  146349. 6,
  146350. 8,
  146351. 5,
  146352. 9,
  146353. 4,
  146354. 10,
  146355. 3,
  146356. 11,
  146357. 2,
  146358. 12,
  146359. 1,
  146360. 13,
  146361. 0,
  146362. 14,
  146363. };
  146364. static long _vq_lengthlist__8u1__p9_1[] = {
  146365. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146366. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146367. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146368. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146369. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146370. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146371. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146372. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146373. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146374. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146375. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146376. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146377. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146378. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146379. 13,
  146380. };
  146381. static float _vq_quantthresh__8u1__p9_1[] = {
  146382. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146383. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146384. };
  146385. static long _vq_quantmap__8u1__p9_1[] = {
  146386. 13, 11, 9, 7, 5, 3, 1, 0,
  146387. 2, 4, 6, 8, 10, 12, 14,
  146388. };
  146389. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146390. _vq_quantthresh__8u1__p9_1,
  146391. _vq_quantmap__8u1__p9_1,
  146392. 15,
  146393. 15
  146394. };
  146395. static static_codebook _8u1__p9_1 = {
  146396. 2, 225,
  146397. _vq_lengthlist__8u1__p9_1,
  146398. 1, -522338304, 1620115456, 4, 0,
  146399. _vq_quantlist__8u1__p9_1,
  146400. NULL,
  146401. &_vq_auxt__8u1__p9_1,
  146402. NULL,
  146403. 0
  146404. };
  146405. static long _vq_quantlist__8u1__p9_2[] = {
  146406. 8,
  146407. 7,
  146408. 9,
  146409. 6,
  146410. 10,
  146411. 5,
  146412. 11,
  146413. 4,
  146414. 12,
  146415. 3,
  146416. 13,
  146417. 2,
  146418. 14,
  146419. 1,
  146420. 15,
  146421. 0,
  146422. 16,
  146423. };
  146424. static long _vq_lengthlist__8u1__p9_2[] = {
  146425. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146426. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146427. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146428. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146429. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146430. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146431. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146432. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146433. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146434. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146435. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146436. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146437. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146438. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146439. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146440. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146441. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146442. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146443. 10,
  146444. };
  146445. static float _vq_quantthresh__8u1__p9_2[] = {
  146446. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146447. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146448. };
  146449. static long _vq_quantmap__8u1__p9_2[] = {
  146450. 15, 13, 11, 9, 7, 5, 3, 1,
  146451. 0, 2, 4, 6, 8, 10, 12, 14,
  146452. 16,
  146453. };
  146454. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146455. _vq_quantthresh__8u1__p9_2,
  146456. _vq_quantmap__8u1__p9_2,
  146457. 17,
  146458. 17
  146459. };
  146460. static static_codebook _8u1__p9_2 = {
  146461. 2, 289,
  146462. _vq_lengthlist__8u1__p9_2,
  146463. 1, -529530880, 1611661312, 5, 0,
  146464. _vq_quantlist__8u1__p9_2,
  146465. NULL,
  146466. &_vq_auxt__8u1__p9_2,
  146467. NULL,
  146468. 0
  146469. };
  146470. static long _huff_lengthlist__8u1__single[] = {
  146471. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146472. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146473. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146474. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146475. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146476. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146477. 13, 8, 8,15,
  146478. };
  146479. static static_codebook _huff_book__8u1__single = {
  146480. 2, 100,
  146481. _huff_lengthlist__8u1__single,
  146482. 0, 0, 0, 0, 0,
  146483. NULL,
  146484. NULL,
  146485. NULL,
  146486. NULL,
  146487. 0
  146488. };
  146489. static long _huff_lengthlist__44u0__long[] = {
  146490. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146491. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146492. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146493. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146494. };
  146495. static static_codebook _huff_book__44u0__long = {
  146496. 2, 64,
  146497. _huff_lengthlist__44u0__long,
  146498. 0, 0, 0, 0, 0,
  146499. NULL,
  146500. NULL,
  146501. NULL,
  146502. NULL,
  146503. 0
  146504. };
  146505. static long _vq_quantlist__44u0__p1_0[] = {
  146506. 1,
  146507. 0,
  146508. 2,
  146509. };
  146510. static long _vq_lengthlist__44u0__p1_0[] = {
  146511. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146512. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146513. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146514. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146515. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146516. 13,
  146517. };
  146518. static float _vq_quantthresh__44u0__p1_0[] = {
  146519. -0.5, 0.5,
  146520. };
  146521. static long _vq_quantmap__44u0__p1_0[] = {
  146522. 1, 0, 2,
  146523. };
  146524. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146525. _vq_quantthresh__44u0__p1_0,
  146526. _vq_quantmap__44u0__p1_0,
  146527. 3,
  146528. 3
  146529. };
  146530. static static_codebook _44u0__p1_0 = {
  146531. 4, 81,
  146532. _vq_lengthlist__44u0__p1_0,
  146533. 1, -535822336, 1611661312, 2, 0,
  146534. _vq_quantlist__44u0__p1_0,
  146535. NULL,
  146536. &_vq_auxt__44u0__p1_0,
  146537. NULL,
  146538. 0
  146539. };
  146540. static long _vq_quantlist__44u0__p2_0[] = {
  146541. 1,
  146542. 0,
  146543. 2,
  146544. };
  146545. static long _vq_lengthlist__44u0__p2_0[] = {
  146546. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146547. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146548. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146549. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146550. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146551. 9,
  146552. };
  146553. static float _vq_quantthresh__44u0__p2_0[] = {
  146554. -0.5, 0.5,
  146555. };
  146556. static long _vq_quantmap__44u0__p2_0[] = {
  146557. 1, 0, 2,
  146558. };
  146559. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146560. _vq_quantthresh__44u0__p2_0,
  146561. _vq_quantmap__44u0__p2_0,
  146562. 3,
  146563. 3
  146564. };
  146565. static static_codebook _44u0__p2_0 = {
  146566. 4, 81,
  146567. _vq_lengthlist__44u0__p2_0,
  146568. 1, -535822336, 1611661312, 2, 0,
  146569. _vq_quantlist__44u0__p2_0,
  146570. NULL,
  146571. &_vq_auxt__44u0__p2_0,
  146572. NULL,
  146573. 0
  146574. };
  146575. static long _vq_quantlist__44u0__p3_0[] = {
  146576. 2,
  146577. 1,
  146578. 3,
  146579. 0,
  146580. 4,
  146581. };
  146582. static long _vq_lengthlist__44u0__p3_0[] = {
  146583. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146584. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146585. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146586. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146587. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146588. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146589. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146590. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146591. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146592. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146593. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146594. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146595. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146596. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146597. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146598. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146599. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146600. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146601. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146602. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146603. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146604. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146605. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146606. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146607. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146608. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146609. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146610. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146611. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146612. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146613. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146614. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146615. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146616. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146617. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146618. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146619. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146620. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146621. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146622. 19,
  146623. };
  146624. static float _vq_quantthresh__44u0__p3_0[] = {
  146625. -1.5, -0.5, 0.5, 1.5,
  146626. };
  146627. static long _vq_quantmap__44u0__p3_0[] = {
  146628. 3, 1, 0, 2, 4,
  146629. };
  146630. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146631. _vq_quantthresh__44u0__p3_0,
  146632. _vq_quantmap__44u0__p3_0,
  146633. 5,
  146634. 5
  146635. };
  146636. static static_codebook _44u0__p3_0 = {
  146637. 4, 625,
  146638. _vq_lengthlist__44u0__p3_0,
  146639. 1, -533725184, 1611661312, 3, 0,
  146640. _vq_quantlist__44u0__p3_0,
  146641. NULL,
  146642. &_vq_auxt__44u0__p3_0,
  146643. NULL,
  146644. 0
  146645. };
  146646. static long _vq_quantlist__44u0__p4_0[] = {
  146647. 2,
  146648. 1,
  146649. 3,
  146650. 0,
  146651. 4,
  146652. };
  146653. static long _vq_lengthlist__44u0__p4_0[] = {
  146654. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146655. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146656. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146657. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146658. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146659. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146660. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146661. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146662. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146663. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146664. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146665. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146666. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146667. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146668. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146669. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146670. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146671. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146672. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146673. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146674. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146675. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146676. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146677. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146678. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146679. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146680. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146681. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146682. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146683. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146684. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146685. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146686. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146687. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146688. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146689. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146690. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146691. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146692. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146693. 12,
  146694. };
  146695. static float _vq_quantthresh__44u0__p4_0[] = {
  146696. -1.5, -0.5, 0.5, 1.5,
  146697. };
  146698. static long _vq_quantmap__44u0__p4_0[] = {
  146699. 3, 1, 0, 2, 4,
  146700. };
  146701. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146702. _vq_quantthresh__44u0__p4_0,
  146703. _vq_quantmap__44u0__p4_0,
  146704. 5,
  146705. 5
  146706. };
  146707. static static_codebook _44u0__p4_0 = {
  146708. 4, 625,
  146709. _vq_lengthlist__44u0__p4_0,
  146710. 1, -533725184, 1611661312, 3, 0,
  146711. _vq_quantlist__44u0__p4_0,
  146712. NULL,
  146713. &_vq_auxt__44u0__p4_0,
  146714. NULL,
  146715. 0
  146716. };
  146717. static long _vq_quantlist__44u0__p5_0[] = {
  146718. 4,
  146719. 3,
  146720. 5,
  146721. 2,
  146722. 6,
  146723. 1,
  146724. 7,
  146725. 0,
  146726. 8,
  146727. };
  146728. static long _vq_lengthlist__44u0__p5_0[] = {
  146729. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146730. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146731. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146732. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146733. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146734. 12,
  146735. };
  146736. static float _vq_quantthresh__44u0__p5_0[] = {
  146737. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146738. };
  146739. static long _vq_quantmap__44u0__p5_0[] = {
  146740. 7, 5, 3, 1, 0, 2, 4, 6,
  146741. 8,
  146742. };
  146743. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146744. _vq_quantthresh__44u0__p5_0,
  146745. _vq_quantmap__44u0__p5_0,
  146746. 9,
  146747. 9
  146748. };
  146749. static static_codebook _44u0__p5_0 = {
  146750. 2, 81,
  146751. _vq_lengthlist__44u0__p5_0,
  146752. 1, -531628032, 1611661312, 4, 0,
  146753. _vq_quantlist__44u0__p5_0,
  146754. NULL,
  146755. &_vq_auxt__44u0__p5_0,
  146756. NULL,
  146757. 0
  146758. };
  146759. static long _vq_quantlist__44u0__p6_0[] = {
  146760. 6,
  146761. 5,
  146762. 7,
  146763. 4,
  146764. 8,
  146765. 3,
  146766. 9,
  146767. 2,
  146768. 10,
  146769. 1,
  146770. 11,
  146771. 0,
  146772. 12,
  146773. };
  146774. static long _vq_lengthlist__44u0__p6_0[] = {
  146775. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146776. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146777. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146778. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146779. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146780. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146781. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146782. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146783. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146784. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146785. 15,17,16,17,18,17,17,18, 0,
  146786. };
  146787. static float _vq_quantthresh__44u0__p6_0[] = {
  146788. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146789. 12.5, 17.5, 22.5, 27.5,
  146790. };
  146791. static long _vq_quantmap__44u0__p6_0[] = {
  146792. 11, 9, 7, 5, 3, 1, 0, 2,
  146793. 4, 6, 8, 10, 12,
  146794. };
  146795. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146796. _vq_quantthresh__44u0__p6_0,
  146797. _vq_quantmap__44u0__p6_0,
  146798. 13,
  146799. 13
  146800. };
  146801. static static_codebook _44u0__p6_0 = {
  146802. 2, 169,
  146803. _vq_lengthlist__44u0__p6_0,
  146804. 1, -526516224, 1616117760, 4, 0,
  146805. _vq_quantlist__44u0__p6_0,
  146806. NULL,
  146807. &_vq_auxt__44u0__p6_0,
  146808. NULL,
  146809. 0
  146810. };
  146811. static long _vq_quantlist__44u0__p6_1[] = {
  146812. 2,
  146813. 1,
  146814. 3,
  146815. 0,
  146816. 4,
  146817. };
  146818. static long _vq_lengthlist__44u0__p6_1[] = {
  146819. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146820. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146821. };
  146822. static float _vq_quantthresh__44u0__p6_1[] = {
  146823. -1.5, -0.5, 0.5, 1.5,
  146824. };
  146825. static long _vq_quantmap__44u0__p6_1[] = {
  146826. 3, 1, 0, 2, 4,
  146827. };
  146828. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146829. _vq_quantthresh__44u0__p6_1,
  146830. _vq_quantmap__44u0__p6_1,
  146831. 5,
  146832. 5
  146833. };
  146834. static static_codebook _44u0__p6_1 = {
  146835. 2, 25,
  146836. _vq_lengthlist__44u0__p6_1,
  146837. 1, -533725184, 1611661312, 3, 0,
  146838. _vq_quantlist__44u0__p6_1,
  146839. NULL,
  146840. &_vq_auxt__44u0__p6_1,
  146841. NULL,
  146842. 0
  146843. };
  146844. static long _vq_quantlist__44u0__p7_0[] = {
  146845. 2,
  146846. 1,
  146847. 3,
  146848. 0,
  146849. 4,
  146850. };
  146851. static long _vq_lengthlist__44u0__p7_0[] = {
  146852. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146855. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146858. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146859. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146861. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146864. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146865. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146866. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146867. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146876. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146877. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146881. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146882. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146883. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146884. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146885. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146886. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146887. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146888. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146889. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146890. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146891. 10,
  146892. };
  146893. static float _vq_quantthresh__44u0__p7_0[] = {
  146894. -253.5, -84.5, 84.5, 253.5,
  146895. };
  146896. static long _vq_quantmap__44u0__p7_0[] = {
  146897. 3, 1, 0, 2, 4,
  146898. };
  146899. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146900. _vq_quantthresh__44u0__p7_0,
  146901. _vq_quantmap__44u0__p7_0,
  146902. 5,
  146903. 5
  146904. };
  146905. static static_codebook _44u0__p7_0 = {
  146906. 4, 625,
  146907. _vq_lengthlist__44u0__p7_0,
  146908. 1, -518709248, 1626677248, 3, 0,
  146909. _vq_quantlist__44u0__p7_0,
  146910. NULL,
  146911. &_vq_auxt__44u0__p7_0,
  146912. NULL,
  146913. 0
  146914. };
  146915. static long _vq_quantlist__44u0__p7_1[] = {
  146916. 6,
  146917. 5,
  146918. 7,
  146919. 4,
  146920. 8,
  146921. 3,
  146922. 9,
  146923. 2,
  146924. 10,
  146925. 1,
  146926. 11,
  146927. 0,
  146928. 12,
  146929. };
  146930. static long _vq_lengthlist__44u0__p7_1[] = {
  146931. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146932. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146933. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146934. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146935. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146936. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146937. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146938. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146939. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146940. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146941. 15,15,15,15,15,15,15,15,15,
  146942. };
  146943. static float _vq_quantthresh__44u0__p7_1[] = {
  146944. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146945. 32.5, 45.5, 58.5, 71.5,
  146946. };
  146947. static long _vq_quantmap__44u0__p7_1[] = {
  146948. 11, 9, 7, 5, 3, 1, 0, 2,
  146949. 4, 6, 8, 10, 12,
  146950. };
  146951. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146952. _vq_quantthresh__44u0__p7_1,
  146953. _vq_quantmap__44u0__p7_1,
  146954. 13,
  146955. 13
  146956. };
  146957. static static_codebook _44u0__p7_1 = {
  146958. 2, 169,
  146959. _vq_lengthlist__44u0__p7_1,
  146960. 1, -523010048, 1618608128, 4, 0,
  146961. _vq_quantlist__44u0__p7_1,
  146962. NULL,
  146963. &_vq_auxt__44u0__p7_1,
  146964. NULL,
  146965. 0
  146966. };
  146967. static long _vq_quantlist__44u0__p7_2[] = {
  146968. 6,
  146969. 5,
  146970. 7,
  146971. 4,
  146972. 8,
  146973. 3,
  146974. 9,
  146975. 2,
  146976. 10,
  146977. 1,
  146978. 11,
  146979. 0,
  146980. 12,
  146981. };
  146982. static long _vq_lengthlist__44u0__p7_2[] = {
  146983. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146984. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146985. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146986. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146987. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146988. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146989. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146990. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146991. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146992. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146993. 9, 9, 9,10, 9, 9,10,10, 9,
  146994. };
  146995. static float _vq_quantthresh__44u0__p7_2[] = {
  146996. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146997. 2.5, 3.5, 4.5, 5.5,
  146998. };
  146999. static long _vq_quantmap__44u0__p7_2[] = {
  147000. 11, 9, 7, 5, 3, 1, 0, 2,
  147001. 4, 6, 8, 10, 12,
  147002. };
  147003. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  147004. _vq_quantthresh__44u0__p7_2,
  147005. _vq_quantmap__44u0__p7_2,
  147006. 13,
  147007. 13
  147008. };
  147009. static static_codebook _44u0__p7_2 = {
  147010. 2, 169,
  147011. _vq_lengthlist__44u0__p7_2,
  147012. 1, -531103744, 1611661312, 4, 0,
  147013. _vq_quantlist__44u0__p7_2,
  147014. NULL,
  147015. &_vq_auxt__44u0__p7_2,
  147016. NULL,
  147017. 0
  147018. };
  147019. static long _huff_lengthlist__44u0__short[] = {
  147020. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147021. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147022. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147023. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147024. };
  147025. static static_codebook _huff_book__44u0__short = {
  147026. 2, 64,
  147027. _huff_lengthlist__44u0__short,
  147028. 0, 0, 0, 0, 0,
  147029. NULL,
  147030. NULL,
  147031. NULL,
  147032. NULL,
  147033. 0
  147034. };
  147035. static long _huff_lengthlist__44u1__long[] = {
  147036. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  147037. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  147038. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  147039. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  147040. };
  147041. static static_codebook _huff_book__44u1__long = {
  147042. 2, 64,
  147043. _huff_lengthlist__44u1__long,
  147044. 0, 0, 0, 0, 0,
  147045. NULL,
  147046. NULL,
  147047. NULL,
  147048. NULL,
  147049. 0
  147050. };
  147051. static long _vq_quantlist__44u1__p1_0[] = {
  147052. 1,
  147053. 0,
  147054. 2,
  147055. };
  147056. static long _vq_lengthlist__44u1__p1_0[] = {
  147057. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147058. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147059. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  147060. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  147061. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  147062. 13,
  147063. };
  147064. static float _vq_quantthresh__44u1__p1_0[] = {
  147065. -0.5, 0.5,
  147066. };
  147067. static long _vq_quantmap__44u1__p1_0[] = {
  147068. 1, 0, 2,
  147069. };
  147070. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  147071. _vq_quantthresh__44u1__p1_0,
  147072. _vq_quantmap__44u1__p1_0,
  147073. 3,
  147074. 3
  147075. };
  147076. static static_codebook _44u1__p1_0 = {
  147077. 4, 81,
  147078. _vq_lengthlist__44u1__p1_0,
  147079. 1, -535822336, 1611661312, 2, 0,
  147080. _vq_quantlist__44u1__p1_0,
  147081. NULL,
  147082. &_vq_auxt__44u1__p1_0,
  147083. NULL,
  147084. 0
  147085. };
  147086. static long _vq_quantlist__44u1__p2_0[] = {
  147087. 1,
  147088. 0,
  147089. 2,
  147090. };
  147091. static long _vq_lengthlist__44u1__p2_0[] = {
  147092. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147093. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  147094. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147095. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  147096. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147097. 9,
  147098. };
  147099. static float _vq_quantthresh__44u1__p2_0[] = {
  147100. -0.5, 0.5,
  147101. };
  147102. static long _vq_quantmap__44u1__p2_0[] = {
  147103. 1, 0, 2,
  147104. };
  147105. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  147106. _vq_quantthresh__44u1__p2_0,
  147107. _vq_quantmap__44u1__p2_0,
  147108. 3,
  147109. 3
  147110. };
  147111. static static_codebook _44u1__p2_0 = {
  147112. 4, 81,
  147113. _vq_lengthlist__44u1__p2_0,
  147114. 1, -535822336, 1611661312, 2, 0,
  147115. _vq_quantlist__44u1__p2_0,
  147116. NULL,
  147117. &_vq_auxt__44u1__p2_0,
  147118. NULL,
  147119. 0
  147120. };
  147121. static long _vq_quantlist__44u1__p3_0[] = {
  147122. 2,
  147123. 1,
  147124. 3,
  147125. 0,
  147126. 4,
  147127. };
  147128. static long _vq_lengthlist__44u1__p3_0[] = {
  147129. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147130. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147131. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147132. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147133. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147134. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147135. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147136. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147137. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147138. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147139. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147140. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147141. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147142. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147143. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147144. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147145. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147146. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147147. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147148. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147149. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147150. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147151. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147152. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147153. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147154. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147155. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147156. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147157. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147158. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147159. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147160. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147161. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147162. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147163. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147164. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147165. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147166. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147167. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147168. 19,
  147169. };
  147170. static float _vq_quantthresh__44u1__p3_0[] = {
  147171. -1.5, -0.5, 0.5, 1.5,
  147172. };
  147173. static long _vq_quantmap__44u1__p3_0[] = {
  147174. 3, 1, 0, 2, 4,
  147175. };
  147176. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147177. _vq_quantthresh__44u1__p3_0,
  147178. _vq_quantmap__44u1__p3_0,
  147179. 5,
  147180. 5
  147181. };
  147182. static static_codebook _44u1__p3_0 = {
  147183. 4, 625,
  147184. _vq_lengthlist__44u1__p3_0,
  147185. 1, -533725184, 1611661312, 3, 0,
  147186. _vq_quantlist__44u1__p3_0,
  147187. NULL,
  147188. &_vq_auxt__44u1__p3_0,
  147189. NULL,
  147190. 0
  147191. };
  147192. static long _vq_quantlist__44u1__p4_0[] = {
  147193. 2,
  147194. 1,
  147195. 3,
  147196. 0,
  147197. 4,
  147198. };
  147199. static long _vq_lengthlist__44u1__p4_0[] = {
  147200. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147201. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147202. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147203. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147204. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147205. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147206. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147207. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147208. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147209. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147210. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147211. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147212. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147213. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147214. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147215. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147216. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147217. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147218. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147219. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147220. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147221. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147222. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147223. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147224. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147225. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147226. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147227. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147228. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147229. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147230. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147231. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147232. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147233. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147234. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147235. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147236. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147237. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147238. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147239. 12,
  147240. };
  147241. static float _vq_quantthresh__44u1__p4_0[] = {
  147242. -1.5, -0.5, 0.5, 1.5,
  147243. };
  147244. static long _vq_quantmap__44u1__p4_0[] = {
  147245. 3, 1, 0, 2, 4,
  147246. };
  147247. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147248. _vq_quantthresh__44u1__p4_0,
  147249. _vq_quantmap__44u1__p4_0,
  147250. 5,
  147251. 5
  147252. };
  147253. static static_codebook _44u1__p4_0 = {
  147254. 4, 625,
  147255. _vq_lengthlist__44u1__p4_0,
  147256. 1, -533725184, 1611661312, 3, 0,
  147257. _vq_quantlist__44u1__p4_0,
  147258. NULL,
  147259. &_vq_auxt__44u1__p4_0,
  147260. NULL,
  147261. 0
  147262. };
  147263. static long _vq_quantlist__44u1__p5_0[] = {
  147264. 4,
  147265. 3,
  147266. 5,
  147267. 2,
  147268. 6,
  147269. 1,
  147270. 7,
  147271. 0,
  147272. 8,
  147273. };
  147274. static long _vq_lengthlist__44u1__p5_0[] = {
  147275. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147276. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147277. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147278. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147279. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147280. 12,
  147281. };
  147282. static float _vq_quantthresh__44u1__p5_0[] = {
  147283. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147284. };
  147285. static long _vq_quantmap__44u1__p5_0[] = {
  147286. 7, 5, 3, 1, 0, 2, 4, 6,
  147287. 8,
  147288. };
  147289. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147290. _vq_quantthresh__44u1__p5_0,
  147291. _vq_quantmap__44u1__p5_0,
  147292. 9,
  147293. 9
  147294. };
  147295. static static_codebook _44u1__p5_0 = {
  147296. 2, 81,
  147297. _vq_lengthlist__44u1__p5_0,
  147298. 1, -531628032, 1611661312, 4, 0,
  147299. _vq_quantlist__44u1__p5_0,
  147300. NULL,
  147301. &_vq_auxt__44u1__p5_0,
  147302. NULL,
  147303. 0
  147304. };
  147305. static long _vq_quantlist__44u1__p6_0[] = {
  147306. 6,
  147307. 5,
  147308. 7,
  147309. 4,
  147310. 8,
  147311. 3,
  147312. 9,
  147313. 2,
  147314. 10,
  147315. 1,
  147316. 11,
  147317. 0,
  147318. 12,
  147319. };
  147320. static long _vq_lengthlist__44u1__p6_0[] = {
  147321. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147322. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147323. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147324. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147325. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147326. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147327. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147328. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147329. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147330. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147331. 15,17,16,17,18,17,17,18, 0,
  147332. };
  147333. static float _vq_quantthresh__44u1__p6_0[] = {
  147334. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147335. 12.5, 17.5, 22.5, 27.5,
  147336. };
  147337. static long _vq_quantmap__44u1__p6_0[] = {
  147338. 11, 9, 7, 5, 3, 1, 0, 2,
  147339. 4, 6, 8, 10, 12,
  147340. };
  147341. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147342. _vq_quantthresh__44u1__p6_0,
  147343. _vq_quantmap__44u1__p6_0,
  147344. 13,
  147345. 13
  147346. };
  147347. static static_codebook _44u1__p6_0 = {
  147348. 2, 169,
  147349. _vq_lengthlist__44u1__p6_0,
  147350. 1, -526516224, 1616117760, 4, 0,
  147351. _vq_quantlist__44u1__p6_0,
  147352. NULL,
  147353. &_vq_auxt__44u1__p6_0,
  147354. NULL,
  147355. 0
  147356. };
  147357. static long _vq_quantlist__44u1__p6_1[] = {
  147358. 2,
  147359. 1,
  147360. 3,
  147361. 0,
  147362. 4,
  147363. };
  147364. static long _vq_lengthlist__44u1__p6_1[] = {
  147365. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147366. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147367. };
  147368. static float _vq_quantthresh__44u1__p6_1[] = {
  147369. -1.5, -0.5, 0.5, 1.5,
  147370. };
  147371. static long _vq_quantmap__44u1__p6_1[] = {
  147372. 3, 1, 0, 2, 4,
  147373. };
  147374. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147375. _vq_quantthresh__44u1__p6_1,
  147376. _vq_quantmap__44u1__p6_1,
  147377. 5,
  147378. 5
  147379. };
  147380. static static_codebook _44u1__p6_1 = {
  147381. 2, 25,
  147382. _vq_lengthlist__44u1__p6_1,
  147383. 1, -533725184, 1611661312, 3, 0,
  147384. _vq_quantlist__44u1__p6_1,
  147385. NULL,
  147386. &_vq_auxt__44u1__p6_1,
  147387. NULL,
  147388. 0
  147389. };
  147390. static long _vq_quantlist__44u1__p7_0[] = {
  147391. 3,
  147392. 2,
  147393. 4,
  147394. 1,
  147395. 5,
  147396. 0,
  147397. 6,
  147398. };
  147399. static long _vq_lengthlist__44u1__p7_0[] = {
  147400. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147401. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147402. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147403. 8,
  147404. };
  147405. static float _vq_quantthresh__44u1__p7_0[] = {
  147406. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147407. };
  147408. static long _vq_quantmap__44u1__p7_0[] = {
  147409. 5, 3, 1, 0, 2, 4, 6,
  147410. };
  147411. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147412. _vq_quantthresh__44u1__p7_0,
  147413. _vq_quantmap__44u1__p7_0,
  147414. 7,
  147415. 7
  147416. };
  147417. static static_codebook _44u1__p7_0 = {
  147418. 2, 49,
  147419. _vq_lengthlist__44u1__p7_0,
  147420. 1, -518017024, 1626677248, 3, 0,
  147421. _vq_quantlist__44u1__p7_0,
  147422. NULL,
  147423. &_vq_auxt__44u1__p7_0,
  147424. NULL,
  147425. 0
  147426. };
  147427. static long _vq_quantlist__44u1__p7_1[] = {
  147428. 6,
  147429. 5,
  147430. 7,
  147431. 4,
  147432. 8,
  147433. 3,
  147434. 9,
  147435. 2,
  147436. 10,
  147437. 1,
  147438. 11,
  147439. 0,
  147440. 12,
  147441. };
  147442. static long _vq_lengthlist__44u1__p7_1[] = {
  147443. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147444. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147445. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147446. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147447. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147448. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147449. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147450. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147451. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147452. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147453. 15,15,15,15,15,15,15,15,15,
  147454. };
  147455. static float _vq_quantthresh__44u1__p7_1[] = {
  147456. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147457. 32.5, 45.5, 58.5, 71.5,
  147458. };
  147459. static long _vq_quantmap__44u1__p7_1[] = {
  147460. 11, 9, 7, 5, 3, 1, 0, 2,
  147461. 4, 6, 8, 10, 12,
  147462. };
  147463. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147464. _vq_quantthresh__44u1__p7_1,
  147465. _vq_quantmap__44u1__p7_1,
  147466. 13,
  147467. 13
  147468. };
  147469. static static_codebook _44u1__p7_1 = {
  147470. 2, 169,
  147471. _vq_lengthlist__44u1__p7_1,
  147472. 1, -523010048, 1618608128, 4, 0,
  147473. _vq_quantlist__44u1__p7_1,
  147474. NULL,
  147475. &_vq_auxt__44u1__p7_1,
  147476. NULL,
  147477. 0
  147478. };
  147479. static long _vq_quantlist__44u1__p7_2[] = {
  147480. 6,
  147481. 5,
  147482. 7,
  147483. 4,
  147484. 8,
  147485. 3,
  147486. 9,
  147487. 2,
  147488. 10,
  147489. 1,
  147490. 11,
  147491. 0,
  147492. 12,
  147493. };
  147494. static long _vq_lengthlist__44u1__p7_2[] = {
  147495. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147496. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147497. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147498. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147499. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147500. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147501. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147502. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147503. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147504. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147505. 9, 9, 9,10, 9, 9,10,10, 9,
  147506. };
  147507. static float _vq_quantthresh__44u1__p7_2[] = {
  147508. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147509. 2.5, 3.5, 4.5, 5.5,
  147510. };
  147511. static long _vq_quantmap__44u1__p7_2[] = {
  147512. 11, 9, 7, 5, 3, 1, 0, 2,
  147513. 4, 6, 8, 10, 12,
  147514. };
  147515. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147516. _vq_quantthresh__44u1__p7_2,
  147517. _vq_quantmap__44u1__p7_2,
  147518. 13,
  147519. 13
  147520. };
  147521. static static_codebook _44u1__p7_2 = {
  147522. 2, 169,
  147523. _vq_lengthlist__44u1__p7_2,
  147524. 1, -531103744, 1611661312, 4, 0,
  147525. _vq_quantlist__44u1__p7_2,
  147526. NULL,
  147527. &_vq_auxt__44u1__p7_2,
  147528. NULL,
  147529. 0
  147530. };
  147531. static long _huff_lengthlist__44u1__short[] = {
  147532. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147533. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147534. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147535. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147536. };
  147537. static static_codebook _huff_book__44u1__short = {
  147538. 2, 64,
  147539. _huff_lengthlist__44u1__short,
  147540. 0, 0, 0, 0, 0,
  147541. NULL,
  147542. NULL,
  147543. NULL,
  147544. NULL,
  147545. 0
  147546. };
  147547. static long _huff_lengthlist__44u2__long[] = {
  147548. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147549. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147550. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147551. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147552. };
  147553. static static_codebook _huff_book__44u2__long = {
  147554. 2, 64,
  147555. _huff_lengthlist__44u2__long,
  147556. 0, 0, 0, 0, 0,
  147557. NULL,
  147558. NULL,
  147559. NULL,
  147560. NULL,
  147561. 0
  147562. };
  147563. static long _vq_quantlist__44u2__p1_0[] = {
  147564. 1,
  147565. 0,
  147566. 2,
  147567. };
  147568. static long _vq_lengthlist__44u2__p1_0[] = {
  147569. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147570. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147571. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147572. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147573. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147574. 13,
  147575. };
  147576. static float _vq_quantthresh__44u2__p1_0[] = {
  147577. -0.5, 0.5,
  147578. };
  147579. static long _vq_quantmap__44u2__p1_0[] = {
  147580. 1, 0, 2,
  147581. };
  147582. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147583. _vq_quantthresh__44u2__p1_0,
  147584. _vq_quantmap__44u2__p1_0,
  147585. 3,
  147586. 3
  147587. };
  147588. static static_codebook _44u2__p1_0 = {
  147589. 4, 81,
  147590. _vq_lengthlist__44u2__p1_0,
  147591. 1, -535822336, 1611661312, 2, 0,
  147592. _vq_quantlist__44u2__p1_0,
  147593. NULL,
  147594. &_vq_auxt__44u2__p1_0,
  147595. NULL,
  147596. 0
  147597. };
  147598. static long _vq_quantlist__44u2__p2_0[] = {
  147599. 1,
  147600. 0,
  147601. 2,
  147602. };
  147603. static long _vq_lengthlist__44u2__p2_0[] = {
  147604. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147605. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147606. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147607. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147608. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147609. 9,
  147610. };
  147611. static float _vq_quantthresh__44u2__p2_0[] = {
  147612. -0.5, 0.5,
  147613. };
  147614. static long _vq_quantmap__44u2__p2_0[] = {
  147615. 1, 0, 2,
  147616. };
  147617. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147618. _vq_quantthresh__44u2__p2_0,
  147619. _vq_quantmap__44u2__p2_0,
  147620. 3,
  147621. 3
  147622. };
  147623. static static_codebook _44u2__p2_0 = {
  147624. 4, 81,
  147625. _vq_lengthlist__44u2__p2_0,
  147626. 1, -535822336, 1611661312, 2, 0,
  147627. _vq_quantlist__44u2__p2_0,
  147628. NULL,
  147629. &_vq_auxt__44u2__p2_0,
  147630. NULL,
  147631. 0
  147632. };
  147633. static long _vq_quantlist__44u2__p3_0[] = {
  147634. 2,
  147635. 1,
  147636. 3,
  147637. 0,
  147638. 4,
  147639. };
  147640. static long _vq_lengthlist__44u2__p3_0[] = {
  147641. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147642. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147643. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147644. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147645. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147646. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147647. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147648. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147649. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147650. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147651. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147652. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147653. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147654. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147655. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147656. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147657. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147658. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147659. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147660. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147661. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147662. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147663. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147664. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147665. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147666. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147667. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147668. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147669. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147670. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147671. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147672. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147673. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147674. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147675. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147676. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147677. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147678. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147679. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147680. 0,
  147681. };
  147682. static float _vq_quantthresh__44u2__p3_0[] = {
  147683. -1.5, -0.5, 0.5, 1.5,
  147684. };
  147685. static long _vq_quantmap__44u2__p3_0[] = {
  147686. 3, 1, 0, 2, 4,
  147687. };
  147688. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147689. _vq_quantthresh__44u2__p3_0,
  147690. _vq_quantmap__44u2__p3_0,
  147691. 5,
  147692. 5
  147693. };
  147694. static static_codebook _44u2__p3_0 = {
  147695. 4, 625,
  147696. _vq_lengthlist__44u2__p3_0,
  147697. 1, -533725184, 1611661312, 3, 0,
  147698. _vq_quantlist__44u2__p3_0,
  147699. NULL,
  147700. &_vq_auxt__44u2__p3_0,
  147701. NULL,
  147702. 0
  147703. };
  147704. static long _vq_quantlist__44u2__p4_0[] = {
  147705. 2,
  147706. 1,
  147707. 3,
  147708. 0,
  147709. 4,
  147710. };
  147711. static long _vq_lengthlist__44u2__p4_0[] = {
  147712. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147713. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147714. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147715. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147716. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147717. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147718. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147719. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147720. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147721. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147722. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147723. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147724. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147725. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147726. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147727. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147728. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147729. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147730. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147731. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147732. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147733. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147734. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147735. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147736. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147737. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147738. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147739. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147740. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147741. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147742. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147743. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147744. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147745. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147746. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147747. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147748. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147749. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147750. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147751. 13,
  147752. };
  147753. static float _vq_quantthresh__44u2__p4_0[] = {
  147754. -1.5, -0.5, 0.5, 1.5,
  147755. };
  147756. static long _vq_quantmap__44u2__p4_0[] = {
  147757. 3, 1, 0, 2, 4,
  147758. };
  147759. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147760. _vq_quantthresh__44u2__p4_0,
  147761. _vq_quantmap__44u2__p4_0,
  147762. 5,
  147763. 5
  147764. };
  147765. static static_codebook _44u2__p4_0 = {
  147766. 4, 625,
  147767. _vq_lengthlist__44u2__p4_0,
  147768. 1, -533725184, 1611661312, 3, 0,
  147769. _vq_quantlist__44u2__p4_0,
  147770. NULL,
  147771. &_vq_auxt__44u2__p4_0,
  147772. NULL,
  147773. 0
  147774. };
  147775. static long _vq_quantlist__44u2__p5_0[] = {
  147776. 4,
  147777. 3,
  147778. 5,
  147779. 2,
  147780. 6,
  147781. 1,
  147782. 7,
  147783. 0,
  147784. 8,
  147785. };
  147786. static long _vq_lengthlist__44u2__p5_0[] = {
  147787. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147788. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147789. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147790. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147791. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147792. 13,
  147793. };
  147794. static float _vq_quantthresh__44u2__p5_0[] = {
  147795. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147796. };
  147797. static long _vq_quantmap__44u2__p5_0[] = {
  147798. 7, 5, 3, 1, 0, 2, 4, 6,
  147799. 8,
  147800. };
  147801. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147802. _vq_quantthresh__44u2__p5_0,
  147803. _vq_quantmap__44u2__p5_0,
  147804. 9,
  147805. 9
  147806. };
  147807. static static_codebook _44u2__p5_0 = {
  147808. 2, 81,
  147809. _vq_lengthlist__44u2__p5_0,
  147810. 1, -531628032, 1611661312, 4, 0,
  147811. _vq_quantlist__44u2__p5_0,
  147812. NULL,
  147813. &_vq_auxt__44u2__p5_0,
  147814. NULL,
  147815. 0
  147816. };
  147817. static long _vq_quantlist__44u2__p6_0[] = {
  147818. 6,
  147819. 5,
  147820. 7,
  147821. 4,
  147822. 8,
  147823. 3,
  147824. 9,
  147825. 2,
  147826. 10,
  147827. 1,
  147828. 11,
  147829. 0,
  147830. 12,
  147831. };
  147832. static long _vq_lengthlist__44u2__p6_0[] = {
  147833. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147834. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147835. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147836. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147837. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147838. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147839. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147840. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147841. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147842. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147843. 15,17,17,16,18,17,18, 0, 0,
  147844. };
  147845. static float _vq_quantthresh__44u2__p6_0[] = {
  147846. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147847. 12.5, 17.5, 22.5, 27.5,
  147848. };
  147849. static long _vq_quantmap__44u2__p6_0[] = {
  147850. 11, 9, 7, 5, 3, 1, 0, 2,
  147851. 4, 6, 8, 10, 12,
  147852. };
  147853. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147854. _vq_quantthresh__44u2__p6_0,
  147855. _vq_quantmap__44u2__p6_0,
  147856. 13,
  147857. 13
  147858. };
  147859. static static_codebook _44u2__p6_0 = {
  147860. 2, 169,
  147861. _vq_lengthlist__44u2__p6_0,
  147862. 1, -526516224, 1616117760, 4, 0,
  147863. _vq_quantlist__44u2__p6_0,
  147864. NULL,
  147865. &_vq_auxt__44u2__p6_0,
  147866. NULL,
  147867. 0
  147868. };
  147869. static long _vq_quantlist__44u2__p6_1[] = {
  147870. 2,
  147871. 1,
  147872. 3,
  147873. 0,
  147874. 4,
  147875. };
  147876. static long _vq_lengthlist__44u2__p6_1[] = {
  147877. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147878. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147879. };
  147880. static float _vq_quantthresh__44u2__p6_1[] = {
  147881. -1.5, -0.5, 0.5, 1.5,
  147882. };
  147883. static long _vq_quantmap__44u2__p6_1[] = {
  147884. 3, 1, 0, 2, 4,
  147885. };
  147886. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147887. _vq_quantthresh__44u2__p6_1,
  147888. _vq_quantmap__44u2__p6_1,
  147889. 5,
  147890. 5
  147891. };
  147892. static static_codebook _44u2__p6_1 = {
  147893. 2, 25,
  147894. _vq_lengthlist__44u2__p6_1,
  147895. 1, -533725184, 1611661312, 3, 0,
  147896. _vq_quantlist__44u2__p6_1,
  147897. NULL,
  147898. &_vq_auxt__44u2__p6_1,
  147899. NULL,
  147900. 0
  147901. };
  147902. static long _vq_quantlist__44u2__p7_0[] = {
  147903. 4,
  147904. 3,
  147905. 5,
  147906. 2,
  147907. 6,
  147908. 1,
  147909. 7,
  147910. 0,
  147911. 8,
  147912. };
  147913. static long _vq_lengthlist__44u2__p7_0[] = {
  147914. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147915. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147919. 11,
  147920. };
  147921. static float _vq_quantthresh__44u2__p7_0[] = {
  147922. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147923. };
  147924. static long _vq_quantmap__44u2__p7_0[] = {
  147925. 7, 5, 3, 1, 0, 2, 4, 6,
  147926. 8,
  147927. };
  147928. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147929. _vq_quantthresh__44u2__p7_0,
  147930. _vq_quantmap__44u2__p7_0,
  147931. 9,
  147932. 9
  147933. };
  147934. static static_codebook _44u2__p7_0 = {
  147935. 2, 81,
  147936. _vq_lengthlist__44u2__p7_0,
  147937. 1, -516612096, 1626677248, 4, 0,
  147938. _vq_quantlist__44u2__p7_0,
  147939. NULL,
  147940. &_vq_auxt__44u2__p7_0,
  147941. NULL,
  147942. 0
  147943. };
  147944. static long _vq_quantlist__44u2__p7_1[] = {
  147945. 6,
  147946. 5,
  147947. 7,
  147948. 4,
  147949. 8,
  147950. 3,
  147951. 9,
  147952. 2,
  147953. 10,
  147954. 1,
  147955. 11,
  147956. 0,
  147957. 12,
  147958. };
  147959. static long _vq_lengthlist__44u2__p7_1[] = {
  147960. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147961. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147962. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147963. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147964. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147965. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147966. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147967. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147968. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147969. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147970. 14,14,14,17,15,17,17,17,17,
  147971. };
  147972. static float _vq_quantthresh__44u2__p7_1[] = {
  147973. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147974. 32.5, 45.5, 58.5, 71.5,
  147975. };
  147976. static long _vq_quantmap__44u2__p7_1[] = {
  147977. 11, 9, 7, 5, 3, 1, 0, 2,
  147978. 4, 6, 8, 10, 12,
  147979. };
  147980. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147981. _vq_quantthresh__44u2__p7_1,
  147982. _vq_quantmap__44u2__p7_1,
  147983. 13,
  147984. 13
  147985. };
  147986. static static_codebook _44u2__p7_1 = {
  147987. 2, 169,
  147988. _vq_lengthlist__44u2__p7_1,
  147989. 1, -523010048, 1618608128, 4, 0,
  147990. _vq_quantlist__44u2__p7_1,
  147991. NULL,
  147992. &_vq_auxt__44u2__p7_1,
  147993. NULL,
  147994. 0
  147995. };
  147996. static long _vq_quantlist__44u2__p7_2[] = {
  147997. 6,
  147998. 5,
  147999. 7,
  148000. 4,
  148001. 8,
  148002. 3,
  148003. 9,
  148004. 2,
  148005. 10,
  148006. 1,
  148007. 11,
  148008. 0,
  148009. 12,
  148010. };
  148011. static long _vq_lengthlist__44u2__p7_2[] = {
  148012. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  148013. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  148014. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  148015. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  148016. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  148017. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  148018. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  148019. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148020. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  148021. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  148022. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148023. };
  148024. static float _vq_quantthresh__44u2__p7_2[] = {
  148025. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  148026. 2.5, 3.5, 4.5, 5.5,
  148027. };
  148028. static long _vq_quantmap__44u2__p7_2[] = {
  148029. 11, 9, 7, 5, 3, 1, 0, 2,
  148030. 4, 6, 8, 10, 12,
  148031. };
  148032. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  148033. _vq_quantthresh__44u2__p7_2,
  148034. _vq_quantmap__44u2__p7_2,
  148035. 13,
  148036. 13
  148037. };
  148038. static static_codebook _44u2__p7_2 = {
  148039. 2, 169,
  148040. _vq_lengthlist__44u2__p7_2,
  148041. 1, -531103744, 1611661312, 4, 0,
  148042. _vq_quantlist__44u2__p7_2,
  148043. NULL,
  148044. &_vq_auxt__44u2__p7_2,
  148045. NULL,
  148046. 0
  148047. };
  148048. static long _huff_lengthlist__44u2__short[] = {
  148049. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  148050. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  148051. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  148052. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  148053. };
  148054. static static_codebook _huff_book__44u2__short = {
  148055. 2, 64,
  148056. _huff_lengthlist__44u2__short,
  148057. 0, 0, 0, 0, 0,
  148058. NULL,
  148059. NULL,
  148060. NULL,
  148061. NULL,
  148062. 0
  148063. };
  148064. static long _huff_lengthlist__44u3__long[] = {
  148065. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  148066. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  148067. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  148068. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  148069. };
  148070. static static_codebook _huff_book__44u3__long = {
  148071. 2, 64,
  148072. _huff_lengthlist__44u3__long,
  148073. 0, 0, 0, 0, 0,
  148074. NULL,
  148075. NULL,
  148076. NULL,
  148077. NULL,
  148078. 0
  148079. };
  148080. static long _vq_quantlist__44u3__p1_0[] = {
  148081. 1,
  148082. 0,
  148083. 2,
  148084. };
  148085. static long _vq_lengthlist__44u3__p1_0[] = {
  148086. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148087. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148088. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  148089. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148090. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  148091. 13,
  148092. };
  148093. static float _vq_quantthresh__44u3__p1_0[] = {
  148094. -0.5, 0.5,
  148095. };
  148096. static long _vq_quantmap__44u3__p1_0[] = {
  148097. 1, 0, 2,
  148098. };
  148099. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  148100. _vq_quantthresh__44u3__p1_0,
  148101. _vq_quantmap__44u3__p1_0,
  148102. 3,
  148103. 3
  148104. };
  148105. static static_codebook _44u3__p1_0 = {
  148106. 4, 81,
  148107. _vq_lengthlist__44u3__p1_0,
  148108. 1, -535822336, 1611661312, 2, 0,
  148109. _vq_quantlist__44u3__p1_0,
  148110. NULL,
  148111. &_vq_auxt__44u3__p1_0,
  148112. NULL,
  148113. 0
  148114. };
  148115. static long _vq_quantlist__44u3__p2_0[] = {
  148116. 1,
  148117. 0,
  148118. 2,
  148119. };
  148120. static long _vq_lengthlist__44u3__p2_0[] = {
  148121. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148122. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148123. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148124. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148125. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148126. 9,
  148127. };
  148128. static float _vq_quantthresh__44u3__p2_0[] = {
  148129. -0.5, 0.5,
  148130. };
  148131. static long _vq_quantmap__44u3__p2_0[] = {
  148132. 1, 0, 2,
  148133. };
  148134. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148135. _vq_quantthresh__44u3__p2_0,
  148136. _vq_quantmap__44u3__p2_0,
  148137. 3,
  148138. 3
  148139. };
  148140. static static_codebook _44u3__p2_0 = {
  148141. 4, 81,
  148142. _vq_lengthlist__44u3__p2_0,
  148143. 1, -535822336, 1611661312, 2, 0,
  148144. _vq_quantlist__44u3__p2_0,
  148145. NULL,
  148146. &_vq_auxt__44u3__p2_0,
  148147. NULL,
  148148. 0
  148149. };
  148150. static long _vq_quantlist__44u3__p3_0[] = {
  148151. 2,
  148152. 1,
  148153. 3,
  148154. 0,
  148155. 4,
  148156. };
  148157. static long _vq_lengthlist__44u3__p3_0[] = {
  148158. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148159. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148160. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148161. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148162. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148163. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148164. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148165. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148166. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148167. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148168. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148169. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148170. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148171. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148172. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148173. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148174. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148175. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148176. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148177. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148178. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148179. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148180. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148181. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148182. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148183. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148184. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148185. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148186. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148187. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148188. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148189. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148190. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148191. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148192. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148193. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148194. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148195. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148196. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148197. 0,
  148198. };
  148199. static float _vq_quantthresh__44u3__p3_0[] = {
  148200. -1.5, -0.5, 0.5, 1.5,
  148201. };
  148202. static long _vq_quantmap__44u3__p3_0[] = {
  148203. 3, 1, 0, 2, 4,
  148204. };
  148205. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148206. _vq_quantthresh__44u3__p3_0,
  148207. _vq_quantmap__44u3__p3_0,
  148208. 5,
  148209. 5
  148210. };
  148211. static static_codebook _44u3__p3_0 = {
  148212. 4, 625,
  148213. _vq_lengthlist__44u3__p3_0,
  148214. 1, -533725184, 1611661312, 3, 0,
  148215. _vq_quantlist__44u3__p3_0,
  148216. NULL,
  148217. &_vq_auxt__44u3__p3_0,
  148218. NULL,
  148219. 0
  148220. };
  148221. static long _vq_quantlist__44u3__p4_0[] = {
  148222. 2,
  148223. 1,
  148224. 3,
  148225. 0,
  148226. 4,
  148227. };
  148228. static long _vq_lengthlist__44u3__p4_0[] = {
  148229. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148230. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148231. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148232. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148233. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148234. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148235. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148236. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148237. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148238. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148239. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148240. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148241. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148242. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148243. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148244. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148245. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148246. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148247. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148248. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148249. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148250. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148251. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148252. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148253. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148254. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148255. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148256. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148257. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148258. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148259. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148260. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148261. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148262. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148263. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148264. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148265. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148266. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148267. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148268. 13,
  148269. };
  148270. static float _vq_quantthresh__44u3__p4_0[] = {
  148271. -1.5, -0.5, 0.5, 1.5,
  148272. };
  148273. static long _vq_quantmap__44u3__p4_0[] = {
  148274. 3, 1, 0, 2, 4,
  148275. };
  148276. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148277. _vq_quantthresh__44u3__p4_0,
  148278. _vq_quantmap__44u3__p4_0,
  148279. 5,
  148280. 5
  148281. };
  148282. static static_codebook _44u3__p4_0 = {
  148283. 4, 625,
  148284. _vq_lengthlist__44u3__p4_0,
  148285. 1, -533725184, 1611661312, 3, 0,
  148286. _vq_quantlist__44u3__p4_0,
  148287. NULL,
  148288. &_vq_auxt__44u3__p4_0,
  148289. NULL,
  148290. 0
  148291. };
  148292. static long _vq_quantlist__44u3__p5_0[] = {
  148293. 4,
  148294. 3,
  148295. 5,
  148296. 2,
  148297. 6,
  148298. 1,
  148299. 7,
  148300. 0,
  148301. 8,
  148302. };
  148303. static long _vq_lengthlist__44u3__p5_0[] = {
  148304. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148305. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148306. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148307. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148308. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148309. 12,
  148310. };
  148311. static float _vq_quantthresh__44u3__p5_0[] = {
  148312. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148313. };
  148314. static long _vq_quantmap__44u3__p5_0[] = {
  148315. 7, 5, 3, 1, 0, 2, 4, 6,
  148316. 8,
  148317. };
  148318. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148319. _vq_quantthresh__44u3__p5_0,
  148320. _vq_quantmap__44u3__p5_0,
  148321. 9,
  148322. 9
  148323. };
  148324. static static_codebook _44u3__p5_0 = {
  148325. 2, 81,
  148326. _vq_lengthlist__44u3__p5_0,
  148327. 1, -531628032, 1611661312, 4, 0,
  148328. _vq_quantlist__44u3__p5_0,
  148329. NULL,
  148330. &_vq_auxt__44u3__p5_0,
  148331. NULL,
  148332. 0
  148333. };
  148334. static long _vq_quantlist__44u3__p6_0[] = {
  148335. 6,
  148336. 5,
  148337. 7,
  148338. 4,
  148339. 8,
  148340. 3,
  148341. 9,
  148342. 2,
  148343. 10,
  148344. 1,
  148345. 11,
  148346. 0,
  148347. 12,
  148348. };
  148349. static long _vq_lengthlist__44u3__p6_0[] = {
  148350. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148351. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148352. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148353. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148354. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148355. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148356. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148357. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148358. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148359. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148360. 15,16,16,16,17,18,16,20,18,
  148361. };
  148362. static float _vq_quantthresh__44u3__p6_0[] = {
  148363. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148364. 12.5, 17.5, 22.5, 27.5,
  148365. };
  148366. static long _vq_quantmap__44u3__p6_0[] = {
  148367. 11, 9, 7, 5, 3, 1, 0, 2,
  148368. 4, 6, 8, 10, 12,
  148369. };
  148370. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148371. _vq_quantthresh__44u3__p6_0,
  148372. _vq_quantmap__44u3__p6_0,
  148373. 13,
  148374. 13
  148375. };
  148376. static static_codebook _44u3__p6_0 = {
  148377. 2, 169,
  148378. _vq_lengthlist__44u3__p6_0,
  148379. 1, -526516224, 1616117760, 4, 0,
  148380. _vq_quantlist__44u3__p6_0,
  148381. NULL,
  148382. &_vq_auxt__44u3__p6_0,
  148383. NULL,
  148384. 0
  148385. };
  148386. static long _vq_quantlist__44u3__p6_1[] = {
  148387. 2,
  148388. 1,
  148389. 3,
  148390. 0,
  148391. 4,
  148392. };
  148393. static long _vq_lengthlist__44u3__p6_1[] = {
  148394. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148395. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148396. };
  148397. static float _vq_quantthresh__44u3__p6_1[] = {
  148398. -1.5, -0.5, 0.5, 1.5,
  148399. };
  148400. static long _vq_quantmap__44u3__p6_1[] = {
  148401. 3, 1, 0, 2, 4,
  148402. };
  148403. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148404. _vq_quantthresh__44u3__p6_1,
  148405. _vq_quantmap__44u3__p6_1,
  148406. 5,
  148407. 5
  148408. };
  148409. static static_codebook _44u3__p6_1 = {
  148410. 2, 25,
  148411. _vq_lengthlist__44u3__p6_1,
  148412. 1, -533725184, 1611661312, 3, 0,
  148413. _vq_quantlist__44u3__p6_1,
  148414. NULL,
  148415. &_vq_auxt__44u3__p6_1,
  148416. NULL,
  148417. 0
  148418. };
  148419. static long _vq_quantlist__44u3__p7_0[] = {
  148420. 4,
  148421. 3,
  148422. 5,
  148423. 2,
  148424. 6,
  148425. 1,
  148426. 7,
  148427. 0,
  148428. 8,
  148429. };
  148430. static long _vq_lengthlist__44u3__p7_0[] = {
  148431. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148432. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148433. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148434. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148435. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148436. 9,
  148437. };
  148438. static float _vq_quantthresh__44u3__p7_0[] = {
  148439. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148440. };
  148441. static long _vq_quantmap__44u3__p7_0[] = {
  148442. 7, 5, 3, 1, 0, 2, 4, 6,
  148443. 8,
  148444. };
  148445. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148446. _vq_quantthresh__44u3__p7_0,
  148447. _vq_quantmap__44u3__p7_0,
  148448. 9,
  148449. 9
  148450. };
  148451. static static_codebook _44u3__p7_0 = {
  148452. 2, 81,
  148453. _vq_lengthlist__44u3__p7_0,
  148454. 1, -515907584, 1627381760, 4, 0,
  148455. _vq_quantlist__44u3__p7_0,
  148456. NULL,
  148457. &_vq_auxt__44u3__p7_0,
  148458. NULL,
  148459. 0
  148460. };
  148461. static long _vq_quantlist__44u3__p7_1[] = {
  148462. 7,
  148463. 6,
  148464. 8,
  148465. 5,
  148466. 9,
  148467. 4,
  148468. 10,
  148469. 3,
  148470. 11,
  148471. 2,
  148472. 12,
  148473. 1,
  148474. 13,
  148475. 0,
  148476. 14,
  148477. };
  148478. static long _vq_lengthlist__44u3__p7_1[] = {
  148479. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148480. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148481. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148482. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148483. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148484. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148485. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148486. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148487. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148488. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148489. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148490. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148491. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148492. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148493. 17,
  148494. };
  148495. static float _vq_quantthresh__44u3__p7_1[] = {
  148496. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148497. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148498. };
  148499. static long _vq_quantmap__44u3__p7_1[] = {
  148500. 13, 11, 9, 7, 5, 3, 1, 0,
  148501. 2, 4, 6, 8, 10, 12, 14,
  148502. };
  148503. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148504. _vq_quantthresh__44u3__p7_1,
  148505. _vq_quantmap__44u3__p7_1,
  148506. 15,
  148507. 15
  148508. };
  148509. static static_codebook _44u3__p7_1 = {
  148510. 2, 225,
  148511. _vq_lengthlist__44u3__p7_1,
  148512. 1, -522338304, 1620115456, 4, 0,
  148513. _vq_quantlist__44u3__p7_1,
  148514. NULL,
  148515. &_vq_auxt__44u3__p7_1,
  148516. NULL,
  148517. 0
  148518. };
  148519. static long _vq_quantlist__44u3__p7_2[] = {
  148520. 8,
  148521. 7,
  148522. 9,
  148523. 6,
  148524. 10,
  148525. 5,
  148526. 11,
  148527. 4,
  148528. 12,
  148529. 3,
  148530. 13,
  148531. 2,
  148532. 14,
  148533. 1,
  148534. 15,
  148535. 0,
  148536. 16,
  148537. };
  148538. static long _vq_lengthlist__44u3__p7_2[] = {
  148539. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148540. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148541. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148542. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148543. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148544. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148545. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148546. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148547. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148548. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148549. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148550. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148551. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148552. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148553. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148554. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148555. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148556. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148557. 11,
  148558. };
  148559. static float _vq_quantthresh__44u3__p7_2[] = {
  148560. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148561. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148562. };
  148563. static long _vq_quantmap__44u3__p7_2[] = {
  148564. 15, 13, 11, 9, 7, 5, 3, 1,
  148565. 0, 2, 4, 6, 8, 10, 12, 14,
  148566. 16,
  148567. };
  148568. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148569. _vq_quantthresh__44u3__p7_2,
  148570. _vq_quantmap__44u3__p7_2,
  148571. 17,
  148572. 17
  148573. };
  148574. static static_codebook _44u3__p7_2 = {
  148575. 2, 289,
  148576. _vq_lengthlist__44u3__p7_2,
  148577. 1, -529530880, 1611661312, 5, 0,
  148578. _vq_quantlist__44u3__p7_2,
  148579. NULL,
  148580. &_vq_auxt__44u3__p7_2,
  148581. NULL,
  148582. 0
  148583. };
  148584. static long _huff_lengthlist__44u3__short[] = {
  148585. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148586. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148587. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148588. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148589. };
  148590. static static_codebook _huff_book__44u3__short = {
  148591. 2, 64,
  148592. _huff_lengthlist__44u3__short,
  148593. 0, 0, 0, 0, 0,
  148594. NULL,
  148595. NULL,
  148596. NULL,
  148597. NULL,
  148598. 0
  148599. };
  148600. static long _huff_lengthlist__44u4__long[] = {
  148601. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148602. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148603. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148604. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148605. };
  148606. static static_codebook _huff_book__44u4__long = {
  148607. 2, 64,
  148608. _huff_lengthlist__44u4__long,
  148609. 0, 0, 0, 0, 0,
  148610. NULL,
  148611. NULL,
  148612. NULL,
  148613. NULL,
  148614. 0
  148615. };
  148616. static long _vq_quantlist__44u4__p1_0[] = {
  148617. 1,
  148618. 0,
  148619. 2,
  148620. };
  148621. static long _vq_lengthlist__44u4__p1_0[] = {
  148622. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148623. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148624. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148625. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148626. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148627. 13,
  148628. };
  148629. static float _vq_quantthresh__44u4__p1_0[] = {
  148630. -0.5, 0.5,
  148631. };
  148632. static long _vq_quantmap__44u4__p1_0[] = {
  148633. 1, 0, 2,
  148634. };
  148635. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148636. _vq_quantthresh__44u4__p1_0,
  148637. _vq_quantmap__44u4__p1_0,
  148638. 3,
  148639. 3
  148640. };
  148641. static static_codebook _44u4__p1_0 = {
  148642. 4, 81,
  148643. _vq_lengthlist__44u4__p1_0,
  148644. 1, -535822336, 1611661312, 2, 0,
  148645. _vq_quantlist__44u4__p1_0,
  148646. NULL,
  148647. &_vq_auxt__44u4__p1_0,
  148648. NULL,
  148649. 0
  148650. };
  148651. static long _vq_quantlist__44u4__p2_0[] = {
  148652. 1,
  148653. 0,
  148654. 2,
  148655. };
  148656. static long _vq_lengthlist__44u4__p2_0[] = {
  148657. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148658. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148659. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148660. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148661. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148662. 9,
  148663. };
  148664. static float _vq_quantthresh__44u4__p2_0[] = {
  148665. -0.5, 0.5,
  148666. };
  148667. static long _vq_quantmap__44u4__p2_0[] = {
  148668. 1, 0, 2,
  148669. };
  148670. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148671. _vq_quantthresh__44u4__p2_0,
  148672. _vq_quantmap__44u4__p2_0,
  148673. 3,
  148674. 3
  148675. };
  148676. static static_codebook _44u4__p2_0 = {
  148677. 4, 81,
  148678. _vq_lengthlist__44u4__p2_0,
  148679. 1, -535822336, 1611661312, 2, 0,
  148680. _vq_quantlist__44u4__p2_0,
  148681. NULL,
  148682. &_vq_auxt__44u4__p2_0,
  148683. NULL,
  148684. 0
  148685. };
  148686. static long _vq_quantlist__44u4__p3_0[] = {
  148687. 2,
  148688. 1,
  148689. 3,
  148690. 0,
  148691. 4,
  148692. };
  148693. static long _vq_lengthlist__44u4__p3_0[] = {
  148694. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148695. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148696. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148697. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148698. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148699. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148700. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148701. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148702. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148703. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148704. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148705. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148706. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148707. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148708. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148709. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148710. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148711. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148712. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148713. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148714. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148715. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148716. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148717. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148718. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148719. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148720. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148721. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148722. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148723. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148724. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148725. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148726. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148727. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148728. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148729. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148730. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148731. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148732. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148733. 0,
  148734. };
  148735. static float _vq_quantthresh__44u4__p3_0[] = {
  148736. -1.5, -0.5, 0.5, 1.5,
  148737. };
  148738. static long _vq_quantmap__44u4__p3_0[] = {
  148739. 3, 1, 0, 2, 4,
  148740. };
  148741. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148742. _vq_quantthresh__44u4__p3_0,
  148743. _vq_quantmap__44u4__p3_0,
  148744. 5,
  148745. 5
  148746. };
  148747. static static_codebook _44u4__p3_0 = {
  148748. 4, 625,
  148749. _vq_lengthlist__44u4__p3_0,
  148750. 1, -533725184, 1611661312, 3, 0,
  148751. _vq_quantlist__44u4__p3_0,
  148752. NULL,
  148753. &_vq_auxt__44u4__p3_0,
  148754. NULL,
  148755. 0
  148756. };
  148757. static long _vq_quantlist__44u4__p4_0[] = {
  148758. 2,
  148759. 1,
  148760. 3,
  148761. 0,
  148762. 4,
  148763. };
  148764. static long _vq_lengthlist__44u4__p4_0[] = {
  148765. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148766. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148767. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148768. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148769. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148770. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148771. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148772. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148773. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148774. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148775. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148776. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148777. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148778. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148779. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148780. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148781. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148782. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148783. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148784. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148785. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148786. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148787. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148788. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148789. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148790. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148791. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148792. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148793. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148794. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148795. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148796. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148797. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148798. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148799. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148800. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148801. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148802. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148803. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148804. 13,
  148805. };
  148806. static float _vq_quantthresh__44u4__p4_0[] = {
  148807. -1.5, -0.5, 0.5, 1.5,
  148808. };
  148809. static long _vq_quantmap__44u4__p4_0[] = {
  148810. 3, 1, 0, 2, 4,
  148811. };
  148812. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148813. _vq_quantthresh__44u4__p4_0,
  148814. _vq_quantmap__44u4__p4_0,
  148815. 5,
  148816. 5
  148817. };
  148818. static static_codebook _44u4__p4_0 = {
  148819. 4, 625,
  148820. _vq_lengthlist__44u4__p4_0,
  148821. 1, -533725184, 1611661312, 3, 0,
  148822. _vq_quantlist__44u4__p4_0,
  148823. NULL,
  148824. &_vq_auxt__44u4__p4_0,
  148825. NULL,
  148826. 0
  148827. };
  148828. static long _vq_quantlist__44u4__p5_0[] = {
  148829. 4,
  148830. 3,
  148831. 5,
  148832. 2,
  148833. 6,
  148834. 1,
  148835. 7,
  148836. 0,
  148837. 8,
  148838. };
  148839. static long _vq_lengthlist__44u4__p5_0[] = {
  148840. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148841. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148842. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148843. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148844. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148845. 12,
  148846. };
  148847. static float _vq_quantthresh__44u4__p5_0[] = {
  148848. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148849. };
  148850. static long _vq_quantmap__44u4__p5_0[] = {
  148851. 7, 5, 3, 1, 0, 2, 4, 6,
  148852. 8,
  148853. };
  148854. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148855. _vq_quantthresh__44u4__p5_0,
  148856. _vq_quantmap__44u4__p5_0,
  148857. 9,
  148858. 9
  148859. };
  148860. static static_codebook _44u4__p5_0 = {
  148861. 2, 81,
  148862. _vq_lengthlist__44u4__p5_0,
  148863. 1, -531628032, 1611661312, 4, 0,
  148864. _vq_quantlist__44u4__p5_0,
  148865. NULL,
  148866. &_vq_auxt__44u4__p5_0,
  148867. NULL,
  148868. 0
  148869. };
  148870. static long _vq_quantlist__44u4__p6_0[] = {
  148871. 6,
  148872. 5,
  148873. 7,
  148874. 4,
  148875. 8,
  148876. 3,
  148877. 9,
  148878. 2,
  148879. 10,
  148880. 1,
  148881. 11,
  148882. 0,
  148883. 12,
  148884. };
  148885. static long _vq_lengthlist__44u4__p6_0[] = {
  148886. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148887. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148888. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148889. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148890. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148891. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148892. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148893. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148894. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148895. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148896. 16,16,16,17,17,18,17,20,21,
  148897. };
  148898. static float _vq_quantthresh__44u4__p6_0[] = {
  148899. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148900. 12.5, 17.5, 22.5, 27.5,
  148901. };
  148902. static long _vq_quantmap__44u4__p6_0[] = {
  148903. 11, 9, 7, 5, 3, 1, 0, 2,
  148904. 4, 6, 8, 10, 12,
  148905. };
  148906. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148907. _vq_quantthresh__44u4__p6_0,
  148908. _vq_quantmap__44u4__p6_0,
  148909. 13,
  148910. 13
  148911. };
  148912. static static_codebook _44u4__p6_0 = {
  148913. 2, 169,
  148914. _vq_lengthlist__44u4__p6_0,
  148915. 1, -526516224, 1616117760, 4, 0,
  148916. _vq_quantlist__44u4__p6_0,
  148917. NULL,
  148918. &_vq_auxt__44u4__p6_0,
  148919. NULL,
  148920. 0
  148921. };
  148922. static long _vq_quantlist__44u4__p6_1[] = {
  148923. 2,
  148924. 1,
  148925. 3,
  148926. 0,
  148927. 4,
  148928. };
  148929. static long _vq_lengthlist__44u4__p6_1[] = {
  148930. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148931. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148932. };
  148933. static float _vq_quantthresh__44u4__p6_1[] = {
  148934. -1.5, -0.5, 0.5, 1.5,
  148935. };
  148936. static long _vq_quantmap__44u4__p6_1[] = {
  148937. 3, 1, 0, 2, 4,
  148938. };
  148939. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148940. _vq_quantthresh__44u4__p6_1,
  148941. _vq_quantmap__44u4__p6_1,
  148942. 5,
  148943. 5
  148944. };
  148945. static static_codebook _44u4__p6_1 = {
  148946. 2, 25,
  148947. _vq_lengthlist__44u4__p6_1,
  148948. 1, -533725184, 1611661312, 3, 0,
  148949. _vq_quantlist__44u4__p6_1,
  148950. NULL,
  148951. &_vq_auxt__44u4__p6_1,
  148952. NULL,
  148953. 0
  148954. };
  148955. static long _vq_quantlist__44u4__p7_0[] = {
  148956. 6,
  148957. 5,
  148958. 7,
  148959. 4,
  148960. 8,
  148961. 3,
  148962. 9,
  148963. 2,
  148964. 10,
  148965. 1,
  148966. 11,
  148967. 0,
  148968. 12,
  148969. };
  148970. static long _vq_lengthlist__44u4__p7_0[] = {
  148971. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148972. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148973. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148974. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148975. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148976. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148977. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148978. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148979. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148980. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148981. 11,11,11,11,11,11,11,11,11,
  148982. };
  148983. static float _vq_quantthresh__44u4__p7_0[] = {
  148984. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148985. 637.5, 892.5, 1147.5, 1402.5,
  148986. };
  148987. static long _vq_quantmap__44u4__p7_0[] = {
  148988. 11, 9, 7, 5, 3, 1, 0, 2,
  148989. 4, 6, 8, 10, 12,
  148990. };
  148991. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148992. _vq_quantthresh__44u4__p7_0,
  148993. _vq_quantmap__44u4__p7_0,
  148994. 13,
  148995. 13
  148996. };
  148997. static static_codebook _44u4__p7_0 = {
  148998. 2, 169,
  148999. _vq_lengthlist__44u4__p7_0,
  149000. 1, -514332672, 1627381760, 4, 0,
  149001. _vq_quantlist__44u4__p7_0,
  149002. NULL,
  149003. &_vq_auxt__44u4__p7_0,
  149004. NULL,
  149005. 0
  149006. };
  149007. static long _vq_quantlist__44u4__p7_1[] = {
  149008. 7,
  149009. 6,
  149010. 8,
  149011. 5,
  149012. 9,
  149013. 4,
  149014. 10,
  149015. 3,
  149016. 11,
  149017. 2,
  149018. 12,
  149019. 1,
  149020. 13,
  149021. 0,
  149022. 14,
  149023. };
  149024. static long _vq_lengthlist__44u4__p7_1[] = {
  149025. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  149026. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  149027. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  149028. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  149029. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  149030. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  149031. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  149032. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  149033. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  149034. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  149035. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  149036. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  149037. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  149038. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  149039. 16,
  149040. };
  149041. static float _vq_quantthresh__44u4__p7_1[] = {
  149042. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149043. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149044. };
  149045. static long _vq_quantmap__44u4__p7_1[] = {
  149046. 13, 11, 9, 7, 5, 3, 1, 0,
  149047. 2, 4, 6, 8, 10, 12, 14,
  149048. };
  149049. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  149050. _vq_quantthresh__44u4__p7_1,
  149051. _vq_quantmap__44u4__p7_1,
  149052. 15,
  149053. 15
  149054. };
  149055. static static_codebook _44u4__p7_1 = {
  149056. 2, 225,
  149057. _vq_lengthlist__44u4__p7_1,
  149058. 1, -522338304, 1620115456, 4, 0,
  149059. _vq_quantlist__44u4__p7_1,
  149060. NULL,
  149061. &_vq_auxt__44u4__p7_1,
  149062. NULL,
  149063. 0
  149064. };
  149065. static long _vq_quantlist__44u4__p7_2[] = {
  149066. 8,
  149067. 7,
  149068. 9,
  149069. 6,
  149070. 10,
  149071. 5,
  149072. 11,
  149073. 4,
  149074. 12,
  149075. 3,
  149076. 13,
  149077. 2,
  149078. 14,
  149079. 1,
  149080. 15,
  149081. 0,
  149082. 16,
  149083. };
  149084. static long _vq_lengthlist__44u4__p7_2[] = {
  149085. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149086. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149087. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149088. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149089. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  149090. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149091. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149092. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149093. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149094. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  149095. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  149096. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  149097. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149098. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  149099. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149100. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149101. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149102. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  149103. 10,
  149104. };
  149105. static float _vq_quantthresh__44u4__p7_2[] = {
  149106. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149107. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149108. };
  149109. static long _vq_quantmap__44u4__p7_2[] = {
  149110. 15, 13, 11, 9, 7, 5, 3, 1,
  149111. 0, 2, 4, 6, 8, 10, 12, 14,
  149112. 16,
  149113. };
  149114. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149115. _vq_quantthresh__44u4__p7_2,
  149116. _vq_quantmap__44u4__p7_2,
  149117. 17,
  149118. 17
  149119. };
  149120. static static_codebook _44u4__p7_2 = {
  149121. 2, 289,
  149122. _vq_lengthlist__44u4__p7_2,
  149123. 1, -529530880, 1611661312, 5, 0,
  149124. _vq_quantlist__44u4__p7_2,
  149125. NULL,
  149126. &_vq_auxt__44u4__p7_2,
  149127. NULL,
  149128. 0
  149129. };
  149130. static long _huff_lengthlist__44u4__short[] = {
  149131. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149132. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149133. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149134. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149135. };
  149136. static static_codebook _huff_book__44u4__short = {
  149137. 2, 64,
  149138. _huff_lengthlist__44u4__short,
  149139. 0, 0, 0, 0, 0,
  149140. NULL,
  149141. NULL,
  149142. NULL,
  149143. NULL,
  149144. 0
  149145. };
  149146. static long _huff_lengthlist__44u5__long[] = {
  149147. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149148. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149149. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149150. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149151. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149152. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149153. 14, 8, 7, 8,
  149154. };
  149155. static static_codebook _huff_book__44u5__long = {
  149156. 2, 100,
  149157. _huff_lengthlist__44u5__long,
  149158. 0, 0, 0, 0, 0,
  149159. NULL,
  149160. NULL,
  149161. NULL,
  149162. NULL,
  149163. 0
  149164. };
  149165. static long _vq_quantlist__44u5__p1_0[] = {
  149166. 1,
  149167. 0,
  149168. 2,
  149169. };
  149170. static long _vq_lengthlist__44u5__p1_0[] = {
  149171. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149172. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149173. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149174. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149175. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149176. 12,
  149177. };
  149178. static float _vq_quantthresh__44u5__p1_0[] = {
  149179. -0.5, 0.5,
  149180. };
  149181. static long _vq_quantmap__44u5__p1_0[] = {
  149182. 1, 0, 2,
  149183. };
  149184. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149185. _vq_quantthresh__44u5__p1_0,
  149186. _vq_quantmap__44u5__p1_0,
  149187. 3,
  149188. 3
  149189. };
  149190. static static_codebook _44u5__p1_0 = {
  149191. 4, 81,
  149192. _vq_lengthlist__44u5__p1_0,
  149193. 1, -535822336, 1611661312, 2, 0,
  149194. _vq_quantlist__44u5__p1_0,
  149195. NULL,
  149196. &_vq_auxt__44u5__p1_0,
  149197. NULL,
  149198. 0
  149199. };
  149200. static long _vq_quantlist__44u5__p2_0[] = {
  149201. 1,
  149202. 0,
  149203. 2,
  149204. };
  149205. static long _vq_lengthlist__44u5__p2_0[] = {
  149206. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149207. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149208. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149209. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149210. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149211. 9,
  149212. };
  149213. static float _vq_quantthresh__44u5__p2_0[] = {
  149214. -0.5, 0.5,
  149215. };
  149216. static long _vq_quantmap__44u5__p2_0[] = {
  149217. 1, 0, 2,
  149218. };
  149219. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149220. _vq_quantthresh__44u5__p2_0,
  149221. _vq_quantmap__44u5__p2_0,
  149222. 3,
  149223. 3
  149224. };
  149225. static static_codebook _44u5__p2_0 = {
  149226. 4, 81,
  149227. _vq_lengthlist__44u5__p2_0,
  149228. 1, -535822336, 1611661312, 2, 0,
  149229. _vq_quantlist__44u5__p2_0,
  149230. NULL,
  149231. &_vq_auxt__44u5__p2_0,
  149232. NULL,
  149233. 0
  149234. };
  149235. static long _vq_quantlist__44u5__p3_0[] = {
  149236. 2,
  149237. 1,
  149238. 3,
  149239. 0,
  149240. 4,
  149241. };
  149242. static long _vq_lengthlist__44u5__p3_0[] = {
  149243. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149244. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149245. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149246. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149247. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149248. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149249. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149250. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149251. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149252. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149253. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149254. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149255. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149256. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149257. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149258. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149259. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149260. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149261. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149262. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149263. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149264. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149265. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149266. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149267. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149268. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149269. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149270. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149271. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149272. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149273. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149274. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149275. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149276. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149277. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149278. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149279. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149280. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149281. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149282. 0,
  149283. };
  149284. static float _vq_quantthresh__44u5__p3_0[] = {
  149285. -1.5, -0.5, 0.5, 1.5,
  149286. };
  149287. static long _vq_quantmap__44u5__p3_0[] = {
  149288. 3, 1, 0, 2, 4,
  149289. };
  149290. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149291. _vq_quantthresh__44u5__p3_0,
  149292. _vq_quantmap__44u5__p3_0,
  149293. 5,
  149294. 5
  149295. };
  149296. static static_codebook _44u5__p3_0 = {
  149297. 4, 625,
  149298. _vq_lengthlist__44u5__p3_0,
  149299. 1, -533725184, 1611661312, 3, 0,
  149300. _vq_quantlist__44u5__p3_0,
  149301. NULL,
  149302. &_vq_auxt__44u5__p3_0,
  149303. NULL,
  149304. 0
  149305. };
  149306. static long _vq_quantlist__44u5__p4_0[] = {
  149307. 2,
  149308. 1,
  149309. 3,
  149310. 0,
  149311. 4,
  149312. };
  149313. static long _vq_lengthlist__44u5__p4_0[] = {
  149314. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149315. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149316. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149317. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149318. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149319. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149320. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149321. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149322. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149323. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149324. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149325. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149326. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149327. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149328. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149329. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149330. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149331. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149332. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149333. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149334. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149335. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149336. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149337. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149338. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149339. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149340. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149341. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149342. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149343. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149344. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149345. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149346. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149347. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149348. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149349. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149350. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149351. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149352. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149353. 12,
  149354. };
  149355. static float _vq_quantthresh__44u5__p4_0[] = {
  149356. -1.5, -0.5, 0.5, 1.5,
  149357. };
  149358. static long _vq_quantmap__44u5__p4_0[] = {
  149359. 3, 1, 0, 2, 4,
  149360. };
  149361. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149362. _vq_quantthresh__44u5__p4_0,
  149363. _vq_quantmap__44u5__p4_0,
  149364. 5,
  149365. 5
  149366. };
  149367. static static_codebook _44u5__p4_0 = {
  149368. 4, 625,
  149369. _vq_lengthlist__44u5__p4_0,
  149370. 1, -533725184, 1611661312, 3, 0,
  149371. _vq_quantlist__44u5__p4_0,
  149372. NULL,
  149373. &_vq_auxt__44u5__p4_0,
  149374. NULL,
  149375. 0
  149376. };
  149377. static long _vq_quantlist__44u5__p5_0[] = {
  149378. 4,
  149379. 3,
  149380. 5,
  149381. 2,
  149382. 6,
  149383. 1,
  149384. 7,
  149385. 0,
  149386. 8,
  149387. };
  149388. static long _vq_lengthlist__44u5__p5_0[] = {
  149389. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149390. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149391. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149392. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149393. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149394. 14,
  149395. };
  149396. static float _vq_quantthresh__44u5__p5_0[] = {
  149397. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149398. };
  149399. static long _vq_quantmap__44u5__p5_0[] = {
  149400. 7, 5, 3, 1, 0, 2, 4, 6,
  149401. 8,
  149402. };
  149403. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149404. _vq_quantthresh__44u5__p5_0,
  149405. _vq_quantmap__44u5__p5_0,
  149406. 9,
  149407. 9
  149408. };
  149409. static static_codebook _44u5__p5_0 = {
  149410. 2, 81,
  149411. _vq_lengthlist__44u5__p5_0,
  149412. 1, -531628032, 1611661312, 4, 0,
  149413. _vq_quantlist__44u5__p5_0,
  149414. NULL,
  149415. &_vq_auxt__44u5__p5_0,
  149416. NULL,
  149417. 0
  149418. };
  149419. static long _vq_quantlist__44u5__p6_0[] = {
  149420. 4,
  149421. 3,
  149422. 5,
  149423. 2,
  149424. 6,
  149425. 1,
  149426. 7,
  149427. 0,
  149428. 8,
  149429. };
  149430. static long _vq_lengthlist__44u5__p6_0[] = {
  149431. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149432. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149433. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149434. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149435. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149436. 11,
  149437. };
  149438. static float _vq_quantthresh__44u5__p6_0[] = {
  149439. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149440. };
  149441. static long _vq_quantmap__44u5__p6_0[] = {
  149442. 7, 5, 3, 1, 0, 2, 4, 6,
  149443. 8,
  149444. };
  149445. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149446. _vq_quantthresh__44u5__p6_0,
  149447. _vq_quantmap__44u5__p6_0,
  149448. 9,
  149449. 9
  149450. };
  149451. static static_codebook _44u5__p6_0 = {
  149452. 2, 81,
  149453. _vq_lengthlist__44u5__p6_0,
  149454. 1, -531628032, 1611661312, 4, 0,
  149455. _vq_quantlist__44u5__p6_0,
  149456. NULL,
  149457. &_vq_auxt__44u5__p6_0,
  149458. NULL,
  149459. 0
  149460. };
  149461. static long _vq_quantlist__44u5__p7_0[] = {
  149462. 1,
  149463. 0,
  149464. 2,
  149465. };
  149466. static long _vq_lengthlist__44u5__p7_0[] = {
  149467. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149468. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149469. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149470. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149471. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149472. 12,
  149473. };
  149474. static float _vq_quantthresh__44u5__p7_0[] = {
  149475. -5.5, 5.5,
  149476. };
  149477. static long _vq_quantmap__44u5__p7_0[] = {
  149478. 1, 0, 2,
  149479. };
  149480. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149481. _vq_quantthresh__44u5__p7_0,
  149482. _vq_quantmap__44u5__p7_0,
  149483. 3,
  149484. 3
  149485. };
  149486. static static_codebook _44u5__p7_0 = {
  149487. 4, 81,
  149488. _vq_lengthlist__44u5__p7_0,
  149489. 1, -529137664, 1618345984, 2, 0,
  149490. _vq_quantlist__44u5__p7_0,
  149491. NULL,
  149492. &_vq_auxt__44u5__p7_0,
  149493. NULL,
  149494. 0
  149495. };
  149496. static long _vq_quantlist__44u5__p7_1[] = {
  149497. 5,
  149498. 4,
  149499. 6,
  149500. 3,
  149501. 7,
  149502. 2,
  149503. 8,
  149504. 1,
  149505. 9,
  149506. 0,
  149507. 10,
  149508. };
  149509. static long _vq_lengthlist__44u5__p7_1[] = {
  149510. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149511. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149512. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149513. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149514. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149515. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149516. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149517. 9, 9, 9, 9, 9,10,10,10,10,
  149518. };
  149519. static float _vq_quantthresh__44u5__p7_1[] = {
  149520. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149521. 3.5, 4.5,
  149522. };
  149523. static long _vq_quantmap__44u5__p7_1[] = {
  149524. 9, 7, 5, 3, 1, 0, 2, 4,
  149525. 6, 8, 10,
  149526. };
  149527. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149528. _vq_quantthresh__44u5__p7_1,
  149529. _vq_quantmap__44u5__p7_1,
  149530. 11,
  149531. 11
  149532. };
  149533. static static_codebook _44u5__p7_1 = {
  149534. 2, 121,
  149535. _vq_lengthlist__44u5__p7_1,
  149536. 1, -531365888, 1611661312, 4, 0,
  149537. _vq_quantlist__44u5__p7_1,
  149538. NULL,
  149539. &_vq_auxt__44u5__p7_1,
  149540. NULL,
  149541. 0
  149542. };
  149543. static long _vq_quantlist__44u5__p8_0[] = {
  149544. 5,
  149545. 4,
  149546. 6,
  149547. 3,
  149548. 7,
  149549. 2,
  149550. 8,
  149551. 1,
  149552. 9,
  149553. 0,
  149554. 10,
  149555. };
  149556. static long _vq_lengthlist__44u5__p8_0[] = {
  149557. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149558. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149559. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149560. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149561. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149562. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149563. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149564. 12,13,13,14,14,14,14,15,15,
  149565. };
  149566. static float _vq_quantthresh__44u5__p8_0[] = {
  149567. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149568. 38.5, 49.5,
  149569. };
  149570. static long _vq_quantmap__44u5__p8_0[] = {
  149571. 9, 7, 5, 3, 1, 0, 2, 4,
  149572. 6, 8, 10,
  149573. };
  149574. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149575. _vq_quantthresh__44u5__p8_0,
  149576. _vq_quantmap__44u5__p8_0,
  149577. 11,
  149578. 11
  149579. };
  149580. static static_codebook _44u5__p8_0 = {
  149581. 2, 121,
  149582. _vq_lengthlist__44u5__p8_0,
  149583. 1, -524582912, 1618345984, 4, 0,
  149584. _vq_quantlist__44u5__p8_0,
  149585. NULL,
  149586. &_vq_auxt__44u5__p8_0,
  149587. NULL,
  149588. 0
  149589. };
  149590. static long _vq_quantlist__44u5__p8_1[] = {
  149591. 5,
  149592. 4,
  149593. 6,
  149594. 3,
  149595. 7,
  149596. 2,
  149597. 8,
  149598. 1,
  149599. 9,
  149600. 0,
  149601. 10,
  149602. };
  149603. static long _vq_lengthlist__44u5__p8_1[] = {
  149604. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149605. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149606. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149607. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149608. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149609. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149610. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149611. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149612. };
  149613. static float _vq_quantthresh__44u5__p8_1[] = {
  149614. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149615. 3.5, 4.5,
  149616. };
  149617. static long _vq_quantmap__44u5__p8_1[] = {
  149618. 9, 7, 5, 3, 1, 0, 2, 4,
  149619. 6, 8, 10,
  149620. };
  149621. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149622. _vq_quantthresh__44u5__p8_1,
  149623. _vq_quantmap__44u5__p8_1,
  149624. 11,
  149625. 11
  149626. };
  149627. static static_codebook _44u5__p8_1 = {
  149628. 2, 121,
  149629. _vq_lengthlist__44u5__p8_1,
  149630. 1, -531365888, 1611661312, 4, 0,
  149631. _vq_quantlist__44u5__p8_1,
  149632. NULL,
  149633. &_vq_auxt__44u5__p8_1,
  149634. NULL,
  149635. 0
  149636. };
  149637. static long _vq_quantlist__44u5__p9_0[] = {
  149638. 6,
  149639. 5,
  149640. 7,
  149641. 4,
  149642. 8,
  149643. 3,
  149644. 9,
  149645. 2,
  149646. 10,
  149647. 1,
  149648. 11,
  149649. 0,
  149650. 12,
  149651. };
  149652. static long _vq_lengthlist__44u5__p9_0[] = {
  149653. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149654. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149655. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149656. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149657. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149658. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149659. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149660. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149661. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149662. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149663. 12,12,12,12,12,12,12,12,12,
  149664. };
  149665. static float _vq_quantthresh__44u5__p9_0[] = {
  149666. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149667. 637.5, 892.5, 1147.5, 1402.5,
  149668. };
  149669. static long _vq_quantmap__44u5__p9_0[] = {
  149670. 11, 9, 7, 5, 3, 1, 0, 2,
  149671. 4, 6, 8, 10, 12,
  149672. };
  149673. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149674. _vq_quantthresh__44u5__p9_0,
  149675. _vq_quantmap__44u5__p9_0,
  149676. 13,
  149677. 13
  149678. };
  149679. static static_codebook _44u5__p9_0 = {
  149680. 2, 169,
  149681. _vq_lengthlist__44u5__p9_0,
  149682. 1, -514332672, 1627381760, 4, 0,
  149683. _vq_quantlist__44u5__p9_0,
  149684. NULL,
  149685. &_vq_auxt__44u5__p9_0,
  149686. NULL,
  149687. 0
  149688. };
  149689. static long _vq_quantlist__44u5__p9_1[] = {
  149690. 7,
  149691. 6,
  149692. 8,
  149693. 5,
  149694. 9,
  149695. 4,
  149696. 10,
  149697. 3,
  149698. 11,
  149699. 2,
  149700. 12,
  149701. 1,
  149702. 13,
  149703. 0,
  149704. 14,
  149705. };
  149706. static long _vq_lengthlist__44u5__p9_1[] = {
  149707. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149708. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149709. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149710. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149711. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149712. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149713. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149714. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149715. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149716. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149717. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149718. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149719. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149720. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149721. 14,
  149722. };
  149723. static float _vq_quantthresh__44u5__p9_1[] = {
  149724. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149725. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149726. };
  149727. static long _vq_quantmap__44u5__p9_1[] = {
  149728. 13, 11, 9, 7, 5, 3, 1, 0,
  149729. 2, 4, 6, 8, 10, 12, 14,
  149730. };
  149731. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149732. _vq_quantthresh__44u5__p9_1,
  149733. _vq_quantmap__44u5__p9_1,
  149734. 15,
  149735. 15
  149736. };
  149737. static static_codebook _44u5__p9_1 = {
  149738. 2, 225,
  149739. _vq_lengthlist__44u5__p9_1,
  149740. 1, -522338304, 1620115456, 4, 0,
  149741. _vq_quantlist__44u5__p9_1,
  149742. NULL,
  149743. &_vq_auxt__44u5__p9_1,
  149744. NULL,
  149745. 0
  149746. };
  149747. static long _vq_quantlist__44u5__p9_2[] = {
  149748. 8,
  149749. 7,
  149750. 9,
  149751. 6,
  149752. 10,
  149753. 5,
  149754. 11,
  149755. 4,
  149756. 12,
  149757. 3,
  149758. 13,
  149759. 2,
  149760. 14,
  149761. 1,
  149762. 15,
  149763. 0,
  149764. 16,
  149765. };
  149766. static long _vq_lengthlist__44u5__p9_2[] = {
  149767. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149768. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149769. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149770. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149771. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149772. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149773. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149774. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149775. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149776. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149777. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149778. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149779. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149780. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149781. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149782. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149783. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149784. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149785. 10,
  149786. };
  149787. static float _vq_quantthresh__44u5__p9_2[] = {
  149788. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149789. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149790. };
  149791. static long _vq_quantmap__44u5__p9_2[] = {
  149792. 15, 13, 11, 9, 7, 5, 3, 1,
  149793. 0, 2, 4, 6, 8, 10, 12, 14,
  149794. 16,
  149795. };
  149796. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149797. _vq_quantthresh__44u5__p9_2,
  149798. _vq_quantmap__44u5__p9_2,
  149799. 17,
  149800. 17
  149801. };
  149802. static static_codebook _44u5__p9_2 = {
  149803. 2, 289,
  149804. _vq_lengthlist__44u5__p9_2,
  149805. 1, -529530880, 1611661312, 5, 0,
  149806. _vq_quantlist__44u5__p9_2,
  149807. NULL,
  149808. &_vq_auxt__44u5__p9_2,
  149809. NULL,
  149810. 0
  149811. };
  149812. static long _huff_lengthlist__44u5__short[] = {
  149813. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149814. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149815. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149816. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149817. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149818. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149819. 6, 8,15,17,
  149820. };
  149821. static static_codebook _huff_book__44u5__short = {
  149822. 2, 100,
  149823. _huff_lengthlist__44u5__short,
  149824. 0, 0, 0, 0, 0,
  149825. NULL,
  149826. NULL,
  149827. NULL,
  149828. NULL,
  149829. 0
  149830. };
  149831. static long _huff_lengthlist__44u6__long[] = {
  149832. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149833. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149834. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149835. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149836. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149837. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149838. 13, 8, 7, 7,
  149839. };
  149840. static static_codebook _huff_book__44u6__long = {
  149841. 2, 100,
  149842. _huff_lengthlist__44u6__long,
  149843. 0, 0, 0, 0, 0,
  149844. NULL,
  149845. NULL,
  149846. NULL,
  149847. NULL,
  149848. 0
  149849. };
  149850. static long _vq_quantlist__44u6__p1_0[] = {
  149851. 1,
  149852. 0,
  149853. 2,
  149854. };
  149855. static long _vq_lengthlist__44u6__p1_0[] = {
  149856. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149857. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149858. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149859. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149860. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149861. 12,
  149862. };
  149863. static float _vq_quantthresh__44u6__p1_0[] = {
  149864. -0.5, 0.5,
  149865. };
  149866. static long _vq_quantmap__44u6__p1_0[] = {
  149867. 1, 0, 2,
  149868. };
  149869. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149870. _vq_quantthresh__44u6__p1_0,
  149871. _vq_quantmap__44u6__p1_0,
  149872. 3,
  149873. 3
  149874. };
  149875. static static_codebook _44u6__p1_0 = {
  149876. 4, 81,
  149877. _vq_lengthlist__44u6__p1_0,
  149878. 1, -535822336, 1611661312, 2, 0,
  149879. _vq_quantlist__44u6__p1_0,
  149880. NULL,
  149881. &_vq_auxt__44u6__p1_0,
  149882. NULL,
  149883. 0
  149884. };
  149885. static long _vq_quantlist__44u6__p2_0[] = {
  149886. 1,
  149887. 0,
  149888. 2,
  149889. };
  149890. static long _vq_lengthlist__44u6__p2_0[] = {
  149891. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149892. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149893. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149894. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149895. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149896. 9,
  149897. };
  149898. static float _vq_quantthresh__44u6__p2_0[] = {
  149899. -0.5, 0.5,
  149900. };
  149901. static long _vq_quantmap__44u6__p2_0[] = {
  149902. 1, 0, 2,
  149903. };
  149904. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149905. _vq_quantthresh__44u6__p2_0,
  149906. _vq_quantmap__44u6__p2_0,
  149907. 3,
  149908. 3
  149909. };
  149910. static static_codebook _44u6__p2_0 = {
  149911. 4, 81,
  149912. _vq_lengthlist__44u6__p2_0,
  149913. 1, -535822336, 1611661312, 2, 0,
  149914. _vq_quantlist__44u6__p2_0,
  149915. NULL,
  149916. &_vq_auxt__44u6__p2_0,
  149917. NULL,
  149918. 0
  149919. };
  149920. static long _vq_quantlist__44u6__p3_0[] = {
  149921. 2,
  149922. 1,
  149923. 3,
  149924. 0,
  149925. 4,
  149926. };
  149927. static long _vq_lengthlist__44u6__p3_0[] = {
  149928. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149929. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149930. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149931. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149932. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149933. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149934. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149935. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149936. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149937. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149938. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149939. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149940. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149941. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149942. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149943. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149944. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149945. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149946. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149947. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149948. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149949. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149950. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149951. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149952. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149953. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149954. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149955. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149956. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149957. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149958. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149959. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149960. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149961. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149962. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149963. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149964. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149965. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149966. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149967. 19,
  149968. };
  149969. static float _vq_quantthresh__44u6__p3_0[] = {
  149970. -1.5, -0.5, 0.5, 1.5,
  149971. };
  149972. static long _vq_quantmap__44u6__p3_0[] = {
  149973. 3, 1, 0, 2, 4,
  149974. };
  149975. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149976. _vq_quantthresh__44u6__p3_0,
  149977. _vq_quantmap__44u6__p3_0,
  149978. 5,
  149979. 5
  149980. };
  149981. static static_codebook _44u6__p3_0 = {
  149982. 4, 625,
  149983. _vq_lengthlist__44u6__p3_0,
  149984. 1, -533725184, 1611661312, 3, 0,
  149985. _vq_quantlist__44u6__p3_0,
  149986. NULL,
  149987. &_vq_auxt__44u6__p3_0,
  149988. NULL,
  149989. 0
  149990. };
  149991. static long _vq_quantlist__44u6__p4_0[] = {
  149992. 2,
  149993. 1,
  149994. 3,
  149995. 0,
  149996. 4,
  149997. };
  149998. static long _vq_lengthlist__44u6__p4_0[] = {
  149999. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150000. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  150001. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  150002. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  150003. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150004. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  150005. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150006. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  150007. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150008. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150009. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  150010. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150011. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150012. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  150013. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  150014. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150015. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  150016. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150017. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  150018. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  150019. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150020. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150021. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  150022. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150023. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  150024. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150025. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150026. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  150027. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  150028. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  150029. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  150030. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150031. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  150032. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150033. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150034. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150035. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  150036. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  150037. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  150038. 13,
  150039. };
  150040. static float _vq_quantthresh__44u6__p4_0[] = {
  150041. -1.5, -0.5, 0.5, 1.5,
  150042. };
  150043. static long _vq_quantmap__44u6__p4_0[] = {
  150044. 3, 1, 0, 2, 4,
  150045. };
  150046. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  150047. _vq_quantthresh__44u6__p4_0,
  150048. _vq_quantmap__44u6__p4_0,
  150049. 5,
  150050. 5
  150051. };
  150052. static static_codebook _44u6__p4_0 = {
  150053. 4, 625,
  150054. _vq_lengthlist__44u6__p4_0,
  150055. 1, -533725184, 1611661312, 3, 0,
  150056. _vq_quantlist__44u6__p4_0,
  150057. NULL,
  150058. &_vq_auxt__44u6__p4_0,
  150059. NULL,
  150060. 0
  150061. };
  150062. static long _vq_quantlist__44u6__p5_0[] = {
  150063. 4,
  150064. 3,
  150065. 5,
  150066. 2,
  150067. 6,
  150068. 1,
  150069. 7,
  150070. 0,
  150071. 8,
  150072. };
  150073. static long _vq_lengthlist__44u6__p5_0[] = {
  150074. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150075. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  150076. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  150077. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  150078. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  150079. 14,
  150080. };
  150081. static float _vq_quantthresh__44u6__p5_0[] = {
  150082. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150083. };
  150084. static long _vq_quantmap__44u6__p5_0[] = {
  150085. 7, 5, 3, 1, 0, 2, 4, 6,
  150086. 8,
  150087. };
  150088. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  150089. _vq_quantthresh__44u6__p5_0,
  150090. _vq_quantmap__44u6__p5_0,
  150091. 9,
  150092. 9
  150093. };
  150094. static static_codebook _44u6__p5_0 = {
  150095. 2, 81,
  150096. _vq_lengthlist__44u6__p5_0,
  150097. 1, -531628032, 1611661312, 4, 0,
  150098. _vq_quantlist__44u6__p5_0,
  150099. NULL,
  150100. &_vq_auxt__44u6__p5_0,
  150101. NULL,
  150102. 0
  150103. };
  150104. static long _vq_quantlist__44u6__p6_0[] = {
  150105. 4,
  150106. 3,
  150107. 5,
  150108. 2,
  150109. 6,
  150110. 1,
  150111. 7,
  150112. 0,
  150113. 8,
  150114. };
  150115. static long _vq_lengthlist__44u6__p6_0[] = {
  150116. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150117. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150118. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150119. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150120. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150121. 12,
  150122. };
  150123. static float _vq_quantthresh__44u6__p6_0[] = {
  150124. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150125. };
  150126. static long _vq_quantmap__44u6__p6_0[] = {
  150127. 7, 5, 3, 1, 0, 2, 4, 6,
  150128. 8,
  150129. };
  150130. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150131. _vq_quantthresh__44u6__p6_0,
  150132. _vq_quantmap__44u6__p6_0,
  150133. 9,
  150134. 9
  150135. };
  150136. static static_codebook _44u6__p6_0 = {
  150137. 2, 81,
  150138. _vq_lengthlist__44u6__p6_0,
  150139. 1, -531628032, 1611661312, 4, 0,
  150140. _vq_quantlist__44u6__p6_0,
  150141. NULL,
  150142. &_vq_auxt__44u6__p6_0,
  150143. NULL,
  150144. 0
  150145. };
  150146. static long _vq_quantlist__44u6__p7_0[] = {
  150147. 1,
  150148. 0,
  150149. 2,
  150150. };
  150151. static long _vq_lengthlist__44u6__p7_0[] = {
  150152. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150153. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150154. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150155. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150156. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150157. 10,
  150158. };
  150159. static float _vq_quantthresh__44u6__p7_0[] = {
  150160. -5.5, 5.5,
  150161. };
  150162. static long _vq_quantmap__44u6__p7_0[] = {
  150163. 1, 0, 2,
  150164. };
  150165. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150166. _vq_quantthresh__44u6__p7_0,
  150167. _vq_quantmap__44u6__p7_0,
  150168. 3,
  150169. 3
  150170. };
  150171. static static_codebook _44u6__p7_0 = {
  150172. 4, 81,
  150173. _vq_lengthlist__44u6__p7_0,
  150174. 1, -529137664, 1618345984, 2, 0,
  150175. _vq_quantlist__44u6__p7_0,
  150176. NULL,
  150177. &_vq_auxt__44u6__p7_0,
  150178. NULL,
  150179. 0
  150180. };
  150181. static long _vq_quantlist__44u6__p7_1[] = {
  150182. 5,
  150183. 4,
  150184. 6,
  150185. 3,
  150186. 7,
  150187. 2,
  150188. 8,
  150189. 1,
  150190. 9,
  150191. 0,
  150192. 10,
  150193. };
  150194. static long _vq_lengthlist__44u6__p7_1[] = {
  150195. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150196. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150197. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150198. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150199. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150200. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150201. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150202. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150203. };
  150204. static float _vq_quantthresh__44u6__p7_1[] = {
  150205. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150206. 3.5, 4.5,
  150207. };
  150208. static long _vq_quantmap__44u6__p7_1[] = {
  150209. 9, 7, 5, 3, 1, 0, 2, 4,
  150210. 6, 8, 10,
  150211. };
  150212. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150213. _vq_quantthresh__44u6__p7_1,
  150214. _vq_quantmap__44u6__p7_1,
  150215. 11,
  150216. 11
  150217. };
  150218. static static_codebook _44u6__p7_1 = {
  150219. 2, 121,
  150220. _vq_lengthlist__44u6__p7_1,
  150221. 1, -531365888, 1611661312, 4, 0,
  150222. _vq_quantlist__44u6__p7_1,
  150223. NULL,
  150224. &_vq_auxt__44u6__p7_1,
  150225. NULL,
  150226. 0
  150227. };
  150228. static long _vq_quantlist__44u6__p8_0[] = {
  150229. 5,
  150230. 4,
  150231. 6,
  150232. 3,
  150233. 7,
  150234. 2,
  150235. 8,
  150236. 1,
  150237. 9,
  150238. 0,
  150239. 10,
  150240. };
  150241. static long _vq_lengthlist__44u6__p8_0[] = {
  150242. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150243. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150244. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150245. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150246. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150247. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150248. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150249. 12,13,13,14,14,14,15,15,15,
  150250. };
  150251. static float _vq_quantthresh__44u6__p8_0[] = {
  150252. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150253. 38.5, 49.5,
  150254. };
  150255. static long _vq_quantmap__44u6__p8_0[] = {
  150256. 9, 7, 5, 3, 1, 0, 2, 4,
  150257. 6, 8, 10,
  150258. };
  150259. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150260. _vq_quantthresh__44u6__p8_0,
  150261. _vq_quantmap__44u6__p8_0,
  150262. 11,
  150263. 11
  150264. };
  150265. static static_codebook _44u6__p8_0 = {
  150266. 2, 121,
  150267. _vq_lengthlist__44u6__p8_0,
  150268. 1, -524582912, 1618345984, 4, 0,
  150269. _vq_quantlist__44u6__p8_0,
  150270. NULL,
  150271. &_vq_auxt__44u6__p8_0,
  150272. NULL,
  150273. 0
  150274. };
  150275. static long _vq_quantlist__44u6__p8_1[] = {
  150276. 5,
  150277. 4,
  150278. 6,
  150279. 3,
  150280. 7,
  150281. 2,
  150282. 8,
  150283. 1,
  150284. 9,
  150285. 0,
  150286. 10,
  150287. };
  150288. static long _vq_lengthlist__44u6__p8_1[] = {
  150289. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150290. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150291. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150292. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150293. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150294. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150295. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150296. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150297. };
  150298. static float _vq_quantthresh__44u6__p8_1[] = {
  150299. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150300. 3.5, 4.5,
  150301. };
  150302. static long _vq_quantmap__44u6__p8_1[] = {
  150303. 9, 7, 5, 3, 1, 0, 2, 4,
  150304. 6, 8, 10,
  150305. };
  150306. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150307. _vq_quantthresh__44u6__p8_1,
  150308. _vq_quantmap__44u6__p8_1,
  150309. 11,
  150310. 11
  150311. };
  150312. static static_codebook _44u6__p8_1 = {
  150313. 2, 121,
  150314. _vq_lengthlist__44u6__p8_1,
  150315. 1, -531365888, 1611661312, 4, 0,
  150316. _vq_quantlist__44u6__p8_1,
  150317. NULL,
  150318. &_vq_auxt__44u6__p8_1,
  150319. NULL,
  150320. 0
  150321. };
  150322. static long _vq_quantlist__44u6__p9_0[] = {
  150323. 7,
  150324. 6,
  150325. 8,
  150326. 5,
  150327. 9,
  150328. 4,
  150329. 10,
  150330. 3,
  150331. 11,
  150332. 2,
  150333. 12,
  150334. 1,
  150335. 13,
  150336. 0,
  150337. 14,
  150338. };
  150339. static long _vq_lengthlist__44u6__p9_0[] = {
  150340. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150341. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150342. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150343. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150344. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150345. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150346. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150347. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150348. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150349. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150350. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150351. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150352. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150353. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150354. 14,
  150355. };
  150356. static float _vq_quantthresh__44u6__p9_0[] = {
  150357. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150358. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150359. };
  150360. static long _vq_quantmap__44u6__p9_0[] = {
  150361. 13, 11, 9, 7, 5, 3, 1, 0,
  150362. 2, 4, 6, 8, 10, 12, 14,
  150363. };
  150364. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150365. _vq_quantthresh__44u6__p9_0,
  150366. _vq_quantmap__44u6__p9_0,
  150367. 15,
  150368. 15
  150369. };
  150370. static static_codebook _44u6__p9_0 = {
  150371. 2, 225,
  150372. _vq_lengthlist__44u6__p9_0,
  150373. 1, -514071552, 1627381760, 4, 0,
  150374. _vq_quantlist__44u6__p9_0,
  150375. NULL,
  150376. &_vq_auxt__44u6__p9_0,
  150377. NULL,
  150378. 0
  150379. };
  150380. static long _vq_quantlist__44u6__p9_1[] = {
  150381. 7,
  150382. 6,
  150383. 8,
  150384. 5,
  150385. 9,
  150386. 4,
  150387. 10,
  150388. 3,
  150389. 11,
  150390. 2,
  150391. 12,
  150392. 1,
  150393. 13,
  150394. 0,
  150395. 14,
  150396. };
  150397. static long _vq_lengthlist__44u6__p9_1[] = {
  150398. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150399. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150400. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150401. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150402. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150403. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150404. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150405. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150406. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150407. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150408. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150409. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150410. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150411. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150412. 13,
  150413. };
  150414. static float _vq_quantthresh__44u6__p9_1[] = {
  150415. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150416. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150417. };
  150418. static long _vq_quantmap__44u6__p9_1[] = {
  150419. 13, 11, 9, 7, 5, 3, 1, 0,
  150420. 2, 4, 6, 8, 10, 12, 14,
  150421. };
  150422. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150423. _vq_quantthresh__44u6__p9_1,
  150424. _vq_quantmap__44u6__p9_1,
  150425. 15,
  150426. 15
  150427. };
  150428. static static_codebook _44u6__p9_1 = {
  150429. 2, 225,
  150430. _vq_lengthlist__44u6__p9_1,
  150431. 1, -522338304, 1620115456, 4, 0,
  150432. _vq_quantlist__44u6__p9_1,
  150433. NULL,
  150434. &_vq_auxt__44u6__p9_1,
  150435. NULL,
  150436. 0
  150437. };
  150438. static long _vq_quantlist__44u6__p9_2[] = {
  150439. 8,
  150440. 7,
  150441. 9,
  150442. 6,
  150443. 10,
  150444. 5,
  150445. 11,
  150446. 4,
  150447. 12,
  150448. 3,
  150449. 13,
  150450. 2,
  150451. 14,
  150452. 1,
  150453. 15,
  150454. 0,
  150455. 16,
  150456. };
  150457. static long _vq_lengthlist__44u6__p9_2[] = {
  150458. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150459. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150460. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150461. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150462. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150463. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150464. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150465. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150466. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150467. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150468. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150469. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150470. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150471. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150472. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150473. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150474. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150475. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150476. 10,
  150477. };
  150478. static float _vq_quantthresh__44u6__p9_2[] = {
  150479. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150480. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150481. };
  150482. static long _vq_quantmap__44u6__p9_2[] = {
  150483. 15, 13, 11, 9, 7, 5, 3, 1,
  150484. 0, 2, 4, 6, 8, 10, 12, 14,
  150485. 16,
  150486. };
  150487. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150488. _vq_quantthresh__44u6__p9_2,
  150489. _vq_quantmap__44u6__p9_2,
  150490. 17,
  150491. 17
  150492. };
  150493. static static_codebook _44u6__p9_2 = {
  150494. 2, 289,
  150495. _vq_lengthlist__44u6__p9_2,
  150496. 1, -529530880, 1611661312, 5, 0,
  150497. _vq_quantlist__44u6__p9_2,
  150498. NULL,
  150499. &_vq_auxt__44u6__p9_2,
  150500. NULL,
  150501. 0
  150502. };
  150503. static long _huff_lengthlist__44u6__short[] = {
  150504. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150505. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150506. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150507. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150508. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150509. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150510. 7, 6, 9,16,
  150511. };
  150512. static static_codebook _huff_book__44u6__short = {
  150513. 2, 100,
  150514. _huff_lengthlist__44u6__short,
  150515. 0, 0, 0, 0, 0,
  150516. NULL,
  150517. NULL,
  150518. NULL,
  150519. NULL,
  150520. 0
  150521. };
  150522. static long _huff_lengthlist__44u7__long[] = {
  150523. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150524. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150525. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150526. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150527. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150528. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150529. 12, 8, 6, 7,
  150530. };
  150531. static static_codebook _huff_book__44u7__long = {
  150532. 2, 100,
  150533. _huff_lengthlist__44u7__long,
  150534. 0, 0, 0, 0, 0,
  150535. NULL,
  150536. NULL,
  150537. NULL,
  150538. NULL,
  150539. 0
  150540. };
  150541. static long _vq_quantlist__44u7__p1_0[] = {
  150542. 1,
  150543. 0,
  150544. 2,
  150545. };
  150546. static long _vq_lengthlist__44u7__p1_0[] = {
  150547. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150548. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150549. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150550. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150551. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150552. 12,
  150553. };
  150554. static float _vq_quantthresh__44u7__p1_0[] = {
  150555. -0.5, 0.5,
  150556. };
  150557. static long _vq_quantmap__44u7__p1_0[] = {
  150558. 1, 0, 2,
  150559. };
  150560. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150561. _vq_quantthresh__44u7__p1_0,
  150562. _vq_quantmap__44u7__p1_0,
  150563. 3,
  150564. 3
  150565. };
  150566. static static_codebook _44u7__p1_0 = {
  150567. 4, 81,
  150568. _vq_lengthlist__44u7__p1_0,
  150569. 1, -535822336, 1611661312, 2, 0,
  150570. _vq_quantlist__44u7__p1_0,
  150571. NULL,
  150572. &_vq_auxt__44u7__p1_0,
  150573. NULL,
  150574. 0
  150575. };
  150576. static long _vq_quantlist__44u7__p2_0[] = {
  150577. 1,
  150578. 0,
  150579. 2,
  150580. };
  150581. static long _vq_lengthlist__44u7__p2_0[] = {
  150582. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150583. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150584. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150585. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150586. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150587. 9,
  150588. };
  150589. static float _vq_quantthresh__44u7__p2_0[] = {
  150590. -0.5, 0.5,
  150591. };
  150592. static long _vq_quantmap__44u7__p2_0[] = {
  150593. 1, 0, 2,
  150594. };
  150595. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150596. _vq_quantthresh__44u7__p2_0,
  150597. _vq_quantmap__44u7__p2_0,
  150598. 3,
  150599. 3
  150600. };
  150601. static static_codebook _44u7__p2_0 = {
  150602. 4, 81,
  150603. _vq_lengthlist__44u7__p2_0,
  150604. 1, -535822336, 1611661312, 2, 0,
  150605. _vq_quantlist__44u7__p2_0,
  150606. NULL,
  150607. &_vq_auxt__44u7__p2_0,
  150608. NULL,
  150609. 0
  150610. };
  150611. static long _vq_quantlist__44u7__p3_0[] = {
  150612. 2,
  150613. 1,
  150614. 3,
  150615. 0,
  150616. 4,
  150617. };
  150618. static long _vq_lengthlist__44u7__p3_0[] = {
  150619. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150620. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150621. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150622. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150623. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150624. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150625. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150626. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150627. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150628. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150629. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150630. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150631. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150632. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150633. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150634. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150635. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150636. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150637. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150638. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150639. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150640. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150641. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150642. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150643. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150644. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150645. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150646. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150647. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150648. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150649. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150650. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150651. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150652. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150653. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150654. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150655. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150656. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150657. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150658. 0,
  150659. };
  150660. static float _vq_quantthresh__44u7__p3_0[] = {
  150661. -1.5, -0.5, 0.5, 1.5,
  150662. };
  150663. static long _vq_quantmap__44u7__p3_0[] = {
  150664. 3, 1, 0, 2, 4,
  150665. };
  150666. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150667. _vq_quantthresh__44u7__p3_0,
  150668. _vq_quantmap__44u7__p3_0,
  150669. 5,
  150670. 5
  150671. };
  150672. static static_codebook _44u7__p3_0 = {
  150673. 4, 625,
  150674. _vq_lengthlist__44u7__p3_0,
  150675. 1, -533725184, 1611661312, 3, 0,
  150676. _vq_quantlist__44u7__p3_0,
  150677. NULL,
  150678. &_vq_auxt__44u7__p3_0,
  150679. NULL,
  150680. 0
  150681. };
  150682. static long _vq_quantlist__44u7__p4_0[] = {
  150683. 2,
  150684. 1,
  150685. 3,
  150686. 0,
  150687. 4,
  150688. };
  150689. static long _vq_lengthlist__44u7__p4_0[] = {
  150690. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150691. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150692. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150693. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150694. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150695. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150696. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150697. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150698. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150699. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150700. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150701. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150702. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150703. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150704. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150705. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150706. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150707. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150708. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150709. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150710. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150711. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150712. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150713. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150714. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150715. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150716. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150717. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150718. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150719. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150720. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150721. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150722. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150723. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150724. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150725. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150726. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150727. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150728. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150729. 14,
  150730. };
  150731. static float _vq_quantthresh__44u7__p4_0[] = {
  150732. -1.5, -0.5, 0.5, 1.5,
  150733. };
  150734. static long _vq_quantmap__44u7__p4_0[] = {
  150735. 3, 1, 0, 2, 4,
  150736. };
  150737. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150738. _vq_quantthresh__44u7__p4_0,
  150739. _vq_quantmap__44u7__p4_0,
  150740. 5,
  150741. 5
  150742. };
  150743. static static_codebook _44u7__p4_0 = {
  150744. 4, 625,
  150745. _vq_lengthlist__44u7__p4_0,
  150746. 1, -533725184, 1611661312, 3, 0,
  150747. _vq_quantlist__44u7__p4_0,
  150748. NULL,
  150749. &_vq_auxt__44u7__p4_0,
  150750. NULL,
  150751. 0
  150752. };
  150753. static long _vq_quantlist__44u7__p5_0[] = {
  150754. 4,
  150755. 3,
  150756. 5,
  150757. 2,
  150758. 6,
  150759. 1,
  150760. 7,
  150761. 0,
  150762. 8,
  150763. };
  150764. static long _vq_lengthlist__44u7__p5_0[] = {
  150765. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150766. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150767. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150768. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150769. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150770. 14,
  150771. };
  150772. static float _vq_quantthresh__44u7__p5_0[] = {
  150773. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150774. };
  150775. static long _vq_quantmap__44u7__p5_0[] = {
  150776. 7, 5, 3, 1, 0, 2, 4, 6,
  150777. 8,
  150778. };
  150779. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150780. _vq_quantthresh__44u7__p5_0,
  150781. _vq_quantmap__44u7__p5_0,
  150782. 9,
  150783. 9
  150784. };
  150785. static static_codebook _44u7__p5_0 = {
  150786. 2, 81,
  150787. _vq_lengthlist__44u7__p5_0,
  150788. 1, -531628032, 1611661312, 4, 0,
  150789. _vq_quantlist__44u7__p5_0,
  150790. NULL,
  150791. &_vq_auxt__44u7__p5_0,
  150792. NULL,
  150793. 0
  150794. };
  150795. static long _vq_quantlist__44u7__p6_0[] = {
  150796. 4,
  150797. 3,
  150798. 5,
  150799. 2,
  150800. 6,
  150801. 1,
  150802. 7,
  150803. 0,
  150804. 8,
  150805. };
  150806. static long _vq_lengthlist__44u7__p6_0[] = {
  150807. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150808. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150809. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150810. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150811. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150812. 12,
  150813. };
  150814. static float _vq_quantthresh__44u7__p6_0[] = {
  150815. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150816. };
  150817. static long _vq_quantmap__44u7__p6_0[] = {
  150818. 7, 5, 3, 1, 0, 2, 4, 6,
  150819. 8,
  150820. };
  150821. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150822. _vq_quantthresh__44u7__p6_0,
  150823. _vq_quantmap__44u7__p6_0,
  150824. 9,
  150825. 9
  150826. };
  150827. static static_codebook _44u7__p6_0 = {
  150828. 2, 81,
  150829. _vq_lengthlist__44u7__p6_0,
  150830. 1, -531628032, 1611661312, 4, 0,
  150831. _vq_quantlist__44u7__p6_0,
  150832. NULL,
  150833. &_vq_auxt__44u7__p6_0,
  150834. NULL,
  150835. 0
  150836. };
  150837. static long _vq_quantlist__44u7__p7_0[] = {
  150838. 1,
  150839. 0,
  150840. 2,
  150841. };
  150842. static long _vq_lengthlist__44u7__p7_0[] = {
  150843. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150844. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150845. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150846. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150847. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150848. 10,
  150849. };
  150850. static float _vq_quantthresh__44u7__p7_0[] = {
  150851. -5.5, 5.5,
  150852. };
  150853. static long _vq_quantmap__44u7__p7_0[] = {
  150854. 1, 0, 2,
  150855. };
  150856. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150857. _vq_quantthresh__44u7__p7_0,
  150858. _vq_quantmap__44u7__p7_0,
  150859. 3,
  150860. 3
  150861. };
  150862. static static_codebook _44u7__p7_0 = {
  150863. 4, 81,
  150864. _vq_lengthlist__44u7__p7_0,
  150865. 1, -529137664, 1618345984, 2, 0,
  150866. _vq_quantlist__44u7__p7_0,
  150867. NULL,
  150868. &_vq_auxt__44u7__p7_0,
  150869. NULL,
  150870. 0
  150871. };
  150872. static long _vq_quantlist__44u7__p7_1[] = {
  150873. 5,
  150874. 4,
  150875. 6,
  150876. 3,
  150877. 7,
  150878. 2,
  150879. 8,
  150880. 1,
  150881. 9,
  150882. 0,
  150883. 10,
  150884. };
  150885. static long _vq_lengthlist__44u7__p7_1[] = {
  150886. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150887. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150888. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150889. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150890. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150891. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150892. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150893. 8, 9, 9, 9, 9, 9,10,10,10,
  150894. };
  150895. static float _vq_quantthresh__44u7__p7_1[] = {
  150896. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150897. 3.5, 4.5,
  150898. };
  150899. static long _vq_quantmap__44u7__p7_1[] = {
  150900. 9, 7, 5, 3, 1, 0, 2, 4,
  150901. 6, 8, 10,
  150902. };
  150903. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150904. _vq_quantthresh__44u7__p7_1,
  150905. _vq_quantmap__44u7__p7_1,
  150906. 11,
  150907. 11
  150908. };
  150909. static static_codebook _44u7__p7_1 = {
  150910. 2, 121,
  150911. _vq_lengthlist__44u7__p7_1,
  150912. 1, -531365888, 1611661312, 4, 0,
  150913. _vq_quantlist__44u7__p7_1,
  150914. NULL,
  150915. &_vq_auxt__44u7__p7_1,
  150916. NULL,
  150917. 0
  150918. };
  150919. static long _vq_quantlist__44u7__p8_0[] = {
  150920. 5,
  150921. 4,
  150922. 6,
  150923. 3,
  150924. 7,
  150925. 2,
  150926. 8,
  150927. 1,
  150928. 9,
  150929. 0,
  150930. 10,
  150931. };
  150932. static long _vq_lengthlist__44u7__p8_0[] = {
  150933. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150934. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150935. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150936. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150937. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150938. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150939. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150940. 12,13,13,14,14,15,15,15,16,
  150941. };
  150942. static float _vq_quantthresh__44u7__p8_0[] = {
  150943. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150944. 38.5, 49.5,
  150945. };
  150946. static long _vq_quantmap__44u7__p8_0[] = {
  150947. 9, 7, 5, 3, 1, 0, 2, 4,
  150948. 6, 8, 10,
  150949. };
  150950. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150951. _vq_quantthresh__44u7__p8_0,
  150952. _vq_quantmap__44u7__p8_0,
  150953. 11,
  150954. 11
  150955. };
  150956. static static_codebook _44u7__p8_0 = {
  150957. 2, 121,
  150958. _vq_lengthlist__44u7__p8_0,
  150959. 1, -524582912, 1618345984, 4, 0,
  150960. _vq_quantlist__44u7__p8_0,
  150961. NULL,
  150962. &_vq_auxt__44u7__p8_0,
  150963. NULL,
  150964. 0
  150965. };
  150966. static long _vq_quantlist__44u7__p8_1[] = {
  150967. 5,
  150968. 4,
  150969. 6,
  150970. 3,
  150971. 7,
  150972. 2,
  150973. 8,
  150974. 1,
  150975. 9,
  150976. 0,
  150977. 10,
  150978. };
  150979. static long _vq_lengthlist__44u7__p8_1[] = {
  150980. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150981. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150982. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150983. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150984. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150985. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150986. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150987. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150988. };
  150989. static float _vq_quantthresh__44u7__p8_1[] = {
  150990. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150991. 3.5, 4.5,
  150992. };
  150993. static long _vq_quantmap__44u7__p8_1[] = {
  150994. 9, 7, 5, 3, 1, 0, 2, 4,
  150995. 6, 8, 10,
  150996. };
  150997. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150998. _vq_quantthresh__44u7__p8_1,
  150999. _vq_quantmap__44u7__p8_1,
  151000. 11,
  151001. 11
  151002. };
  151003. static static_codebook _44u7__p8_1 = {
  151004. 2, 121,
  151005. _vq_lengthlist__44u7__p8_1,
  151006. 1, -531365888, 1611661312, 4, 0,
  151007. _vq_quantlist__44u7__p8_1,
  151008. NULL,
  151009. &_vq_auxt__44u7__p8_1,
  151010. NULL,
  151011. 0
  151012. };
  151013. static long _vq_quantlist__44u7__p9_0[] = {
  151014. 5,
  151015. 4,
  151016. 6,
  151017. 3,
  151018. 7,
  151019. 2,
  151020. 8,
  151021. 1,
  151022. 9,
  151023. 0,
  151024. 10,
  151025. };
  151026. static long _vq_lengthlist__44u7__p9_0[] = {
  151027. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  151028. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  151029. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151030. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151031. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151032. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151033. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  151034. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151035. };
  151036. static float _vq_quantthresh__44u7__p9_0[] = {
  151037. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  151038. 2229.5, 2866.5,
  151039. };
  151040. static long _vq_quantmap__44u7__p9_0[] = {
  151041. 9, 7, 5, 3, 1, 0, 2, 4,
  151042. 6, 8, 10,
  151043. };
  151044. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  151045. _vq_quantthresh__44u7__p9_0,
  151046. _vq_quantmap__44u7__p9_0,
  151047. 11,
  151048. 11
  151049. };
  151050. static static_codebook _44u7__p9_0 = {
  151051. 2, 121,
  151052. _vq_lengthlist__44u7__p9_0,
  151053. 1, -512171520, 1630791680, 4, 0,
  151054. _vq_quantlist__44u7__p9_0,
  151055. NULL,
  151056. &_vq_auxt__44u7__p9_0,
  151057. NULL,
  151058. 0
  151059. };
  151060. static long _vq_quantlist__44u7__p9_1[] = {
  151061. 6,
  151062. 5,
  151063. 7,
  151064. 4,
  151065. 8,
  151066. 3,
  151067. 9,
  151068. 2,
  151069. 10,
  151070. 1,
  151071. 11,
  151072. 0,
  151073. 12,
  151074. };
  151075. static long _vq_lengthlist__44u7__p9_1[] = {
  151076. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  151077. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  151078. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  151079. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  151080. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  151081. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  151082. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  151083. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  151084. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  151085. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  151086. 15,15,15,15,17,17,16,17,16,
  151087. };
  151088. static float _vq_quantthresh__44u7__p9_1[] = {
  151089. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  151090. 122.5, 171.5, 220.5, 269.5,
  151091. };
  151092. static long _vq_quantmap__44u7__p9_1[] = {
  151093. 11, 9, 7, 5, 3, 1, 0, 2,
  151094. 4, 6, 8, 10, 12,
  151095. };
  151096. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  151097. _vq_quantthresh__44u7__p9_1,
  151098. _vq_quantmap__44u7__p9_1,
  151099. 13,
  151100. 13
  151101. };
  151102. static static_codebook _44u7__p9_1 = {
  151103. 2, 169,
  151104. _vq_lengthlist__44u7__p9_1,
  151105. 1, -518889472, 1622704128, 4, 0,
  151106. _vq_quantlist__44u7__p9_1,
  151107. NULL,
  151108. &_vq_auxt__44u7__p9_1,
  151109. NULL,
  151110. 0
  151111. };
  151112. static long _vq_quantlist__44u7__p9_2[] = {
  151113. 24,
  151114. 23,
  151115. 25,
  151116. 22,
  151117. 26,
  151118. 21,
  151119. 27,
  151120. 20,
  151121. 28,
  151122. 19,
  151123. 29,
  151124. 18,
  151125. 30,
  151126. 17,
  151127. 31,
  151128. 16,
  151129. 32,
  151130. 15,
  151131. 33,
  151132. 14,
  151133. 34,
  151134. 13,
  151135. 35,
  151136. 12,
  151137. 36,
  151138. 11,
  151139. 37,
  151140. 10,
  151141. 38,
  151142. 9,
  151143. 39,
  151144. 8,
  151145. 40,
  151146. 7,
  151147. 41,
  151148. 6,
  151149. 42,
  151150. 5,
  151151. 43,
  151152. 4,
  151153. 44,
  151154. 3,
  151155. 45,
  151156. 2,
  151157. 46,
  151158. 1,
  151159. 47,
  151160. 0,
  151161. 48,
  151162. };
  151163. static long _vq_lengthlist__44u7__p9_2[] = {
  151164. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151165. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151166. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151167. 8,
  151168. };
  151169. static float _vq_quantthresh__44u7__p9_2[] = {
  151170. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151171. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151172. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151173. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151174. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151175. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151176. };
  151177. static long _vq_quantmap__44u7__p9_2[] = {
  151178. 47, 45, 43, 41, 39, 37, 35, 33,
  151179. 31, 29, 27, 25, 23, 21, 19, 17,
  151180. 15, 13, 11, 9, 7, 5, 3, 1,
  151181. 0, 2, 4, 6, 8, 10, 12, 14,
  151182. 16, 18, 20, 22, 24, 26, 28, 30,
  151183. 32, 34, 36, 38, 40, 42, 44, 46,
  151184. 48,
  151185. };
  151186. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151187. _vq_quantthresh__44u7__p9_2,
  151188. _vq_quantmap__44u7__p9_2,
  151189. 49,
  151190. 49
  151191. };
  151192. static static_codebook _44u7__p9_2 = {
  151193. 1, 49,
  151194. _vq_lengthlist__44u7__p9_2,
  151195. 1, -526909440, 1611661312, 6, 0,
  151196. _vq_quantlist__44u7__p9_2,
  151197. NULL,
  151198. &_vq_auxt__44u7__p9_2,
  151199. NULL,
  151200. 0
  151201. };
  151202. static long _huff_lengthlist__44u7__short[] = {
  151203. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151204. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151205. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151206. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151207. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151208. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151209. 6, 8, 5, 9,
  151210. };
  151211. static static_codebook _huff_book__44u7__short = {
  151212. 2, 100,
  151213. _huff_lengthlist__44u7__short,
  151214. 0, 0, 0, 0, 0,
  151215. NULL,
  151216. NULL,
  151217. NULL,
  151218. NULL,
  151219. 0
  151220. };
  151221. static long _huff_lengthlist__44u8__long[] = {
  151222. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151223. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151224. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151225. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151226. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151227. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151228. 10, 8, 8, 9,
  151229. };
  151230. static static_codebook _huff_book__44u8__long = {
  151231. 2, 100,
  151232. _huff_lengthlist__44u8__long,
  151233. 0, 0, 0, 0, 0,
  151234. NULL,
  151235. NULL,
  151236. NULL,
  151237. NULL,
  151238. 0
  151239. };
  151240. static long _huff_lengthlist__44u8__short[] = {
  151241. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151242. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151243. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151244. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151245. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151246. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151247. 10,10,15,17,
  151248. };
  151249. static static_codebook _huff_book__44u8__short = {
  151250. 2, 100,
  151251. _huff_lengthlist__44u8__short,
  151252. 0, 0, 0, 0, 0,
  151253. NULL,
  151254. NULL,
  151255. NULL,
  151256. NULL,
  151257. 0
  151258. };
  151259. static long _vq_quantlist__44u8_p1_0[] = {
  151260. 1,
  151261. 0,
  151262. 2,
  151263. };
  151264. static long _vq_lengthlist__44u8_p1_0[] = {
  151265. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151266. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151267. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151268. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151269. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151270. 10,
  151271. };
  151272. static float _vq_quantthresh__44u8_p1_0[] = {
  151273. -0.5, 0.5,
  151274. };
  151275. static long _vq_quantmap__44u8_p1_0[] = {
  151276. 1, 0, 2,
  151277. };
  151278. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151279. _vq_quantthresh__44u8_p1_0,
  151280. _vq_quantmap__44u8_p1_0,
  151281. 3,
  151282. 3
  151283. };
  151284. static static_codebook _44u8_p1_0 = {
  151285. 4, 81,
  151286. _vq_lengthlist__44u8_p1_0,
  151287. 1, -535822336, 1611661312, 2, 0,
  151288. _vq_quantlist__44u8_p1_0,
  151289. NULL,
  151290. &_vq_auxt__44u8_p1_0,
  151291. NULL,
  151292. 0
  151293. };
  151294. static long _vq_quantlist__44u8_p2_0[] = {
  151295. 2,
  151296. 1,
  151297. 3,
  151298. 0,
  151299. 4,
  151300. };
  151301. static long _vq_lengthlist__44u8_p2_0[] = {
  151302. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151303. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151304. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151305. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151306. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151307. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151308. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151309. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151310. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151311. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151312. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151313. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151314. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151315. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151316. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151317. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151318. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151319. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151320. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151321. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151322. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151323. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151324. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151325. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151326. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151327. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151328. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151329. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151330. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151331. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151332. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151333. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151334. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151335. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151336. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151337. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151338. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151339. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151340. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151341. 14,
  151342. };
  151343. static float _vq_quantthresh__44u8_p2_0[] = {
  151344. -1.5, -0.5, 0.5, 1.5,
  151345. };
  151346. static long _vq_quantmap__44u8_p2_0[] = {
  151347. 3, 1, 0, 2, 4,
  151348. };
  151349. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151350. _vq_quantthresh__44u8_p2_0,
  151351. _vq_quantmap__44u8_p2_0,
  151352. 5,
  151353. 5
  151354. };
  151355. static static_codebook _44u8_p2_0 = {
  151356. 4, 625,
  151357. _vq_lengthlist__44u8_p2_0,
  151358. 1, -533725184, 1611661312, 3, 0,
  151359. _vq_quantlist__44u8_p2_0,
  151360. NULL,
  151361. &_vq_auxt__44u8_p2_0,
  151362. NULL,
  151363. 0
  151364. };
  151365. static long _vq_quantlist__44u8_p3_0[] = {
  151366. 4,
  151367. 3,
  151368. 5,
  151369. 2,
  151370. 6,
  151371. 1,
  151372. 7,
  151373. 0,
  151374. 8,
  151375. };
  151376. static long _vq_lengthlist__44u8_p3_0[] = {
  151377. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151378. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151379. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151380. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151381. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151382. 12,
  151383. };
  151384. static float _vq_quantthresh__44u8_p3_0[] = {
  151385. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151386. };
  151387. static long _vq_quantmap__44u8_p3_0[] = {
  151388. 7, 5, 3, 1, 0, 2, 4, 6,
  151389. 8,
  151390. };
  151391. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151392. _vq_quantthresh__44u8_p3_0,
  151393. _vq_quantmap__44u8_p3_0,
  151394. 9,
  151395. 9
  151396. };
  151397. static static_codebook _44u8_p3_0 = {
  151398. 2, 81,
  151399. _vq_lengthlist__44u8_p3_0,
  151400. 1, -531628032, 1611661312, 4, 0,
  151401. _vq_quantlist__44u8_p3_0,
  151402. NULL,
  151403. &_vq_auxt__44u8_p3_0,
  151404. NULL,
  151405. 0
  151406. };
  151407. static long _vq_quantlist__44u8_p4_0[] = {
  151408. 8,
  151409. 7,
  151410. 9,
  151411. 6,
  151412. 10,
  151413. 5,
  151414. 11,
  151415. 4,
  151416. 12,
  151417. 3,
  151418. 13,
  151419. 2,
  151420. 14,
  151421. 1,
  151422. 15,
  151423. 0,
  151424. 16,
  151425. };
  151426. static long _vq_lengthlist__44u8_p4_0[] = {
  151427. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151428. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151429. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151430. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151431. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151432. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151433. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151434. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151435. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151436. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151437. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151438. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151439. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151440. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151441. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151442. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151443. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151444. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151445. 14,
  151446. };
  151447. static float _vq_quantthresh__44u8_p4_0[] = {
  151448. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151449. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151450. };
  151451. static long _vq_quantmap__44u8_p4_0[] = {
  151452. 15, 13, 11, 9, 7, 5, 3, 1,
  151453. 0, 2, 4, 6, 8, 10, 12, 14,
  151454. 16,
  151455. };
  151456. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151457. _vq_quantthresh__44u8_p4_0,
  151458. _vq_quantmap__44u8_p4_0,
  151459. 17,
  151460. 17
  151461. };
  151462. static static_codebook _44u8_p4_0 = {
  151463. 2, 289,
  151464. _vq_lengthlist__44u8_p4_0,
  151465. 1, -529530880, 1611661312, 5, 0,
  151466. _vq_quantlist__44u8_p4_0,
  151467. NULL,
  151468. &_vq_auxt__44u8_p4_0,
  151469. NULL,
  151470. 0
  151471. };
  151472. static long _vq_quantlist__44u8_p5_0[] = {
  151473. 1,
  151474. 0,
  151475. 2,
  151476. };
  151477. static long _vq_lengthlist__44u8_p5_0[] = {
  151478. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151479. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151480. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151481. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151482. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151483. 10,
  151484. };
  151485. static float _vq_quantthresh__44u8_p5_0[] = {
  151486. -5.5, 5.5,
  151487. };
  151488. static long _vq_quantmap__44u8_p5_0[] = {
  151489. 1, 0, 2,
  151490. };
  151491. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151492. _vq_quantthresh__44u8_p5_0,
  151493. _vq_quantmap__44u8_p5_0,
  151494. 3,
  151495. 3
  151496. };
  151497. static static_codebook _44u8_p5_0 = {
  151498. 4, 81,
  151499. _vq_lengthlist__44u8_p5_0,
  151500. 1, -529137664, 1618345984, 2, 0,
  151501. _vq_quantlist__44u8_p5_0,
  151502. NULL,
  151503. &_vq_auxt__44u8_p5_0,
  151504. NULL,
  151505. 0
  151506. };
  151507. static long _vq_quantlist__44u8_p5_1[] = {
  151508. 5,
  151509. 4,
  151510. 6,
  151511. 3,
  151512. 7,
  151513. 2,
  151514. 8,
  151515. 1,
  151516. 9,
  151517. 0,
  151518. 10,
  151519. };
  151520. static long _vq_lengthlist__44u8_p5_1[] = {
  151521. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151522. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151523. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151524. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151525. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151526. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151527. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151528. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151529. };
  151530. static float _vq_quantthresh__44u8_p5_1[] = {
  151531. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151532. 3.5, 4.5,
  151533. };
  151534. static long _vq_quantmap__44u8_p5_1[] = {
  151535. 9, 7, 5, 3, 1, 0, 2, 4,
  151536. 6, 8, 10,
  151537. };
  151538. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151539. _vq_quantthresh__44u8_p5_1,
  151540. _vq_quantmap__44u8_p5_1,
  151541. 11,
  151542. 11
  151543. };
  151544. static static_codebook _44u8_p5_1 = {
  151545. 2, 121,
  151546. _vq_lengthlist__44u8_p5_1,
  151547. 1, -531365888, 1611661312, 4, 0,
  151548. _vq_quantlist__44u8_p5_1,
  151549. NULL,
  151550. &_vq_auxt__44u8_p5_1,
  151551. NULL,
  151552. 0
  151553. };
  151554. static long _vq_quantlist__44u8_p6_0[] = {
  151555. 6,
  151556. 5,
  151557. 7,
  151558. 4,
  151559. 8,
  151560. 3,
  151561. 9,
  151562. 2,
  151563. 10,
  151564. 1,
  151565. 11,
  151566. 0,
  151567. 12,
  151568. };
  151569. static long _vq_lengthlist__44u8_p6_0[] = {
  151570. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151571. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151572. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151573. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151574. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151575. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151576. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151577. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151578. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151579. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151580. 11,11,11,11,11,12,11,12,12,
  151581. };
  151582. static float _vq_quantthresh__44u8_p6_0[] = {
  151583. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151584. 12.5, 17.5, 22.5, 27.5,
  151585. };
  151586. static long _vq_quantmap__44u8_p6_0[] = {
  151587. 11, 9, 7, 5, 3, 1, 0, 2,
  151588. 4, 6, 8, 10, 12,
  151589. };
  151590. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151591. _vq_quantthresh__44u8_p6_0,
  151592. _vq_quantmap__44u8_p6_0,
  151593. 13,
  151594. 13
  151595. };
  151596. static static_codebook _44u8_p6_0 = {
  151597. 2, 169,
  151598. _vq_lengthlist__44u8_p6_0,
  151599. 1, -526516224, 1616117760, 4, 0,
  151600. _vq_quantlist__44u8_p6_0,
  151601. NULL,
  151602. &_vq_auxt__44u8_p6_0,
  151603. NULL,
  151604. 0
  151605. };
  151606. static long _vq_quantlist__44u8_p6_1[] = {
  151607. 2,
  151608. 1,
  151609. 3,
  151610. 0,
  151611. 4,
  151612. };
  151613. static long _vq_lengthlist__44u8_p6_1[] = {
  151614. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151615. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151616. };
  151617. static float _vq_quantthresh__44u8_p6_1[] = {
  151618. -1.5, -0.5, 0.5, 1.5,
  151619. };
  151620. static long _vq_quantmap__44u8_p6_1[] = {
  151621. 3, 1, 0, 2, 4,
  151622. };
  151623. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151624. _vq_quantthresh__44u8_p6_1,
  151625. _vq_quantmap__44u8_p6_1,
  151626. 5,
  151627. 5
  151628. };
  151629. static static_codebook _44u8_p6_1 = {
  151630. 2, 25,
  151631. _vq_lengthlist__44u8_p6_1,
  151632. 1, -533725184, 1611661312, 3, 0,
  151633. _vq_quantlist__44u8_p6_1,
  151634. NULL,
  151635. &_vq_auxt__44u8_p6_1,
  151636. NULL,
  151637. 0
  151638. };
  151639. static long _vq_quantlist__44u8_p7_0[] = {
  151640. 6,
  151641. 5,
  151642. 7,
  151643. 4,
  151644. 8,
  151645. 3,
  151646. 9,
  151647. 2,
  151648. 10,
  151649. 1,
  151650. 11,
  151651. 0,
  151652. 12,
  151653. };
  151654. static long _vq_lengthlist__44u8_p7_0[] = {
  151655. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151656. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151657. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151658. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151659. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151660. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151661. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151662. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151663. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151664. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151665. 13,13,14,14,14,15,15,15,16,
  151666. };
  151667. static float _vq_quantthresh__44u8_p7_0[] = {
  151668. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151669. 27.5, 38.5, 49.5, 60.5,
  151670. };
  151671. static long _vq_quantmap__44u8_p7_0[] = {
  151672. 11, 9, 7, 5, 3, 1, 0, 2,
  151673. 4, 6, 8, 10, 12,
  151674. };
  151675. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151676. _vq_quantthresh__44u8_p7_0,
  151677. _vq_quantmap__44u8_p7_0,
  151678. 13,
  151679. 13
  151680. };
  151681. static static_codebook _44u8_p7_0 = {
  151682. 2, 169,
  151683. _vq_lengthlist__44u8_p7_0,
  151684. 1, -523206656, 1618345984, 4, 0,
  151685. _vq_quantlist__44u8_p7_0,
  151686. NULL,
  151687. &_vq_auxt__44u8_p7_0,
  151688. NULL,
  151689. 0
  151690. };
  151691. static long _vq_quantlist__44u8_p7_1[] = {
  151692. 5,
  151693. 4,
  151694. 6,
  151695. 3,
  151696. 7,
  151697. 2,
  151698. 8,
  151699. 1,
  151700. 9,
  151701. 0,
  151702. 10,
  151703. };
  151704. static long _vq_lengthlist__44u8_p7_1[] = {
  151705. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151706. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151707. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151708. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151709. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151710. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151711. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151712. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151713. };
  151714. static float _vq_quantthresh__44u8_p7_1[] = {
  151715. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151716. 3.5, 4.5,
  151717. };
  151718. static long _vq_quantmap__44u8_p7_1[] = {
  151719. 9, 7, 5, 3, 1, 0, 2, 4,
  151720. 6, 8, 10,
  151721. };
  151722. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151723. _vq_quantthresh__44u8_p7_1,
  151724. _vq_quantmap__44u8_p7_1,
  151725. 11,
  151726. 11
  151727. };
  151728. static static_codebook _44u8_p7_1 = {
  151729. 2, 121,
  151730. _vq_lengthlist__44u8_p7_1,
  151731. 1, -531365888, 1611661312, 4, 0,
  151732. _vq_quantlist__44u8_p7_1,
  151733. NULL,
  151734. &_vq_auxt__44u8_p7_1,
  151735. NULL,
  151736. 0
  151737. };
  151738. static long _vq_quantlist__44u8_p8_0[] = {
  151739. 7,
  151740. 6,
  151741. 8,
  151742. 5,
  151743. 9,
  151744. 4,
  151745. 10,
  151746. 3,
  151747. 11,
  151748. 2,
  151749. 12,
  151750. 1,
  151751. 13,
  151752. 0,
  151753. 14,
  151754. };
  151755. static long _vq_lengthlist__44u8_p8_0[] = {
  151756. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151757. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151758. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151759. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151760. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151761. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151762. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151763. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151764. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151765. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151766. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151767. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151768. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151769. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151770. 17,
  151771. };
  151772. static float _vq_quantthresh__44u8_p8_0[] = {
  151773. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151774. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151775. };
  151776. static long _vq_quantmap__44u8_p8_0[] = {
  151777. 13, 11, 9, 7, 5, 3, 1, 0,
  151778. 2, 4, 6, 8, 10, 12, 14,
  151779. };
  151780. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151781. _vq_quantthresh__44u8_p8_0,
  151782. _vq_quantmap__44u8_p8_0,
  151783. 15,
  151784. 15
  151785. };
  151786. static static_codebook _44u8_p8_0 = {
  151787. 2, 225,
  151788. _vq_lengthlist__44u8_p8_0,
  151789. 1, -520986624, 1620377600, 4, 0,
  151790. _vq_quantlist__44u8_p8_0,
  151791. NULL,
  151792. &_vq_auxt__44u8_p8_0,
  151793. NULL,
  151794. 0
  151795. };
  151796. static long _vq_quantlist__44u8_p8_1[] = {
  151797. 10,
  151798. 9,
  151799. 11,
  151800. 8,
  151801. 12,
  151802. 7,
  151803. 13,
  151804. 6,
  151805. 14,
  151806. 5,
  151807. 15,
  151808. 4,
  151809. 16,
  151810. 3,
  151811. 17,
  151812. 2,
  151813. 18,
  151814. 1,
  151815. 19,
  151816. 0,
  151817. 20,
  151818. };
  151819. static long _vq_lengthlist__44u8_p8_1[] = {
  151820. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151821. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151822. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151823. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151824. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151825. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151826. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151827. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151828. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151829. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151830. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151831. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151832. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151833. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151834. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151835. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151836. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151837. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151838. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151839. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151840. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151841. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151842. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151843. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151844. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151845. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151846. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151847. 10,10,10,10,10,10,10,10,10,
  151848. };
  151849. static float _vq_quantthresh__44u8_p8_1[] = {
  151850. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151851. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151852. 6.5, 7.5, 8.5, 9.5,
  151853. };
  151854. static long _vq_quantmap__44u8_p8_1[] = {
  151855. 19, 17, 15, 13, 11, 9, 7, 5,
  151856. 3, 1, 0, 2, 4, 6, 8, 10,
  151857. 12, 14, 16, 18, 20,
  151858. };
  151859. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151860. _vq_quantthresh__44u8_p8_1,
  151861. _vq_quantmap__44u8_p8_1,
  151862. 21,
  151863. 21
  151864. };
  151865. static static_codebook _44u8_p8_1 = {
  151866. 2, 441,
  151867. _vq_lengthlist__44u8_p8_1,
  151868. 1, -529268736, 1611661312, 5, 0,
  151869. _vq_quantlist__44u8_p8_1,
  151870. NULL,
  151871. &_vq_auxt__44u8_p8_1,
  151872. NULL,
  151873. 0
  151874. };
  151875. static long _vq_quantlist__44u8_p9_0[] = {
  151876. 4,
  151877. 3,
  151878. 5,
  151879. 2,
  151880. 6,
  151881. 1,
  151882. 7,
  151883. 0,
  151884. 8,
  151885. };
  151886. static long _vq_lengthlist__44u8_p9_0[] = {
  151887. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151888. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151889. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151890. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151891. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151892. 8,
  151893. };
  151894. static float _vq_quantthresh__44u8_p9_0[] = {
  151895. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151896. };
  151897. static long _vq_quantmap__44u8_p9_0[] = {
  151898. 7, 5, 3, 1, 0, 2, 4, 6,
  151899. 8,
  151900. };
  151901. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151902. _vq_quantthresh__44u8_p9_0,
  151903. _vq_quantmap__44u8_p9_0,
  151904. 9,
  151905. 9
  151906. };
  151907. static static_codebook _44u8_p9_0 = {
  151908. 2, 81,
  151909. _vq_lengthlist__44u8_p9_0,
  151910. 1, -511895552, 1631393792, 4, 0,
  151911. _vq_quantlist__44u8_p9_0,
  151912. NULL,
  151913. &_vq_auxt__44u8_p9_0,
  151914. NULL,
  151915. 0
  151916. };
  151917. static long _vq_quantlist__44u8_p9_1[] = {
  151918. 9,
  151919. 8,
  151920. 10,
  151921. 7,
  151922. 11,
  151923. 6,
  151924. 12,
  151925. 5,
  151926. 13,
  151927. 4,
  151928. 14,
  151929. 3,
  151930. 15,
  151931. 2,
  151932. 16,
  151933. 1,
  151934. 17,
  151935. 0,
  151936. 18,
  151937. };
  151938. static long _vq_lengthlist__44u8_p9_1[] = {
  151939. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151940. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151941. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151942. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151943. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151944. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151945. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151946. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151947. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151948. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151949. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151950. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151951. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151952. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151953. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151954. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151955. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151956. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151957. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151958. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151959. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151960. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151961. 16,15,16,16,16,16,16,16,16,
  151962. };
  151963. static float _vq_quantthresh__44u8_p9_1[] = {
  151964. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151965. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151966. 367.5, 416.5,
  151967. };
  151968. static long _vq_quantmap__44u8_p9_1[] = {
  151969. 17, 15, 13, 11, 9, 7, 5, 3,
  151970. 1, 0, 2, 4, 6, 8, 10, 12,
  151971. 14, 16, 18,
  151972. };
  151973. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151974. _vq_quantthresh__44u8_p9_1,
  151975. _vq_quantmap__44u8_p9_1,
  151976. 19,
  151977. 19
  151978. };
  151979. static static_codebook _44u8_p9_1 = {
  151980. 2, 361,
  151981. _vq_lengthlist__44u8_p9_1,
  151982. 1, -518287360, 1622704128, 5, 0,
  151983. _vq_quantlist__44u8_p9_1,
  151984. NULL,
  151985. &_vq_auxt__44u8_p9_1,
  151986. NULL,
  151987. 0
  151988. };
  151989. static long _vq_quantlist__44u8_p9_2[] = {
  151990. 24,
  151991. 23,
  151992. 25,
  151993. 22,
  151994. 26,
  151995. 21,
  151996. 27,
  151997. 20,
  151998. 28,
  151999. 19,
  152000. 29,
  152001. 18,
  152002. 30,
  152003. 17,
  152004. 31,
  152005. 16,
  152006. 32,
  152007. 15,
  152008. 33,
  152009. 14,
  152010. 34,
  152011. 13,
  152012. 35,
  152013. 12,
  152014. 36,
  152015. 11,
  152016. 37,
  152017. 10,
  152018. 38,
  152019. 9,
  152020. 39,
  152021. 8,
  152022. 40,
  152023. 7,
  152024. 41,
  152025. 6,
  152026. 42,
  152027. 5,
  152028. 43,
  152029. 4,
  152030. 44,
  152031. 3,
  152032. 45,
  152033. 2,
  152034. 46,
  152035. 1,
  152036. 47,
  152037. 0,
  152038. 48,
  152039. };
  152040. static long _vq_lengthlist__44u8_p9_2[] = {
  152041. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  152042. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152043. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152044. 7,
  152045. };
  152046. static float _vq_quantthresh__44u8_p9_2[] = {
  152047. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152048. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152049. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152050. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152051. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152052. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152053. };
  152054. static long _vq_quantmap__44u8_p9_2[] = {
  152055. 47, 45, 43, 41, 39, 37, 35, 33,
  152056. 31, 29, 27, 25, 23, 21, 19, 17,
  152057. 15, 13, 11, 9, 7, 5, 3, 1,
  152058. 0, 2, 4, 6, 8, 10, 12, 14,
  152059. 16, 18, 20, 22, 24, 26, 28, 30,
  152060. 32, 34, 36, 38, 40, 42, 44, 46,
  152061. 48,
  152062. };
  152063. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  152064. _vq_quantthresh__44u8_p9_2,
  152065. _vq_quantmap__44u8_p9_2,
  152066. 49,
  152067. 49
  152068. };
  152069. static static_codebook _44u8_p9_2 = {
  152070. 1, 49,
  152071. _vq_lengthlist__44u8_p9_2,
  152072. 1, -526909440, 1611661312, 6, 0,
  152073. _vq_quantlist__44u8_p9_2,
  152074. NULL,
  152075. &_vq_auxt__44u8_p9_2,
  152076. NULL,
  152077. 0
  152078. };
  152079. static long _huff_lengthlist__44u9__long[] = {
  152080. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  152081. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  152082. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  152083. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  152084. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  152085. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  152086. 10, 8, 8, 9,
  152087. };
  152088. static static_codebook _huff_book__44u9__long = {
  152089. 2, 100,
  152090. _huff_lengthlist__44u9__long,
  152091. 0, 0, 0, 0, 0,
  152092. NULL,
  152093. NULL,
  152094. NULL,
  152095. NULL,
  152096. 0
  152097. };
  152098. static long _huff_lengthlist__44u9__short[] = {
  152099. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  152100. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  152101. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  152102. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  152103. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  152104. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  152105. 9, 9,12,15,
  152106. };
  152107. static static_codebook _huff_book__44u9__short = {
  152108. 2, 100,
  152109. _huff_lengthlist__44u9__short,
  152110. 0, 0, 0, 0, 0,
  152111. NULL,
  152112. NULL,
  152113. NULL,
  152114. NULL,
  152115. 0
  152116. };
  152117. static long _vq_quantlist__44u9_p1_0[] = {
  152118. 1,
  152119. 0,
  152120. 2,
  152121. };
  152122. static long _vq_lengthlist__44u9_p1_0[] = {
  152123. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152124. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152125. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152126. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152127. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152128. 10,
  152129. };
  152130. static float _vq_quantthresh__44u9_p1_0[] = {
  152131. -0.5, 0.5,
  152132. };
  152133. static long _vq_quantmap__44u9_p1_0[] = {
  152134. 1, 0, 2,
  152135. };
  152136. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152137. _vq_quantthresh__44u9_p1_0,
  152138. _vq_quantmap__44u9_p1_0,
  152139. 3,
  152140. 3
  152141. };
  152142. static static_codebook _44u9_p1_0 = {
  152143. 4, 81,
  152144. _vq_lengthlist__44u9_p1_0,
  152145. 1, -535822336, 1611661312, 2, 0,
  152146. _vq_quantlist__44u9_p1_0,
  152147. NULL,
  152148. &_vq_auxt__44u9_p1_0,
  152149. NULL,
  152150. 0
  152151. };
  152152. static long _vq_quantlist__44u9_p2_0[] = {
  152153. 2,
  152154. 1,
  152155. 3,
  152156. 0,
  152157. 4,
  152158. };
  152159. static long _vq_lengthlist__44u9_p2_0[] = {
  152160. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152161. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152162. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152163. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152164. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152165. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152166. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152167. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152168. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152169. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152170. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152171. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152172. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152173. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152174. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152175. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152176. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152177. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152178. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152179. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152180. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152181. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152182. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152183. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152184. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152185. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152186. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152187. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152188. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152189. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152190. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152191. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152192. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152193. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152194. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152195. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152196. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152197. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152198. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152199. 14,
  152200. };
  152201. static float _vq_quantthresh__44u9_p2_0[] = {
  152202. -1.5, -0.5, 0.5, 1.5,
  152203. };
  152204. static long _vq_quantmap__44u9_p2_0[] = {
  152205. 3, 1, 0, 2, 4,
  152206. };
  152207. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152208. _vq_quantthresh__44u9_p2_0,
  152209. _vq_quantmap__44u9_p2_0,
  152210. 5,
  152211. 5
  152212. };
  152213. static static_codebook _44u9_p2_0 = {
  152214. 4, 625,
  152215. _vq_lengthlist__44u9_p2_0,
  152216. 1, -533725184, 1611661312, 3, 0,
  152217. _vq_quantlist__44u9_p2_0,
  152218. NULL,
  152219. &_vq_auxt__44u9_p2_0,
  152220. NULL,
  152221. 0
  152222. };
  152223. static long _vq_quantlist__44u9_p3_0[] = {
  152224. 4,
  152225. 3,
  152226. 5,
  152227. 2,
  152228. 6,
  152229. 1,
  152230. 7,
  152231. 0,
  152232. 8,
  152233. };
  152234. static long _vq_lengthlist__44u9_p3_0[] = {
  152235. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152236. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152237. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152238. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152239. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152240. 11,
  152241. };
  152242. static float _vq_quantthresh__44u9_p3_0[] = {
  152243. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152244. };
  152245. static long _vq_quantmap__44u9_p3_0[] = {
  152246. 7, 5, 3, 1, 0, 2, 4, 6,
  152247. 8,
  152248. };
  152249. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152250. _vq_quantthresh__44u9_p3_0,
  152251. _vq_quantmap__44u9_p3_0,
  152252. 9,
  152253. 9
  152254. };
  152255. static static_codebook _44u9_p3_0 = {
  152256. 2, 81,
  152257. _vq_lengthlist__44u9_p3_0,
  152258. 1, -531628032, 1611661312, 4, 0,
  152259. _vq_quantlist__44u9_p3_0,
  152260. NULL,
  152261. &_vq_auxt__44u9_p3_0,
  152262. NULL,
  152263. 0
  152264. };
  152265. static long _vq_quantlist__44u9_p4_0[] = {
  152266. 8,
  152267. 7,
  152268. 9,
  152269. 6,
  152270. 10,
  152271. 5,
  152272. 11,
  152273. 4,
  152274. 12,
  152275. 3,
  152276. 13,
  152277. 2,
  152278. 14,
  152279. 1,
  152280. 15,
  152281. 0,
  152282. 16,
  152283. };
  152284. static long _vq_lengthlist__44u9_p4_0[] = {
  152285. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152286. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152287. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152288. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152289. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152290. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152291. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152292. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152293. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152294. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152295. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152296. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152297. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152298. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152299. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152300. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152301. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152302. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152303. 14,
  152304. };
  152305. static float _vq_quantthresh__44u9_p4_0[] = {
  152306. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152307. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152308. };
  152309. static long _vq_quantmap__44u9_p4_0[] = {
  152310. 15, 13, 11, 9, 7, 5, 3, 1,
  152311. 0, 2, 4, 6, 8, 10, 12, 14,
  152312. 16,
  152313. };
  152314. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152315. _vq_quantthresh__44u9_p4_0,
  152316. _vq_quantmap__44u9_p4_0,
  152317. 17,
  152318. 17
  152319. };
  152320. static static_codebook _44u9_p4_0 = {
  152321. 2, 289,
  152322. _vq_lengthlist__44u9_p4_0,
  152323. 1, -529530880, 1611661312, 5, 0,
  152324. _vq_quantlist__44u9_p4_0,
  152325. NULL,
  152326. &_vq_auxt__44u9_p4_0,
  152327. NULL,
  152328. 0
  152329. };
  152330. static long _vq_quantlist__44u9_p5_0[] = {
  152331. 1,
  152332. 0,
  152333. 2,
  152334. };
  152335. static long _vq_lengthlist__44u9_p5_0[] = {
  152336. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152337. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152338. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152339. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152340. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152341. 10,
  152342. };
  152343. static float _vq_quantthresh__44u9_p5_0[] = {
  152344. -5.5, 5.5,
  152345. };
  152346. static long _vq_quantmap__44u9_p5_0[] = {
  152347. 1, 0, 2,
  152348. };
  152349. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152350. _vq_quantthresh__44u9_p5_0,
  152351. _vq_quantmap__44u9_p5_0,
  152352. 3,
  152353. 3
  152354. };
  152355. static static_codebook _44u9_p5_0 = {
  152356. 4, 81,
  152357. _vq_lengthlist__44u9_p5_0,
  152358. 1, -529137664, 1618345984, 2, 0,
  152359. _vq_quantlist__44u9_p5_0,
  152360. NULL,
  152361. &_vq_auxt__44u9_p5_0,
  152362. NULL,
  152363. 0
  152364. };
  152365. static long _vq_quantlist__44u9_p5_1[] = {
  152366. 5,
  152367. 4,
  152368. 6,
  152369. 3,
  152370. 7,
  152371. 2,
  152372. 8,
  152373. 1,
  152374. 9,
  152375. 0,
  152376. 10,
  152377. };
  152378. static long _vq_lengthlist__44u9_p5_1[] = {
  152379. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152380. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152381. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152382. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152383. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152384. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152385. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152386. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152387. };
  152388. static float _vq_quantthresh__44u9_p5_1[] = {
  152389. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152390. 3.5, 4.5,
  152391. };
  152392. static long _vq_quantmap__44u9_p5_1[] = {
  152393. 9, 7, 5, 3, 1, 0, 2, 4,
  152394. 6, 8, 10,
  152395. };
  152396. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152397. _vq_quantthresh__44u9_p5_1,
  152398. _vq_quantmap__44u9_p5_1,
  152399. 11,
  152400. 11
  152401. };
  152402. static static_codebook _44u9_p5_1 = {
  152403. 2, 121,
  152404. _vq_lengthlist__44u9_p5_1,
  152405. 1, -531365888, 1611661312, 4, 0,
  152406. _vq_quantlist__44u9_p5_1,
  152407. NULL,
  152408. &_vq_auxt__44u9_p5_1,
  152409. NULL,
  152410. 0
  152411. };
  152412. static long _vq_quantlist__44u9_p6_0[] = {
  152413. 6,
  152414. 5,
  152415. 7,
  152416. 4,
  152417. 8,
  152418. 3,
  152419. 9,
  152420. 2,
  152421. 10,
  152422. 1,
  152423. 11,
  152424. 0,
  152425. 12,
  152426. };
  152427. static long _vq_lengthlist__44u9_p6_0[] = {
  152428. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152429. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152430. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152431. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152432. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152433. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152434. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152435. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152436. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152437. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152438. 10,11,11,11,11,12,11,12,12,
  152439. };
  152440. static float _vq_quantthresh__44u9_p6_0[] = {
  152441. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152442. 12.5, 17.5, 22.5, 27.5,
  152443. };
  152444. static long _vq_quantmap__44u9_p6_0[] = {
  152445. 11, 9, 7, 5, 3, 1, 0, 2,
  152446. 4, 6, 8, 10, 12,
  152447. };
  152448. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152449. _vq_quantthresh__44u9_p6_0,
  152450. _vq_quantmap__44u9_p6_0,
  152451. 13,
  152452. 13
  152453. };
  152454. static static_codebook _44u9_p6_0 = {
  152455. 2, 169,
  152456. _vq_lengthlist__44u9_p6_0,
  152457. 1, -526516224, 1616117760, 4, 0,
  152458. _vq_quantlist__44u9_p6_0,
  152459. NULL,
  152460. &_vq_auxt__44u9_p6_0,
  152461. NULL,
  152462. 0
  152463. };
  152464. static long _vq_quantlist__44u9_p6_1[] = {
  152465. 2,
  152466. 1,
  152467. 3,
  152468. 0,
  152469. 4,
  152470. };
  152471. static long _vq_lengthlist__44u9_p6_1[] = {
  152472. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152473. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152474. };
  152475. static float _vq_quantthresh__44u9_p6_1[] = {
  152476. -1.5, -0.5, 0.5, 1.5,
  152477. };
  152478. static long _vq_quantmap__44u9_p6_1[] = {
  152479. 3, 1, 0, 2, 4,
  152480. };
  152481. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152482. _vq_quantthresh__44u9_p6_1,
  152483. _vq_quantmap__44u9_p6_1,
  152484. 5,
  152485. 5
  152486. };
  152487. static static_codebook _44u9_p6_1 = {
  152488. 2, 25,
  152489. _vq_lengthlist__44u9_p6_1,
  152490. 1, -533725184, 1611661312, 3, 0,
  152491. _vq_quantlist__44u9_p6_1,
  152492. NULL,
  152493. &_vq_auxt__44u9_p6_1,
  152494. NULL,
  152495. 0
  152496. };
  152497. static long _vq_quantlist__44u9_p7_0[] = {
  152498. 6,
  152499. 5,
  152500. 7,
  152501. 4,
  152502. 8,
  152503. 3,
  152504. 9,
  152505. 2,
  152506. 10,
  152507. 1,
  152508. 11,
  152509. 0,
  152510. 12,
  152511. };
  152512. static long _vq_lengthlist__44u9_p7_0[] = {
  152513. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152514. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152515. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152516. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152517. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152518. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152519. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152520. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152521. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152522. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152523. 12,13,13,14,14,14,15,15,15,
  152524. };
  152525. static float _vq_quantthresh__44u9_p7_0[] = {
  152526. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152527. 27.5, 38.5, 49.5, 60.5,
  152528. };
  152529. static long _vq_quantmap__44u9_p7_0[] = {
  152530. 11, 9, 7, 5, 3, 1, 0, 2,
  152531. 4, 6, 8, 10, 12,
  152532. };
  152533. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152534. _vq_quantthresh__44u9_p7_0,
  152535. _vq_quantmap__44u9_p7_0,
  152536. 13,
  152537. 13
  152538. };
  152539. static static_codebook _44u9_p7_0 = {
  152540. 2, 169,
  152541. _vq_lengthlist__44u9_p7_0,
  152542. 1, -523206656, 1618345984, 4, 0,
  152543. _vq_quantlist__44u9_p7_0,
  152544. NULL,
  152545. &_vq_auxt__44u9_p7_0,
  152546. NULL,
  152547. 0
  152548. };
  152549. static long _vq_quantlist__44u9_p7_1[] = {
  152550. 5,
  152551. 4,
  152552. 6,
  152553. 3,
  152554. 7,
  152555. 2,
  152556. 8,
  152557. 1,
  152558. 9,
  152559. 0,
  152560. 10,
  152561. };
  152562. static long _vq_lengthlist__44u9_p7_1[] = {
  152563. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152564. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152565. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152566. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152567. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152568. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152569. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152570. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152571. };
  152572. static float _vq_quantthresh__44u9_p7_1[] = {
  152573. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152574. 3.5, 4.5,
  152575. };
  152576. static long _vq_quantmap__44u9_p7_1[] = {
  152577. 9, 7, 5, 3, 1, 0, 2, 4,
  152578. 6, 8, 10,
  152579. };
  152580. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152581. _vq_quantthresh__44u9_p7_1,
  152582. _vq_quantmap__44u9_p7_1,
  152583. 11,
  152584. 11
  152585. };
  152586. static static_codebook _44u9_p7_1 = {
  152587. 2, 121,
  152588. _vq_lengthlist__44u9_p7_1,
  152589. 1, -531365888, 1611661312, 4, 0,
  152590. _vq_quantlist__44u9_p7_1,
  152591. NULL,
  152592. &_vq_auxt__44u9_p7_1,
  152593. NULL,
  152594. 0
  152595. };
  152596. static long _vq_quantlist__44u9_p8_0[] = {
  152597. 7,
  152598. 6,
  152599. 8,
  152600. 5,
  152601. 9,
  152602. 4,
  152603. 10,
  152604. 3,
  152605. 11,
  152606. 2,
  152607. 12,
  152608. 1,
  152609. 13,
  152610. 0,
  152611. 14,
  152612. };
  152613. static long _vq_lengthlist__44u9_p8_0[] = {
  152614. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152615. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152616. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152617. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152618. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152619. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152620. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152621. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152622. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152623. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152624. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152625. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152626. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152627. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152628. 15,
  152629. };
  152630. static float _vq_quantthresh__44u9_p8_0[] = {
  152631. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152632. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152633. };
  152634. static long _vq_quantmap__44u9_p8_0[] = {
  152635. 13, 11, 9, 7, 5, 3, 1, 0,
  152636. 2, 4, 6, 8, 10, 12, 14,
  152637. };
  152638. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152639. _vq_quantthresh__44u9_p8_0,
  152640. _vq_quantmap__44u9_p8_0,
  152641. 15,
  152642. 15
  152643. };
  152644. static static_codebook _44u9_p8_0 = {
  152645. 2, 225,
  152646. _vq_lengthlist__44u9_p8_0,
  152647. 1, -520986624, 1620377600, 4, 0,
  152648. _vq_quantlist__44u9_p8_0,
  152649. NULL,
  152650. &_vq_auxt__44u9_p8_0,
  152651. NULL,
  152652. 0
  152653. };
  152654. static long _vq_quantlist__44u9_p8_1[] = {
  152655. 10,
  152656. 9,
  152657. 11,
  152658. 8,
  152659. 12,
  152660. 7,
  152661. 13,
  152662. 6,
  152663. 14,
  152664. 5,
  152665. 15,
  152666. 4,
  152667. 16,
  152668. 3,
  152669. 17,
  152670. 2,
  152671. 18,
  152672. 1,
  152673. 19,
  152674. 0,
  152675. 20,
  152676. };
  152677. static long _vq_lengthlist__44u9_p8_1[] = {
  152678. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152679. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152680. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152681. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152682. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152683. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152684. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152685. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152686. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152687. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152688. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152689. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152690. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152691. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152692. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152693. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152694. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152695. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152696. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152697. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152698. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152699. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152700. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152701. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152702. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152703. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152704. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152705. 10,10,10,10,10,10,10,10,10,
  152706. };
  152707. static float _vq_quantthresh__44u9_p8_1[] = {
  152708. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152709. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152710. 6.5, 7.5, 8.5, 9.5,
  152711. };
  152712. static long _vq_quantmap__44u9_p8_1[] = {
  152713. 19, 17, 15, 13, 11, 9, 7, 5,
  152714. 3, 1, 0, 2, 4, 6, 8, 10,
  152715. 12, 14, 16, 18, 20,
  152716. };
  152717. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152718. _vq_quantthresh__44u9_p8_1,
  152719. _vq_quantmap__44u9_p8_1,
  152720. 21,
  152721. 21
  152722. };
  152723. static static_codebook _44u9_p8_1 = {
  152724. 2, 441,
  152725. _vq_lengthlist__44u9_p8_1,
  152726. 1, -529268736, 1611661312, 5, 0,
  152727. _vq_quantlist__44u9_p8_1,
  152728. NULL,
  152729. &_vq_auxt__44u9_p8_1,
  152730. NULL,
  152731. 0
  152732. };
  152733. static long _vq_quantlist__44u9_p9_0[] = {
  152734. 7,
  152735. 6,
  152736. 8,
  152737. 5,
  152738. 9,
  152739. 4,
  152740. 10,
  152741. 3,
  152742. 11,
  152743. 2,
  152744. 12,
  152745. 1,
  152746. 13,
  152747. 0,
  152748. 14,
  152749. };
  152750. static long _vq_lengthlist__44u9_p9_0[] = {
  152751. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152752. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152753. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152754. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152755. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152759. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152760. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152761. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152762. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152763. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152764. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152765. 10,
  152766. };
  152767. static float _vq_quantthresh__44u9_p9_0[] = {
  152768. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152769. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152770. };
  152771. static long _vq_quantmap__44u9_p9_0[] = {
  152772. 13, 11, 9, 7, 5, 3, 1, 0,
  152773. 2, 4, 6, 8, 10, 12, 14,
  152774. };
  152775. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152776. _vq_quantthresh__44u9_p9_0,
  152777. _vq_quantmap__44u9_p9_0,
  152778. 15,
  152779. 15
  152780. };
  152781. static static_codebook _44u9_p9_0 = {
  152782. 2, 225,
  152783. _vq_lengthlist__44u9_p9_0,
  152784. 1, -510036736, 1631393792, 4, 0,
  152785. _vq_quantlist__44u9_p9_0,
  152786. NULL,
  152787. &_vq_auxt__44u9_p9_0,
  152788. NULL,
  152789. 0
  152790. };
  152791. static long _vq_quantlist__44u9_p9_1[] = {
  152792. 9,
  152793. 8,
  152794. 10,
  152795. 7,
  152796. 11,
  152797. 6,
  152798. 12,
  152799. 5,
  152800. 13,
  152801. 4,
  152802. 14,
  152803. 3,
  152804. 15,
  152805. 2,
  152806. 16,
  152807. 1,
  152808. 17,
  152809. 0,
  152810. 18,
  152811. };
  152812. static long _vq_lengthlist__44u9_p9_1[] = {
  152813. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152814. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152815. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152816. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152817. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152818. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152819. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152820. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152821. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152822. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152823. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152824. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152825. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152826. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152827. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152828. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152829. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152830. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152831. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152832. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152833. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152834. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152835. 17,17,15,17,15,17,16,16,17,
  152836. };
  152837. static float _vq_quantthresh__44u9_p9_1[] = {
  152838. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152839. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152840. 367.5, 416.5,
  152841. };
  152842. static long _vq_quantmap__44u9_p9_1[] = {
  152843. 17, 15, 13, 11, 9, 7, 5, 3,
  152844. 1, 0, 2, 4, 6, 8, 10, 12,
  152845. 14, 16, 18,
  152846. };
  152847. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152848. _vq_quantthresh__44u9_p9_1,
  152849. _vq_quantmap__44u9_p9_1,
  152850. 19,
  152851. 19
  152852. };
  152853. static static_codebook _44u9_p9_1 = {
  152854. 2, 361,
  152855. _vq_lengthlist__44u9_p9_1,
  152856. 1, -518287360, 1622704128, 5, 0,
  152857. _vq_quantlist__44u9_p9_1,
  152858. NULL,
  152859. &_vq_auxt__44u9_p9_1,
  152860. NULL,
  152861. 0
  152862. };
  152863. static long _vq_quantlist__44u9_p9_2[] = {
  152864. 24,
  152865. 23,
  152866. 25,
  152867. 22,
  152868. 26,
  152869. 21,
  152870. 27,
  152871. 20,
  152872. 28,
  152873. 19,
  152874. 29,
  152875. 18,
  152876. 30,
  152877. 17,
  152878. 31,
  152879. 16,
  152880. 32,
  152881. 15,
  152882. 33,
  152883. 14,
  152884. 34,
  152885. 13,
  152886. 35,
  152887. 12,
  152888. 36,
  152889. 11,
  152890. 37,
  152891. 10,
  152892. 38,
  152893. 9,
  152894. 39,
  152895. 8,
  152896. 40,
  152897. 7,
  152898. 41,
  152899. 6,
  152900. 42,
  152901. 5,
  152902. 43,
  152903. 4,
  152904. 44,
  152905. 3,
  152906. 45,
  152907. 2,
  152908. 46,
  152909. 1,
  152910. 47,
  152911. 0,
  152912. 48,
  152913. };
  152914. static long _vq_lengthlist__44u9_p9_2[] = {
  152915. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152916. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152917. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152918. 7,
  152919. };
  152920. static float _vq_quantthresh__44u9_p9_2[] = {
  152921. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152922. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152923. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152924. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152925. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152926. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152927. };
  152928. static long _vq_quantmap__44u9_p9_2[] = {
  152929. 47, 45, 43, 41, 39, 37, 35, 33,
  152930. 31, 29, 27, 25, 23, 21, 19, 17,
  152931. 15, 13, 11, 9, 7, 5, 3, 1,
  152932. 0, 2, 4, 6, 8, 10, 12, 14,
  152933. 16, 18, 20, 22, 24, 26, 28, 30,
  152934. 32, 34, 36, 38, 40, 42, 44, 46,
  152935. 48,
  152936. };
  152937. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152938. _vq_quantthresh__44u9_p9_2,
  152939. _vq_quantmap__44u9_p9_2,
  152940. 49,
  152941. 49
  152942. };
  152943. static static_codebook _44u9_p9_2 = {
  152944. 1, 49,
  152945. _vq_lengthlist__44u9_p9_2,
  152946. 1, -526909440, 1611661312, 6, 0,
  152947. _vq_quantlist__44u9_p9_2,
  152948. NULL,
  152949. &_vq_auxt__44u9_p9_2,
  152950. NULL,
  152951. 0
  152952. };
  152953. static long _huff_lengthlist__44un1__long[] = {
  152954. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152955. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152956. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152957. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152958. };
  152959. static static_codebook _huff_book__44un1__long = {
  152960. 2, 64,
  152961. _huff_lengthlist__44un1__long,
  152962. 0, 0, 0, 0, 0,
  152963. NULL,
  152964. NULL,
  152965. NULL,
  152966. NULL,
  152967. 0
  152968. };
  152969. static long _vq_quantlist__44un1__p1_0[] = {
  152970. 1,
  152971. 0,
  152972. 2,
  152973. };
  152974. static long _vq_lengthlist__44un1__p1_0[] = {
  152975. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152976. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152977. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152978. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152979. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152980. 12,
  152981. };
  152982. static float _vq_quantthresh__44un1__p1_0[] = {
  152983. -0.5, 0.5,
  152984. };
  152985. static long _vq_quantmap__44un1__p1_0[] = {
  152986. 1, 0, 2,
  152987. };
  152988. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152989. _vq_quantthresh__44un1__p1_0,
  152990. _vq_quantmap__44un1__p1_0,
  152991. 3,
  152992. 3
  152993. };
  152994. static static_codebook _44un1__p1_0 = {
  152995. 4, 81,
  152996. _vq_lengthlist__44un1__p1_0,
  152997. 1, -535822336, 1611661312, 2, 0,
  152998. _vq_quantlist__44un1__p1_0,
  152999. NULL,
  153000. &_vq_auxt__44un1__p1_0,
  153001. NULL,
  153002. 0
  153003. };
  153004. static long _vq_quantlist__44un1__p2_0[] = {
  153005. 1,
  153006. 0,
  153007. 2,
  153008. };
  153009. static long _vq_lengthlist__44un1__p2_0[] = {
  153010. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  153011. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  153012. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  153013. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  153014. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  153015. 8,
  153016. };
  153017. static float _vq_quantthresh__44un1__p2_0[] = {
  153018. -0.5, 0.5,
  153019. };
  153020. static long _vq_quantmap__44un1__p2_0[] = {
  153021. 1, 0, 2,
  153022. };
  153023. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  153024. _vq_quantthresh__44un1__p2_0,
  153025. _vq_quantmap__44un1__p2_0,
  153026. 3,
  153027. 3
  153028. };
  153029. static static_codebook _44un1__p2_0 = {
  153030. 4, 81,
  153031. _vq_lengthlist__44un1__p2_0,
  153032. 1, -535822336, 1611661312, 2, 0,
  153033. _vq_quantlist__44un1__p2_0,
  153034. NULL,
  153035. &_vq_auxt__44un1__p2_0,
  153036. NULL,
  153037. 0
  153038. };
  153039. static long _vq_quantlist__44un1__p3_0[] = {
  153040. 2,
  153041. 1,
  153042. 3,
  153043. 0,
  153044. 4,
  153045. };
  153046. static long _vq_lengthlist__44un1__p3_0[] = {
  153047. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  153048. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  153049. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  153050. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  153051. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  153052. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  153053. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  153054. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  153055. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  153056. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  153057. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  153058. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  153059. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  153060. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  153061. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  153062. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  153063. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  153064. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  153065. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  153066. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  153067. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  153068. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  153069. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  153070. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  153071. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  153072. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  153073. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  153074. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  153075. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  153076. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  153077. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  153078. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  153079. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  153080. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  153081. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  153082. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  153083. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  153084. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  153085. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  153086. 17,
  153087. };
  153088. static float _vq_quantthresh__44un1__p3_0[] = {
  153089. -1.5, -0.5, 0.5, 1.5,
  153090. };
  153091. static long _vq_quantmap__44un1__p3_0[] = {
  153092. 3, 1, 0, 2, 4,
  153093. };
  153094. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  153095. _vq_quantthresh__44un1__p3_0,
  153096. _vq_quantmap__44un1__p3_0,
  153097. 5,
  153098. 5
  153099. };
  153100. static static_codebook _44un1__p3_0 = {
  153101. 4, 625,
  153102. _vq_lengthlist__44un1__p3_0,
  153103. 1, -533725184, 1611661312, 3, 0,
  153104. _vq_quantlist__44un1__p3_0,
  153105. NULL,
  153106. &_vq_auxt__44un1__p3_0,
  153107. NULL,
  153108. 0
  153109. };
  153110. static long _vq_quantlist__44un1__p4_0[] = {
  153111. 2,
  153112. 1,
  153113. 3,
  153114. 0,
  153115. 4,
  153116. };
  153117. static long _vq_lengthlist__44un1__p4_0[] = {
  153118. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153119. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153120. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153121. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153122. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153123. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153124. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153125. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153126. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153127. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153128. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153129. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153130. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153131. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153132. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153133. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153134. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153135. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153136. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153137. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153138. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153139. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153140. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153141. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153142. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153143. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153144. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153145. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153146. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153147. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153148. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153149. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153150. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153151. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153152. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153153. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153154. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153155. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153156. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153157. 12,
  153158. };
  153159. static float _vq_quantthresh__44un1__p4_0[] = {
  153160. -1.5, -0.5, 0.5, 1.5,
  153161. };
  153162. static long _vq_quantmap__44un1__p4_0[] = {
  153163. 3, 1, 0, 2, 4,
  153164. };
  153165. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153166. _vq_quantthresh__44un1__p4_0,
  153167. _vq_quantmap__44un1__p4_0,
  153168. 5,
  153169. 5
  153170. };
  153171. static static_codebook _44un1__p4_0 = {
  153172. 4, 625,
  153173. _vq_lengthlist__44un1__p4_0,
  153174. 1, -533725184, 1611661312, 3, 0,
  153175. _vq_quantlist__44un1__p4_0,
  153176. NULL,
  153177. &_vq_auxt__44un1__p4_0,
  153178. NULL,
  153179. 0
  153180. };
  153181. static long _vq_quantlist__44un1__p5_0[] = {
  153182. 4,
  153183. 3,
  153184. 5,
  153185. 2,
  153186. 6,
  153187. 1,
  153188. 7,
  153189. 0,
  153190. 8,
  153191. };
  153192. static long _vq_lengthlist__44un1__p5_0[] = {
  153193. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153194. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153195. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153196. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153197. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153198. 12,
  153199. };
  153200. static float _vq_quantthresh__44un1__p5_0[] = {
  153201. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153202. };
  153203. static long _vq_quantmap__44un1__p5_0[] = {
  153204. 7, 5, 3, 1, 0, 2, 4, 6,
  153205. 8,
  153206. };
  153207. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153208. _vq_quantthresh__44un1__p5_0,
  153209. _vq_quantmap__44un1__p5_0,
  153210. 9,
  153211. 9
  153212. };
  153213. static static_codebook _44un1__p5_0 = {
  153214. 2, 81,
  153215. _vq_lengthlist__44un1__p5_0,
  153216. 1, -531628032, 1611661312, 4, 0,
  153217. _vq_quantlist__44un1__p5_0,
  153218. NULL,
  153219. &_vq_auxt__44un1__p5_0,
  153220. NULL,
  153221. 0
  153222. };
  153223. static long _vq_quantlist__44un1__p6_0[] = {
  153224. 6,
  153225. 5,
  153226. 7,
  153227. 4,
  153228. 8,
  153229. 3,
  153230. 9,
  153231. 2,
  153232. 10,
  153233. 1,
  153234. 11,
  153235. 0,
  153236. 12,
  153237. };
  153238. static long _vq_lengthlist__44un1__p6_0[] = {
  153239. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153240. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153241. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153242. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153243. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153244. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153245. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153246. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153247. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153248. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153249. 16, 0,15,18,18, 0,16, 0, 0,
  153250. };
  153251. static float _vq_quantthresh__44un1__p6_0[] = {
  153252. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153253. 12.5, 17.5, 22.5, 27.5,
  153254. };
  153255. static long _vq_quantmap__44un1__p6_0[] = {
  153256. 11, 9, 7, 5, 3, 1, 0, 2,
  153257. 4, 6, 8, 10, 12,
  153258. };
  153259. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153260. _vq_quantthresh__44un1__p6_0,
  153261. _vq_quantmap__44un1__p6_0,
  153262. 13,
  153263. 13
  153264. };
  153265. static static_codebook _44un1__p6_0 = {
  153266. 2, 169,
  153267. _vq_lengthlist__44un1__p6_0,
  153268. 1, -526516224, 1616117760, 4, 0,
  153269. _vq_quantlist__44un1__p6_0,
  153270. NULL,
  153271. &_vq_auxt__44un1__p6_0,
  153272. NULL,
  153273. 0
  153274. };
  153275. static long _vq_quantlist__44un1__p6_1[] = {
  153276. 2,
  153277. 1,
  153278. 3,
  153279. 0,
  153280. 4,
  153281. };
  153282. static long _vq_lengthlist__44un1__p6_1[] = {
  153283. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153284. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153285. };
  153286. static float _vq_quantthresh__44un1__p6_1[] = {
  153287. -1.5, -0.5, 0.5, 1.5,
  153288. };
  153289. static long _vq_quantmap__44un1__p6_1[] = {
  153290. 3, 1, 0, 2, 4,
  153291. };
  153292. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153293. _vq_quantthresh__44un1__p6_1,
  153294. _vq_quantmap__44un1__p6_1,
  153295. 5,
  153296. 5
  153297. };
  153298. static static_codebook _44un1__p6_1 = {
  153299. 2, 25,
  153300. _vq_lengthlist__44un1__p6_1,
  153301. 1, -533725184, 1611661312, 3, 0,
  153302. _vq_quantlist__44un1__p6_1,
  153303. NULL,
  153304. &_vq_auxt__44un1__p6_1,
  153305. NULL,
  153306. 0
  153307. };
  153308. static long _vq_quantlist__44un1__p7_0[] = {
  153309. 2,
  153310. 1,
  153311. 3,
  153312. 0,
  153313. 4,
  153314. };
  153315. static long _vq_lengthlist__44un1__p7_0[] = {
  153316. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153317. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153318. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153319. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153320. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153321. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153322. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153323. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153324. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153325. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153326. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153327. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153328. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153329. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153330. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153331. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153332. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153333. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153334. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153335. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153336. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153337. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153338. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153339. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153340. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153341. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153342. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153343. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153348. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153350. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153351. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153352. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153353. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153354. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153355. 10,
  153356. };
  153357. static float _vq_quantthresh__44un1__p7_0[] = {
  153358. -253.5, -84.5, 84.5, 253.5,
  153359. };
  153360. static long _vq_quantmap__44un1__p7_0[] = {
  153361. 3, 1, 0, 2, 4,
  153362. };
  153363. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153364. _vq_quantthresh__44un1__p7_0,
  153365. _vq_quantmap__44un1__p7_0,
  153366. 5,
  153367. 5
  153368. };
  153369. static static_codebook _44un1__p7_0 = {
  153370. 4, 625,
  153371. _vq_lengthlist__44un1__p7_0,
  153372. 1, -518709248, 1626677248, 3, 0,
  153373. _vq_quantlist__44un1__p7_0,
  153374. NULL,
  153375. &_vq_auxt__44un1__p7_0,
  153376. NULL,
  153377. 0
  153378. };
  153379. static long _vq_quantlist__44un1__p7_1[] = {
  153380. 6,
  153381. 5,
  153382. 7,
  153383. 4,
  153384. 8,
  153385. 3,
  153386. 9,
  153387. 2,
  153388. 10,
  153389. 1,
  153390. 11,
  153391. 0,
  153392. 12,
  153393. };
  153394. static long _vq_lengthlist__44un1__p7_1[] = {
  153395. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153396. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153397. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153398. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153399. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153400. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153401. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153402. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153403. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153404. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153405. 12,13,13,12,13,13,14,14,14,
  153406. };
  153407. static float _vq_quantthresh__44un1__p7_1[] = {
  153408. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153409. 32.5, 45.5, 58.5, 71.5,
  153410. };
  153411. static long _vq_quantmap__44un1__p7_1[] = {
  153412. 11, 9, 7, 5, 3, 1, 0, 2,
  153413. 4, 6, 8, 10, 12,
  153414. };
  153415. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153416. _vq_quantthresh__44un1__p7_1,
  153417. _vq_quantmap__44un1__p7_1,
  153418. 13,
  153419. 13
  153420. };
  153421. static static_codebook _44un1__p7_1 = {
  153422. 2, 169,
  153423. _vq_lengthlist__44un1__p7_1,
  153424. 1, -523010048, 1618608128, 4, 0,
  153425. _vq_quantlist__44un1__p7_1,
  153426. NULL,
  153427. &_vq_auxt__44un1__p7_1,
  153428. NULL,
  153429. 0
  153430. };
  153431. static long _vq_quantlist__44un1__p7_2[] = {
  153432. 6,
  153433. 5,
  153434. 7,
  153435. 4,
  153436. 8,
  153437. 3,
  153438. 9,
  153439. 2,
  153440. 10,
  153441. 1,
  153442. 11,
  153443. 0,
  153444. 12,
  153445. };
  153446. static long _vq_lengthlist__44un1__p7_2[] = {
  153447. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153448. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153449. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153450. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153451. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153452. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153453. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153454. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153455. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153456. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153457. 9, 9, 9,10,10,10,10,10,10,
  153458. };
  153459. static float _vq_quantthresh__44un1__p7_2[] = {
  153460. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153461. 2.5, 3.5, 4.5, 5.5,
  153462. };
  153463. static long _vq_quantmap__44un1__p7_2[] = {
  153464. 11, 9, 7, 5, 3, 1, 0, 2,
  153465. 4, 6, 8, 10, 12,
  153466. };
  153467. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153468. _vq_quantthresh__44un1__p7_2,
  153469. _vq_quantmap__44un1__p7_2,
  153470. 13,
  153471. 13
  153472. };
  153473. static static_codebook _44un1__p7_2 = {
  153474. 2, 169,
  153475. _vq_lengthlist__44un1__p7_2,
  153476. 1, -531103744, 1611661312, 4, 0,
  153477. _vq_quantlist__44un1__p7_2,
  153478. NULL,
  153479. &_vq_auxt__44un1__p7_2,
  153480. NULL,
  153481. 0
  153482. };
  153483. static long _huff_lengthlist__44un1__short[] = {
  153484. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153485. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153486. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153487. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153488. };
  153489. static static_codebook _huff_book__44un1__short = {
  153490. 2, 64,
  153491. _huff_lengthlist__44un1__short,
  153492. 0, 0, 0, 0, 0,
  153493. NULL,
  153494. NULL,
  153495. NULL,
  153496. NULL,
  153497. 0
  153498. };
  153499. /*** End of inlined file: res_books_uncoupled.h ***/
  153500. /***** residue backends *********************************************/
  153501. static vorbis_info_residue0 _residue_44_low_un={
  153502. 0,-1, -1, 8,-1,
  153503. {0},
  153504. {-1},
  153505. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153506. { -1, 25, -1, 45, -1, -1, -1}
  153507. };
  153508. static vorbis_info_residue0 _residue_44_mid_un={
  153509. 0,-1, -1, 10,-1,
  153510. /* 0 1 2 3 4 5 6 7 8 9 */
  153511. {0},
  153512. {-1},
  153513. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153514. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153515. };
  153516. static vorbis_info_residue0 _residue_44_hi_un={
  153517. 0,-1, -1, 10,-1,
  153518. /* 0 1 2 3 4 5 6 7 8 9 */
  153519. {0},
  153520. {-1},
  153521. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153522. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153523. };
  153524. /* mapping conventions:
  153525. only one submap (this would change for efficient 5.1 support for example)*/
  153526. /* Four psychoacoustic profiles are used, one for each blocktype */
  153527. static vorbis_info_mapping0 _map_nominal_u[2]={
  153528. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153529. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153530. };
  153531. static static_bookblock _resbook_44u_n1={
  153532. {
  153533. {0},
  153534. {0,0,&_44un1__p1_0},
  153535. {0,0,&_44un1__p2_0},
  153536. {0,0,&_44un1__p3_0},
  153537. {0,0,&_44un1__p4_0},
  153538. {0,0,&_44un1__p5_0},
  153539. {&_44un1__p6_0,&_44un1__p6_1},
  153540. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153541. }
  153542. };
  153543. static static_bookblock _resbook_44u_0={
  153544. {
  153545. {0},
  153546. {0,0,&_44u0__p1_0},
  153547. {0,0,&_44u0__p2_0},
  153548. {0,0,&_44u0__p3_0},
  153549. {0,0,&_44u0__p4_0},
  153550. {0,0,&_44u0__p5_0},
  153551. {&_44u0__p6_0,&_44u0__p6_1},
  153552. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153553. }
  153554. };
  153555. static static_bookblock _resbook_44u_1={
  153556. {
  153557. {0},
  153558. {0,0,&_44u1__p1_0},
  153559. {0,0,&_44u1__p2_0},
  153560. {0,0,&_44u1__p3_0},
  153561. {0,0,&_44u1__p4_0},
  153562. {0,0,&_44u1__p5_0},
  153563. {&_44u1__p6_0,&_44u1__p6_1},
  153564. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153565. }
  153566. };
  153567. static static_bookblock _resbook_44u_2={
  153568. {
  153569. {0},
  153570. {0,0,&_44u2__p1_0},
  153571. {0,0,&_44u2__p2_0},
  153572. {0,0,&_44u2__p3_0},
  153573. {0,0,&_44u2__p4_0},
  153574. {0,0,&_44u2__p5_0},
  153575. {&_44u2__p6_0,&_44u2__p6_1},
  153576. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153577. }
  153578. };
  153579. static static_bookblock _resbook_44u_3={
  153580. {
  153581. {0},
  153582. {0,0,&_44u3__p1_0},
  153583. {0,0,&_44u3__p2_0},
  153584. {0,0,&_44u3__p3_0},
  153585. {0,0,&_44u3__p4_0},
  153586. {0,0,&_44u3__p5_0},
  153587. {&_44u3__p6_0,&_44u3__p6_1},
  153588. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153589. }
  153590. };
  153591. static static_bookblock _resbook_44u_4={
  153592. {
  153593. {0},
  153594. {0,0,&_44u4__p1_0},
  153595. {0,0,&_44u4__p2_0},
  153596. {0,0,&_44u4__p3_0},
  153597. {0,0,&_44u4__p4_0},
  153598. {0,0,&_44u4__p5_0},
  153599. {&_44u4__p6_0,&_44u4__p6_1},
  153600. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153601. }
  153602. };
  153603. static static_bookblock _resbook_44u_5={
  153604. {
  153605. {0},
  153606. {0,0,&_44u5__p1_0},
  153607. {0,0,&_44u5__p2_0},
  153608. {0,0,&_44u5__p3_0},
  153609. {0,0,&_44u5__p4_0},
  153610. {0,0,&_44u5__p5_0},
  153611. {0,0,&_44u5__p6_0},
  153612. {&_44u5__p7_0,&_44u5__p7_1},
  153613. {&_44u5__p8_0,&_44u5__p8_1},
  153614. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153615. }
  153616. };
  153617. static static_bookblock _resbook_44u_6={
  153618. {
  153619. {0},
  153620. {0,0,&_44u6__p1_0},
  153621. {0,0,&_44u6__p2_0},
  153622. {0,0,&_44u6__p3_0},
  153623. {0,0,&_44u6__p4_0},
  153624. {0,0,&_44u6__p5_0},
  153625. {0,0,&_44u6__p6_0},
  153626. {&_44u6__p7_0,&_44u6__p7_1},
  153627. {&_44u6__p8_0,&_44u6__p8_1},
  153628. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153629. }
  153630. };
  153631. static static_bookblock _resbook_44u_7={
  153632. {
  153633. {0},
  153634. {0,0,&_44u7__p1_0},
  153635. {0,0,&_44u7__p2_0},
  153636. {0,0,&_44u7__p3_0},
  153637. {0,0,&_44u7__p4_0},
  153638. {0,0,&_44u7__p5_0},
  153639. {0,0,&_44u7__p6_0},
  153640. {&_44u7__p7_0,&_44u7__p7_1},
  153641. {&_44u7__p8_0,&_44u7__p8_1},
  153642. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153643. }
  153644. };
  153645. static static_bookblock _resbook_44u_8={
  153646. {
  153647. {0},
  153648. {0,0,&_44u8_p1_0},
  153649. {0,0,&_44u8_p2_0},
  153650. {0,0,&_44u8_p3_0},
  153651. {0,0,&_44u8_p4_0},
  153652. {&_44u8_p5_0,&_44u8_p5_1},
  153653. {&_44u8_p6_0,&_44u8_p6_1},
  153654. {&_44u8_p7_0,&_44u8_p7_1},
  153655. {&_44u8_p8_0,&_44u8_p8_1},
  153656. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153657. }
  153658. };
  153659. static static_bookblock _resbook_44u_9={
  153660. {
  153661. {0},
  153662. {0,0,&_44u9_p1_0},
  153663. {0,0,&_44u9_p2_0},
  153664. {0,0,&_44u9_p3_0},
  153665. {0,0,&_44u9_p4_0},
  153666. {&_44u9_p5_0,&_44u9_p5_1},
  153667. {&_44u9_p6_0,&_44u9_p6_1},
  153668. {&_44u9_p7_0,&_44u9_p7_1},
  153669. {&_44u9_p8_0,&_44u9_p8_1},
  153670. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153671. }
  153672. };
  153673. static vorbis_residue_template _res_44u_n1[]={
  153674. {1,0, &_residue_44_low_un,
  153675. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153676. &_resbook_44u_n1,&_resbook_44u_n1},
  153677. {1,0, &_residue_44_low_un,
  153678. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153679. &_resbook_44u_n1,&_resbook_44u_n1}
  153680. };
  153681. static vorbis_residue_template _res_44u_0[]={
  153682. {1,0, &_residue_44_low_un,
  153683. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153684. &_resbook_44u_0,&_resbook_44u_0},
  153685. {1,0, &_residue_44_low_un,
  153686. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153687. &_resbook_44u_0,&_resbook_44u_0}
  153688. };
  153689. static vorbis_residue_template _res_44u_1[]={
  153690. {1,0, &_residue_44_low_un,
  153691. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153692. &_resbook_44u_1,&_resbook_44u_1},
  153693. {1,0, &_residue_44_low_un,
  153694. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153695. &_resbook_44u_1,&_resbook_44u_1}
  153696. };
  153697. static vorbis_residue_template _res_44u_2[]={
  153698. {1,0, &_residue_44_low_un,
  153699. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153700. &_resbook_44u_2,&_resbook_44u_2},
  153701. {1,0, &_residue_44_low_un,
  153702. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153703. &_resbook_44u_2,&_resbook_44u_2}
  153704. };
  153705. static vorbis_residue_template _res_44u_3[]={
  153706. {1,0, &_residue_44_low_un,
  153707. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153708. &_resbook_44u_3,&_resbook_44u_3},
  153709. {1,0, &_residue_44_low_un,
  153710. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153711. &_resbook_44u_3,&_resbook_44u_3}
  153712. };
  153713. static vorbis_residue_template _res_44u_4[]={
  153714. {1,0, &_residue_44_low_un,
  153715. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153716. &_resbook_44u_4,&_resbook_44u_4},
  153717. {1,0, &_residue_44_low_un,
  153718. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153719. &_resbook_44u_4,&_resbook_44u_4}
  153720. };
  153721. static vorbis_residue_template _res_44u_5[]={
  153722. {1,0, &_residue_44_mid_un,
  153723. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153724. &_resbook_44u_5,&_resbook_44u_5},
  153725. {1,0, &_residue_44_mid_un,
  153726. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153727. &_resbook_44u_5,&_resbook_44u_5}
  153728. };
  153729. static vorbis_residue_template _res_44u_6[]={
  153730. {1,0, &_residue_44_mid_un,
  153731. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153732. &_resbook_44u_6,&_resbook_44u_6},
  153733. {1,0, &_residue_44_mid_un,
  153734. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153735. &_resbook_44u_6,&_resbook_44u_6}
  153736. };
  153737. static vorbis_residue_template _res_44u_7[]={
  153738. {1,0, &_residue_44_mid_un,
  153739. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153740. &_resbook_44u_7,&_resbook_44u_7},
  153741. {1,0, &_residue_44_mid_un,
  153742. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153743. &_resbook_44u_7,&_resbook_44u_7}
  153744. };
  153745. static vorbis_residue_template _res_44u_8[]={
  153746. {1,0, &_residue_44_hi_un,
  153747. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153748. &_resbook_44u_8,&_resbook_44u_8},
  153749. {1,0, &_residue_44_hi_un,
  153750. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153751. &_resbook_44u_8,&_resbook_44u_8}
  153752. };
  153753. static vorbis_residue_template _res_44u_9[]={
  153754. {1,0, &_residue_44_hi_un,
  153755. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153756. &_resbook_44u_9,&_resbook_44u_9},
  153757. {1,0, &_residue_44_hi_un,
  153758. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153759. &_resbook_44u_9,&_resbook_44u_9}
  153760. };
  153761. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153762. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153763. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153764. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153765. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153766. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153767. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153768. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153769. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153770. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153771. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153772. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153773. };
  153774. /*** End of inlined file: residue_44u.h ***/
  153775. static double rate_mapping_44_un[12]={
  153776. 32000.,48000.,60000.,70000.,80000.,86000.,
  153777. 96000.,110000.,120000.,140000.,160000.,240001.
  153778. };
  153779. ve_setup_data_template ve_setup_44_uncoupled={
  153780. 11,
  153781. rate_mapping_44_un,
  153782. quality_mapping_44,
  153783. -1,
  153784. 40000,
  153785. 50000,
  153786. blocksize_short_44,
  153787. blocksize_long_44,
  153788. _psy_tone_masteratt_44,
  153789. _psy_tone_0dB,
  153790. _psy_tone_suppress,
  153791. _vp_tonemask_adj_otherblock,
  153792. _vp_tonemask_adj_longblock,
  153793. _vp_tonemask_adj_otherblock,
  153794. _psy_noiseguards_44,
  153795. _psy_noisebias_impulse,
  153796. _psy_noisebias_padding,
  153797. _psy_noisebias_trans,
  153798. _psy_noisebias_long,
  153799. _psy_noise_suppress,
  153800. _psy_compand_44,
  153801. _psy_compand_short_mapping,
  153802. _psy_compand_long_mapping,
  153803. {_noise_start_short_44,_noise_start_long_44},
  153804. {_noise_part_short_44,_noise_part_long_44},
  153805. _noise_thresh_44,
  153806. _psy_ath_floater,
  153807. _psy_ath_abs,
  153808. _psy_lowpass_44,
  153809. _psy_global_44,
  153810. _global_mapping_44,
  153811. NULL,
  153812. _floor_books,
  153813. _floor,
  153814. _floor_short_mapping_44,
  153815. _floor_long_mapping_44,
  153816. _mapres_template_44_uncoupled
  153817. };
  153818. /*** End of inlined file: setup_44u.h ***/
  153819. /*** Start of inlined file: setup_32.h ***/
  153820. static double rate_mapping_32[12]={
  153821. 18000.,28000.,35000.,45000.,56000.,60000.,
  153822. 75000.,90000.,100000.,115000.,150000.,190000.,
  153823. };
  153824. static double rate_mapping_32_un[12]={
  153825. 30000.,42000.,52000.,64000.,72000.,78000.,
  153826. 86000.,92000.,110000.,120000.,140000.,190000.,
  153827. };
  153828. static double _psy_lowpass_32[12]={
  153829. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153830. };
  153831. ve_setup_data_template ve_setup_32_stereo={
  153832. 11,
  153833. rate_mapping_32,
  153834. quality_mapping_44,
  153835. 2,
  153836. 26000,
  153837. 40000,
  153838. blocksize_short_44,
  153839. blocksize_long_44,
  153840. _psy_tone_masteratt_44,
  153841. _psy_tone_0dB,
  153842. _psy_tone_suppress,
  153843. _vp_tonemask_adj_otherblock,
  153844. _vp_tonemask_adj_longblock,
  153845. _vp_tonemask_adj_otherblock,
  153846. _psy_noiseguards_44,
  153847. _psy_noisebias_impulse,
  153848. _psy_noisebias_padding,
  153849. _psy_noisebias_trans,
  153850. _psy_noisebias_long,
  153851. _psy_noise_suppress,
  153852. _psy_compand_44,
  153853. _psy_compand_short_mapping,
  153854. _psy_compand_long_mapping,
  153855. {_noise_start_short_44,_noise_start_long_44},
  153856. {_noise_part_short_44,_noise_part_long_44},
  153857. _noise_thresh_44,
  153858. _psy_ath_floater,
  153859. _psy_ath_abs,
  153860. _psy_lowpass_32,
  153861. _psy_global_44,
  153862. _global_mapping_44,
  153863. _psy_stereo_modes_44,
  153864. _floor_books,
  153865. _floor,
  153866. _floor_short_mapping_44,
  153867. _floor_long_mapping_44,
  153868. _mapres_template_44_stereo
  153869. };
  153870. ve_setup_data_template ve_setup_32_uncoupled={
  153871. 11,
  153872. rate_mapping_32_un,
  153873. quality_mapping_44,
  153874. -1,
  153875. 26000,
  153876. 40000,
  153877. blocksize_short_44,
  153878. blocksize_long_44,
  153879. _psy_tone_masteratt_44,
  153880. _psy_tone_0dB,
  153881. _psy_tone_suppress,
  153882. _vp_tonemask_adj_otherblock,
  153883. _vp_tonemask_adj_longblock,
  153884. _vp_tonemask_adj_otherblock,
  153885. _psy_noiseguards_44,
  153886. _psy_noisebias_impulse,
  153887. _psy_noisebias_padding,
  153888. _psy_noisebias_trans,
  153889. _psy_noisebias_long,
  153890. _psy_noise_suppress,
  153891. _psy_compand_44,
  153892. _psy_compand_short_mapping,
  153893. _psy_compand_long_mapping,
  153894. {_noise_start_short_44,_noise_start_long_44},
  153895. {_noise_part_short_44,_noise_part_long_44},
  153896. _noise_thresh_44,
  153897. _psy_ath_floater,
  153898. _psy_ath_abs,
  153899. _psy_lowpass_32,
  153900. _psy_global_44,
  153901. _global_mapping_44,
  153902. NULL,
  153903. _floor_books,
  153904. _floor,
  153905. _floor_short_mapping_44,
  153906. _floor_long_mapping_44,
  153907. _mapres_template_44_uncoupled
  153908. };
  153909. /*** End of inlined file: setup_32.h ***/
  153910. /*** Start of inlined file: setup_8.h ***/
  153911. /*** Start of inlined file: psych_8.h ***/
  153912. static att3 _psy_tone_masteratt_8[3]={
  153913. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153914. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153915. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153916. };
  153917. static vp_adjblock _vp_tonemask_adj_8[3]={
  153918. /* adjust for mode zero */
  153919. /* 63 125 250 500 1 2 4 8 16 */
  153920. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153921. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153922. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153923. };
  153924. static noise3 _psy_noisebias_8[3]={
  153925. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153926. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153927. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153928. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153929. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153930. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153931. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153932. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153933. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153934. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153935. };
  153936. /* stereo mode by base quality level */
  153937. static adj_stereo _psy_stereo_modes_8[3]={
  153938. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153939. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153940. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153941. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153942. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153943. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153944. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153945. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153946. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153947. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153948. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153949. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153950. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153951. };
  153952. static noiseguard _psy_noiseguards_8[2]={
  153953. {10,10,-1},
  153954. {10,10,-1},
  153955. };
  153956. static compandblock _psy_compand_8[2]={
  153957. {{
  153958. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153959. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153960. 12,12,13,13,14,14,15, 15, /* 23dB */
  153961. 16,16,17,17,17,18,18, 19, /* 31dB */
  153962. 19,19,20,21,22,23,24, 25, /* 39dB */
  153963. }},
  153964. {{
  153965. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153966. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153967. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153968. 9,10,11,12,13,14,15, 16, /* 31dB */
  153969. 17,18,19,20,21,22,23, 24, /* 39dB */
  153970. }},
  153971. };
  153972. static double _psy_lowpass_8[3]={3.,4.,4.};
  153973. static int _noise_start_8[2]={
  153974. 64,64,
  153975. };
  153976. static int _noise_part_8[2]={
  153977. 8,8,
  153978. };
  153979. static int _psy_ath_floater_8[3]={
  153980. -100,-100,-105,
  153981. };
  153982. static int _psy_ath_abs_8[3]={
  153983. -130,-130,-140,
  153984. };
  153985. /*** End of inlined file: psych_8.h ***/
  153986. /*** Start of inlined file: residue_8.h ***/
  153987. /***** residue backends *********************************************/
  153988. static static_bookblock _resbook_8s_0={
  153989. {
  153990. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153991. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153992. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153993. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153994. }
  153995. };
  153996. static static_bookblock _resbook_8s_1={
  153997. {
  153998. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153999. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  154000. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  154001. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  154002. }
  154003. };
  154004. static vorbis_residue_template _res_8s_0[]={
  154005. {2,0, &_residue_44_mid,
  154006. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  154007. &_resbook_8s_0,&_resbook_8s_0},
  154008. };
  154009. static vorbis_residue_template _res_8s_1[]={
  154010. {2,0, &_residue_44_mid,
  154011. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  154012. &_resbook_8s_1,&_resbook_8s_1},
  154013. };
  154014. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  154015. { _map_nominal, _res_8s_0 }, /* 0 */
  154016. { _map_nominal, _res_8s_1 }, /* 1 */
  154017. };
  154018. static static_bookblock _resbook_8u_0={
  154019. {
  154020. {0},
  154021. {0,0,&_8u0__p1_0},
  154022. {0,0,&_8u0__p2_0},
  154023. {0,0,&_8u0__p3_0},
  154024. {0,0,&_8u0__p4_0},
  154025. {0,0,&_8u0__p5_0},
  154026. {&_8u0__p6_0,&_8u0__p6_1},
  154027. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  154028. }
  154029. };
  154030. static static_bookblock _resbook_8u_1={
  154031. {
  154032. {0},
  154033. {0,0,&_8u1__p1_0},
  154034. {0,0,&_8u1__p2_0},
  154035. {0,0,&_8u1__p3_0},
  154036. {0,0,&_8u1__p4_0},
  154037. {0,0,&_8u1__p5_0},
  154038. {0,0,&_8u1__p6_0},
  154039. {&_8u1__p7_0,&_8u1__p7_1},
  154040. {&_8u1__p8_0,&_8u1__p8_1},
  154041. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  154042. }
  154043. };
  154044. static vorbis_residue_template _res_8u_0[]={
  154045. {1,0, &_residue_44_low_un,
  154046. &_huff_book__8u0__single,&_huff_book__8u0__single,
  154047. &_resbook_8u_0,&_resbook_8u_0},
  154048. };
  154049. static vorbis_residue_template _res_8u_1[]={
  154050. {1,0, &_residue_44_mid_un,
  154051. &_huff_book__8u1__single,&_huff_book__8u1__single,
  154052. &_resbook_8u_1,&_resbook_8u_1},
  154053. };
  154054. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  154055. { _map_nominal_u, _res_8u_0 }, /* 0 */
  154056. { _map_nominal_u, _res_8u_1 }, /* 1 */
  154057. };
  154058. /*** End of inlined file: residue_8.h ***/
  154059. static int blocksize_8[2]={
  154060. 512,512
  154061. };
  154062. static int _floor_mapping_8[2]={
  154063. 6,6,
  154064. };
  154065. static double rate_mapping_8[3]={
  154066. 6000.,9000.,32000.,
  154067. };
  154068. static double rate_mapping_8_uncoupled[3]={
  154069. 8000.,14000.,42000.,
  154070. };
  154071. static double quality_mapping_8[3]={
  154072. -.1,.0,1.
  154073. };
  154074. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  154075. static double _global_mapping_8[3]={ 1., 2., 3. };
  154076. ve_setup_data_template ve_setup_8_stereo={
  154077. 2,
  154078. rate_mapping_8,
  154079. quality_mapping_8,
  154080. 2,
  154081. 8000,
  154082. 9000,
  154083. blocksize_8,
  154084. blocksize_8,
  154085. _psy_tone_masteratt_8,
  154086. _psy_tone_0dB,
  154087. _psy_tone_suppress,
  154088. _vp_tonemask_adj_8,
  154089. NULL,
  154090. _vp_tonemask_adj_8,
  154091. _psy_noiseguards_8,
  154092. _psy_noisebias_8,
  154093. _psy_noisebias_8,
  154094. NULL,
  154095. NULL,
  154096. _psy_noise_suppress,
  154097. _psy_compand_8,
  154098. _psy_compand_8_mapping,
  154099. NULL,
  154100. {_noise_start_8,_noise_start_8},
  154101. {_noise_part_8,_noise_part_8},
  154102. _noise_thresh_5only,
  154103. _psy_ath_floater_8,
  154104. _psy_ath_abs_8,
  154105. _psy_lowpass_8,
  154106. _psy_global_44,
  154107. _global_mapping_8,
  154108. _psy_stereo_modes_8,
  154109. _floor_books,
  154110. _floor,
  154111. _floor_mapping_8,
  154112. NULL,
  154113. _mapres_template_8_stereo
  154114. };
  154115. ve_setup_data_template ve_setup_8_uncoupled={
  154116. 2,
  154117. rate_mapping_8_uncoupled,
  154118. quality_mapping_8,
  154119. -1,
  154120. 8000,
  154121. 9000,
  154122. blocksize_8,
  154123. blocksize_8,
  154124. _psy_tone_masteratt_8,
  154125. _psy_tone_0dB,
  154126. _psy_tone_suppress,
  154127. _vp_tonemask_adj_8,
  154128. NULL,
  154129. _vp_tonemask_adj_8,
  154130. _psy_noiseguards_8,
  154131. _psy_noisebias_8,
  154132. _psy_noisebias_8,
  154133. NULL,
  154134. NULL,
  154135. _psy_noise_suppress,
  154136. _psy_compand_8,
  154137. _psy_compand_8_mapping,
  154138. NULL,
  154139. {_noise_start_8,_noise_start_8},
  154140. {_noise_part_8,_noise_part_8},
  154141. _noise_thresh_5only,
  154142. _psy_ath_floater_8,
  154143. _psy_ath_abs_8,
  154144. _psy_lowpass_8,
  154145. _psy_global_44,
  154146. _global_mapping_8,
  154147. _psy_stereo_modes_8,
  154148. _floor_books,
  154149. _floor,
  154150. _floor_mapping_8,
  154151. NULL,
  154152. _mapres_template_8_uncoupled
  154153. };
  154154. /*** End of inlined file: setup_8.h ***/
  154155. /*** Start of inlined file: setup_11.h ***/
  154156. /*** Start of inlined file: psych_11.h ***/
  154157. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154158. static att3 _psy_tone_masteratt_11[3]={
  154159. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154160. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154161. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154162. };
  154163. static vp_adjblock _vp_tonemask_adj_11[3]={
  154164. /* adjust for mode zero */
  154165. /* 63 125 250 500 1 2 4 8 16 */
  154166. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154167. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154168. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154169. };
  154170. static noise3 _psy_noisebias_11[3]={
  154171. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154172. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154173. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154174. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154175. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154176. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154177. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154178. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154179. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154180. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154181. };
  154182. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154183. /*** End of inlined file: psych_11.h ***/
  154184. static int blocksize_11[2]={
  154185. 512,512
  154186. };
  154187. static int _floor_mapping_11[2]={
  154188. 6,6,
  154189. };
  154190. static double rate_mapping_11[3]={
  154191. 8000.,13000.,44000.,
  154192. };
  154193. static double rate_mapping_11_uncoupled[3]={
  154194. 12000.,20000.,50000.,
  154195. };
  154196. static double quality_mapping_11[3]={
  154197. -.1,.0,1.
  154198. };
  154199. ve_setup_data_template ve_setup_11_stereo={
  154200. 2,
  154201. rate_mapping_11,
  154202. quality_mapping_11,
  154203. 2,
  154204. 9000,
  154205. 15000,
  154206. blocksize_11,
  154207. blocksize_11,
  154208. _psy_tone_masteratt_11,
  154209. _psy_tone_0dB,
  154210. _psy_tone_suppress,
  154211. _vp_tonemask_adj_11,
  154212. NULL,
  154213. _vp_tonemask_adj_11,
  154214. _psy_noiseguards_8,
  154215. _psy_noisebias_11,
  154216. _psy_noisebias_11,
  154217. NULL,
  154218. NULL,
  154219. _psy_noise_suppress,
  154220. _psy_compand_8,
  154221. _psy_compand_8_mapping,
  154222. NULL,
  154223. {_noise_start_8,_noise_start_8},
  154224. {_noise_part_8,_noise_part_8},
  154225. _noise_thresh_11,
  154226. _psy_ath_floater_8,
  154227. _psy_ath_abs_8,
  154228. _psy_lowpass_11,
  154229. _psy_global_44,
  154230. _global_mapping_8,
  154231. _psy_stereo_modes_8,
  154232. _floor_books,
  154233. _floor,
  154234. _floor_mapping_11,
  154235. NULL,
  154236. _mapres_template_8_stereo
  154237. };
  154238. ve_setup_data_template ve_setup_11_uncoupled={
  154239. 2,
  154240. rate_mapping_11_uncoupled,
  154241. quality_mapping_11,
  154242. -1,
  154243. 9000,
  154244. 15000,
  154245. blocksize_11,
  154246. blocksize_11,
  154247. _psy_tone_masteratt_11,
  154248. _psy_tone_0dB,
  154249. _psy_tone_suppress,
  154250. _vp_tonemask_adj_11,
  154251. NULL,
  154252. _vp_tonemask_adj_11,
  154253. _psy_noiseguards_8,
  154254. _psy_noisebias_11,
  154255. _psy_noisebias_11,
  154256. NULL,
  154257. NULL,
  154258. _psy_noise_suppress,
  154259. _psy_compand_8,
  154260. _psy_compand_8_mapping,
  154261. NULL,
  154262. {_noise_start_8,_noise_start_8},
  154263. {_noise_part_8,_noise_part_8},
  154264. _noise_thresh_11,
  154265. _psy_ath_floater_8,
  154266. _psy_ath_abs_8,
  154267. _psy_lowpass_11,
  154268. _psy_global_44,
  154269. _global_mapping_8,
  154270. _psy_stereo_modes_8,
  154271. _floor_books,
  154272. _floor,
  154273. _floor_mapping_11,
  154274. NULL,
  154275. _mapres_template_8_uncoupled
  154276. };
  154277. /*** End of inlined file: setup_11.h ***/
  154278. /*** Start of inlined file: setup_16.h ***/
  154279. /*** Start of inlined file: psych_16.h ***/
  154280. /* stereo mode by base quality level */
  154281. static adj_stereo _psy_stereo_modes_16[4]={
  154282. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154283. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154284. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154285. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154286. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154287. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154288. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154289. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154290. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154291. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154292. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154293. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154294. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154295. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154296. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154297. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154298. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154299. };
  154300. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154301. static att3 _psy_tone_masteratt_16[4]={
  154302. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154303. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154304. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154305. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154306. };
  154307. static vp_adjblock _vp_tonemask_adj_16[4]={
  154308. /* adjust for mode zero */
  154309. /* 63 125 250 500 1 2 4 8 16 */
  154310. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154311. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154312. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154313. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154314. };
  154315. static noise3 _psy_noisebias_16_short[4]={
  154316. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154317. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154318. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154319. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154320. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154321. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154322. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154323. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154324. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154325. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154326. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154327. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154328. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154329. };
  154330. static noise3 _psy_noisebias_16_impulse[4]={
  154331. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154332. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154333. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154334. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154335. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154336. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154337. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154338. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154339. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154340. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154341. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154342. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154343. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154344. };
  154345. static noise3 _psy_noisebias_16[4]={
  154346. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154347. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154348. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154349. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154350. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154351. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154352. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154353. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154354. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154355. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154356. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154357. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154358. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154359. };
  154360. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154361. static int _noise_start_16[3]={ 256,256,9999 };
  154362. static int _noise_part_16[4]={ 8,8,8,8 };
  154363. static int _psy_ath_floater_16[4]={
  154364. -100,-100,-100,-105,
  154365. };
  154366. static int _psy_ath_abs_16[4]={
  154367. -130,-130,-130,-140,
  154368. };
  154369. /*** End of inlined file: psych_16.h ***/
  154370. /*** Start of inlined file: residue_16.h ***/
  154371. /***** residue backends *********************************************/
  154372. static static_bookblock _resbook_16s_0={
  154373. {
  154374. {0},
  154375. {0,0,&_16c0_s_p1_0},
  154376. {0,0,&_16c0_s_p2_0},
  154377. {0,0,&_16c0_s_p3_0},
  154378. {0,0,&_16c0_s_p4_0},
  154379. {0,0,&_16c0_s_p5_0},
  154380. {0,0,&_16c0_s_p6_0},
  154381. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154382. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154383. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154384. }
  154385. };
  154386. static static_bookblock _resbook_16s_1={
  154387. {
  154388. {0},
  154389. {0,0,&_16c1_s_p1_0},
  154390. {0,0,&_16c1_s_p2_0},
  154391. {0,0,&_16c1_s_p3_0},
  154392. {0,0,&_16c1_s_p4_0},
  154393. {0,0,&_16c1_s_p5_0},
  154394. {0,0,&_16c1_s_p6_0},
  154395. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154396. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154397. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154398. }
  154399. };
  154400. static static_bookblock _resbook_16s_2={
  154401. {
  154402. {0},
  154403. {0,0,&_16c2_s_p1_0},
  154404. {0,0,&_16c2_s_p2_0},
  154405. {0,0,&_16c2_s_p3_0},
  154406. {0,0,&_16c2_s_p4_0},
  154407. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154408. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154409. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154410. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154411. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154412. }
  154413. };
  154414. static vorbis_residue_template _res_16s_0[]={
  154415. {2,0, &_residue_44_mid,
  154416. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154417. &_resbook_16s_0,&_resbook_16s_0},
  154418. };
  154419. static vorbis_residue_template _res_16s_1[]={
  154420. {2,0, &_residue_44_mid,
  154421. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154422. &_resbook_16s_1,&_resbook_16s_1},
  154423. {2,0, &_residue_44_mid,
  154424. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154425. &_resbook_16s_1,&_resbook_16s_1}
  154426. };
  154427. static vorbis_residue_template _res_16s_2[]={
  154428. {2,0, &_residue_44_high,
  154429. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154430. &_resbook_16s_2,&_resbook_16s_2},
  154431. {2,0, &_residue_44_high,
  154432. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154433. &_resbook_16s_2,&_resbook_16s_2}
  154434. };
  154435. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154436. { _map_nominal, _res_16s_0 }, /* 0 */
  154437. { _map_nominal, _res_16s_1 }, /* 1 */
  154438. { _map_nominal, _res_16s_2 }, /* 2 */
  154439. };
  154440. static static_bookblock _resbook_16u_0={
  154441. {
  154442. {0},
  154443. {0,0,&_16u0__p1_0},
  154444. {0,0,&_16u0__p2_0},
  154445. {0,0,&_16u0__p3_0},
  154446. {0,0,&_16u0__p4_0},
  154447. {0,0,&_16u0__p5_0},
  154448. {&_16u0__p6_0,&_16u0__p6_1},
  154449. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154450. }
  154451. };
  154452. static static_bookblock _resbook_16u_1={
  154453. {
  154454. {0},
  154455. {0,0,&_16u1__p1_0},
  154456. {0,0,&_16u1__p2_0},
  154457. {0,0,&_16u1__p3_0},
  154458. {0,0,&_16u1__p4_0},
  154459. {0,0,&_16u1__p5_0},
  154460. {0,0,&_16u1__p6_0},
  154461. {&_16u1__p7_0,&_16u1__p7_1},
  154462. {&_16u1__p8_0,&_16u1__p8_1},
  154463. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154464. }
  154465. };
  154466. static static_bookblock _resbook_16u_2={
  154467. {
  154468. {0},
  154469. {0,0,&_16u2_p1_0},
  154470. {0,0,&_16u2_p2_0},
  154471. {0,0,&_16u2_p3_0},
  154472. {0,0,&_16u2_p4_0},
  154473. {&_16u2_p5_0,&_16u2_p5_1},
  154474. {&_16u2_p6_0,&_16u2_p6_1},
  154475. {&_16u2_p7_0,&_16u2_p7_1},
  154476. {&_16u2_p8_0,&_16u2_p8_1},
  154477. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154478. }
  154479. };
  154480. static vorbis_residue_template _res_16u_0[]={
  154481. {1,0, &_residue_44_low_un,
  154482. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154483. &_resbook_16u_0,&_resbook_16u_0},
  154484. };
  154485. static vorbis_residue_template _res_16u_1[]={
  154486. {1,0, &_residue_44_mid_un,
  154487. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154488. &_resbook_16u_1,&_resbook_16u_1},
  154489. {1,0, &_residue_44_mid_un,
  154490. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154491. &_resbook_16u_1,&_resbook_16u_1}
  154492. };
  154493. static vorbis_residue_template _res_16u_2[]={
  154494. {1,0, &_residue_44_hi_un,
  154495. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154496. &_resbook_16u_2,&_resbook_16u_2},
  154497. {1,0, &_residue_44_hi_un,
  154498. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154499. &_resbook_16u_2,&_resbook_16u_2}
  154500. };
  154501. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154502. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154503. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154504. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154505. };
  154506. /*** End of inlined file: residue_16.h ***/
  154507. static int blocksize_16_short[3]={
  154508. 1024,512,512
  154509. };
  154510. static int blocksize_16_long[3]={
  154511. 1024,1024,1024
  154512. };
  154513. static int _floor_mapping_16_short[3]={
  154514. 9,3,3
  154515. };
  154516. static int _floor_mapping_16[3]={
  154517. 9,9,9
  154518. };
  154519. static double rate_mapping_16[4]={
  154520. 12000.,20000.,44000.,86000.
  154521. };
  154522. static double rate_mapping_16_uncoupled[4]={
  154523. 16000.,28000.,64000.,100000.
  154524. };
  154525. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154526. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154527. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154528. ve_setup_data_template ve_setup_16_stereo={
  154529. 3,
  154530. rate_mapping_16,
  154531. quality_mapping_16,
  154532. 2,
  154533. 15000,
  154534. 19000,
  154535. blocksize_16_short,
  154536. blocksize_16_long,
  154537. _psy_tone_masteratt_16,
  154538. _psy_tone_0dB,
  154539. _psy_tone_suppress,
  154540. _vp_tonemask_adj_16,
  154541. _vp_tonemask_adj_16,
  154542. _vp_tonemask_adj_16,
  154543. _psy_noiseguards_8,
  154544. _psy_noisebias_16_impulse,
  154545. _psy_noisebias_16_short,
  154546. _psy_noisebias_16_short,
  154547. _psy_noisebias_16,
  154548. _psy_noise_suppress,
  154549. _psy_compand_8,
  154550. _psy_compand_16_mapping,
  154551. _psy_compand_16_mapping,
  154552. {_noise_start_16,_noise_start_16},
  154553. { _noise_part_16, _noise_part_16},
  154554. _noise_thresh_16,
  154555. _psy_ath_floater_16,
  154556. _psy_ath_abs_16,
  154557. _psy_lowpass_16,
  154558. _psy_global_44,
  154559. _global_mapping_16,
  154560. _psy_stereo_modes_16,
  154561. _floor_books,
  154562. _floor,
  154563. _floor_mapping_16_short,
  154564. _floor_mapping_16,
  154565. _mapres_template_16_stereo
  154566. };
  154567. ve_setup_data_template ve_setup_16_uncoupled={
  154568. 3,
  154569. rate_mapping_16_uncoupled,
  154570. quality_mapping_16,
  154571. -1,
  154572. 15000,
  154573. 19000,
  154574. blocksize_16_short,
  154575. blocksize_16_long,
  154576. _psy_tone_masteratt_16,
  154577. _psy_tone_0dB,
  154578. _psy_tone_suppress,
  154579. _vp_tonemask_adj_16,
  154580. _vp_tonemask_adj_16,
  154581. _vp_tonemask_adj_16,
  154582. _psy_noiseguards_8,
  154583. _psy_noisebias_16_impulse,
  154584. _psy_noisebias_16_short,
  154585. _psy_noisebias_16_short,
  154586. _psy_noisebias_16,
  154587. _psy_noise_suppress,
  154588. _psy_compand_8,
  154589. _psy_compand_16_mapping,
  154590. _psy_compand_16_mapping,
  154591. {_noise_start_16,_noise_start_16},
  154592. { _noise_part_16, _noise_part_16},
  154593. _noise_thresh_16,
  154594. _psy_ath_floater_16,
  154595. _psy_ath_abs_16,
  154596. _psy_lowpass_16,
  154597. _psy_global_44,
  154598. _global_mapping_16,
  154599. _psy_stereo_modes_16,
  154600. _floor_books,
  154601. _floor,
  154602. _floor_mapping_16_short,
  154603. _floor_mapping_16,
  154604. _mapres_template_16_uncoupled
  154605. };
  154606. /*** End of inlined file: setup_16.h ***/
  154607. /*** Start of inlined file: setup_22.h ***/
  154608. static double rate_mapping_22[4]={
  154609. 15000.,20000.,44000.,86000.
  154610. };
  154611. static double rate_mapping_22_uncoupled[4]={
  154612. 16000.,28000.,50000.,90000.
  154613. };
  154614. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154615. ve_setup_data_template ve_setup_22_stereo={
  154616. 3,
  154617. rate_mapping_22,
  154618. quality_mapping_16,
  154619. 2,
  154620. 19000,
  154621. 26000,
  154622. blocksize_16_short,
  154623. blocksize_16_long,
  154624. _psy_tone_masteratt_16,
  154625. _psy_tone_0dB,
  154626. _psy_tone_suppress,
  154627. _vp_tonemask_adj_16,
  154628. _vp_tonemask_adj_16,
  154629. _vp_tonemask_adj_16,
  154630. _psy_noiseguards_8,
  154631. _psy_noisebias_16_impulse,
  154632. _psy_noisebias_16_short,
  154633. _psy_noisebias_16_short,
  154634. _psy_noisebias_16,
  154635. _psy_noise_suppress,
  154636. _psy_compand_8,
  154637. _psy_compand_8_mapping,
  154638. _psy_compand_8_mapping,
  154639. {_noise_start_16,_noise_start_16},
  154640. { _noise_part_16, _noise_part_16},
  154641. _noise_thresh_16,
  154642. _psy_ath_floater_16,
  154643. _psy_ath_abs_16,
  154644. _psy_lowpass_22,
  154645. _psy_global_44,
  154646. _global_mapping_16,
  154647. _psy_stereo_modes_16,
  154648. _floor_books,
  154649. _floor,
  154650. _floor_mapping_16_short,
  154651. _floor_mapping_16,
  154652. _mapres_template_16_stereo
  154653. };
  154654. ve_setup_data_template ve_setup_22_uncoupled={
  154655. 3,
  154656. rate_mapping_22_uncoupled,
  154657. quality_mapping_16,
  154658. -1,
  154659. 19000,
  154660. 26000,
  154661. blocksize_16_short,
  154662. blocksize_16_long,
  154663. _psy_tone_masteratt_16,
  154664. _psy_tone_0dB,
  154665. _psy_tone_suppress,
  154666. _vp_tonemask_adj_16,
  154667. _vp_tonemask_adj_16,
  154668. _vp_tonemask_adj_16,
  154669. _psy_noiseguards_8,
  154670. _psy_noisebias_16_impulse,
  154671. _psy_noisebias_16_short,
  154672. _psy_noisebias_16_short,
  154673. _psy_noisebias_16,
  154674. _psy_noise_suppress,
  154675. _psy_compand_8,
  154676. _psy_compand_8_mapping,
  154677. _psy_compand_8_mapping,
  154678. {_noise_start_16,_noise_start_16},
  154679. { _noise_part_16, _noise_part_16},
  154680. _noise_thresh_16,
  154681. _psy_ath_floater_16,
  154682. _psy_ath_abs_16,
  154683. _psy_lowpass_22,
  154684. _psy_global_44,
  154685. _global_mapping_16,
  154686. _psy_stereo_modes_16,
  154687. _floor_books,
  154688. _floor,
  154689. _floor_mapping_16_short,
  154690. _floor_mapping_16,
  154691. _mapres_template_16_uncoupled
  154692. };
  154693. /*** End of inlined file: setup_22.h ***/
  154694. /*** Start of inlined file: setup_X.h ***/
  154695. static double rate_mapping_X[12]={
  154696. -1.,-1.,-1.,-1.,-1.,-1.,
  154697. -1.,-1.,-1.,-1.,-1.,-1.
  154698. };
  154699. ve_setup_data_template ve_setup_X_stereo={
  154700. 11,
  154701. rate_mapping_X,
  154702. quality_mapping_44,
  154703. 2,
  154704. 50000,
  154705. 200000,
  154706. blocksize_short_44,
  154707. blocksize_long_44,
  154708. _psy_tone_masteratt_44,
  154709. _psy_tone_0dB,
  154710. _psy_tone_suppress,
  154711. _vp_tonemask_adj_otherblock,
  154712. _vp_tonemask_adj_longblock,
  154713. _vp_tonemask_adj_otherblock,
  154714. _psy_noiseguards_44,
  154715. _psy_noisebias_impulse,
  154716. _psy_noisebias_padding,
  154717. _psy_noisebias_trans,
  154718. _psy_noisebias_long,
  154719. _psy_noise_suppress,
  154720. _psy_compand_44,
  154721. _psy_compand_short_mapping,
  154722. _psy_compand_long_mapping,
  154723. {_noise_start_short_44,_noise_start_long_44},
  154724. {_noise_part_short_44,_noise_part_long_44},
  154725. _noise_thresh_44,
  154726. _psy_ath_floater,
  154727. _psy_ath_abs,
  154728. _psy_lowpass_44,
  154729. _psy_global_44,
  154730. _global_mapping_44,
  154731. _psy_stereo_modes_44,
  154732. _floor_books,
  154733. _floor,
  154734. _floor_short_mapping_44,
  154735. _floor_long_mapping_44,
  154736. _mapres_template_44_stereo
  154737. };
  154738. ve_setup_data_template ve_setup_X_uncoupled={
  154739. 11,
  154740. rate_mapping_X,
  154741. quality_mapping_44,
  154742. -1,
  154743. 50000,
  154744. 200000,
  154745. blocksize_short_44,
  154746. blocksize_long_44,
  154747. _psy_tone_masteratt_44,
  154748. _psy_tone_0dB,
  154749. _psy_tone_suppress,
  154750. _vp_tonemask_adj_otherblock,
  154751. _vp_tonemask_adj_longblock,
  154752. _vp_tonemask_adj_otherblock,
  154753. _psy_noiseguards_44,
  154754. _psy_noisebias_impulse,
  154755. _psy_noisebias_padding,
  154756. _psy_noisebias_trans,
  154757. _psy_noisebias_long,
  154758. _psy_noise_suppress,
  154759. _psy_compand_44,
  154760. _psy_compand_short_mapping,
  154761. _psy_compand_long_mapping,
  154762. {_noise_start_short_44,_noise_start_long_44},
  154763. {_noise_part_short_44,_noise_part_long_44},
  154764. _noise_thresh_44,
  154765. _psy_ath_floater,
  154766. _psy_ath_abs,
  154767. _psy_lowpass_44,
  154768. _psy_global_44,
  154769. _global_mapping_44,
  154770. NULL,
  154771. _floor_books,
  154772. _floor,
  154773. _floor_short_mapping_44,
  154774. _floor_long_mapping_44,
  154775. _mapres_template_44_uncoupled
  154776. };
  154777. ve_setup_data_template ve_setup_XX_stereo={
  154778. 2,
  154779. rate_mapping_X,
  154780. quality_mapping_8,
  154781. 2,
  154782. 0,
  154783. 8000,
  154784. blocksize_8,
  154785. blocksize_8,
  154786. _psy_tone_masteratt_8,
  154787. _psy_tone_0dB,
  154788. _psy_tone_suppress,
  154789. _vp_tonemask_adj_8,
  154790. NULL,
  154791. _vp_tonemask_adj_8,
  154792. _psy_noiseguards_8,
  154793. _psy_noisebias_8,
  154794. _psy_noisebias_8,
  154795. NULL,
  154796. NULL,
  154797. _psy_noise_suppress,
  154798. _psy_compand_8,
  154799. _psy_compand_8_mapping,
  154800. NULL,
  154801. {_noise_start_8,_noise_start_8},
  154802. {_noise_part_8,_noise_part_8},
  154803. _noise_thresh_5only,
  154804. _psy_ath_floater_8,
  154805. _psy_ath_abs_8,
  154806. _psy_lowpass_8,
  154807. _psy_global_44,
  154808. _global_mapping_8,
  154809. _psy_stereo_modes_8,
  154810. _floor_books,
  154811. _floor,
  154812. _floor_mapping_8,
  154813. NULL,
  154814. _mapres_template_8_stereo
  154815. };
  154816. ve_setup_data_template ve_setup_XX_uncoupled={
  154817. 2,
  154818. rate_mapping_X,
  154819. quality_mapping_8,
  154820. -1,
  154821. 0,
  154822. 8000,
  154823. blocksize_8,
  154824. blocksize_8,
  154825. _psy_tone_masteratt_8,
  154826. _psy_tone_0dB,
  154827. _psy_tone_suppress,
  154828. _vp_tonemask_adj_8,
  154829. NULL,
  154830. _vp_tonemask_adj_8,
  154831. _psy_noiseguards_8,
  154832. _psy_noisebias_8,
  154833. _psy_noisebias_8,
  154834. NULL,
  154835. NULL,
  154836. _psy_noise_suppress,
  154837. _psy_compand_8,
  154838. _psy_compand_8_mapping,
  154839. NULL,
  154840. {_noise_start_8,_noise_start_8},
  154841. {_noise_part_8,_noise_part_8},
  154842. _noise_thresh_5only,
  154843. _psy_ath_floater_8,
  154844. _psy_ath_abs_8,
  154845. _psy_lowpass_8,
  154846. _psy_global_44,
  154847. _global_mapping_8,
  154848. _psy_stereo_modes_8,
  154849. _floor_books,
  154850. _floor,
  154851. _floor_mapping_8,
  154852. NULL,
  154853. _mapres_template_8_uncoupled
  154854. };
  154855. /*** End of inlined file: setup_X.h ***/
  154856. static ve_setup_data_template *setup_list[]={
  154857. &ve_setup_44_stereo,
  154858. &ve_setup_44_uncoupled,
  154859. &ve_setup_32_stereo,
  154860. &ve_setup_32_uncoupled,
  154861. &ve_setup_22_stereo,
  154862. &ve_setup_22_uncoupled,
  154863. &ve_setup_16_stereo,
  154864. &ve_setup_16_uncoupled,
  154865. &ve_setup_11_stereo,
  154866. &ve_setup_11_uncoupled,
  154867. &ve_setup_8_stereo,
  154868. &ve_setup_8_uncoupled,
  154869. &ve_setup_X_stereo,
  154870. &ve_setup_X_uncoupled,
  154871. &ve_setup_XX_stereo,
  154872. &ve_setup_XX_uncoupled,
  154873. 0
  154874. };
  154875. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154876. if(vi && vi->codec_setup){
  154877. vi->version=0;
  154878. vi->channels=ch;
  154879. vi->rate=rate;
  154880. return(0);
  154881. }
  154882. return(OV_EINVAL);
  154883. }
  154884. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154885. static_codebook ***books,
  154886. vorbis_info_floor1 *in,
  154887. int *x){
  154888. int i,k,is=s;
  154889. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154890. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154891. memcpy(f,in+x[is],sizeof(*f));
  154892. /* fill in the lowpass field, even if it's temporary */
  154893. f->n=ci->blocksizes[block]>>1;
  154894. /* books */
  154895. {
  154896. int partitions=f->partitions;
  154897. int maxclass=-1;
  154898. int maxbook=-1;
  154899. for(i=0;i<partitions;i++)
  154900. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154901. for(i=0;i<=maxclass;i++){
  154902. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154903. f->class_book[i]+=ci->books;
  154904. for(k=0;k<(1<<f->class_subs[i]);k++){
  154905. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154906. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154907. }
  154908. }
  154909. for(i=0;i<=maxbook;i++)
  154910. ci->book_param[ci->books++]=books[x[is]][i];
  154911. }
  154912. /* for now, we're only using floor 1 */
  154913. ci->floor_type[ci->floors]=1;
  154914. ci->floor_param[ci->floors]=f;
  154915. ci->floors++;
  154916. return;
  154917. }
  154918. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154919. vorbis_info_psy_global *in,
  154920. double *x){
  154921. int i,is=s;
  154922. double ds=s-is;
  154923. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154924. vorbis_info_psy_global *g=&ci->psy_g_param;
  154925. memcpy(g,in+(int)x[is],sizeof(*g));
  154926. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154927. is=(int)ds;
  154928. ds-=is;
  154929. if(ds==0 && is>0){
  154930. is--;
  154931. ds=1.;
  154932. }
  154933. /* interpolate the trigger threshholds */
  154934. for(i=0;i<4;i++){
  154935. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154936. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154937. }
  154938. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154939. return;
  154940. }
  154941. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154942. highlevel_encode_setup *hi,
  154943. adj_stereo *p){
  154944. float s=hi->stereo_point_setting;
  154945. int i,is=s;
  154946. double ds=s-is;
  154947. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154948. vorbis_info_psy_global *g=&ci->psy_g_param;
  154949. if(p){
  154950. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154951. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154952. if(hi->managed){
  154953. /* interpolate the kHz threshholds */
  154954. for(i=0;i<PACKETBLOBS;i++){
  154955. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154956. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154957. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154958. g->coupling_pkHz[i]=kHz;
  154959. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154960. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154961. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154962. }
  154963. }else{
  154964. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154965. for(i=0;i<PACKETBLOBS;i++){
  154966. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154967. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154968. g->coupling_pkHz[i]=kHz;
  154969. }
  154970. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154971. for(i=0;i<PACKETBLOBS;i++){
  154972. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154973. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154974. }
  154975. }
  154976. }else{
  154977. for(i=0;i<PACKETBLOBS;i++){
  154978. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154979. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154980. }
  154981. }
  154982. return;
  154983. }
  154984. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154985. int *nn_start,
  154986. int *nn_partition,
  154987. double *nn_thresh,
  154988. int block){
  154989. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154990. vorbis_info_psy *p=ci->psy_param[block];
  154991. highlevel_encode_setup *hi=&ci->hi;
  154992. int is=s;
  154993. if(block>=ci->psys)
  154994. ci->psys=block+1;
  154995. if(!p){
  154996. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154997. ci->psy_param[block]=p;
  154998. }
  154999. memcpy(p,&_psy_info_template,sizeof(*p));
  155000. p->blockflag=block>>1;
  155001. if(hi->noise_normalize_p){
  155002. p->normal_channel_p=1;
  155003. p->normal_point_p=1;
  155004. p->normal_start=nn_start[is];
  155005. p->normal_partition=nn_partition[is];
  155006. p->normal_thresh=nn_thresh[is];
  155007. }
  155008. return;
  155009. }
  155010. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  155011. att3 *att,
  155012. int *max,
  155013. vp_adjblock *in){
  155014. int i,is=s;
  155015. double ds=s-is;
  155016. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155017. vorbis_info_psy *p=ci->psy_param[block];
  155018. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  155019. filling the values in here */
  155020. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  155021. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  155022. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  155023. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  155024. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  155025. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  155026. for(i=0;i<P_BANDS;i++)
  155027. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  155028. return;
  155029. }
  155030. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  155031. compandblock *in, double *x){
  155032. int i,is=s;
  155033. double ds=s-is;
  155034. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155035. vorbis_info_psy *p=ci->psy_param[block];
  155036. ds=x[is]*(1.-ds)+x[is+1]*ds;
  155037. is=(int)ds;
  155038. ds-=is;
  155039. if(ds==0 && is>0){
  155040. is--;
  155041. ds=1.;
  155042. }
  155043. /* interpolate the compander settings */
  155044. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  155045. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  155046. return;
  155047. }
  155048. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  155049. int *suppress){
  155050. int is=s;
  155051. double ds=s-is;
  155052. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155053. vorbis_info_psy *p=ci->psy_param[block];
  155054. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  155055. return;
  155056. }
  155057. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  155058. int *suppress,
  155059. noise3 *in,
  155060. noiseguard *guard,
  155061. double userbias){
  155062. int i,is=s,j;
  155063. double ds=s-is;
  155064. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155065. vorbis_info_psy *p=ci->psy_param[block];
  155066. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  155067. p->noisewindowlomin=guard[block].lo;
  155068. p->noisewindowhimin=guard[block].hi;
  155069. p->noisewindowfixed=guard[block].fixed;
  155070. for(j=0;j<P_NOISECURVES;j++)
  155071. for(i=0;i<P_BANDS;i++)
  155072. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  155073. /* impulse blocks may take a user specified bias to boost the
  155074. nominal/high noise encoding depth */
  155075. for(j=0;j<P_NOISECURVES;j++){
  155076. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  155077. for(i=0;i<P_BANDS;i++){
  155078. p->noiseoff[j][i]+=userbias;
  155079. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  155080. }
  155081. }
  155082. return;
  155083. }
  155084. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  155085. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155086. vorbis_info_psy *p=ci->psy_param[block];
  155087. p->ath_adjatt=ci->hi.ath_floating_dB;
  155088. p->ath_maxatt=ci->hi.ath_absolute_dB;
  155089. return;
  155090. }
  155091. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  155092. int i;
  155093. for(i=0;i<ci->books;i++)
  155094. if(ci->book_param[i]==book)return(i);
  155095. return(ci->books++);
  155096. }
  155097. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  155098. int *shortb,int *longb){
  155099. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155100. int is=s;
  155101. int blockshort=shortb[is];
  155102. int blocklong=longb[is];
  155103. ci->blocksizes[0]=blockshort;
  155104. ci->blocksizes[1]=blocklong;
  155105. }
  155106. static void vorbis_encode_residue_setup(vorbis_info *vi,
  155107. int number, int block,
  155108. vorbis_residue_template *res){
  155109. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155110. int i,n;
  155111. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  155112. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  155113. memcpy(r,res->res,sizeof(*r));
  155114. if(ci->residues<=number)ci->residues=number+1;
  155115. switch(ci->blocksizes[block]){
  155116. case 64:case 128:case 256:
  155117. r->grouping=16;
  155118. break;
  155119. default:
  155120. r->grouping=32;
  155121. break;
  155122. }
  155123. ci->residue_type[number]=res->res_type;
  155124. /* to be adjusted by lowpass/pointlimit later */
  155125. n=r->end=ci->blocksizes[block]>>1;
  155126. if(res->res_type==2)
  155127. n=r->end*=vi->channels;
  155128. /* fill in all the books */
  155129. {
  155130. int booklist=0,k;
  155131. if(ci->hi.managed){
  155132. for(i=0;i<r->partitions;i++)
  155133. for(k=0;k<3;k++)
  155134. if(res->books_base_managed->books[i][k])
  155135. r->secondstages[i]|=(1<<k);
  155136. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155137. ci->book_param[r->groupbook]=res->book_aux_managed;
  155138. for(i=0;i<r->partitions;i++){
  155139. for(k=0;k<3;k++){
  155140. if(res->books_base_managed->books[i][k]){
  155141. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155142. r->booklist[booklist++]=bookid;
  155143. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155144. }
  155145. }
  155146. }
  155147. }else{
  155148. for(i=0;i<r->partitions;i++)
  155149. for(k=0;k<3;k++)
  155150. if(res->books_base->books[i][k])
  155151. r->secondstages[i]|=(1<<k);
  155152. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155153. ci->book_param[r->groupbook]=res->book_aux;
  155154. for(i=0;i<r->partitions;i++){
  155155. for(k=0;k<3;k++){
  155156. if(res->books_base->books[i][k]){
  155157. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155158. r->booklist[booklist++]=bookid;
  155159. ci->book_param[bookid]=res->books_base->books[i][k];
  155160. }
  155161. }
  155162. }
  155163. }
  155164. }
  155165. /* lowpass setup/pointlimit */
  155166. {
  155167. double freq=ci->hi.lowpass_kHz*1000.;
  155168. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155169. double nyq=vi->rate/2.;
  155170. long blocksize=ci->blocksizes[block]>>1;
  155171. /* lowpass needs to be set in the floor and the residue. */
  155172. if(freq>nyq)freq=nyq;
  155173. /* in the floor, the granularity can be very fine; it doesn't alter
  155174. the encoding structure, only the samples used to fit the floor
  155175. approximation */
  155176. f->n=freq/nyq*blocksize;
  155177. /* this res may by limited by the maximum pointlimit of the mode,
  155178. not the lowpass. the floor is always lowpass limited. */
  155179. if(res->limit_type){
  155180. if(ci->hi.managed)
  155181. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155182. else
  155183. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155184. if(freq>nyq)freq=nyq;
  155185. }
  155186. /* in the residue, we're constrained, physically, by partition
  155187. boundaries. We still lowpass 'wherever', but we have to round up
  155188. here to next boundary, or the vorbis spec will round it *down* to
  155189. previous boundary in encode/decode */
  155190. if(ci->residue_type[block]==2)
  155191. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155192. r->grouping;
  155193. else
  155194. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155195. r->grouping;
  155196. }
  155197. }
  155198. /* we assume two maps in this encoder */
  155199. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155200. vorbis_mapping_template *maps){
  155201. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155202. int i,j,is=s,modes=2;
  155203. vorbis_info_mapping0 *map=maps[is].map;
  155204. vorbis_info_mode *mode=_mode_template;
  155205. vorbis_residue_template *res=maps[is].res;
  155206. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155207. for(i=0;i<modes;i++){
  155208. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155209. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155210. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155211. if(i>=ci->modes)ci->modes=i+1;
  155212. ci->map_type[i]=0;
  155213. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155214. if(i>=ci->maps)ci->maps=i+1;
  155215. for(j=0;j<map[i].submaps;j++)
  155216. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155217. ,res+map[i].residuesubmap[j]);
  155218. }
  155219. }
  155220. static double setting_to_approx_bitrate(vorbis_info *vi){
  155221. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155222. highlevel_encode_setup *hi=&ci->hi;
  155223. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155224. int is=hi->base_setting;
  155225. double ds=hi->base_setting-is;
  155226. int ch=vi->channels;
  155227. double *r=setup->rate_mapping;
  155228. if(r==NULL)
  155229. return(-1);
  155230. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155231. }
  155232. static void get_setup_template(vorbis_info *vi,
  155233. long ch,long srate,
  155234. double req,int q_or_bitrate){
  155235. int i=0,j;
  155236. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155237. highlevel_encode_setup *hi=&ci->hi;
  155238. if(q_or_bitrate)req/=ch;
  155239. while(setup_list[i]){
  155240. if(setup_list[i]->coupling_restriction==-1 ||
  155241. setup_list[i]->coupling_restriction==ch){
  155242. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155243. srate<=setup_list[i]->samplerate_max_restriction){
  155244. int mappings=setup_list[i]->mappings;
  155245. double *map=(q_or_bitrate?
  155246. setup_list[i]->rate_mapping:
  155247. setup_list[i]->quality_mapping);
  155248. /* the template matches. Does the requested quality mode
  155249. fall within this template's modes? */
  155250. if(req<map[0]){++i;continue;}
  155251. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155252. for(j=0;j<mappings;j++)
  155253. if(req>=map[j] && req<map[j+1])break;
  155254. /* an all-points match */
  155255. hi->setup=setup_list[i];
  155256. if(j==mappings)
  155257. hi->base_setting=j-.001;
  155258. else{
  155259. float low=map[j];
  155260. float high=map[j+1];
  155261. float del=(req-low)/(high-low);
  155262. hi->base_setting=j+del;
  155263. }
  155264. return;
  155265. }
  155266. }
  155267. i++;
  155268. }
  155269. hi->setup=NULL;
  155270. }
  155271. /* encoders will need to use vorbis_info_init beforehand and call
  155272. vorbis_info clear when all done */
  155273. /* two interfaces; this, more detailed one, and later a convenience
  155274. layer on top */
  155275. /* the final setup call */
  155276. int vorbis_encode_setup_init(vorbis_info *vi){
  155277. int i0=0,singleblock=0;
  155278. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155279. ve_setup_data_template *setup=NULL;
  155280. highlevel_encode_setup *hi=&ci->hi;
  155281. if(ci==NULL)return(OV_EINVAL);
  155282. if(!hi->impulse_block_p)i0=1;
  155283. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155284. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155285. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155286. /* again, bound this to avoid the app shooting itself int he foot
  155287. too badly */
  155288. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155289. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155290. /* get the appropriate setup template; matches the fetch in previous
  155291. stages */
  155292. setup=(ve_setup_data_template *)hi->setup;
  155293. if(setup==NULL)return(OV_EINVAL);
  155294. hi->set_in_stone=1;
  155295. /* choose block sizes from configured sizes as well as paying
  155296. attention to long_block_p and short_block_p. If the configured
  155297. short and long blocks are the same length, we set long_block_p
  155298. and unset short_block_p */
  155299. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155300. setup->blocksize_short,
  155301. setup->blocksize_long);
  155302. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155303. /* floor setup; choose proper floor params. Allocated on the floor
  155304. stack in order; if we alloc only long floor, it's 0 */
  155305. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155306. setup->floor_books,
  155307. setup->floor_params,
  155308. setup->floor_short_mapping);
  155309. if(!singleblock)
  155310. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155311. setup->floor_books,
  155312. setup->floor_params,
  155313. setup->floor_long_mapping);
  155314. /* setup of [mostly] short block detection and stereo*/
  155315. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155316. setup->global_params,
  155317. setup->global_mapping);
  155318. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155319. /* basic psych setup and noise normalization */
  155320. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155321. setup->psy_noise_normal_start[0],
  155322. setup->psy_noise_normal_partition[0],
  155323. setup->psy_noise_normal_thresh,
  155324. 0);
  155325. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155326. setup->psy_noise_normal_start[0],
  155327. setup->psy_noise_normal_partition[0],
  155328. setup->psy_noise_normal_thresh,
  155329. 1);
  155330. if(!singleblock){
  155331. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155332. setup->psy_noise_normal_start[1],
  155333. setup->psy_noise_normal_partition[1],
  155334. setup->psy_noise_normal_thresh,
  155335. 2);
  155336. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155337. setup->psy_noise_normal_start[1],
  155338. setup->psy_noise_normal_partition[1],
  155339. setup->psy_noise_normal_thresh,
  155340. 3);
  155341. }
  155342. /* tone masking setup */
  155343. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155344. setup->psy_tone_masteratt,
  155345. setup->psy_tone_0dB,
  155346. setup->psy_tone_adj_impulse);
  155347. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155348. setup->psy_tone_masteratt,
  155349. setup->psy_tone_0dB,
  155350. setup->psy_tone_adj_other);
  155351. if(!singleblock){
  155352. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155353. setup->psy_tone_masteratt,
  155354. setup->psy_tone_0dB,
  155355. setup->psy_tone_adj_other);
  155356. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155357. setup->psy_tone_masteratt,
  155358. setup->psy_tone_0dB,
  155359. setup->psy_tone_adj_long);
  155360. }
  155361. /* noise companding setup */
  155362. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155363. setup->psy_noise_compand,
  155364. setup->psy_noise_compand_short_mapping);
  155365. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155366. setup->psy_noise_compand,
  155367. setup->psy_noise_compand_short_mapping);
  155368. if(!singleblock){
  155369. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155370. setup->psy_noise_compand,
  155371. setup->psy_noise_compand_long_mapping);
  155372. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155373. setup->psy_noise_compand,
  155374. setup->psy_noise_compand_long_mapping);
  155375. }
  155376. /* peak guarding setup */
  155377. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155378. setup->psy_tone_dBsuppress);
  155379. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155380. setup->psy_tone_dBsuppress);
  155381. if(!singleblock){
  155382. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155383. setup->psy_tone_dBsuppress);
  155384. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155385. setup->psy_tone_dBsuppress);
  155386. }
  155387. /* noise bias setup */
  155388. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155389. setup->psy_noise_dBsuppress,
  155390. setup->psy_noise_bias_impulse,
  155391. setup->psy_noiseguards,
  155392. (i0==0?hi->impulse_noisetune:0.));
  155393. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155394. setup->psy_noise_dBsuppress,
  155395. setup->psy_noise_bias_padding,
  155396. setup->psy_noiseguards,0.);
  155397. if(!singleblock){
  155398. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155399. setup->psy_noise_dBsuppress,
  155400. setup->psy_noise_bias_trans,
  155401. setup->psy_noiseguards,0.);
  155402. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155403. setup->psy_noise_dBsuppress,
  155404. setup->psy_noise_bias_long,
  155405. setup->psy_noiseguards,0.);
  155406. }
  155407. vorbis_encode_ath_setup(vi,0);
  155408. vorbis_encode_ath_setup(vi,1);
  155409. if(!singleblock){
  155410. vorbis_encode_ath_setup(vi,2);
  155411. vorbis_encode_ath_setup(vi,3);
  155412. }
  155413. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155414. /* set bitrate readonlies and management */
  155415. if(hi->bitrate_av>0)
  155416. vi->bitrate_nominal=hi->bitrate_av;
  155417. else{
  155418. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155419. }
  155420. vi->bitrate_lower=hi->bitrate_min;
  155421. vi->bitrate_upper=hi->bitrate_max;
  155422. if(hi->bitrate_av)
  155423. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155424. else
  155425. vi->bitrate_window=0.;
  155426. if(hi->managed){
  155427. ci->bi.avg_rate=hi->bitrate_av;
  155428. ci->bi.min_rate=hi->bitrate_min;
  155429. ci->bi.max_rate=hi->bitrate_max;
  155430. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155431. ci->bi.reservoir_bias=
  155432. hi->bitrate_reservoir_bias;
  155433. ci->bi.slew_damp=hi->bitrate_av_damp;
  155434. }
  155435. return(0);
  155436. }
  155437. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155438. long channels,
  155439. long rate){
  155440. int ret=0,i,is;
  155441. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155442. highlevel_encode_setup *hi=&ci->hi;
  155443. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155444. double ds;
  155445. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155446. if(ret)return(ret);
  155447. is=hi->base_setting;
  155448. ds=hi->base_setting-is;
  155449. hi->short_setting=hi->base_setting;
  155450. hi->long_setting=hi->base_setting;
  155451. hi->managed=0;
  155452. hi->impulse_block_p=1;
  155453. hi->noise_normalize_p=1;
  155454. hi->stereo_point_setting=hi->base_setting;
  155455. hi->lowpass_kHz=
  155456. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155457. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155458. setup->psy_ath_float[is+1]*ds;
  155459. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155460. setup->psy_ath_abs[is+1]*ds;
  155461. hi->amplitude_track_dBpersec=-6.;
  155462. hi->trigger_setting=hi->base_setting;
  155463. for(i=0;i<4;i++){
  155464. hi->block[i].tone_mask_setting=hi->base_setting;
  155465. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155466. hi->block[i].noise_bias_setting=hi->base_setting;
  155467. hi->block[i].noise_compand_setting=hi->base_setting;
  155468. }
  155469. return(ret);
  155470. }
  155471. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155472. long channels,
  155473. long rate,
  155474. float quality){
  155475. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155476. highlevel_encode_setup *hi=&ci->hi;
  155477. quality+=.0000001;
  155478. if(quality>=1.)quality=.9999;
  155479. get_setup_template(vi,channels,rate,quality,0);
  155480. if(!hi->setup)return OV_EIMPL;
  155481. return vorbis_encode_setup_setting(vi,channels,rate);
  155482. }
  155483. int vorbis_encode_init_vbr(vorbis_info *vi,
  155484. long channels,
  155485. long rate,
  155486. float base_quality /* 0. to 1. */
  155487. ){
  155488. int ret=0;
  155489. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155490. if(ret){
  155491. vorbis_info_clear(vi);
  155492. return ret;
  155493. }
  155494. ret=vorbis_encode_setup_init(vi);
  155495. if(ret)
  155496. vorbis_info_clear(vi);
  155497. return(ret);
  155498. }
  155499. int vorbis_encode_setup_managed(vorbis_info *vi,
  155500. long channels,
  155501. long rate,
  155502. long max_bitrate,
  155503. long nominal_bitrate,
  155504. long min_bitrate){
  155505. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155506. highlevel_encode_setup *hi=&ci->hi;
  155507. double tnominal=nominal_bitrate;
  155508. int ret=0;
  155509. if(nominal_bitrate<=0.){
  155510. if(max_bitrate>0.){
  155511. if(min_bitrate>0.)
  155512. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155513. else
  155514. nominal_bitrate=max_bitrate*.875;
  155515. }else{
  155516. if(min_bitrate>0.){
  155517. nominal_bitrate=min_bitrate;
  155518. }else{
  155519. return(OV_EINVAL);
  155520. }
  155521. }
  155522. }
  155523. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155524. if(!hi->setup)return OV_EIMPL;
  155525. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155526. if(ret){
  155527. vorbis_info_clear(vi);
  155528. return ret;
  155529. }
  155530. /* initialize management with sane defaults */
  155531. hi->managed=1;
  155532. hi->bitrate_min=min_bitrate;
  155533. hi->bitrate_max=max_bitrate;
  155534. hi->bitrate_av=tnominal;
  155535. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155536. hi->bitrate_reservoir=nominal_bitrate*2;
  155537. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155538. return(ret);
  155539. }
  155540. int vorbis_encode_init(vorbis_info *vi,
  155541. long channels,
  155542. long rate,
  155543. long max_bitrate,
  155544. long nominal_bitrate,
  155545. long min_bitrate){
  155546. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155547. max_bitrate,
  155548. nominal_bitrate,
  155549. min_bitrate);
  155550. if(ret){
  155551. vorbis_info_clear(vi);
  155552. return(ret);
  155553. }
  155554. ret=vorbis_encode_setup_init(vi);
  155555. if(ret)
  155556. vorbis_info_clear(vi);
  155557. return(ret);
  155558. }
  155559. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155560. if(vi){
  155561. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155562. highlevel_encode_setup *hi=&ci->hi;
  155563. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155564. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155565. switch(number){
  155566. /* now deprecated *****************/
  155567. case OV_ECTL_RATEMANAGE_GET:
  155568. {
  155569. struct ovectl_ratemanage_arg *ai=
  155570. (struct ovectl_ratemanage_arg *)arg;
  155571. ai->management_active=hi->managed;
  155572. ai->bitrate_hard_window=ai->bitrate_av_window=
  155573. (double)hi->bitrate_reservoir/vi->rate;
  155574. ai->bitrate_av_window_center=1.;
  155575. ai->bitrate_hard_min=hi->bitrate_min;
  155576. ai->bitrate_hard_max=hi->bitrate_max;
  155577. ai->bitrate_av_lo=hi->bitrate_av;
  155578. ai->bitrate_av_hi=hi->bitrate_av;
  155579. }
  155580. return(0);
  155581. /* now deprecated *****************/
  155582. case OV_ECTL_RATEMANAGE_SET:
  155583. {
  155584. struct ovectl_ratemanage_arg *ai=
  155585. (struct ovectl_ratemanage_arg *)arg;
  155586. if(ai==NULL){
  155587. hi->managed=0;
  155588. }else{
  155589. hi->managed=ai->management_active;
  155590. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155591. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155592. }
  155593. }
  155594. return 0;
  155595. /* now deprecated *****************/
  155596. case OV_ECTL_RATEMANAGE_AVG:
  155597. {
  155598. struct ovectl_ratemanage_arg *ai=
  155599. (struct ovectl_ratemanage_arg *)arg;
  155600. if(ai==NULL){
  155601. hi->bitrate_av=0;
  155602. }else{
  155603. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155604. }
  155605. }
  155606. return(0);
  155607. /* now deprecated *****************/
  155608. case OV_ECTL_RATEMANAGE_HARD:
  155609. {
  155610. struct ovectl_ratemanage_arg *ai=
  155611. (struct ovectl_ratemanage_arg *)arg;
  155612. if(ai==NULL){
  155613. hi->bitrate_min=0;
  155614. hi->bitrate_max=0;
  155615. }else{
  155616. hi->bitrate_min=ai->bitrate_hard_min;
  155617. hi->bitrate_max=ai->bitrate_hard_max;
  155618. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155619. (hi->bitrate_max+hi->bitrate_min)*.5;
  155620. }
  155621. if(hi->bitrate_reservoir<128.)
  155622. hi->bitrate_reservoir=128.;
  155623. }
  155624. return(0);
  155625. /* replacement ratemanage interface */
  155626. case OV_ECTL_RATEMANAGE2_GET:
  155627. {
  155628. struct ovectl_ratemanage2_arg *ai=
  155629. (struct ovectl_ratemanage2_arg *)arg;
  155630. if(ai==NULL)return OV_EINVAL;
  155631. ai->management_active=hi->managed;
  155632. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155633. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155634. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155635. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155636. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155637. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155638. }
  155639. return (0);
  155640. case OV_ECTL_RATEMANAGE2_SET:
  155641. {
  155642. struct ovectl_ratemanage2_arg *ai=
  155643. (struct ovectl_ratemanage2_arg *)arg;
  155644. if(ai==NULL){
  155645. hi->managed=0;
  155646. }else{
  155647. /* sanity check; only catch invariant violations */
  155648. if(ai->bitrate_limit_min_kbps>0 &&
  155649. ai->bitrate_average_kbps>0 &&
  155650. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155651. return OV_EINVAL;
  155652. if(ai->bitrate_limit_max_kbps>0 &&
  155653. ai->bitrate_average_kbps>0 &&
  155654. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155655. return OV_EINVAL;
  155656. if(ai->bitrate_limit_min_kbps>0 &&
  155657. ai->bitrate_limit_max_kbps>0 &&
  155658. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155659. return OV_EINVAL;
  155660. if(ai->bitrate_average_damping <= 0.)
  155661. return OV_EINVAL;
  155662. if(ai->bitrate_limit_reservoir_bits < 0)
  155663. return OV_EINVAL;
  155664. if(ai->bitrate_limit_reservoir_bias < 0.)
  155665. return OV_EINVAL;
  155666. if(ai->bitrate_limit_reservoir_bias > 1.)
  155667. return OV_EINVAL;
  155668. hi->managed=ai->management_active;
  155669. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155670. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155671. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155672. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155673. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155674. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155675. }
  155676. }
  155677. return 0;
  155678. case OV_ECTL_LOWPASS_GET:
  155679. {
  155680. double *farg=(double *)arg;
  155681. *farg=hi->lowpass_kHz;
  155682. }
  155683. return(0);
  155684. case OV_ECTL_LOWPASS_SET:
  155685. {
  155686. double *farg=(double *)arg;
  155687. hi->lowpass_kHz=*farg;
  155688. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155689. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155690. }
  155691. return(0);
  155692. case OV_ECTL_IBLOCK_GET:
  155693. {
  155694. double *farg=(double *)arg;
  155695. *farg=hi->impulse_noisetune;
  155696. }
  155697. return(0);
  155698. case OV_ECTL_IBLOCK_SET:
  155699. {
  155700. double *farg=(double *)arg;
  155701. hi->impulse_noisetune=*farg;
  155702. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155703. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155704. }
  155705. return(0);
  155706. }
  155707. return(OV_EIMPL);
  155708. }
  155709. return(OV_EINVAL);
  155710. }
  155711. #endif
  155712. /*** End of inlined file: vorbisenc.c ***/
  155713. /*** Start of inlined file: vorbisfile.c ***/
  155714. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155715. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155716. // tasks..
  155717. #if JUCE_MSVC
  155718. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155719. #endif
  155720. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155721. #if JUCE_USE_OGGVORBIS
  155722. #include <stdlib.h>
  155723. #include <stdio.h>
  155724. #include <errno.h>
  155725. #include <string.h>
  155726. #include <math.h>
  155727. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155728. one logical bitstream arranged end to end (the only form of Ogg
  155729. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155730. multiplexing] is not allowed in Vorbis) */
  155731. /* A Vorbis file can be played beginning to end (streamed) without
  155732. worrying ahead of time about chaining (see decoder_example.c). If
  155733. we have the whole file, however, and want random access
  155734. (seeking/scrubbing) or desire to know the total length/time of a
  155735. file, we need to account for the possibility of chaining. */
  155736. /* We can handle things a number of ways; we can determine the entire
  155737. bitstream structure right off the bat, or find pieces on demand.
  155738. This example determines and caches structure for the entire
  155739. bitstream, but builds a virtual decoder on the fly when moving
  155740. between links in the chain. */
  155741. /* There are also different ways to implement seeking. Enough
  155742. information exists in an Ogg bitstream to seek to
  155743. sample-granularity positions in the output. Or, one can seek by
  155744. picking some portion of the stream roughly in the desired area if
  155745. we only want coarse navigation through the stream. */
  155746. /*************************************************************************
  155747. * Many, many internal helpers. The intention is not to be confusing;
  155748. * rampant duplication and monolithic function implementation would be
  155749. * harder to understand anyway. The high level functions are last. Begin
  155750. * grokking near the end of the file */
  155751. /* read a little more data from the file/pipe into the ogg_sync framer
  155752. */
  155753. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155754. over 8k gets what they deserve */
  155755. static long _get_data(OggVorbis_File *vf){
  155756. errno=0;
  155757. if(vf->datasource){
  155758. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155759. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155760. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155761. if(bytes==0 && errno)return(-1);
  155762. return(bytes);
  155763. }else
  155764. return(0);
  155765. }
  155766. /* save a tiny smidge of verbosity to make the code more readable */
  155767. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155768. if(vf->datasource){
  155769. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155770. vf->offset=offset;
  155771. ogg_sync_reset(&vf->oy);
  155772. }else{
  155773. /* shouldn't happen unless someone writes a broken callback */
  155774. return;
  155775. }
  155776. }
  155777. /* The read/seek functions track absolute position within the stream */
  155778. /* from the head of the stream, get the next page. boundary specifies
  155779. if the function is allowed to fetch more data from the stream (and
  155780. how much) or only use internally buffered data.
  155781. boundary: -1) unbounded search
  155782. 0) read no additional data; use cached only
  155783. n) search for a new page beginning for n bytes
  155784. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155785. n) found a page at absolute offset n */
  155786. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155787. ogg_int64_t boundary){
  155788. if(boundary>0)boundary+=vf->offset;
  155789. while(1){
  155790. long more;
  155791. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155792. more=ogg_sync_pageseek(&vf->oy,og);
  155793. if(more<0){
  155794. /* skipped n bytes */
  155795. vf->offset-=more;
  155796. }else{
  155797. if(more==0){
  155798. /* send more paramedics */
  155799. if(!boundary)return(OV_FALSE);
  155800. {
  155801. long ret=_get_data(vf);
  155802. if(ret==0)return(OV_EOF);
  155803. if(ret<0)return(OV_EREAD);
  155804. }
  155805. }else{
  155806. /* got a page. Return the offset at the page beginning,
  155807. advance the internal offset past the page end */
  155808. ogg_int64_t ret=vf->offset;
  155809. vf->offset+=more;
  155810. return(ret);
  155811. }
  155812. }
  155813. }
  155814. }
  155815. /* find the latest page beginning before the current stream cursor
  155816. position. Much dirtier than the above as Ogg doesn't have any
  155817. backward search linkage. no 'readp' as it will certainly have to
  155818. read. */
  155819. /* returns offset or OV_EREAD, OV_FAULT */
  155820. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155821. ogg_int64_t begin=vf->offset;
  155822. ogg_int64_t end=begin;
  155823. ogg_int64_t ret;
  155824. ogg_int64_t offset=-1;
  155825. while(offset==-1){
  155826. begin-=CHUNKSIZE;
  155827. if(begin<0)
  155828. begin=0;
  155829. _seek_helper(vf,begin);
  155830. while(vf->offset<end){
  155831. ret=_get_next_page(vf,og,end-vf->offset);
  155832. if(ret==OV_EREAD)return(OV_EREAD);
  155833. if(ret<0){
  155834. break;
  155835. }else{
  155836. offset=ret;
  155837. }
  155838. }
  155839. }
  155840. /* we have the offset. Actually snork and hold the page now */
  155841. _seek_helper(vf,offset);
  155842. ret=_get_next_page(vf,og,CHUNKSIZE);
  155843. if(ret<0)
  155844. /* this shouldn't be possible */
  155845. return(OV_EFAULT);
  155846. return(offset);
  155847. }
  155848. /* finds each bitstream link one at a time using a bisection search
  155849. (has to begin by knowing the offset of the lb's initial page).
  155850. Recurses for each link so it can alloc the link storage after
  155851. finding them all, then unroll and fill the cache at the same time */
  155852. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155853. ogg_int64_t begin,
  155854. ogg_int64_t searched,
  155855. ogg_int64_t end,
  155856. long currentno,
  155857. long m){
  155858. ogg_int64_t endsearched=end;
  155859. ogg_int64_t next=end;
  155860. ogg_page og;
  155861. ogg_int64_t ret;
  155862. /* the below guards against garbage seperating the last and
  155863. first pages of two links. */
  155864. while(searched<endsearched){
  155865. ogg_int64_t bisect;
  155866. if(endsearched-searched<CHUNKSIZE){
  155867. bisect=searched;
  155868. }else{
  155869. bisect=(searched+endsearched)/2;
  155870. }
  155871. _seek_helper(vf,bisect);
  155872. ret=_get_next_page(vf,&og,-1);
  155873. if(ret==OV_EREAD)return(OV_EREAD);
  155874. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155875. endsearched=bisect;
  155876. if(ret>=0)next=ret;
  155877. }else{
  155878. searched=ret+og.header_len+og.body_len;
  155879. }
  155880. }
  155881. _seek_helper(vf,next);
  155882. ret=_get_next_page(vf,&og,-1);
  155883. if(ret==OV_EREAD)return(OV_EREAD);
  155884. if(searched>=end || ret<0){
  155885. vf->links=m+1;
  155886. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155887. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155888. vf->offsets[m+1]=searched;
  155889. }else{
  155890. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155891. end,ogg_page_serialno(&og),m+1);
  155892. if(ret==OV_EREAD)return(OV_EREAD);
  155893. }
  155894. vf->offsets[m]=begin;
  155895. vf->serialnos[m]=currentno;
  155896. return(0);
  155897. }
  155898. /* uses the local ogg_stream storage in vf; this is important for
  155899. non-streaming input sources */
  155900. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155901. long *serialno,ogg_page *og_ptr){
  155902. ogg_page og;
  155903. ogg_packet op;
  155904. int i,ret;
  155905. if(!og_ptr){
  155906. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155907. if(llret==OV_EREAD)return(OV_EREAD);
  155908. if(llret<0)return OV_ENOTVORBIS;
  155909. og_ptr=&og;
  155910. }
  155911. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155912. if(serialno)*serialno=vf->os.serialno;
  155913. vf->ready_state=STREAMSET;
  155914. /* extract the initial header from the first page and verify that the
  155915. Ogg bitstream is in fact Vorbis data */
  155916. vorbis_info_init(vi);
  155917. vorbis_comment_init(vc);
  155918. i=0;
  155919. while(i<3){
  155920. ogg_stream_pagein(&vf->os,og_ptr);
  155921. while(i<3){
  155922. int result=ogg_stream_packetout(&vf->os,&op);
  155923. if(result==0)break;
  155924. if(result==-1){
  155925. ret=OV_EBADHEADER;
  155926. goto bail_header;
  155927. }
  155928. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155929. goto bail_header;
  155930. }
  155931. i++;
  155932. }
  155933. if(i<3)
  155934. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155935. ret=OV_EBADHEADER;
  155936. goto bail_header;
  155937. }
  155938. }
  155939. return 0;
  155940. bail_header:
  155941. vorbis_info_clear(vi);
  155942. vorbis_comment_clear(vc);
  155943. vf->ready_state=OPENED;
  155944. return ret;
  155945. }
  155946. /* last step of the OggVorbis_File initialization; get all the
  155947. vorbis_info structs and PCM positions. Only called by the seekable
  155948. initialization (local stream storage is hacked slightly; pay
  155949. attention to how that's done) */
  155950. /* this is void and does not propogate errors up because we want to be
  155951. able to open and use damaged bitstreams as well as we can. Just
  155952. watch out for missing information for links in the OggVorbis_File
  155953. struct */
  155954. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155955. ogg_page og;
  155956. int i;
  155957. ogg_int64_t ret;
  155958. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155959. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155960. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155961. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155962. for(i=0;i<vf->links;i++){
  155963. if(i==0){
  155964. /* we already grabbed the initial header earlier. Just set the offset */
  155965. vf->dataoffsets[i]=dataoffset;
  155966. _seek_helper(vf,dataoffset);
  155967. }else{
  155968. /* seek to the location of the initial header */
  155969. _seek_helper(vf,vf->offsets[i]);
  155970. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155971. vf->dataoffsets[i]=-1;
  155972. }else{
  155973. vf->dataoffsets[i]=vf->offset;
  155974. }
  155975. }
  155976. /* fetch beginning PCM offset */
  155977. if(vf->dataoffsets[i]!=-1){
  155978. ogg_int64_t accumulated=0;
  155979. long lastblock=-1;
  155980. int result;
  155981. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155982. while(1){
  155983. ogg_packet op;
  155984. ret=_get_next_page(vf,&og,-1);
  155985. if(ret<0)
  155986. /* this should not be possible unless the file is
  155987. truncated/mangled */
  155988. break;
  155989. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155990. break;
  155991. /* count blocksizes of all frames in the page */
  155992. ogg_stream_pagein(&vf->os,&og);
  155993. while((result=ogg_stream_packetout(&vf->os,&op))){
  155994. if(result>0){ /* ignore holes */
  155995. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155996. if(lastblock!=-1)
  155997. accumulated+=(lastblock+thisblock)>>2;
  155998. lastblock=thisblock;
  155999. }
  156000. }
  156001. if(ogg_page_granulepos(&og)!=-1){
  156002. /* pcm offset of last packet on the first audio page */
  156003. accumulated= ogg_page_granulepos(&og)-accumulated;
  156004. break;
  156005. }
  156006. }
  156007. /* less than zero? This is a stream with samples trimmed off
  156008. the beginning, a normal occurrence; set the offset to zero */
  156009. if(accumulated<0)accumulated=0;
  156010. vf->pcmlengths[i*2]=accumulated;
  156011. }
  156012. /* get the PCM length of this link. To do this,
  156013. get the last page of the stream */
  156014. {
  156015. ogg_int64_t end=vf->offsets[i+1];
  156016. _seek_helper(vf,end);
  156017. while(1){
  156018. ret=_get_prev_page(vf,&og);
  156019. if(ret<0){
  156020. /* this should not be possible */
  156021. vorbis_info_clear(vf->vi+i);
  156022. vorbis_comment_clear(vf->vc+i);
  156023. break;
  156024. }
  156025. if(ogg_page_granulepos(&og)!=-1){
  156026. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  156027. break;
  156028. }
  156029. vf->offset=ret;
  156030. }
  156031. }
  156032. }
  156033. }
  156034. static int _make_decode_ready(OggVorbis_File *vf){
  156035. if(vf->ready_state>STREAMSET)return 0;
  156036. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  156037. if(vf->seekable){
  156038. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  156039. return OV_EBADLINK;
  156040. }else{
  156041. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  156042. return OV_EBADLINK;
  156043. }
  156044. vorbis_block_init(&vf->vd,&vf->vb);
  156045. vf->ready_state=INITSET;
  156046. vf->bittrack=0.f;
  156047. vf->samptrack=0.f;
  156048. return 0;
  156049. }
  156050. static int _open_seekable2(OggVorbis_File *vf){
  156051. long serialno=vf->current_serialno;
  156052. ogg_int64_t dataoffset=vf->offset, end;
  156053. ogg_page og;
  156054. /* we're partially open and have a first link header state in
  156055. storage in vf */
  156056. /* we can seek, so set out learning all about this file */
  156057. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  156058. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  156059. /* We get the offset for the last page of the physical bitstream.
  156060. Most OggVorbis files will contain a single logical bitstream */
  156061. end=_get_prev_page(vf,&og);
  156062. if(end<0)return(end);
  156063. /* more than one logical bitstream? */
  156064. if(ogg_page_serialno(&og)!=serialno){
  156065. /* Chained bitstream. Bisect-search each logical bitstream
  156066. section. Do so based on serial number only */
  156067. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  156068. }else{
  156069. /* Only one logical bitstream */
  156070. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  156071. }
  156072. /* the initial header memory is referenced by vf after; don't free it */
  156073. _prefetch_all_headers(vf,dataoffset);
  156074. return(ov_raw_seek(vf,0));
  156075. }
  156076. /* clear out the current logical bitstream decoder */
  156077. static void _decode_clear(OggVorbis_File *vf){
  156078. vorbis_dsp_clear(&vf->vd);
  156079. vorbis_block_clear(&vf->vb);
  156080. vf->ready_state=OPENED;
  156081. }
  156082. /* fetch and process a packet. Handles the case where we're at a
  156083. bitstream boundary and dumps the decoding machine. If the decoding
  156084. machine is unloaded, it loads it. It also keeps pcm_offset up to
  156085. date (seek and read both use this. seek uses a special hack with
  156086. readp).
  156087. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  156088. 0) need more data (only if readp==0)
  156089. 1) got a packet
  156090. */
  156091. static int _fetch_and_process_packet(OggVorbis_File *vf,
  156092. ogg_packet *op_in,
  156093. int readp,
  156094. int spanp){
  156095. ogg_page og;
  156096. /* handle one packet. Try to fetch it from current stream state */
  156097. /* extract packets from page */
  156098. while(1){
  156099. /* process a packet if we can. If the machine isn't loaded,
  156100. neither is a page */
  156101. if(vf->ready_state==INITSET){
  156102. while(1) {
  156103. ogg_packet op;
  156104. ogg_packet *op_ptr=(op_in?op_in:&op);
  156105. int result=ogg_stream_packetout(&vf->os,op_ptr);
  156106. ogg_int64_t granulepos;
  156107. op_in=NULL;
  156108. if(result==-1)return(OV_HOLE); /* hole in the data. */
  156109. if(result>0){
  156110. /* got a packet. process it */
  156111. granulepos=op_ptr->granulepos;
  156112. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  156113. header handling. The
  156114. header packets aren't
  156115. audio, so if/when we
  156116. submit them,
  156117. vorbis_synthesis will
  156118. reject them */
  156119. /* suck in the synthesis data and track bitrate */
  156120. {
  156121. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156122. /* for proper use of libvorbis within libvorbisfile,
  156123. oldsamples will always be zero. */
  156124. if(oldsamples)return(OV_EFAULT);
  156125. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156126. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156127. vf->bittrack+=op_ptr->bytes*8;
  156128. }
  156129. /* update the pcm offset. */
  156130. if(granulepos!=-1 && !op_ptr->e_o_s){
  156131. int link=(vf->seekable?vf->current_link:0);
  156132. int i,samples;
  156133. /* this packet has a pcm_offset on it (the last packet
  156134. completed on a page carries the offset) After processing
  156135. (above), we know the pcm position of the *last* sample
  156136. ready to be returned. Find the offset of the *first*
  156137. As an aside, this trick is inaccurate if we begin
  156138. reading anew right at the last page; the end-of-stream
  156139. granulepos declares the last frame in the stream, and the
  156140. last packet of the last page may be a partial frame.
  156141. So, we need a previous granulepos from an in-sequence page
  156142. to have a reference point. Thus the !op_ptr->e_o_s clause
  156143. above */
  156144. if(vf->seekable && link>0)
  156145. granulepos-=vf->pcmlengths[link*2];
  156146. if(granulepos<0)granulepos=0; /* actually, this
  156147. shouldn't be possible
  156148. here unless the stream
  156149. is very broken */
  156150. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156151. granulepos-=samples;
  156152. for(i=0;i<link;i++)
  156153. granulepos+=vf->pcmlengths[i*2+1];
  156154. vf->pcm_offset=granulepos;
  156155. }
  156156. return(1);
  156157. }
  156158. }
  156159. else
  156160. break;
  156161. }
  156162. }
  156163. if(vf->ready_state>=OPENED){
  156164. ogg_int64_t ret;
  156165. if(!readp)return(0);
  156166. if((ret=_get_next_page(vf,&og,-1))<0){
  156167. return(OV_EOF); /* eof.
  156168. leave unitialized */
  156169. }
  156170. /* bitrate tracking; add the header's bytes here, the body bytes
  156171. are done by packet above */
  156172. vf->bittrack+=og.header_len*8;
  156173. /* has our decoding just traversed a bitstream boundary? */
  156174. if(vf->ready_state==INITSET){
  156175. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156176. if(!spanp)
  156177. return(OV_EOF);
  156178. _decode_clear(vf);
  156179. if(!vf->seekable){
  156180. vorbis_info_clear(vf->vi);
  156181. vorbis_comment_clear(vf->vc);
  156182. }
  156183. }
  156184. }
  156185. }
  156186. /* Do we need to load a new machine before submitting the page? */
  156187. /* This is different in the seekable and non-seekable cases.
  156188. In the seekable case, we already have all the header
  156189. information loaded and cached; we just initialize the machine
  156190. with it and continue on our merry way.
  156191. In the non-seekable (streaming) case, we'll only be at a
  156192. boundary if we just left the previous logical bitstream and
  156193. we're now nominally at the header of the next bitstream
  156194. */
  156195. if(vf->ready_state!=INITSET){
  156196. int link;
  156197. if(vf->ready_state<STREAMSET){
  156198. if(vf->seekable){
  156199. vf->current_serialno=ogg_page_serialno(&og);
  156200. /* match the serialno to bitstream section. We use this rather than
  156201. offset positions to avoid problems near logical bitstream
  156202. boundaries */
  156203. for(link=0;link<vf->links;link++)
  156204. if(vf->serialnos[link]==vf->current_serialno)break;
  156205. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156206. stream. error out,
  156207. leave machine
  156208. uninitialized */
  156209. vf->current_link=link;
  156210. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156211. vf->ready_state=STREAMSET;
  156212. }else{
  156213. /* we're streaming */
  156214. /* fetch the three header packets, build the info struct */
  156215. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156216. if(ret)return(ret);
  156217. vf->current_link++;
  156218. link=0;
  156219. }
  156220. }
  156221. {
  156222. int ret=_make_decode_ready(vf);
  156223. if(ret<0)return ret;
  156224. }
  156225. }
  156226. ogg_stream_pagein(&vf->os,&og);
  156227. }
  156228. }
  156229. /* if, eg, 64 bit stdio is configured by default, this will build with
  156230. fseek64 */
  156231. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156232. if(f==NULL)return(-1);
  156233. return fseek(f,off,whence);
  156234. }
  156235. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156236. long ibytes, ov_callbacks callbacks){
  156237. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156238. int ret;
  156239. memset(vf,0,sizeof(*vf));
  156240. vf->datasource=f;
  156241. vf->callbacks = callbacks;
  156242. /* init the framing state */
  156243. ogg_sync_init(&vf->oy);
  156244. /* perhaps some data was previously read into a buffer for testing
  156245. against other stream types. Allow initialization from this
  156246. previously read data (as we may be reading from a non-seekable
  156247. stream) */
  156248. if(initial){
  156249. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156250. memcpy(buffer,initial,ibytes);
  156251. ogg_sync_wrote(&vf->oy,ibytes);
  156252. }
  156253. /* can we seek? Stevens suggests the seek test was portable */
  156254. if(offsettest!=-1)vf->seekable=1;
  156255. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156256. entry for partial open */
  156257. vf->links=1;
  156258. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156259. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156260. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156261. /* Try to fetch the headers, maintaining all the storage */
  156262. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156263. vf->datasource=NULL;
  156264. ov_clear(vf);
  156265. }else
  156266. vf->ready_state=PARTOPEN;
  156267. return(ret);
  156268. }
  156269. static int _ov_open2(OggVorbis_File *vf){
  156270. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156271. vf->ready_state=OPENED;
  156272. if(vf->seekable){
  156273. int ret=_open_seekable2(vf);
  156274. if(ret){
  156275. vf->datasource=NULL;
  156276. ov_clear(vf);
  156277. }
  156278. return(ret);
  156279. }else
  156280. vf->ready_state=STREAMSET;
  156281. return 0;
  156282. }
  156283. /* clear out the OggVorbis_File struct */
  156284. int ov_clear(OggVorbis_File *vf){
  156285. if(vf){
  156286. vorbis_block_clear(&vf->vb);
  156287. vorbis_dsp_clear(&vf->vd);
  156288. ogg_stream_clear(&vf->os);
  156289. if(vf->vi && vf->links){
  156290. int i;
  156291. for(i=0;i<vf->links;i++){
  156292. vorbis_info_clear(vf->vi+i);
  156293. vorbis_comment_clear(vf->vc+i);
  156294. }
  156295. _ogg_free(vf->vi);
  156296. _ogg_free(vf->vc);
  156297. }
  156298. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156299. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156300. if(vf->serialnos)_ogg_free(vf->serialnos);
  156301. if(vf->offsets)_ogg_free(vf->offsets);
  156302. ogg_sync_clear(&vf->oy);
  156303. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156304. memset(vf,0,sizeof(*vf));
  156305. }
  156306. #ifdef DEBUG_LEAKS
  156307. _VDBG_dump();
  156308. #endif
  156309. return(0);
  156310. }
  156311. /* inspects the OggVorbis file and finds/documents all the logical
  156312. bitstreams contained in it. Tries to be tolerant of logical
  156313. bitstream sections that are truncated/woogie.
  156314. return: -1) error
  156315. 0) OK
  156316. */
  156317. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156318. ov_callbacks callbacks){
  156319. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156320. if(ret)return ret;
  156321. return _ov_open2(vf);
  156322. }
  156323. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156324. ov_callbacks callbacks = {
  156325. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156326. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156327. (int (*)(void *)) fclose,
  156328. (long (*)(void *)) ftell
  156329. };
  156330. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156331. }
  156332. /* cheap hack for game usage where downsampling is desirable; there's
  156333. no need for SRC as we can just do it cheaply in libvorbis. */
  156334. int ov_halfrate(OggVorbis_File *vf,int flag){
  156335. int i;
  156336. if(vf->vi==NULL)return OV_EINVAL;
  156337. if(!vf->seekable)return OV_EINVAL;
  156338. if(vf->ready_state>=STREAMSET)
  156339. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156340. will be able to swap this on the fly, but
  156341. for now dumping the decode machine is needed
  156342. to reinit the MDCT lookups. 1.1 libvorbis
  156343. is planned to be able to switch on the fly */
  156344. for(i=0;i<vf->links;i++){
  156345. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156346. ov_halfrate(vf,0);
  156347. return OV_EINVAL;
  156348. }
  156349. }
  156350. return 0;
  156351. }
  156352. int ov_halfrate_p(OggVorbis_File *vf){
  156353. if(vf->vi==NULL)return OV_EINVAL;
  156354. return vorbis_synthesis_halfrate_p(vf->vi);
  156355. }
  156356. /* Only partially open the vorbis file; test for Vorbisness, and load
  156357. the headers for the first chain. Do not seek (although test for
  156358. seekability). Use ov_test_open to finish opening the file, else
  156359. ov_clear to close/free it. Same return codes as open. */
  156360. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156361. ov_callbacks callbacks)
  156362. {
  156363. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156364. }
  156365. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156366. ov_callbacks callbacks = {
  156367. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156368. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156369. (int (*)(void *)) fclose,
  156370. (long (*)(void *)) ftell
  156371. };
  156372. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156373. }
  156374. int ov_test_open(OggVorbis_File *vf){
  156375. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156376. return _ov_open2(vf);
  156377. }
  156378. /* How many logical bitstreams in this physical bitstream? */
  156379. long ov_streams(OggVorbis_File *vf){
  156380. return vf->links;
  156381. }
  156382. /* Is the FILE * associated with vf seekable? */
  156383. long ov_seekable(OggVorbis_File *vf){
  156384. return vf->seekable;
  156385. }
  156386. /* returns the bitrate for a given logical bitstream or the entire
  156387. physical bitstream. If the file is open for random access, it will
  156388. find the *actual* average bitrate. If the file is streaming, it
  156389. returns the nominal bitrate (if set) else the average of the
  156390. upper/lower bounds (if set) else -1 (unset).
  156391. If you want the actual bitrate field settings, get them from the
  156392. vorbis_info structs */
  156393. long ov_bitrate(OggVorbis_File *vf,int i){
  156394. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156395. if(i>=vf->links)return(OV_EINVAL);
  156396. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156397. if(i<0){
  156398. ogg_int64_t bits=0;
  156399. int i;
  156400. float br;
  156401. for(i=0;i<vf->links;i++)
  156402. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156403. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156404. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156405. * so this is slightly transformed to make it work.
  156406. */
  156407. br = bits/ov_time_total(vf,-1);
  156408. return(rint(br));
  156409. }else{
  156410. if(vf->seekable){
  156411. /* return the actual bitrate */
  156412. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156413. }else{
  156414. /* return nominal if set */
  156415. if(vf->vi[i].bitrate_nominal>0){
  156416. return vf->vi[i].bitrate_nominal;
  156417. }else{
  156418. if(vf->vi[i].bitrate_upper>0){
  156419. if(vf->vi[i].bitrate_lower>0){
  156420. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156421. }else{
  156422. return vf->vi[i].bitrate_upper;
  156423. }
  156424. }
  156425. return(OV_FALSE);
  156426. }
  156427. }
  156428. }
  156429. }
  156430. /* returns the actual bitrate since last call. returns -1 if no
  156431. additional data to offer since last call (or at beginning of stream),
  156432. EINVAL if stream is only partially open
  156433. */
  156434. long ov_bitrate_instant(OggVorbis_File *vf){
  156435. int link=(vf->seekable?vf->current_link:0);
  156436. long ret;
  156437. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156438. if(vf->samptrack==0)return(OV_FALSE);
  156439. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156440. vf->bittrack=0.f;
  156441. vf->samptrack=0.f;
  156442. return(ret);
  156443. }
  156444. /* Guess */
  156445. long ov_serialnumber(OggVorbis_File *vf,int i){
  156446. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156447. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156448. if(i<0){
  156449. return(vf->current_serialno);
  156450. }else{
  156451. return(vf->serialnos[i]);
  156452. }
  156453. }
  156454. /* returns: total raw (compressed) length of content if i==-1
  156455. raw (compressed) length of that logical bitstream for i==0 to n
  156456. OV_EINVAL if the stream is not seekable (we can't know the length)
  156457. or if stream is only partially open
  156458. */
  156459. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156460. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156461. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156462. if(i<0){
  156463. ogg_int64_t acc=0;
  156464. int i;
  156465. for(i=0;i<vf->links;i++)
  156466. acc+=ov_raw_total(vf,i);
  156467. return(acc);
  156468. }else{
  156469. return(vf->offsets[i+1]-vf->offsets[i]);
  156470. }
  156471. }
  156472. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156473. (samples) of that logical bitstream for i==0 to n
  156474. OV_EINVAL if the stream is not seekable (we can't know the
  156475. length) or only partially open
  156476. */
  156477. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156478. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156479. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156480. if(i<0){
  156481. ogg_int64_t acc=0;
  156482. int i;
  156483. for(i=0;i<vf->links;i++)
  156484. acc+=ov_pcm_total(vf,i);
  156485. return(acc);
  156486. }else{
  156487. return(vf->pcmlengths[i*2+1]);
  156488. }
  156489. }
  156490. /* returns: total seconds of content if i==-1
  156491. seconds in that logical bitstream for i==0 to n
  156492. OV_EINVAL if the stream is not seekable (we can't know the
  156493. length) or only partially open
  156494. */
  156495. double ov_time_total(OggVorbis_File *vf,int i){
  156496. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156497. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156498. if(i<0){
  156499. double acc=0;
  156500. int i;
  156501. for(i=0;i<vf->links;i++)
  156502. acc+=ov_time_total(vf,i);
  156503. return(acc);
  156504. }else{
  156505. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156506. }
  156507. }
  156508. /* seek to an offset relative to the *compressed* data. This also
  156509. scans packets to update the PCM cursor. It will cross a logical
  156510. bitstream boundary, but only if it can't get any packets out of the
  156511. tail of the bitstream we seek to (so no surprises).
  156512. returns zero on success, nonzero on failure */
  156513. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156514. ogg_stream_state work_os;
  156515. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156516. if(!vf->seekable)
  156517. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156518. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156519. /* don't yet clear out decoding machine (if it's initialized), in
  156520. the case we're in the same link. Restart the decode lapping, and
  156521. let _fetch_and_process_packet deal with a potential bitstream
  156522. boundary */
  156523. vf->pcm_offset=-1;
  156524. ogg_stream_reset_serialno(&vf->os,
  156525. vf->current_serialno); /* must set serialno */
  156526. vorbis_synthesis_restart(&vf->vd);
  156527. _seek_helper(vf,pos);
  156528. /* we need to make sure the pcm_offset is set, but we don't want to
  156529. advance the raw cursor past good packets just to get to the first
  156530. with a granulepos. That's not equivalent behavior to beginning
  156531. decoding as immediately after the seek position as possible.
  156532. So, a hack. We use two stream states; a local scratch state and
  156533. the shared vf->os stream state. We use the local state to
  156534. scan, and the shared state as a buffer for later decode.
  156535. Unfortuantely, on the last page we still advance to last packet
  156536. because the granulepos on the last page is not necessarily on a
  156537. packet boundary, and we need to make sure the granpos is
  156538. correct.
  156539. */
  156540. {
  156541. ogg_page og;
  156542. ogg_packet op;
  156543. int lastblock=0;
  156544. int accblock=0;
  156545. int thisblock;
  156546. int eosflag;
  156547. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156548. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156549. return from not necessarily
  156550. starting from the beginning */
  156551. while(1){
  156552. if(vf->ready_state>=STREAMSET){
  156553. /* snarf/scan a packet if we can */
  156554. int result=ogg_stream_packetout(&work_os,&op);
  156555. if(result>0){
  156556. if(vf->vi[vf->current_link].codec_setup){
  156557. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156558. if(thisblock<0){
  156559. ogg_stream_packetout(&vf->os,NULL);
  156560. thisblock=0;
  156561. }else{
  156562. if(eosflag)
  156563. ogg_stream_packetout(&vf->os,NULL);
  156564. else
  156565. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156566. }
  156567. if(op.granulepos!=-1){
  156568. int i,link=vf->current_link;
  156569. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156570. if(granulepos<0)granulepos=0;
  156571. for(i=0;i<link;i++)
  156572. granulepos+=vf->pcmlengths[i*2+1];
  156573. vf->pcm_offset=granulepos-accblock;
  156574. break;
  156575. }
  156576. lastblock=thisblock;
  156577. continue;
  156578. }else
  156579. ogg_stream_packetout(&vf->os,NULL);
  156580. }
  156581. }
  156582. if(!lastblock){
  156583. if(_get_next_page(vf,&og,-1)<0){
  156584. vf->pcm_offset=ov_pcm_total(vf,-1);
  156585. break;
  156586. }
  156587. }else{
  156588. /* huh? Bogus stream with packets but no granulepos */
  156589. vf->pcm_offset=-1;
  156590. break;
  156591. }
  156592. /* has our decoding just traversed a bitstream boundary? */
  156593. if(vf->ready_state>=STREAMSET)
  156594. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156595. _decode_clear(vf); /* clear out stream state */
  156596. ogg_stream_clear(&work_os);
  156597. }
  156598. if(vf->ready_state<STREAMSET){
  156599. int link;
  156600. vf->current_serialno=ogg_page_serialno(&og);
  156601. for(link=0;link<vf->links;link++)
  156602. if(vf->serialnos[link]==vf->current_serialno)break;
  156603. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156604. error out, leave
  156605. machine uninitialized */
  156606. vf->current_link=link;
  156607. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156608. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156609. vf->ready_state=STREAMSET;
  156610. }
  156611. ogg_stream_pagein(&vf->os,&og);
  156612. ogg_stream_pagein(&work_os,&og);
  156613. eosflag=ogg_page_eos(&og);
  156614. }
  156615. }
  156616. ogg_stream_clear(&work_os);
  156617. vf->bittrack=0.f;
  156618. vf->samptrack=0.f;
  156619. return(0);
  156620. seek_error:
  156621. /* dump the machine so we're in a known state */
  156622. vf->pcm_offset=-1;
  156623. ogg_stream_clear(&work_os);
  156624. _decode_clear(vf);
  156625. return OV_EBADLINK;
  156626. }
  156627. /* Page granularity seek (faster than sample granularity because we
  156628. don't do the last bit of decode to find a specific sample).
  156629. Seek to the last [granule marked] page preceeding the specified pos
  156630. location, such that decoding past the returned point will quickly
  156631. arrive at the requested position. */
  156632. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156633. int link=-1;
  156634. ogg_int64_t result=0;
  156635. ogg_int64_t total=ov_pcm_total(vf,-1);
  156636. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156637. if(!vf->seekable)return(OV_ENOSEEK);
  156638. if(pos<0 || pos>total)return(OV_EINVAL);
  156639. /* which bitstream section does this pcm offset occur in? */
  156640. for(link=vf->links-1;link>=0;link--){
  156641. total-=vf->pcmlengths[link*2+1];
  156642. if(pos>=total)break;
  156643. }
  156644. /* search within the logical bitstream for the page with the highest
  156645. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156646. missing pages or incorrect frame number information in the
  156647. bitstream could make our task impossible. Account for that (it
  156648. would be an error condition) */
  156649. /* new search algorithm by HB (Nicholas Vinen) */
  156650. {
  156651. ogg_int64_t end=vf->offsets[link+1];
  156652. ogg_int64_t begin=vf->offsets[link];
  156653. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156654. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156655. ogg_int64_t target=pos-total+begintime;
  156656. ogg_int64_t best=begin;
  156657. ogg_page og;
  156658. while(begin<end){
  156659. ogg_int64_t bisect;
  156660. if(end-begin<CHUNKSIZE){
  156661. bisect=begin;
  156662. }else{
  156663. /* take a (pretty decent) guess. */
  156664. bisect=begin +
  156665. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156666. if(bisect<=begin)
  156667. bisect=begin+1;
  156668. }
  156669. _seek_helper(vf,bisect);
  156670. while(begin<end){
  156671. result=_get_next_page(vf,&og,end-vf->offset);
  156672. if(result==OV_EREAD) goto seek_error;
  156673. if(result<0){
  156674. if(bisect<=begin+1)
  156675. end=begin; /* found it */
  156676. else{
  156677. if(bisect==0) goto seek_error;
  156678. bisect-=CHUNKSIZE;
  156679. if(bisect<=begin)bisect=begin+1;
  156680. _seek_helper(vf,bisect);
  156681. }
  156682. }else{
  156683. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156684. if(granulepos==-1)continue;
  156685. if(granulepos<target){
  156686. best=result; /* raw offset of packet with granulepos */
  156687. begin=vf->offset; /* raw offset of next page */
  156688. begintime=granulepos;
  156689. if(target-begintime>44100)break;
  156690. bisect=begin; /* *not* begin + 1 */
  156691. }else{
  156692. if(bisect<=begin+1)
  156693. end=begin; /* found it */
  156694. else{
  156695. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156696. end=result;
  156697. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156698. if(bisect<=begin)bisect=begin+1;
  156699. _seek_helper(vf,bisect);
  156700. }else{
  156701. end=result;
  156702. endtime=granulepos;
  156703. break;
  156704. }
  156705. }
  156706. }
  156707. }
  156708. }
  156709. }
  156710. /* found our page. seek to it, update pcm offset. Easier case than
  156711. raw_seek, don't keep packets preceeding granulepos. */
  156712. {
  156713. ogg_page og;
  156714. ogg_packet op;
  156715. /* seek */
  156716. _seek_helper(vf,best);
  156717. vf->pcm_offset=-1;
  156718. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156719. if(link!=vf->current_link){
  156720. /* Different link; dump entire decode machine */
  156721. _decode_clear(vf);
  156722. vf->current_link=link;
  156723. vf->current_serialno=ogg_page_serialno(&og);
  156724. vf->ready_state=STREAMSET;
  156725. }else{
  156726. vorbis_synthesis_restart(&vf->vd);
  156727. }
  156728. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156729. ogg_stream_pagein(&vf->os,&og);
  156730. /* pull out all but last packet; the one with granulepos */
  156731. while(1){
  156732. result=ogg_stream_packetpeek(&vf->os,&op);
  156733. if(result==0){
  156734. /* !!! the packet finishing this page originated on a
  156735. preceeding page. Keep fetching previous pages until we
  156736. get one with a granulepos or without the 'continued' flag
  156737. set. Then just use raw_seek for simplicity. */
  156738. _seek_helper(vf,best);
  156739. while(1){
  156740. result=_get_prev_page(vf,&og);
  156741. if(result<0) goto seek_error;
  156742. if(ogg_page_granulepos(&og)>-1 ||
  156743. !ogg_page_continued(&og)){
  156744. return ov_raw_seek(vf,result);
  156745. }
  156746. vf->offset=result;
  156747. }
  156748. }
  156749. if(result<0){
  156750. result = OV_EBADPACKET;
  156751. goto seek_error;
  156752. }
  156753. if(op.granulepos!=-1){
  156754. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156755. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156756. vf->pcm_offset+=total;
  156757. break;
  156758. }else
  156759. result=ogg_stream_packetout(&vf->os,NULL);
  156760. }
  156761. }
  156762. }
  156763. /* verify result */
  156764. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156765. result=OV_EFAULT;
  156766. goto seek_error;
  156767. }
  156768. vf->bittrack=0.f;
  156769. vf->samptrack=0.f;
  156770. return(0);
  156771. seek_error:
  156772. /* dump machine so we're in a known state */
  156773. vf->pcm_offset=-1;
  156774. _decode_clear(vf);
  156775. return (int)result;
  156776. }
  156777. /* seek to a sample offset relative to the decompressed pcm stream
  156778. returns zero on success, nonzero on failure */
  156779. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156780. int thisblock,lastblock=0;
  156781. int ret=ov_pcm_seek_page(vf,pos);
  156782. if(ret<0)return(ret);
  156783. if((ret=_make_decode_ready(vf)))return ret;
  156784. /* discard leading packets we don't need for the lapping of the
  156785. position we want; don't decode them */
  156786. while(1){
  156787. ogg_packet op;
  156788. ogg_page og;
  156789. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156790. if(ret>0){
  156791. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156792. if(thisblock<0){
  156793. ogg_stream_packetout(&vf->os,NULL);
  156794. continue; /* non audio packet */
  156795. }
  156796. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156797. if(vf->pcm_offset+((thisblock+
  156798. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156799. /* remove the packet from packet queue and track its granulepos */
  156800. ogg_stream_packetout(&vf->os,NULL);
  156801. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156802. only tracking, no
  156803. pcm_decode */
  156804. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156805. /* end of logical stream case is hard, especially with exact
  156806. length positioning. */
  156807. if(op.granulepos>-1){
  156808. int i;
  156809. /* always believe the stream markers */
  156810. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156811. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156812. for(i=0;i<vf->current_link;i++)
  156813. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156814. }
  156815. lastblock=thisblock;
  156816. }else{
  156817. if(ret<0 && ret!=OV_HOLE)break;
  156818. /* suck in a new page */
  156819. if(_get_next_page(vf,&og,-1)<0)break;
  156820. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156821. if(vf->ready_state<STREAMSET){
  156822. int link;
  156823. vf->current_serialno=ogg_page_serialno(&og);
  156824. for(link=0;link<vf->links;link++)
  156825. if(vf->serialnos[link]==vf->current_serialno)break;
  156826. if(link==vf->links)return(OV_EBADLINK);
  156827. vf->current_link=link;
  156828. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156829. vf->ready_state=STREAMSET;
  156830. ret=_make_decode_ready(vf);
  156831. if(ret)return ret;
  156832. lastblock=0;
  156833. }
  156834. ogg_stream_pagein(&vf->os,&og);
  156835. }
  156836. }
  156837. vf->bittrack=0.f;
  156838. vf->samptrack=0.f;
  156839. /* discard samples until we reach the desired position. Crossing a
  156840. logical bitstream boundary with abandon is OK. */
  156841. while(vf->pcm_offset<pos){
  156842. ogg_int64_t target=pos-vf->pcm_offset;
  156843. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156844. if(samples>target)samples=target;
  156845. vorbis_synthesis_read(&vf->vd,samples);
  156846. vf->pcm_offset+=samples;
  156847. if(samples<target)
  156848. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156849. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156850. }
  156851. return 0;
  156852. }
  156853. /* seek to a playback time relative to the decompressed pcm stream
  156854. returns zero on success, nonzero on failure */
  156855. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156856. /* translate time to PCM position and call ov_pcm_seek */
  156857. int link=-1;
  156858. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156859. double time_total=ov_time_total(vf,-1);
  156860. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156861. if(!vf->seekable)return(OV_ENOSEEK);
  156862. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156863. /* which bitstream section does this time offset occur in? */
  156864. for(link=vf->links-1;link>=0;link--){
  156865. pcm_total-=vf->pcmlengths[link*2+1];
  156866. time_total-=ov_time_total(vf,link);
  156867. if(seconds>=time_total)break;
  156868. }
  156869. /* enough information to convert time offset to pcm offset */
  156870. {
  156871. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156872. return(ov_pcm_seek(vf,target));
  156873. }
  156874. }
  156875. /* page-granularity version of ov_time_seek
  156876. returns zero on success, nonzero on failure */
  156877. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156878. /* translate time to PCM position and call ov_pcm_seek */
  156879. int link=-1;
  156880. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156881. double time_total=ov_time_total(vf,-1);
  156882. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156883. if(!vf->seekable)return(OV_ENOSEEK);
  156884. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156885. /* which bitstream section does this time offset occur in? */
  156886. for(link=vf->links-1;link>=0;link--){
  156887. pcm_total-=vf->pcmlengths[link*2+1];
  156888. time_total-=ov_time_total(vf,link);
  156889. if(seconds>=time_total)break;
  156890. }
  156891. /* enough information to convert time offset to pcm offset */
  156892. {
  156893. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156894. return(ov_pcm_seek_page(vf,target));
  156895. }
  156896. }
  156897. /* tell the current stream offset cursor. Note that seek followed by
  156898. tell will likely not give the set offset due to caching */
  156899. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156900. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156901. return(vf->offset);
  156902. }
  156903. /* return PCM offset (sample) of next PCM sample to be read */
  156904. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156905. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156906. return(vf->pcm_offset);
  156907. }
  156908. /* return time offset (seconds) of next PCM sample to be read */
  156909. double ov_time_tell(OggVorbis_File *vf){
  156910. int link=0;
  156911. ogg_int64_t pcm_total=0;
  156912. double time_total=0.f;
  156913. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156914. if(vf->seekable){
  156915. pcm_total=ov_pcm_total(vf,-1);
  156916. time_total=ov_time_total(vf,-1);
  156917. /* which bitstream section does this time offset occur in? */
  156918. for(link=vf->links-1;link>=0;link--){
  156919. pcm_total-=vf->pcmlengths[link*2+1];
  156920. time_total-=ov_time_total(vf,link);
  156921. if(vf->pcm_offset>=pcm_total)break;
  156922. }
  156923. }
  156924. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156925. }
  156926. /* link: -1) return the vorbis_info struct for the bitstream section
  156927. currently being decoded
  156928. 0-n) to request information for a specific bitstream section
  156929. In the case of a non-seekable bitstream, any call returns the
  156930. current bitstream. NULL in the case that the machine is not
  156931. initialized */
  156932. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156933. if(vf->seekable){
  156934. if(link<0)
  156935. if(vf->ready_state>=STREAMSET)
  156936. return vf->vi+vf->current_link;
  156937. else
  156938. return vf->vi;
  156939. else
  156940. if(link>=vf->links)
  156941. return NULL;
  156942. else
  156943. return vf->vi+link;
  156944. }else{
  156945. return vf->vi;
  156946. }
  156947. }
  156948. /* grr, strong typing, grr, no templates/inheritence, grr */
  156949. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156950. if(vf->seekable){
  156951. if(link<0)
  156952. if(vf->ready_state>=STREAMSET)
  156953. return vf->vc+vf->current_link;
  156954. else
  156955. return vf->vc;
  156956. else
  156957. if(link>=vf->links)
  156958. return NULL;
  156959. else
  156960. return vf->vc+link;
  156961. }else{
  156962. return vf->vc;
  156963. }
  156964. }
  156965. static int host_is_big_endian() {
  156966. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156967. unsigned char *bytewise = (unsigned char *)&pattern;
  156968. if (bytewise[0] == 0xfe) return 1;
  156969. return 0;
  156970. }
  156971. /* up to this point, everything could more or less hide the multiple
  156972. logical bitstream nature of chaining from the toplevel application
  156973. if the toplevel application didn't particularly care. However, at
  156974. the point that we actually read audio back, the multiple-section
  156975. nature must surface: Multiple bitstream sections do not necessarily
  156976. have to have the same number of channels or sampling rate.
  156977. ov_read returns the sequential logical bitstream number currently
  156978. being decoded along with the PCM data in order that the toplevel
  156979. application can take action on channel/sample rate changes. This
  156980. number will be incremented even for streamed (non-seekable) streams
  156981. (for seekable streams, it represents the actual logical bitstream
  156982. index within the physical bitstream. Note that the accessor
  156983. functions above are aware of this dichotomy).
  156984. input values: buffer) a buffer to hold packed PCM data for return
  156985. length) the byte length requested to be placed into buffer
  156986. bigendianp) should the data be packed LSB first (0) or
  156987. MSB first (1)
  156988. word) word size for output. currently 1 (byte) or
  156989. 2 (16 bit short)
  156990. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156991. 0) EOF
  156992. n) number of bytes of PCM actually returned. The
  156993. below works on a packet-by-packet basis, so the
  156994. return length is not related to the 'length' passed
  156995. in, just guaranteed to fit.
  156996. *section) set to the logical bitstream number */
  156997. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156998. int bigendianp,int word,int sgned,int *bitstream){
  156999. int i,j;
  157000. int host_endian = host_is_big_endian();
  157001. float **pcm;
  157002. long samples;
  157003. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157004. while(1){
  157005. if(vf->ready_state==INITSET){
  157006. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157007. if(samples)break;
  157008. }
  157009. /* suck in another packet */
  157010. {
  157011. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157012. if(ret==OV_EOF)
  157013. return(0);
  157014. if(ret<=0)
  157015. return(ret);
  157016. }
  157017. }
  157018. if(samples>0){
  157019. /* yay! proceed to pack data into the byte buffer */
  157020. long channels=ov_info(vf,-1)->channels;
  157021. long bytespersample=word * channels;
  157022. vorbis_fpu_control fpu;
  157023. (void) fpu; // (to avoid a warning about it being unused)
  157024. if(samples>length/bytespersample)samples=length/bytespersample;
  157025. if(samples <= 0)
  157026. return OV_EINVAL;
  157027. /* a tight loop to pack each size */
  157028. {
  157029. int val;
  157030. if(word==1){
  157031. int off=(sgned?0:128);
  157032. vorbis_fpu_setround(&fpu);
  157033. for(j=0;j<samples;j++)
  157034. for(i=0;i<channels;i++){
  157035. val=vorbis_ftoi(pcm[i][j]*128.f);
  157036. if(val>127)val=127;
  157037. else if(val<-128)val=-128;
  157038. *buffer++=val+off;
  157039. }
  157040. vorbis_fpu_restore(fpu);
  157041. }else{
  157042. int off=(sgned?0:32768);
  157043. if(host_endian==bigendianp){
  157044. if(sgned){
  157045. vorbis_fpu_setround(&fpu);
  157046. for(i=0;i<channels;i++) { /* It's faster in this order */
  157047. float *src=pcm[i];
  157048. short *dest=((short *)buffer)+i;
  157049. for(j=0;j<samples;j++) {
  157050. val=vorbis_ftoi(src[j]*32768.f);
  157051. if(val>32767)val=32767;
  157052. else if(val<-32768)val=-32768;
  157053. *dest=val;
  157054. dest+=channels;
  157055. }
  157056. }
  157057. vorbis_fpu_restore(fpu);
  157058. }else{
  157059. vorbis_fpu_setround(&fpu);
  157060. for(i=0;i<channels;i++) {
  157061. float *src=pcm[i];
  157062. short *dest=((short *)buffer)+i;
  157063. for(j=0;j<samples;j++) {
  157064. val=vorbis_ftoi(src[j]*32768.f);
  157065. if(val>32767)val=32767;
  157066. else if(val<-32768)val=-32768;
  157067. *dest=val+off;
  157068. dest+=channels;
  157069. }
  157070. }
  157071. vorbis_fpu_restore(fpu);
  157072. }
  157073. }else if(bigendianp){
  157074. vorbis_fpu_setround(&fpu);
  157075. for(j=0;j<samples;j++)
  157076. for(i=0;i<channels;i++){
  157077. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157078. if(val>32767)val=32767;
  157079. else if(val<-32768)val=-32768;
  157080. val+=off;
  157081. *buffer++=(val>>8);
  157082. *buffer++=(val&0xff);
  157083. }
  157084. vorbis_fpu_restore(fpu);
  157085. }else{
  157086. int val;
  157087. vorbis_fpu_setround(&fpu);
  157088. for(j=0;j<samples;j++)
  157089. for(i=0;i<channels;i++){
  157090. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157091. if(val>32767)val=32767;
  157092. else if(val<-32768)val=-32768;
  157093. val+=off;
  157094. *buffer++=(val&0xff);
  157095. *buffer++=(val>>8);
  157096. }
  157097. vorbis_fpu_restore(fpu);
  157098. }
  157099. }
  157100. }
  157101. vorbis_synthesis_read(&vf->vd,samples);
  157102. vf->pcm_offset+=samples;
  157103. if(bitstream)*bitstream=vf->current_link;
  157104. return(samples*bytespersample);
  157105. }else{
  157106. return(samples);
  157107. }
  157108. }
  157109. /* input values: pcm_channels) a float vector per channel of output
  157110. length) the sample length being read by the app
  157111. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157112. 0) EOF
  157113. n) number of samples of PCM actually returned. The
  157114. below works on a packet-by-packet basis, so the
  157115. return length is not related to the 'length' passed
  157116. in, just guaranteed to fit.
  157117. *section) set to the logical bitstream number */
  157118. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157119. int *bitstream){
  157120. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157121. while(1){
  157122. if(vf->ready_state==INITSET){
  157123. float **pcm;
  157124. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157125. if(samples){
  157126. if(pcm_channels)*pcm_channels=pcm;
  157127. if(samples>length)samples=length;
  157128. vorbis_synthesis_read(&vf->vd,samples);
  157129. vf->pcm_offset+=samples;
  157130. if(bitstream)*bitstream=vf->current_link;
  157131. return samples;
  157132. }
  157133. }
  157134. /* suck in another packet */
  157135. {
  157136. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157137. if(ret==OV_EOF)return(0);
  157138. if(ret<=0)return(ret);
  157139. }
  157140. }
  157141. }
  157142. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157143. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  157144. ogg_int64_t off);
  157145. static void _ov_splice(float **pcm,float **lappcm,
  157146. int n1, int n2,
  157147. int ch1, int ch2,
  157148. float *w1, float *w2){
  157149. int i,j;
  157150. float *w=w1;
  157151. int n=n1;
  157152. if(n1>n2){
  157153. n=n2;
  157154. w=w2;
  157155. }
  157156. /* splice */
  157157. for(j=0;j<ch1 && j<ch2;j++){
  157158. float *s=lappcm[j];
  157159. float *d=pcm[j];
  157160. for(i=0;i<n;i++){
  157161. float wd=w[i]*w[i];
  157162. float ws=1.-wd;
  157163. d[i]=d[i]*wd + s[i]*ws;
  157164. }
  157165. }
  157166. /* window from zero */
  157167. for(;j<ch2;j++){
  157168. float *d=pcm[j];
  157169. for(i=0;i<n;i++){
  157170. float wd=w[i]*w[i];
  157171. d[i]=d[i]*wd;
  157172. }
  157173. }
  157174. }
  157175. /* make sure vf is INITSET */
  157176. static int _ov_initset(OggVorbis_File *vf){
  157177. while(1){
  157178. if(vf->ready_state==INITSET)break;
  157179. /* suck in another packet */
  157180. {
  157181. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157182. if(ret<0 && ret!=OV_HOLE)return(ret);
  157183. }
  157184. }
  157185. return 0;
  157186. }
  157187. /* make sure vf is INITSET and that we have a primed buffer; if
  157188. we're crosslapping at a stream section boundary, this also makes
  157189. sure we're sanity checking against the right stream information */
  157190. static int _ov_initprime(OggVorbis_File *vf){
  157191. vorbis_dsp_state *vd=&vf->vd;
  157192. while(1){
  157193. if(vf->ready_state==INITSET)
  157194. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157195. /* suck in another packet */
  157196. {
  157197. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157198. if(ret<0 && ret!=OV_HOLE)return(ret);
  157199. }
  157200. }
  157201. return 0;
  157202. }
  157203. /* grab enough data for lapping from vf; this may be in the form of
  157204. unreturned, already-decoded pcm, remaining PCM we will need to
  157205. decode, or synthetic postextrapolation from last packets. */
  157206. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157207. float **lappcm,int lapsize){
  157208. int lapcount=0,i;
  157209. float **pcm;
  157210. /* try first to decode the lapping data */
  157211. while(lapcount<lapsize){
  157212. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157213. if(samples){
  157214. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157215. for(i=0;i<vi->channels;i++)
  157216. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157217. lapcount+=samples;
  157218. vorbis_synthesis_read(vd,samples);
  157219. }else{
  157220. /* suck in another packet */
  157221. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157222. if(ret==OV_EOF)break;
  157223. }
  157224. }
  157225. if(lapcount<lapsize){
  157226. /* failed to get lapping data from normal decode; pry it from the
  157227. postextrapolation buffering, or the second half of the MDCT
  157228. from the last packet */
  157229. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157230. if(samples==0){
  157231. for(i=0;i<vi->channels;i++)
  157232. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157233. lapcount=lapsize;
  157234. }else{
  157235. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157236. for(i=0;i<vi->channels;i++)
  157237. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157238. lapcount+=samples;
  157239. }
  157240. }
  157241. }
  157242. /* this sets up crosslapping of a sample by using trailing data from
  157243. sample 1 and lapping it into the windowing buffer of sample 2 */
  157244. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157245. vorbis_info *vi1,*vi2;
  157246. float **lappcm;
  157247. float **pcm;
  157248. float *w1,*w2;
  157249. int n1,n2,i,ret,hs1,hs2;
  157250. if(vf1==vf2)return(0); /* degenerate case */
  157251. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157252. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157253. /* the relevant overlap buffers must be pre-checked and pre-primed
  157254. before looking at settings in the event that priming would cross
  157255. a bitstream boundary. So, do it now */
  157256. ret=_ov_initset(vf1);
  157257. if(ret)return(ret);
  157258. ret=_ov_initprime(vf2);
  157259. if(ret)return(ret);
  157260. vi1=ov_info(vf1,-1);
  157261. vi2=ov_info(vf2,-1);
  157262. hs1=ov_halfrate_p(vf1);
  157263. hs2=ov_halfrate_p(vf2);
  157264. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157265. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157266. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157267. w1=vorbis_window(&vf1->vd,0);
  157268. w2=vorbis_window(&vf2->vd,0);
  157269. for(i=0;i<vi1->channels;i++)
  157270. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157271. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157272. /* have a lapping buffer from vf1; now to splice it into the lapping
  157273. buffer of vf2 */
  157274. /* consolidate and expose the buffer. */
  157275. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157276. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157277. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157278. /* splice */
  157279. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157280. /* done */
  157281. return(0);
  157282. }
  157283. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157284. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157285. vorbis_info *vi;
  157286. float **lappcm;
  157287. float **pcm;
  157288. float *w1,*w2;
  157289. int n1,n2,ch1,ch2,hs;
  157290. int i,ret;
  157291. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157292. ret=_ov_initset(vf);
  157293. if(ret)return(ret);
  157294. vi=ov_info(vf,-1);
  157295. hs=ov_halfrate_p(vf);
  157296. ch1=vi->channels;
  157297. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157298. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157299. persistent; even if the decode state
  157300. from this link gets dumped, this
  157301. window array continues to exist */
  157302. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157303. for(i=0;i<ch1;i++)
  157304. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157305. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157306. /* have lapping data; seek and prime the buffer */
  157307. ret=localseek(vf,pos);
  157308. if(ret)return ret;
  157309. ret=_ov_initprime(vf);
  157310. if(ret)return(ret);
  157311. /* Guard against cross-link changes; they're perfectly legal */
  157312. vi=ov_info(vf,-1);
  157313. ch2=vi->channels;
  157314. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157315. w2=vorbis_window(&vf->vd,0);
  157316. /* consolidate and expose the buffer. */
  157317. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157318. /* splice */
  157319. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157320. /* done */
  157321. return(0);
  157322. }
  157323. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157324. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157325. }
  157326. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157327. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157328. }
  157329. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157330. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157331. }
  157332. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157333. int (*localseek)(OggVorbis_File *,double)){
  157334. vorbis_info *vi;
  157335. float **lappcm;
  157336. float **pcm;
  157337. float *w1,*w2;
  157338. int n1,n2,ch1,ch2,hs;
  157339. int i,ret;
  157340. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157341. ret=_ov_initset(vf);
  157342. if(ret)return(ret);
  157343. vi=ov_info(vf,-1);
  157344. hs=ov_halfrate_p(vf);
  157345. ch1=vi->channels;
  157346. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157347. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157348. persistent; even if the decode state
  157349. from this link gets dumped, this
  157350. window array continues to exist */
  157351. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157352. for(i=0;i<ch1;i++)
  157353. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157354. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157355. /* have lapping data; seek and prime the buffer */
  157356. ret=localseek(vf,pos);
  157357. if(ret)return ret;
  157358. ret=_ov_initprime(vf);
  157359. if(ret)return(ret);
  157360. /* Guard against cross-link changes; they're perfectly legal */
  157361. vi=ov_info(vf,-1);
  157362. ch2=vi->channels;
  157363. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157364. w2=vorbis_window(&vf->vd,0);
  157365. /* consolidate and expose the buffer. */
  157366. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157367. /* splice */
  157368. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157369. /* done */
  157370. return(0);
  157371. }
  157372. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157373. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157374. }
  157375. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157376. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157377. }
  157378. #endif
  157379. /*** End of inlined file: vorbisfile.c ***/
  157380. /*** Start of inlined file: window.c ***/
  157381. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157382. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157383. // tasks..
  157384. #if JUCE_MSVC
  157385. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157386. #endif
  157387. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157388. #if JUCE_USE_OGGVORBIS
  157389. #include <stdlib.h>
  157390. #include <math.h>
  157391. static float vwin64[32] = {
  157392. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157393. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157394. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157395. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157396. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157397. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157398. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157399. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157400. };
  157401. static float vwin128[64] = {
  157402. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157403. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157404. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157405. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157406. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157407. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157408. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157409. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157410. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157411. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157412. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157413. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157414. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157415. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157416. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157417. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157418. };
  157419. static float vwin256[128] = {
  157420. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157421. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157422. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157423. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157424. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157425. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157426. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157427. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157428. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157429. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157430. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157431. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157432. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157433. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157434. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157435. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157436. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157437. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157438. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157439. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157440. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157441. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157442. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157443. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157444. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157445. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157446. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157447. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157448. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157449. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157450. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157451. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157452. };
  157453. static float vwin512[256] = {
  157454. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157455. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157456. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157457. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157458. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157459. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157460. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157461. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157462. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157463. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157464. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157465. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157466. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157467. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157468. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157469. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157470. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157471. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157472. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157473. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157474. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157475. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157476. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157477. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157478. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157479. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157480. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157481. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157482. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157483. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157484. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157485. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157486. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157487. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157488. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157489. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157490. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157491. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157492. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157493. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157494. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157495. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157496. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157497. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157498. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157499. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157500. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157501. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157502. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157503. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157504. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157505. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157506. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157507. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157508. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157509. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157510. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157511. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157512. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157513. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157514. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157515. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157516. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157517. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157518. };
  157519. static float vwin1024[512] = {
  157520. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157521. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157522. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157523. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157524. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157525. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157526. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157527. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157528. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157529. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157530. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157531. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157532. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157533. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157534. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157535. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157536. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157537. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157538. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157539. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157540. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157541. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157542. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157543. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157544. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157545. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157546. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157547. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157548. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157549. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157550. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157551. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157552. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157553. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157554. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157555. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157556. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157557. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157558. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157559. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157560. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157561. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157562. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157563. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157564. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157565. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157566. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157567. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157568. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157569. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157570. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157571. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157572. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157573. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157574. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157575. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157576. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157577. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157578. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157579. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157580. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157581. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157582. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157583. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157584. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157585. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157586. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157587. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157588. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157589. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157590. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157591. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157592. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157593. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157594. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157595. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157596. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157597. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157598. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157599. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157600. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157601. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157602. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157603. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157604. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157605. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157606. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157607. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157608. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157609. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157610. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157611. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157612. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157613. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157614. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157615. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157616. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157617. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157618. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157619. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157620. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157621. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157622. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157623. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157624. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157625. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157626. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157627. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157628. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157629. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157630. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157631. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157632. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157633. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157634. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157635. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157636. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157637. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157638. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157639. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157640. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157641. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157642. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157643. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157644. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157645. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157646. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157647. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157648. };
  157649. static float vwin2048[1024] = {
  157650. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157651. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157652. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157653. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157654. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157655. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157656. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157657. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157658. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157659. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157660. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157661. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157662. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157663. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157664. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157665. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157666. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157667. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157668. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157669. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157670. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157671. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157672. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157673. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157674. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157675. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157676. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157677. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157678. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157679. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157680. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157681. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157682. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157683. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157684. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157685. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157686. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157687. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157688. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157689. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157690. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157691. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157692. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157693. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157694. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157695. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157696. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157697. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157698. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157699. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157700. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157701. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157702. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157703. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157704. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157705. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157706. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157707. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157708. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157709. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157710. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157711. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157712. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157713. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157714. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157715. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157716. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157717. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157718. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157719. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157720. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157721. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157722. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157723. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157724. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157725. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157726. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157727. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157728. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157729. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157730. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157731. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157732. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157733. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157734. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157735. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157736. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157737. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157738. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157739. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157740. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157741. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157742. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157743. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157744. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157745. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157746. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157747. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157748. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157749. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157750. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157751. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157752. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157753. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157754. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157755. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157756. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157757. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157758. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157759. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157760. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157761. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157762. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157763. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157764. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157765. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157766. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157767. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157768. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157769. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157770. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157771. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157772. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157773. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157774. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157775. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157776. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157777. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157778. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157779. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157780. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157781. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157782. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157783. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157784. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157785. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157786. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157787. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157788. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157789. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157790. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157791. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157792. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157793. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157794. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157795. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157796. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157797. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157798. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157799. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157800. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157801. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157802. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157803. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157804. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157805. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157806. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157807. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157808. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157809. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157810. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157811. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157812. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157813. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157814. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157815. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157816. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157817. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157818. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157819. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157820. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157821. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157822. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157823. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157824. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157825. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157826. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157827. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157828. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157829. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157830. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157831. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157832. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157833. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157834. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157835. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157836. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157837. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157838. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157839. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157840. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157841. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157842. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157843. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157844. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157845. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157846. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157847. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157848. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157849. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157850. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157851. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157852. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157853. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157854. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157855. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157856. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157857. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157858. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157859. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157860. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157861. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157862. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157863. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157864. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157865. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157866. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157867. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157868. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157869. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157870. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157871. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157872. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157873. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157874. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157875. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157876. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157877. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157878. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157879. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157880. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157881. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157882. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157883. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157884. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157885. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157886. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157887. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157888. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157889. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157890. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157891. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157892. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157893. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157894. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157895. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157896. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157897. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157898. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157899. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157900. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157901. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157902. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157903. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157904. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157905. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157906. };
  157907. static float vwin4096[2048] = {
  157908. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157909. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157910. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157911. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157912. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157913. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157914. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157915. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157916. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157917. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157918. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157919. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157920. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157921. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157922. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157923. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157924. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157925. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157926. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157927. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157928. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157929. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157930. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157931. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157932. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157933. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157934. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157935. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157936. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157937. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157938. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157939. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157940. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157941. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157942. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157943. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157944. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157945. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157946. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157947. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157948. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157949. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157950. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157951. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157952. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157953. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157954. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157955. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157956. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157957. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157958. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157959. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157960. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157961. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157962. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157963. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157964. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157965. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157966. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157967. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157968. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157969. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157970. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157971. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157972. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157973. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157974. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157975. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157976. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157977. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157978. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157979. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157980. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157981. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157982. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157983. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157984. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157985. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157986. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157987. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157988. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157989. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157990. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157991. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157992. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157993. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157994. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157995. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157996. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157997. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157998. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157999. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  158000. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  158001. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  158002. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  158003. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  158004. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  158005. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  158006. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  158007. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  158008. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  158009. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  158010. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  158011. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  158012. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  158013. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  158014. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  158015. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  158016. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  158017. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  158018. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  158019. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  158020. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  158021. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  158022. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  158023. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  158024. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  158025. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  158026. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  158027. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  158028. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  158029. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  158030. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  158031. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  158032. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  158033. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  158034. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  158035. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  158036. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  158037. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  158038. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  158039. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  158040. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  158041. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  158042. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  158043. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  158044. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  158045. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  158046. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  158047. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  158048. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  158049. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  158050. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  158051. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  158052. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  158053. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  158054. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  158055. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  158056. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  158057. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  158058. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  158059. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  158060. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  158061. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  158062. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  158063. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  158064. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  158065. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  158066. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  158067. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  158068. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  158069. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  158070. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  158071. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  158072. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  158073. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  158074. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  158075. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  158076. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  158077. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  158078. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  158079. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  158080. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  158081. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  158082. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  158083. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  158084. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  158085. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  158086. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  158087. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  158088. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  158089. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  158090. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  158091. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  158092. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  158093. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  158094. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  158095. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  158096. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  158097. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  158098. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  158099. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  158100. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  158101. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  158102. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  158103. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  158104. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  158105. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  158106. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  158107. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  158108. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  158109. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  158110. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  158111. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  158112. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  158113. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  158114. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158115. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158116. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158117. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158118. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158119. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158120. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158121. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158122. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158123. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158124. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158125. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158126. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158127. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158128. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158129. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158130. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158131. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158132. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158133. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158134. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158135. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158136. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158137. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158138. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158139. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158140. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158141. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158142. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158143. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158144. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158145. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158146. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158147. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158148. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158149. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158150. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158151. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158152. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158153. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158154. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158155. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158156. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158157. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158158. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158159. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158160. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158161. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158162. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158163. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158164. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158165. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158166. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158167. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158168. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158169. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158170. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158171. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158172. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158173. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158174. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158175. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158176. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158177. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158178. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158179. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158180. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158181. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158182. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158183. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158184. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158185. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158186. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158187. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158188. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158189. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158190. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158191. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158192. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158193. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158194. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158195. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158196. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158197. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158198. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158199. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158200. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158201. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158202. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158203. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158204. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158205. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158206. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158207. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158208. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158209. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158210. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158211. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158212. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158213. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158214. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158215. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158216. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158217. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158218. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158219. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158220. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158221. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158222. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158223. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158224. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158225. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158226. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158227. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158228. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158229. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158230. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158231. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158232. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158233. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158234. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158235. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158236. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158237. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158238. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158239. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158240. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158241. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158242. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158243. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158244. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158245. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158246. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158247. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158248. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158249. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158250. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158251. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158252. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158253. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158254. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158255. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158256. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158257. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158258. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158259. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158260. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158261. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158262. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158263. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158264. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158265. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158266. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158267. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158268. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158269. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158270. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158271. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158272. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158273. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158274. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158275. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158276. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158277. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158278. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158279. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158280. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158281. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158282. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158283. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158284. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158285. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158286. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158287. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158288. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158289. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158290. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158291. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158292. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158293. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158294. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158295. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158296. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158297. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158298. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158299. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158300. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158301. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158302. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158303. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158304. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158305. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158306. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158307. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158308. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158309. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158310. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158311. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158312. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158313. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158314. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158315. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158316. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158317. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158318. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158319. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158320. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158321. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158322. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158323. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158324. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158325. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158326. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158327. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158328. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158329. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158330. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158331. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158332. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158333. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158334. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158335. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158336. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158337. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158338. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158339. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158340. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158341. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158342. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158343. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158344. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158345. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158346. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158347. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158348. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158349. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158350. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158351. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158352. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158353. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158354. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158355. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158356. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158357. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158358. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158359. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158360. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158361. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158362. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158363. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158364. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158365. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158366. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158367. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158368. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158369. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158370. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158371. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158372. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158373. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158374. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158375. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158376. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158377. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158378. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158379. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158380. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158381. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158382. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158383. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158384. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158385. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158386. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158387. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158388. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158389. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158390. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158391. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158392. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158393. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158394. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158395. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158396. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158397. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158398. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158399. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158400. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158401. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158402. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158403. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158404. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158405. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158406. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158407. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158408. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158409. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158410. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158411. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158412. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158413. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158414. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158415. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158416. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158417. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158418. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158419. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158420. };
  158421. static float vwin8192[4096] = {
  158422. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158423. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158424. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158425. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158426. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158427. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158428. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158429. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158430. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158431. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158432. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158433. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158434. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158435. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158436. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158437. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158438. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158439. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158440. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158441. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158442. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158443. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158444. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158445. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158446. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158447. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158448. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158449. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158450. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158451. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158452. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158453. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158454. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158455. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158456. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158457. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158458. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158459. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158460. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158461. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158462. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158463. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158464. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158465. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158466. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158467. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158468. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158469. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158470. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158471. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158472. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158473. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158474. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158475. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158476. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158477. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158478. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158479. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158480. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158481. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158482. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158483. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158484. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158485. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158486. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158487. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158488. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158489. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158490. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158491. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158492. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158493. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158494. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158495. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158496. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158497. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158498. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158499. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158500. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158501. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158502. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158503. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158504. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158505. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158506. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158507. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158508. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158509. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158510. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158511. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158512. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158513. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158514. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158515. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158516. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158517. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158518. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158519. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158520. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158521. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158522. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158523. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158524. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158525. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158526. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158527. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158528. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158529. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158530. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158531. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158532. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158533. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158534. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158535. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158536. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158537. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158538. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158539. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158540. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158541. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158542. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158543. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158544. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158545. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158546. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158547. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158548. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158549. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158550. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158551. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158552. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158553. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158554. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158555. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158556. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158557. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158558. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158559. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158560. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158561. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158562. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158563. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158564. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158565. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158566. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158567. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158568. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158569. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158570. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158571. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158572. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158573. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158574. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158575. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158576. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158577. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158578. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158579. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158580. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158581. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158582. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158583. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158584. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158585. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158586. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158587. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158588. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158589. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158590. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158591. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158592. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158593. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158594. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158595. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158596. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158597. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158598. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158599. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158600. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158601. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158602. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158603. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158604. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158605. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158606. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158607. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158608. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158609. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158610. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158611. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158612. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158613. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158614. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158615. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158616. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158617. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158618. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158619. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158620. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158621. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158622. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158623. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158624. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158625. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158626. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158627. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158628. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158629. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158630. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158631. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158632. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158633. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158634. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158635. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158636. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158637. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158638. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158639. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158640. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158641. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158642. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158643. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158644. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158645. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158646. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158647. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158648. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158649. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158650. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158651. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158652. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158653. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158654. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158655. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158656. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158657. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158658. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158659. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158660. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158661. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158662. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158663. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158664. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158665. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158666. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158667. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158668. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158669. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158670. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158671. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158672. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158673. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158674. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158675. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158676. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158677. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158678. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158679. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158680. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158681. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158682. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158683. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158684. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158685. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158686. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158687. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158688. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158689. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158690. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158691. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158692. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158693. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158694. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158695. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158696. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158697. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158698. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158699. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158700. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158701. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158702. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158703. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158704. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158705. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158706. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158707. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158708. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158709. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158710. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158711. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158712. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158713. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158714. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158715. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158716. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158717. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158718. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158719. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158720. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158721. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158722. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158723. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158724. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158725. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158726. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158727. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158728. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158729. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158730. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158731. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158732. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158733. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158734. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158735. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158736. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158737. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158738. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158739. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158740. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158741. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158742. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158743. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158744. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158745. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158746. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158747. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158748. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158749. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158750. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158751. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158752. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158753. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158754. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158755. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158756. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158757. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158758. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158759. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158760. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158761. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158762. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158763. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158764. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158765. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158766. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158767. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158768. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158769. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158770. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158771. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158772. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158773. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158774. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158775. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158776. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158777. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158778. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158779. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158780. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158781. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158782. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158783. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158784. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158785. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158786. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158787. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158788. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158789. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158790. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158791. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158792. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158793. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158794. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158795. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158796. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158797. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158798. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158799. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158800. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158801. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158802. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158803. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158804. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158805. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158806. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158807. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158808. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158809. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158810. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158811. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158812. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158813. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158814. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158815. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158816. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158817. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158818. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158819. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158820. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158821. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158822. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158823. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158824. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158825. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158826. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158827. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158828. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158829. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158830. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158831. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158832. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158833. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158834. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158835. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158836. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158837. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158838. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158839. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158840. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158841. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158842. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158843. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158844. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158845. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158846. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158847. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158848. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158849. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158850. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158851. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158852. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158853. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158854. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158855. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158856. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158857. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158858. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158859. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158860. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158861. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158862. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158863. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158864. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158865. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158866. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158867. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158868. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158869. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158870. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158871. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158872. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158873. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158874. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158875. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158876. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158877. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158878. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158879. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158880. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158881. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158882. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158883. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158884. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158885. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158886. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158887. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158888. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158889. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158890. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158891. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158892. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158893. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158894. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158895. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158896. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158897. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158898. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158899. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158900. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158901. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158902. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158903. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158904. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158905. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158906. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158907. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158908. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158909. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158910. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158911. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158912. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158913. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158914. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158915. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158916. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158917. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158918. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158919. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158920. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158921. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158922. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158923. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158924. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158925. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158926. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158927. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158928. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158929. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158930. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158931. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158932. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158933. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158934. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158935. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158936. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158937. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158938. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158939. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158940. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158941. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158942. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158943. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158944. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158945. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158946. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158947. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158948. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158949. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158950. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158951. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158952. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158953. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158954. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158955. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158956. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158957. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158958. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158959. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158960. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158961. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158962. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158963. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158964. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158965. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158966. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158967. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158968. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158969. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158970. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158971. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158972. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158973. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158974. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158975. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158976. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158977. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158978. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158979. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158980. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158981. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158982. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158983. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158984. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158985. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158986. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158987. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158988. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158989. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158990. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158991. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158992. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158993. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158994. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158995. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158996. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158997. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158998. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158999. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  159000. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  159001. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  159002. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  159003. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  159004. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  159005. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  159006. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  159007. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  159008. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  159009. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  159010. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  159011. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  159012. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  159013. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  159014. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  159015. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  159016. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  159017. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  159018. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  159019. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  159020. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  159021. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  159022. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  159023. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  159024. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  159025. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  159026. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  159027. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  159028. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  159029. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  159030. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  159031. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  159032. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  159033. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  159034. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  159035. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  159036. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  159037. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  159038. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  159039. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  159040. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  159041. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  159042. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  159043. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  159044. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  159045. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  159046. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  159047. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  159048. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  159049. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  159050. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  159051. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  159052. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  159053. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  159054. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  159055. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  159056. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  159057. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  159058. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  159059. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  159060. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  159061. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  159062. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  159063. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  159064. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  159065. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  159066. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  159067. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  159068. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  159069. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  159070. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  159071. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  159072. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  159073. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  159074. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  159075. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  159076. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  159077. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  159078. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  159079. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  159080. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  159081. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  159082. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  159083. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  159084. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  159085. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  159086. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  159087. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  159088. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  159089. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  159090. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  159091. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  159092. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  159093. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  159094. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  159095. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  159096. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  159097. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  159098. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  159099. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  159100. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  159101. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  159102. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  159103. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  159104. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  159105. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  159106. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  159107. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  159108. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  159109. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  159110. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  159111. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  159112. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  159113. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  159114. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159115. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159116. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159117. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159118. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159119. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159120. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159121. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159122. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159123. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159124. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159125. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159126. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159127. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159128. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159129. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159130. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159131. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159132. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159133. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159134. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159135. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159136. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159137. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159138. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159139. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159140. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159141. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159142. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159143. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159144. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159145. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159146. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159147. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159148. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159149. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159150. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159151. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159152. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159153. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159154. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159155. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159156. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159157. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159158. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159159. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159160. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159161. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159162. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159163. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159164. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159165. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159166. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159167. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159168. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159169. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159170. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159171. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159172. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159173. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159174. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159175. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159176. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159177. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159178. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159179. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159180. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159181. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159182. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159183. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159184. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159185. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159186. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159187. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159188. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159189. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159190. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159191. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159192. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159193. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159194. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159195. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159196. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159197. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159198. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159199. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159200. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159201. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159202. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159203. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159204. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159205. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159206. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159207. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159208. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159209. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159210. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159211. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159212. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159213. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159214. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159215. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159216. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159217. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159218. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159219. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159220. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159221. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159222. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159223. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159224. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159225. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159226. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159227. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159228. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159229. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159230. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159231. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159232. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159233. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159234. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159235. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159236. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159237. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159238. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159239. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159240. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159241. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159242. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159243. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159244. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159245. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159246. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159247. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159248. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159249. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159250. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159251. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159252. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159253. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159254. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159255. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159256. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159257. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159258. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159259. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159260. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159261. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159262. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159263. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159264. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159265. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159266. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159267. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159268. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159269. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159270. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159271. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159272. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159273. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159274. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159275. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159276. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159277. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159278. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159279. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159280. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159281. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159282. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159283. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159284. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159285. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159286. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159287. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159288. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159289. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159290. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159291. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159292. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159293. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159294. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159295. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159296. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159297. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159298. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159299. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159300. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159301. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159302. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159303. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159304. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159305. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159306. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159307. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159308. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159309. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159310. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159311. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159312. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159313. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159314. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159315. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159316. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159317. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159318. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159319. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159320. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159321. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159322. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159323. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159324. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159325. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159326. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159327. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159328. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159329. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159330. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159331. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159332. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159333. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159334. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159335. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159336. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159337. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159338. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159339. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159340. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159341. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159342. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159343. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159344. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159345. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159346. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159347. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159348. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159349. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159350. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159351. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159352. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159353. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159354. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159355. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159356. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159357. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159358. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159359. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159360. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159361. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159362. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159363. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159364. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159365. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159366. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159367. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159368. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159369. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159370. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159371. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159372. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159373. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159374. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159375. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159376. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159377. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159378. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159379. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159380. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159381. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159382. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159383. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159384. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159385. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159386. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159387. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159388. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159389. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159390. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159391. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159392. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159393. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159394. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159395. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159396. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159397. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159398. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159399. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159400. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159401. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159402. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159403. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159404. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159405. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159406. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159407. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159408. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159409. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159410. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159411. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159412. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159413. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159414. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159415. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159416. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159417. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159418. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159419. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159420. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159421. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159422. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159423. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159424. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159425. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159426. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159427. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159428. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159429. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159430. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159431. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159432. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159433. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159434. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159435. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159436. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159437. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159438. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159439. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159440. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159441. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159442. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159443. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159444. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159445. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159446. };
  159447. static float *vwin[8] = {
  159448. vwin64,
  159449. vwin128,
  159450. vwin256,
  159451. vwin512,
  159452. vwin1024,
  159453. vwin2048,
  159454. vwin4096,
  159455. vwin8192,
  159456. };
  159457. float *_vorbis_window_get(int n){
  159458. return vwin[n];
  159459. }
  159460. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159461. int lW,int W,int nW){
  159462. lW=(W?lW:0);
  159463. nW=(W?nW:0);
  159464. {
  159465. float *windowLW=vwin[winno[lW]];
  159466. float *windowNW=vwin[winno[nW]];
  159467. long n=blocksizes[W];
  159468. long ln=blocksizes[lW];
  159469. long rn=blocksizes[nW];
  159470. long leftbegin=n/4-ln/4;
  159471. long leftend=leftbegin+ln/2;
  159472. long rightbegin=n/2+n/4-rn/4;
  159473. long rightend=rightbegin+rn/2;
  159474. int i,p;
  159475. for(i=0;i<leftbegin;i++)
  159476. d[i]=0.f;
  159477. for(p=0;i<leftend;i++,p++)
  159478. d[i]*=windowLW[p];
  159479. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159480. d[i]*=windowNW[p];
  159481. for(;i<n;i++)
  159482. d[i]=0.f;
  159483. }
  159484. }
  159485. #endif
  159486. /*** End of inlined file: window.c ***/
  159487. #else
  159488. #include <vorbis/vorbisenc.h>
  159489. #include <vorbis/codec.h>
  159490. #include <vorbis/vorbisfile.h>
  159491. #endif
  159492. }
  159493. #undef max
  159494. #undef min
  159495. BEGIN_JUCE_NAMESPACE
  159496. static const char* const oggFormatName = "Ogg-Vorbis file";
  159497. static const char* const oggExtensions[] = { ".ogg", 0 };
  159498. class OggReader : public AudioFormatReader
  159499. {
  159500. OggVorbisNamespace::OggVorbis_File ovFile;
  159501. OggVorbisNamespace::ov_callbacks callbacks;
  159502. AudioSampleBuffer reservoir;
  159503. int reservoirStart, samplesInReservoir;
  159504. public:
  159505. OggReader (InputStream* const inp)
  159506. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159507. reservoir (2, 4096),
  159508. reservoirStart (0),
  159509. samplesInReservoir (0)
  159510. {
  159511. using namespace OggVorbisNamespace;
  159512. sampleRate = 0;
  159513. usesFloatingPointData = true;
  159514. callbacks.read_func = &oggReadCallback;
  159515. callbacks.seek_func = &oggSeekCallback;
  159516. callbacks.close_func = &oggCloseCallback;
  159517. callbacks.tell_func = &oggTellCallback;
  159518. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159519. if (err == 0)
  159520. {
  159521. vorbis_info* info = ov_info (&ovFile, -1);
  159522. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159523. numChannels = info->channels;
  159524. bitsPerSample = 16;
  159525. sampleRate = info->rate;
  159526. reservoir.setSize (numChannels,
  159527. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159528. }
  159529. }
  159530. ~OggReader()
  159531. {
  159532. OggVorbisNamespace::ov_clear (&ovFile);
  159533. }
  159534. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159535. int64 startSampleInFile, int numSamples)
  159536. {
  159537. while (numSamples > 0)
  159538. {
  159539. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159540. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159541. {
  159542. // got a few samples overlapping, so use them before seeking..
  159543. const int numToUse = jmin (numSamples, numAvailable);
  159544. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159545. if (destSamples[i] != 0)
  159546. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159547. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159548. sizeof (float) * numToUse);
  159549. startSampleInFile += numToUse;
  159550. numSamples -= numToUse;
  159551. startOffsetInDestBuffer += numToUse;
  159552. if (numSamples == 0)
  159553. break;
  159554. }
  159555. if (startSampleInFile < reservoirStart
  159556. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159557. {
  159558. // buffer miss, so refill the reservoir
  159559. int bitStream = 0;
  159560. reservoirStart = jmax (0, (int) startSampleInFile);
  159561. samplesInReservoir = reservoir.getNumSamples();
  159562. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159563. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159564. int offset = 0;
  159565. int numToRead = samplesInReservoir;
  159566. while (numToRead > 0)
  159567. {
  159568. float** dataIn = 0;
  159569. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159570. if (samps <= 0)
  159571. break;
  159572. jassert (samps <= numToRead);
  159573. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159574. {
  159575. memcpy (reservoir.getSampleData (i, offset),
  159576. dataIn[i],
  159577. sizeof (float) * samps);
  159578. }
  159579. numToRead -= samps;
  159580. offset += samps;
  159581. }
  159582. if (numToRead > 0)
  159583. reservoir.clear (offset, numToRead);
  159584. }
  159585. }
  159586. if (numSamples > 0)
  159587. {
  159588. for (int i = numDestChannels; --i >= 0;)
  159589. if (destSamples[i] != 0)
  159590. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159591. sizeof (int) * numSamples);
  159592. }
  159593. return true;
  159594. }
  159595. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159596. {
  159597. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159598. }
  159599. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159600. {
  159601. InputStream* const in = static_cast <InputStream*> (datasource);
  159602. if (whence == SEEK_CUR)
  159603. offset += in->getPosition();
  159604. else if (whence == SEEK_END)
  159605. offset += in->getTotalLength();
  159606. in->setPosition (offset);
  159607. return 0;
  159608. }
  159609. static int oggCloseCallback (void*)
  159610. {
  159611. return 0;
  159612. }
  159613. static long oggTellCallback (void* datasource)
  159614. {
  159615. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159616. }
  159617. juce_UseDebuggingNewOperator
  159618. };
  159619. class OggWriter : public AudioFormatWriter
  159620. {
  159621. OggVorbisNamespace::ogg_stream_state os;
  159622. OggVorbisNamespace::ogg_page og;
  159623. OggVorbisNamespace::ogg_packet op;
  159624. OggVorbisNamespace::vorbis_info vi;
  159625. OggVorbisNamespace::vorbis_comment vc;
  159626. OggVorbisNamespace::vorbis_dsp_state vd;
  159627. OggVorbisNamespace::vorbis_block vb;
  159628. public:
  159629. bool ok;
  159630. OggWriter (OutputStream* const out,
  159631. const double sampleRate,
  159632. const int numChannels,
  159633. const int bitsPerSample,
  159634. const int qualityIndex)
  159635. : AudioFormatWriter (out, TRANS (oggFormatName),
  159636. sampleRate,
  159637. numChannels,
  159638. bitsPerSample)
  159639. {
  159640. using namespace OggVorbisNamespace;
  159641. ok = false;
  159642. vorbis_info_init (&vi);
  159643. if (vorbis_encode_init_vbr (&vi,
  159644. numChannels,
  159645. (int) sampleRate,
  159646. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159647. {
  159648. vorbis_comment_init (&vc);
  159649. if (JUCEApplication::getInstance() != 0)
  159650. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159651. vorbis_analysis_init (&vd, &vi);
  159652. vorbis_block_init (&vd, &vb);
  159653. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159654. ogg_packet header;
  159655. ogg_packet header_comm;
  159656. ogg_packet header_code;
  159657. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159658. ogg_stream_packetin (&os, &header);
  159659. ogg_stream_packetin (&os, &header_comm);
  159660. ogg_stream_packetin (&os, &header_code);
  159661. for (;;)
  159662. {
  159663. if (ogg_stream_flush (&os, &og) == 0)
  159664. break;
  159665. output->write (og.header, og.header_len);
  159666. output->write (og.body, og.body_len);
  159667. }
  159668. ok = true;
  159669. }
  159670. }
  159671. ~OggWriter()
  159672. {
  159673. using namespace OggVorbisNamespace;
  159674. if (ok)
  159675. {
  159676. // write a zero-length packet to show ogg that we're finished..
  159677. write (0, 0);
  159678. ogg_stream_clear (&os);
  159679. vorbis_block_clear (&vb);
  159680. vorbis_dsp_clear (&vd);
  159681. vorbis_comment_clear (&vc);
  159682. vorbis_info_clear (&vi);
  159683. output->flush();
  159684. }
  159685. else
  159686. {
  159687. vorbis_info_clear (&vi);
  159688. output = 0; // to stop the base class deleting this, as it needs to be returned
  159689. // to the caller of createWriter()
  159690. }
  159691. }
  159692. bool write (const int** samplesToWrite, int numSamples)
  159693. {
  159694. using namespace OggVorbisNamespace;
  159695. if (! ok)
  159696. return false;
  159697. if (numSamples > 0)
  159698. {
  159699. const double gain = 1.0 / 0x80000000u;
  159700. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159701. for (int i = numChannels; --i >= 0;)
  159702. {
  159703. float* const dst = vorbisBuffer[i];
  159704. const int* const src = samplesToWrite [i];
  159705. if (src != 0 && dst != 0)
  159706. {
  159707. for (int j = 0; j < numSamples; ++j)
  159708. dst[j] = (float) (src[j] * gain);
  159709. }
  159710. }
  159711. }
  159712. vorbis_analysis_wrote (&vd, numSamples);
  159713. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159714. {
  159715. vorbis_analysis (&vb, 0);
  159716. vorbis_bitrate_addblock (&vb);
  159717. while (vorbis_bitrate_flushpacket (&vd, &op))
  159718. {
  159719. ogg_stream_packetin (&os, &op);
  159720. for (;;)
  159721. {
  159722. if (ogg_stream_pageout (&os, &og) == 0)
  159723. break;
  159724. output->write (og.header, og.header_len);
  159725. output->write (og.body, og.body_len);
  159726. if (ogg_page_eos (&og))
  159727. break;
  159728. }
  159729. }
  159730. }
  159731. return true;
  159732. }
  159733. juce_UseDebuggingNewOperator
  159734. };
  159735. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159736. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159737. {
  159738. }
  159739. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159740. {
  159741. }
  159742. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159743. {
  159744. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159745. return Array <int> (rates);
  159746. }
  159747. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159748. {
  159749. Array <int> depths;
  159750. depths.add (32);
  159751. return depths;
  159752. }
  159753. bool OggVorbisAudioFormat::canDoStereo()
  159754. {
  159755. return true;
  159756. }
  159757. bool OggVorbisAudioFormat::canDoMono()
  159758. {
  159759. return true;
  159760. }
  159761. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159762. const bool deleteStreamIfOpeningFails)
  159763. {
  159764. ScopedPointer <OggReader> r (new OggReader (in));
  159765. if (r->sampleRate != 0)
  159766. return r.release();
  159767. if (! deleteStreamIfOpeningFails)
  159768. r->input = 0;
  159769. return 0;
  159770. }
  159771. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159772. double sampleRate,
  159773. unsigned int numChannels,
  159774. int bitsPerSample,
  159775. const StringPairArray& /*metadataValues*/,
  159776. int qualityOptionIndex)
  159777. {
  159778. ScopedPointer <OggWriter> w (new OggWriter (out,
  159779. sampleRate,
  159780. numChannels,
  159781. bitsPerSample,
  159782. qualityOptionIndex));
  159783. return w->ok ? w.release() : 0;
  159784. }
  159785. bool OggVorbisAudioFormat::isCompressed()
  159786. {
  159787. return true;
  159788. }
  159789. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159790. {
  159791. StringArray s;
  159792. s.add ("Low Quality");
  159793. s.add ("Medium Quality");
  159794. s.add ("High Quality");
  159795. return s;
  159796. }
  159797. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159798. {
  159799. FileInputStream* const in = source.createInputStream();
  159800. if (in != 0)
  159801. {
  159802. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159803. if (r != 0)
  159804. {
  159805. const int64 numSamps = r->lengthInSamples;
  159806. r = 0;
  159807. const int64 fileNumSamps = source.getSize() / 4;
  159808. const double ratio = numSamps / (double) fileNumSamps;
  159809. if (ratio > 12.0)
  159810. return 0;
  159811. else if (ratio > 6.0)
  159812. return 1;
  159813. else
  159814. return 2;
  159815. }
  159816. }
  159817. return 1;
  159818. }
  159819. END_JUCE_NAMESPACE
  159820. #endif
  159821. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159822. #endif
  159823. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159824. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159825. #if JUCE_MSVC
  159826. #pragma warning (push)
  159827. #endif
  159828. namespace jpeglibNamespace
  159829. {
  159830. #if JUCE_INCLUDE_JPEGLIB_CODE
  159831. #if JUCE_MINGW
  159832. typedef unsigned char boolean;
  159833. #endif
  159834. #define JPEG_INTERNALS
  159835. #undef FAR
  159836. /*** Start of inlined file: jpeglib.h ***/
  159837. #ifndef JPEGLIB_H
  159838. #define JPEGLIB_H
  159839. /*
  159840. * First we include the configuration files that record how this
  159841. * installation of the JPEG library is set up. jconfig.h can be
  159842. * generated automatically for many systems. jmorecfg.h contains
  159843. * manual configuration options that most people need not worry about.
  159844. */
  159845. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159846. /*** Start of inlined file: jconfig.h ***/
  159847. /* see jconfig.doc for explanations */
  159848. // disable all the warnings under MSVC
  159849. #ifdef _MSC_VER
  159850. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159851. #endif
  159852. #ifdef __BORLANDC__
  159853. #pragma warn -8057
  159854. #pragma warn -8019
  159855. #pragma warn -8004
  159856. #pragma warn -8008
  159857. #endif
  159858. #define HAVE_PROTOTYPES
  159859. #define HAVE_UNSIGNED_CHAR
  159860. #define HAVE_UNSIGNED_SHORT
  159861. /* #define void char */
  159862. /* #define const */
  159863. #undef CHAR_IS_UNSIGNED
  159864. #define HAVE_STDDEF_H
  159865. #define HAVE_STDLIB_H
  159866. #undef NEED_BSD_STRINGS
  159867. #undef NEED_SYS_TYPES_H
  159868. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159869. #undef NEED_SHORT_EXTERNAL_NAMES
  159870. #undef INCOMPLETE_TYPES_BROKEN
  159871. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159872. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159873. typedef unsigned char boolean;
  159874. #endif
  159875. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159876. #ifdef JPEG_INTERNALS
  159877. #undef RIGHT_SHIFT_IS_UNSIGNED
  159878. #endif /* JPEG_INTERNALS */
  159879. #ifdef JPEG_CJPEG_DJPEG
  159880. #define BMP_SUPPORTED /* BMP image file format */
  159881. #define GIF_SUPPORTED /* GIF image file format */
  159882. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159883. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159884. #define TARGA_SUPPORTED /* Targa image file format */
  159885. #define TWO_FILE_COMMANDLINE /* optional */
  159886. #define USE_SETMODE /* Microsoft has setmode() */
  159887. #undef NEED_SIGNAL_CATCHER
  159888. #undef DONT_USE_B_MODE
  159889. #undef PROGRESS_REPORT /* optional */
  159890. #endif /* JPEG_CJPEG_DJPEG */
  159891. /*** End of inlined file: jconfig.h ***/
  159892. /* widely used configuration options */
  159893. #endif
  159894. /*** Start of inlined file: jmorecfg.h ***/
  159895. /*
  159896. * Define BITS_IN_JSAMPLE as either
  159897. * 8 for 8-bit sample values (the usual setting)
  159898. * 12 for 12-bit sample values
  159899. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159900. * JPEG standard, and the IJG code does not support anything else!
  159901. * We do not support run-time selection of data precision, sorry.
  159902. */
  159903. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159904. /*
  159905. * Maximum number of components (color channels) allowed in JPEG image.
  159906. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159907. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159908. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159909. * really short on memory. (Each allowed component costs a hundred or so
  159910. * bytes of storage, whether actually used in an image or not.)
  159911. */
  159912. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159913. /*
  159914. * Basic data types.
  159915. * You may need to change these if you have a machine with unusual data
  159916. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159917. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159918. * but it had better be at least 16.
  159919. */
  159920. /* Representation of a single sample (pixel element value).
  159921. * We frequently allocate large arrays of these, so it's important to keep
  159922. * them small. But if you have memory to burn and access to char or short
  159923. * arrays is very slow on your hardware, you might want to change these.
  159924. */
  159925. #if BITS_IN_JSAMPLE == 8
  159926. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159927. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159928. */
  159929. #ifdef HAVE_UNSIGNED_CHAR
  159930. typedef unsigned char JSAMPLE;
  159931. #define GETJSAMPLE(value) ((int) (value))
  159932. #else /* not HAVE_UNSIGNED_CHAR */
  159933. typedef char JSAMPLE;
  159934. #ifdef CHAR_IS_UNSIGNED
  159935. #define GETJSAMPLE(value) ((int) (value))
  159936. #else
  159937. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159938. #endif /* CHAR_IS_UNSIGNED */
  159939. #endif /* HAVE_UNSIGNED_CHAR */
  159940. #define MAXJSAMPLE 255
  159941. #define CENTERJSAMPLE 128
  159942. #endif /* BITS_IN_JSAMPLE == 8 */
  159943. #if BITS_IN_JSAMPLE == 12
  159944. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159945. * On nearly all machines "short" will do nicely.
  159946. */
  159947. typedef short JSAMPLE;
  159948. #define GETJSAMPLE(value) ((int) (value))
  159949. #define MAXJSAMPLE 4095
  159950. #define CENTERJSAMPLE 2048
  159951. #endif /* BITS_IN_JSAMPLE == 12 */
  159952. /* Representation of a DCT frequency coefficient.
  159953. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159954. * Again, we allocate large arrays of these, but you can change to int
  159955. * if you have memory to burn and "short" is really slow.
  159956. */
  159957. typedef short JCOEF;
  159958. /* Compressed datastreams are represented as arrays of JOCTET.
  159959. * These must be EXACTLY 8 bits wide, at least once they are written to
  159960. * external storage. Note that when using the stdio data source/destination
  159961. * managers, this is also the data type passed to fread/fwrite.
  159962. */
  159963. #ifdef HAVE_UNSIGNED_CHAR
  159964. typedef unsigned char JOCTET;
  159965. #define GETJOCTET(value) (value)
  159966. #else /* not HAVE_UNSIGNED_CHAR */
  159967. typedef char JOCTET;
  159968. #ifdef CHAR_IS_UNSIGNED
  159969. #define GETJOCTET(value) (value)
  159970. #else
  159971. #define GETJOCTET(value) ((value) & 0xFF)
  159972. #endif /* CHAR_IS_UNSIGNED */
  159973. #endif /* HAVE_UNSIGNED_CHAR */
  159974. /* These typedefs are used for various table entries and so forth.
  159975. * They must be at least as wide as specified; but making them too big
  159976. * won't cost a huge amount of memory, so we don't provide special
  159977. * extraction code like we did for JSAMPLE. (In other words, these
  159978. * typedefs live at a different point on the speed/space tradeoff curve.)
  159979. */
  159980. /* UINT8 must hold at least the values 0..255. */
  159981. #ifdef HAVE_UNSIGNED_CHAR
  159982. typedef unsigned char UINT8;
  159983. #else /* not HAVE_UNSIGNED_CHAR */
  159984. #ifdef CHAR_IS_UNSIGNED
  159985. typedef char UINT8;
  159986. #else /* not CHAR_IS_UNSIGNED */
  159987. typedef short UINT8;
  159988. #endif /* CHAR_IS_UNSIGNED */
  159989. #endif /* HAVE_UNSIGNED_CHAR */
  159990. /* UINT16 must hold at least the values 0..65535. */
  159991. #ifdef HAVE_UNSIGNED_SHORT
  159992. typedef unsigned short UINT16;
  159993. #else /* not HAVE_UNSIGNED_SHORT */
  159994. typedef unsigned int UINT16;
  159995. #endif /* HAVE_UNSIGNED_SHORT */
  159996. /* INT16 must hold at least the values -32768..32767. */
  159997. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159998. typedef short INT16;
  159999. #endif
  160000. /* INT32 must hold at least signed 32-bit values. */
  160001. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  160002. typedef long INT32;
  160003. #endif
  160004. /* Datatype used for image dimensions. The JPEG standard only supports
  160005. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  160006. * "unsigned int" is sufficient on all machines. However, if you need to
  160007. * handle larger images and you don't mind deviating from the spec, you
  160008. * can change this datatype.
  160009. */
  160010. typedef unsigned int JDIMENSION;
  160011. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  160012. /* These macros are used in all function definitions and extern declarations.
  160013. * You could modify them if you need to change function linkage conventions;
  160014. * in particular, you'll need to do that to make the library a Windows DLL.
  160015. * Another application is to make all functions global for use with debuggers
  160016. * or code profilers that require it.
  160017. */
  160018. /* a function called through method pointers: */
  160019. #define METHODDEF(type) static type
  160020. /* a function used only in its module: */
  160021. #define LOCAL(type) static type
  160022. /* a function referenced thru EXTERNs: */
  160023. #define GLOBAL(type) type
  160024. /* a reference to a GLOBAL function: */
  160025. #define EXTERN(type) extern type
  160026. /* This macro is used to declare a "method", that is, a function pointer.
  160027. * We want to supply prototype parameters if the compiler can cope.
  160028. * Note that the arglist parameter must be parenthesized!
  160029. * Again, you can customize this if you need special linkage keywords.
  160030. */
  160031. #ifdef HAVE_PROTOTYPES
  160032. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  160033. #else
  160034. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  160035. #endif
  160036. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  160037. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  160038. * by just saying "FAR *" where such a pointer is needed. In a few places
  160039. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  160040. */
  160041. #ifdef NEED_FAR_POINTERS
  160042. #define FAR far
  160043. #else
  160044. #define FAR
  160045. #endif
  160046. /*
  160047. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  160048. * in standard header files. Or you may have conflicts with application-
  160049. * specific header files that you want to include together with these files.
  160050. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  160051. */
  160052. #ifndef HAVE_BOOLEAN
  160053. typedef int boolean;
  160054. #endif
  160055. #ifndef FALSE /* in case these macros already exist */
  160056. #define FALSE 0 /* values of boolean */
  160057. #endif
  160058. #ifndef TRUE
  160059. #define TRUE 1
  160060. #endif
  160061. /*
  160062. * The remaining options affect code selection within the JPEG library,
  160063. * but they don't need to be visible to most applications using the library.
  160064. * To minimize application namespace pollution, the symbols won't be
  160065. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  160066. */
  160067. #ifdef JPEG_INTERNALS
  160068. #define JPEG_INTERNAL_OPTIONS
  160069. #endif
  160070. #ifdef JPEG_INTERNAL_OPTIONS
  160071. /*
  160072. * These defines indicate whether to include various optional functions.
  160073. * Undefining some of these symbols will produce a smaller but less capable
  160074. * library. Note that you can leave certain source files out of the
  160075. * compilation/linking process if you've #undef'd the corresponding symbols.
  160076. * (You may HAVE to do that if your compiler doesn't like null source files.)
  160077. */
  160078. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  160079. /* Capability options common to encoder and decoder: */
  160080. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  160081. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  160082. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  160083. /* Encoder capability options: */
  160084. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160085. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160086. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160087. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  160088. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  160089. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  160090. * precision, so jchuff.c normally uses entropy optimization to compute
  160091. * usable tables for higher precision. If you don't want to do optimization,
  160092. * you'll have to supply different default Huffman tables.
  160093. * The exact same statements apply for progressive JPEG: the default tables
  160094. * don't work for progressive mode. (This may get fixed, however.)
  160095. */
  160096. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  160097. /* Decoder capability options: */
  160098. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160099. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160100. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160101. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  160102. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  160103. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  160104. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  160105. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  160106. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  160107. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  160108. /* more capability options later, no doubt */
  160109. /*
  160110. * Ordering of RGB data in scanlines passed to or from the application.
  160111. * If your application wants to deal with data in the order B,G,R, just
  160112. * change these macros. You can also deal with formats such as R,G,B,X
  160113. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  160114. * the offsets will also change the order in which colormap data is organized.
  160115. * RESTRICTIONS:
  160116. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  160117. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  160118. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  160119. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  160120. * is not 3 (they don't understand about dummy color components!). So you
  160121. * can't use color quantization if you change that value.
  160122. */
  160123. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160124. #define RGB_GREEN 1 /* Offset of Green */
  160125. #define RGB_BLUE 2 /* Offset of Blue */
  160126. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160127. /* Definitions for speed-related optimizations. */
  160128. /* If your compiler supports inline functions, define INLINE
  160129. * as the inline keyword; otherwise define it as empty.
  160130. */
  160131. #ifndef INLINE
  160132. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160133. #define INLINE __inline__
  160134. #endif
  160135. #ifndef INLINE
  160136. #define INLINE /* default is to define it as empty */
  160137. #endif
  160138. #endif
  160139. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160140. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160141. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160142. */
  160143. #ifndef MULTIPLIER
  160144. #define MULTIPLIER int /* type for fastest integer multiply */
  160145. #endif
  160146. /* FAST_FLOAT should be either float or double, whichever is done faster
  160147. * by your compiler. (Note that this type is only used in the floating point
  160148. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160149. * Typically, float is faster in ANSI C compilers, while double is faster in
  160150. * pre-ANSI compilers (because they insist on converting to double anyway).
  160151. * The code below therefore chooses float if we have ANSI-style prototypes.
  160152. */
  160153. #ifndef FAST_FLOAT
  160154. #ifdef HAVE_PROTOTYPES
  160155. #define FAST_FLOAT float
  160156. #else
  160157. #define FAST_FLOAT double
  160158. #endif
  160159. #endif
  160160. #endif /* JPEG_INTERNAL_OPTIONS */
  160161. /*** End of inlined file: jmorecfg.h ***/
  160162. /* seldom changed options */
  160163. /* Version ID for the JPEG library.
  160164. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160165. */
  160166. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160167. /* Various constants determining the sizes of things.
  160168. * All of these are specified by the JPEG standard, so don't change them
  160169. * if you want to be compatible.
  160170. */
  160171. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160172. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160173. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160174. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160175. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160176. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160177. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160178. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160179. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160180. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160181. * to handle it. We even let you do this from the jconfig.h file. However,
  160182. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160183. * sometimes emits noncompliant files doesn't mean you should too.
  160184. */
  160185. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160186. #ifndef D_MAX_BLOCKS_IN_MCU
  160187. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160188. #endif
  160189. /* Data structures for images (arrays of samples and of DCT coefficients).
  160190. * On 80x86 machines, the image arrays are too big for near pointers,
  160191. * but the pointer arrays can fit in near memory.
  160192. */
  160193. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160194. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160195. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160196. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160197. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160198. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160199. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160200. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160201. /* Types for JPEG compression parameters and working tables. */
  160202. /* DCT coefficient quantization tables. */
  160203. typedef struct {
  160204. /* This array gives the coefficient quantizers in natural array order
  160205. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160206. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160207. */
  160208. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160209. /* This field is used only during compression. It's initialized FALSE when
  160210. * the table is created, and set TRUE when it's been output to the file.
  160211. * You could suppress output of a table by setting this to TRUE.
  160212. * (See jpeg_suppress_tables for an example.)
  160213. */
  160214. boolean sent_table; /* TRUE when table has been output */
  160215. } JQUANT_TBL;
  160216. /* Huffman coding tables. */
  160217. typedef struct {
  160218. /* These two fields directly represent the contents of a JPEG DHT marker */
  160219. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160220. /* length k bits; bits[0] is unused */
  160221. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160222. /* This field is used only during compression. It's initialized FALSE when
  160223. * the table is created, and set TRUE when it's been output to the file.
  160224. * You could suppress output of a table by setting this to TRUE.
  160225. * (See jpeg_suppress_tables for an example.)
  160226. */
  160227. boolean sent_table; /* TRUE when table has been output */
  160228. } JHUFF_TBL;
  160229. /* Basic info about one component (color channel). */
  160230. typedef struct {
  160231. /* These values are fixed over the whole image. */
  160232. /* For compression, they must be supplied by parameter setup; */
  160233. /* for decompression, they are read from the SOF marker. */
  160234. int component_id; /* identifier for this component (0..255) */
  160235. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160236. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160237. int v_samp_factor; /* vertical sampling factor (1..4) */
  160238. int quant_tbl_no; /* quantization table selector (0..3) */
  160239. /* These values may vary between scans. */
  160240. /* For compression, they must be supplied by parameter setup; */
  160241. /* for decompression, they are read from the SOS marker. */
  160242. /* The decompressor output side may not use these variables. */
  160243. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160244. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160245. /* Remaining fields should be treated as private by applications. */
  160246. /* These values are computed during compression or decompression startup: */
  160247. /* Component's size in DCT blocks.
  160248. * Any dummy blocks added to complete an MCU are not counted; therefore
  160249. * these values do not depend on whether a scan is interleaved or not.
  160250. */
  160251. JDIMENSION width_in_blocks;
  160252. JDIMENSION height_in_blocks;
  160253. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160254. * For decompression this is the size of the output from one DCT block,
  160255. * reflecting any scaling we choose to apply during the IDCT step.
  160256. * Values of 1,2,4,8 are likely to be supported. Note that different
  160257. * components may receive different IDCT scalings.
  160258. */
  160259. int DCT_scaled_size;
  160260. /* The downsampled dimensions are the component's actual, unpadded number
  160261. * of samples at the main buffer (preprocessing/compression interface), thus
  160262. * downsampled_width = ceil(image_width * Hi/Hmax)
  160263. * and similarly for height. For decompression, IDCT scaling is included, so
  160264. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160265. */
  160266. JDIMENSION downsampled_width; /* actual width in samples */
  160267. JDIMENSION downsampled_height; /* actual height in samples */
  160268. /* This flag is used only for decompression. In cases where some of the
  160269. * components will be ignored (eg grayscale output from YCbCr image),
  160270. * we can skip most computations for the unused components.
  160271. */
  160272. boolean component_needed; /* do we need the value of this component? */
  160273. /* These values are computed before starting a scan of the component. */
  160274. /* The decompressor output side may not use these variables. */
  160275. int MCU_width; /* number of blocks per MCU, horizontally */
  160276. int MCU_height; /* number of blocks per MCU, vertically */
  160277. int MCU_blocks; /* MCU_width * MCU_height */
  160278. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160279. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160280. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160281. /* Saved quantization table for component; NULL if none yet saved.
  160282. * See jdinput.c comments about the need for this information.
  160283. * This field is currently used only for decompression.
  160284. */
  160285. JQUANT_TBL * quant_table;
  160286. /* Private per-component storage for DCT or IDCT subsystem. */
  160287. void * dct_table;
  160288. } jpeg_component_info;
  160289. /* The script for encoding a multiple-scan file is an array of these: */
  160290. typedef struct {
  160291. int comps_in_scan; /* number of components encoded in this scan */
  160292. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160293. int Ss, Se; /* progressive JPEG spectral selection parms */
  160294. int Ah, Al; /* progressive JPEG successive approx. parms */
  160295. } jpeg_scan_info;
  160296. /* The decompressor can save APPn and COM markers in a list of these: */
  160297. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160298. struct jpeg_marker_struct {
  160299. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160300. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160301. unsigned int original_length; /* # bytes of data in the file */
  160302. unsigned int data_length; /* # bytes of data saved at data[] */
  160303. JOCTET FAR * data; /* the data contained in the marker */
  160304. /* the marker length word is not counted in data_length or original_length */
  160305. };
  160306. /* Known color spaces. */
  160307. typedef enum {
  160308. JCS_UNKNOWN, /* error/unspecified */
  160309. JCS_GRAYSCALE, /* monochrome */
  160310. JCS_RGB, /* red/green/blue */
  160311. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160312. JCS_CMYK, /* C/M/Y/K */
  160313. JCS_YCCK /* Y/Cb/Cr/K */
  160314. } J_COLOR_SPACE;
  160315. /* DCT/IDCT algorithm options. */
  160316. typedef enum {
  160317. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160318. JDCT_IFAST, /* faster, less accurate integer method */
  160319. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160320. } J_DCT_METHOD;
  160321. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160322. #define JDCT_DEFAULT JDCT_ISLOW
  160323. #endif
  160324. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160325. #define JDCT_FASTEST JDCT_IFAST
  160326. #endif
  160327. /* Dithering options for decompression. */
  160328. typedef enum {
  160329. JDITHER_NONE, /* no dithering */
  160330. JDITHER_ORDERED, /* simple ordered dither */
  160331. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160332. } J_DITHER_MODE;
  160333. /* Common fields between JPEG compression and decompression master structs. */
  160334. #define jpeg_common_fields \
  160335. struct jpeg_error_mgr * err; /* Error handler module */\
  160336. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160337. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160338. void * client_data; /* Available for use by application */\
  160339. boolean is_decompressor; /* So common code can tell which is which */\
  160340. int global_state /* For checking call sequence validity */
  160341. /* Routines that are to be used by both halves of the library are declared
  160342. * to receive a pointer to this structure. There are no actual instances of
  160343. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160344. */
  160345. struct jpeg_common_struct {
  160346. jpeg_common_fields; /* Fields common to both master struct types */
  160347. /* Additional fields follow in an actual jpeg_compress_struct or
  160348. * jpeg_decompress_struct. All three structs must agree on these
  160349. * initial fields! (This would be a lot cleaner in C++.)
  160350. */
  160351. };
  160352. typedef struct jpeg_common_struct * j_common_ptr;
  160353. typedef struct jpeg_compress_struct * j_compress_ptr;
  160354. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160355. /* Master record for a compression instance */
  160356. struct jpeg_compress_struct {
  160357. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160358. /* Destination for compressed data */
  160359. struct jpeg_destination_mgr * dest;
  160360. /* Description of source image --- these fields must be filled in by
  160361. * outer application before starting compression. in_color_space must
  160362. * be correct before you can even call jpeg_set_defaults().
  160363. */
  160364. JDIMENSION image_width; /* input image width */
  160365. JDIMENSION image_height; /* input image height */
  160366. int input_components; /* # of color components in input image */
  160367. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160368. double input_gamma; /* image gamma of input image */
  160369. /* Compression parameters --- these fields must be set before calling
  160370. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160371. * initialize everything to reasonable defaults, then changing anything
  160372. * the application specifically wants to change. That way you won't get
  160373. * burnt when new parameters are added. Also note that there are several
  160374. * helper routines to simplify changing parameters.
  160375. */
  160376. int data_precision; /* bits of precision in image data */
  160377. int num_components; /* # of color components in JPEG image */
  160378. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160379. jpeg_component_info * comp_info;
  160380. /* comp_info[i] describes component that appears i'th in SOF */
  160381. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160382. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160383. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160384. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160385. /* ptrs to Huffman coding tables, or NULL if not defined */
  160386. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160387. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160388. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160389. int num_scans; /* # of entries in scan_info array */
  160390. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160391. /* The default value of scan_info is NULL, which causes a single-scan
  160392. * sequential JPEG file to be emitted. To create a multi-scan file,
  160393. * set num_scans and scan_info to point to an array of scan definitions.
  160394. */
  160395. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160396. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160397. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160398. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160399. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160400. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160401. /* The restart interval can be specified in absolute MCUs by setting
  160402. * restart_interval, or in MCU rows by setting restart_in_rows
  160403. * (in which case the correct restart_interval will be figured
  160404. * for each scan).
  160405. */
  160406. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160407. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160408. /* Parameters controlling emission of special markers. */
  160409. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160410. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160411. UINT8 JFIF_minor_version;
  160412. /* These three values are not used by the JPEG code, merely copied */
  160413. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160414. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160415. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160416. UINT8 density_unit; /* JFIF code for pixel size units */
  160417. UINT16 X_density; /* Horizontal pixel density */
  160418. UINT16 Y_density; /* Vertical pixel density */
  160419. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160420. /* State variable: index of next scanline to be written to
  160421. * jpeg_write_scanlines(). Application may use this to control its
  160422. * processing loop, e.g., "while (next_scanline < image_height)".
  160423. */
  160424. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160425. /* Remaining fields are known throughout compressor, but generally
  160426. * should not be touched by a surrounding application.
  160427. */
  160428. /*
  160429. * These fields are computed during compression startup
  160430. */
  160431. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160432. int max_h_samp_factor; /* largest h_samp_factor */
  160433. int max_v_samp_factor; /* largest v_samp_factor */
  160434. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160435. /* The coefficient controller receives data in units of MCU rows as defined
  160436. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160437. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160438. * "iMCU" (interleaved MCU) row.
  160439. */
  160440. /*
  160441. * These fields are valid during any one scan.
  160442. * They describe the components and MCUs actually appearing in the scan.
  160443. */
  160444. int comps_in_scan; /* # of JPEG components in this scan */
  160445. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160446. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160447. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160448. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160449. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160450. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160451. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160452. /* i'th block in an MCU */
  160453. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160454. /*
  160455. * Links to compression subobjects (methods and private variables of modules)
  160456. */
  160457. struct jpeg_comp_master * master;
  160458. struct jpeg_c_main_controller * main;
  160459. struct jpeg_c_prep_controller * prep;
  160460. struct jpeg_c_coef_controller * coef;
  160461. struct jpeg_marker_writer * marker;
  160462. struct jpeg_color_converter * cconvert;
  160463. struct jpeg_downsampler * downsample;
  160464. struct jpeg_forward_dct * fdct;
  160465. struct jpeg_entropy_encoder * entropy;
  160466. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160467. int script_space_size;
  160468. };
  160469. /* Master record for a decompression instance */
  160470. struct jpeg_decompress_struct {
  160471. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160472. /* Source of compressed data */
  160473. struct jpeg_source_mgr * src;
  160474. /* Basic description of image --- filled in by jpeg_read_header(). */
  160475. /* Application may inspect these values to decide how to process image. */
  160476. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160477. JDIMENSION image_height; /* nominal image height */
  160478. int num_components; /* # of color components in JPEG image */
  160479. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160480. /* Decompression processing parameters --- these fields must be set before
  160481. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160482. * them to default values.
  160483. */
  160484. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160485. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160486. double output_gamma; /* image gamma wanted in output */
  160487. boolean buffered_image; /* TRUE=multiple output passes */
  160488. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160489. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160490. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160491. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160492. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160493. /* the following are ignored if not quantize_colors: */
  160494. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160495. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160496. int desired_number_of_colors; /* max # colors to use in created colormap */
  160497. /* these are significant only in buffered-image mode: */
  160498. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160499. boolean enable_external_quant;/* enable future use of external colormap */
  160500. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160501. /* Description of actual output image that will be returned to application.
  160502. * These fields are computed by jpeg_start_decompress().
  160503. * You can also use jpeg_calc_output_dimensions() to determine these values
  160504. * in advance of calling jpeg_start_decompress().
  160505. */
  160506. JDIMENSION output_width; /* scaled image width */
  160507. JDIMENSION output_height; /* scaled image height */
  160508. int out_color_components; /* # of color components in out_color_space */
  160509. int output_components; /* # of color components returned */
  160510. /* output_components is 1 (a colormap index) when quantizing colors;
  160511. * otherwise it equals out_color_components.
  160512. */
  160513. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160514. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160515. * high, space and time will be wasted due to unnecessary data copying.
  160516. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160517. */
  160518. /* When quantizing colors, the output colormap is described by these fields.
  160519. * The application can supply a colormap by setting colormap non-NULL before
  160520. * calling jpeg_start_decompress; otherwise a colormap is created during
  160521. * jpeg_start_decompress or jpeg_start_output.
  160522. * The map has out_color_components rows and actual_number_of_colors columns.
  160523. */
  160524. int actual_number_of_colors; /* number of entries in use */
  160525. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160526. /* State variables: these variables indicate the progress of decompression.
  160527. * The application may examine these but must not modify them.
  160528. */
  160529. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160530. * Application may use this to control its processing loop, e.g.,
  160531. * "while (output_scanline < output_height)".
  160532. */
  160533. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160534. /* Current input scan number and number of iMCU rows completed in scan.
  160535. * These indicate the progress of the decompressor input side.
  160536. */
  160537. int input_scan_number; /* Number of SOS markers seen so far */
  160538. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160539. /* The "output scan number" is the notional scan being displayed by the
  160540. * output side. The decompressor will not allow output scan/row number
  160541. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160542. */
  160543. int output_scan_number; /* Nominal scan number being displayed */
  160544. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160545. /* Current progression status. coef_bits[c][i] indicates the precision
  160546. * with which component c's DCT coefficient i (in zigzag order) is known.
  160547. * It is -1 when no data has yet been received, otherwise it is the point
  160548. * transform (shift) value for the most recent scan of the coefficient
  160549. * (thus, 0 at completion of the progression).
  160550. * This pointer is NULL when reading a non-progressive file.
  160551. */
  160552. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160553. /* Internal JPEG parameters --- the application usually need not look at
  160554. * these fields. Note that the decompressor output side may not use
  160555. * any parameters that can change between scans.
  160556. */
  160557. /* Quantization and Huffman tables are carried forward across input
  160558. * datastreams when processing abbreviated JPEG datastreams.
  160559. */
  160560. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160561. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160562. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160563. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160564. /* ptrs to Huffman coding tables, or NULL if not defined */
  160565. /* These parameters are never carried across datastreams, since they
  160566. * are given in SOF/SOS markers or defined to be reset by SOI.
  160567. */
  160568. int data_precision; /* bits of precision in image data */
  160569. jpeg_component_info * comp_info;
  160570. /* comp_info[i] describes component that appears i'th in SOF */
  160571. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160572. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160573. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160574. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160575. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160576. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160577. /* These fields record data obtained from optional markers recognized by
  160578. * the JPEG library.
  160579. */
  160580. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160581. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160582. UINT8 JFIF_major_version; /* JFIF version number */
  160583. UINT8 JFIF_minor_version;
  160584. UINT8 density_unit; /* JFIF code for pixel size units */
  160585. UINT16 X_density; /* Horizontal pixel density */
  160586. UINT16 Y_density; /* Vertical pixel density */
  160587. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160588. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160589. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160590. /* Aside from the specific data retained from APPn markers known to the
  160591. * library, the uninterpreted contents of any or all APPn and COM markers
  160592. * can be saved in a list for examination by the application.
  160593. */
  160594. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160595. /* Remaining fields are known throughout decompressor, but generally
  160596. * should not be touched by a surrounding application.
  160597. */
  160598. /*
  160599. * These fields are computed during decompression startup
  160600. */
  160601. int max_h_samp_factor; /* largest h_samp_factor */
  160602. int max_v_samp_factor; /* largest v_samp_factor */
  160603. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160604. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160605. /* The coefficient controller's input and output progress is measured in
  160606. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160607. * in fully interleaved JPEG scans, but are used whether the scan is
  160608. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160609. * rows of each component. Therefore, the IDCT output contains
  160610. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160611. */
  160612. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160613. /*
  160614. * These fields are valid during any one scan.
  160615. * They describe the components and MCUs actually appearing in the scan.
  160616. * Note that the decompressor output side must not use these fields.
  160617. */
  160618. int comps_in_scan; /* # of JPEG components in this scan */
  160619. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160620. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160621. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160622. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160623. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160624. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160625. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160626. /* i'th block in an MCU */
  160627. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160628. /* This field is shared between entropy decoder and marker parser.
  160629. * It is either zero or the code of a JPEG marker that has been
  160630. * read from the data source, but has not yet been processed.
  160631. */
  160632. int unread_marker;
  160633. /*
  160634. * Links to decompression subobjects (methods, private variables of modules)
  160635. */
  160636. struct jpeg_decomp_master * master;
  160637. struct jpeg_d_main_controller * main;
  160638. struct jpeg_d_coef_controller * coef;
  160639. struct jpeg_d_post_controller * post;
  160640. struct jpeg_input_controller * inputctl;
  160641. struct jpeg_marker_reader * marker;
  160642. struct jpeg_entropy_decoder * entropy;
  160643. struct jpeg_inverse_dct * idct;
  160644. struct jpeg_upsampler * upsample;
  160645. struct jpeg_color_deconverter * cconvert;
  160646. struct jpeg_color_quantizer * cquantize;
  160647. };
  160648. /* "Object" declarations for JPEG modules that may be supplied or called
  160649. * directly by the surrounding application.
  160650. * As with all objects in the JPEG library, these structs only define the
  160651. * publicly visible methods and state variables of a module. Additional
  160652. * private fields may exist after the public ones.
  160653. */
  160654. /* Error handler object */
  160655. struct jpeg_error_mgr {
  160656. /* Error exit handler: does not return to caller */
  160657. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160658. /* Conditionally emit a trace or warning message */
  160659. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160660. /* Routine that actually outputs a trace or error message */
  160661. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160662. /* Format a message string for the most recent JPEG error or message */
  160663. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160664. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160665. /* Reset error state variables at start of a new image */
  160666. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160667. /* The message ID code and any parameters are saved here.
  160668. * A message can have one string parameter or up to 8 int parameters.
  160669. */
  160670. int msg_code;
  160671. #define JMSG_STR_PARM_MAX 80
  160672. union {
  160673. int i[8];
  160674. char s[JMSG_STR_PARM_MAX];
  160675. } msg_parm;
  160676. /* Standard state variables for error facility */
  160677. int trace_level; /* max msg_level that will be displayed */
  160678. /* For recoverable corrupt-data errors, we emit a warning message,
  160679. * but keep going unless emit_message chooses to abort. emit_message
  160680. * should count warnings in num_warnings. The surrounding application
  160681. * can check for bad data by seeing if num_warnings is nonzero at the
  160682. * end of processing.
  160683. */
  160684. long num_warnings; /* number of corrupt-data warnings */
  160685. /* These fields point to the table(s) of error message strings.
  160686. * An application can change the table pointer to switch to a different
  160687. * message list (typically, to change the language in which errors are
  160688. * reported). Some applications may wish to add additional error codes
  160689. * that will be handled by the JPEG library error mechanism; the second
  160690. * table pointer is used for this purpose.
  160691. *
  160692. * First table includes all errors generated by JPEG library itself.
  160693. * Error code 0 is reserved for a "no such error string" message.
  160694. */
  160695. const char * const * jpeg_message_table; /* Library errors */
  160696. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160697. /* Second table can be added by application (see cjpeg/djpeg for example).
  160698. * It contains strings numbered first_addon_message..last_addon_message.
  160699. */
  160700. const char * const * addon_message_table; /* Non-library errors */
  160701. int first_addon_message; /* code for first string in addon table */
  160702. int last_addon_message; /* code for last string in addon table */
  160703. };
  160704. /* Progress monitor object */
  160705. struct jpeg_progress_mgr {
  160706. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160707. long pass_counter; /* work units completed in this pass */
  160708. long pass_limit; /* total number of work units in this pass */
  160709. int completed_passes; /* passes completed so far */
  160710. int total_passes; /* total number of passes expected */
  160711. };
  160712. /* Data destination object for compression */
  160713. struct jpeg_destination_mgr {
  160714. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160715. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160716. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160717. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160718. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160719. };
  160720. /* Data source object for decompression */
  160721. struct jpeg_source_mgr {
  160722. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160723. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160724. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160725. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160726. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160727. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160728. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160729. };
  160730. /* Memory manager object.
  160731. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160732. * and "really big" objects (virtual arrays with backing store if needed).
  160733. * The memory manager does not allow individual objects to be freed; rather,
  160734. * each created object is assigned to a pool, and whole pools can be freed
  160735. * at once. This is faster and more convenient than remembering exactly what
  160736. * to free, especially where malloc()/free() are not too speedy.
  160737. * NB: alloc routines never return NULL. They exit to error_exit if not
  160738. * successful.
  160739. */
  160740. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160741. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160742. #define JPOOL_NUMPOOLS 2
  160743. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160744. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160745. struct jpeg_memory_mgr {
  160746. /* Method pointers */
  160747. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160748. size_t sizeofobject));
  160749. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160750. size_t sizeofobject));
  160751. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160752. JDIMENSION samplesperrow,
  160753. JDIMENSION numrows));
  160754. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160755. JDIMENSION blocksperrow,
  160756. JDIMENSION numrows));
  160757. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160758. int pool_id,
  160759. boolean pre_zero,
  160760. JDIMENSION samplesperrow,
  160761. JDIMENSION numrows,
  160762. JDIMENSION maxaccess));
  160763. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160764. int pool_id,
  160765. boolean pre_zero,
  160766. JDIMENSION blocksperrow,
  160767. JDIMENSION numrows,
  160768. JDIMENSION maxaccess));
  160769. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160770. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160771. jvirt_sarray_ptr ptr,
  160772. JDIMENSION start_row,
  160773. JDIMENSION num_rows,
  160774. boolean writable));
  160775. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160776. jvirt_barray_ptr ptr,
  160777. JDIMENSION start_row,
  160778. JDIMENSION num_rows,
  160779. boolean writable));
  160780. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160781. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160782. /* Limit on memory allocation for this JPEG object. (Note that this is
  160783. * merely advisory, not a guaranteed maximum; it only affects the space
  160784. * used for virtual-array buffers.) May be changed by outer application
  160785. * after creating the JPEG object.
  160786. */
  160787. long max_memory_to_use;
  160788. /* Maximum allocation request accepted by alloc_large. */
  160789. long max_alloc_chunk;
  160790. };
  160791. /* Routine signature for application-supplied marker processing methods.
  160792. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160793. */
  160794. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160795. /* Declarations for routines called by application.
  160796. * The JPP macro hides prototype parameters from compilers that can't cope.
  160797. * Note JPP requires double parentheses.
  160798. */
  160799. #ifdef HAVE_PROTOTYPES
  160800. #define JPP(arglist) arglist
  160801. #else
  160802. #define JPP(arglist) ()
  160803. #endif
  160804. /* Short forms of external names for systems with brain-damaged linkers.
  160805. * We shorten external names to be unique in the first six letters, which
  160806. * is good enough for all known systems.
  160807. * (If your compiler itself needs names to be unique in less than 15
  160808. * characters, you are out of luck. Get a better compiler.)
  160809. */
  160810. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160811. #define jpeg_std_error jStdError
  160812. #define jpeg_CreateCompress jCreaCompress
  160813. #define jpeg_CreateDecompress jCreaDecompress
  160814. #define jpeg_destroy_compress jDestCompress
  160815. #define jpeg_destroy_decompress jDestDecompress
  160816. #define jpeg_stdio_dest jStdDest
  160817. #define jpeg_stdio_src jStdSrc
  160818. #define jpeg_set_defaults jSetDefaults
  160819. #define jpeg_set_colorspace jSetColorspace
  160820. #define jpeg_default_colorspace jDefColorspace
  160821. #define jpeg_set_quality jSetQuality
  160822. #define jpeg_set_linear_quality jSetLQuality
  160823. #define jpeg_add_quant_table jAddQuantTable
  160824. #define jpeg_quality_scaling jQualityScaling
  160825. #define jpeg_simple_progression jSimProgress
  160826. #define jpeg_suppress_tables jSuppressTables
  160827. #define jpeg_alloc_quant_table jAlcQTable
  160828. #define jpeg_alloc_huff_table jAlcHTable
  160829. #define jpeg_start_compress jStrtCompress
  160830. #define jpeg_write_scanlines jWrtScanlines
  160831. #define jpeg_finish_compress jFinCompress
  160832. #define jpeg_write_raw_data jWrtRawData
  160833. #define jpeg_write_marker jWrtMarker
  160834. #define jpeg_write_m_header jWrtMHeader
  160835. #define jpeg_write_m_byte jWrtMByte
  160836. #define jpeg_write_tables jWrtTables
  160837. #define jpeg_read_header jReadHeader
  160838. #define jpeg_start_decompress jStrtDecompress
  160839. #define jpeg_read_scanlines jReadScanlines
  160840. #define jpeg_finish_decompress jFinDecompress
  160841. #define jpeg_read_raw_data jReadRawData
  160842. #define jpeg_has_multiple_scans jHasMultScn
  160843. #define jpeg_start_output jStrtOutput
  160844. #define jpeg_finish_output jFinOutput
  160845. #define jpeg_input_complete jInComplete
  160846. #define jpeg_new_colormap jNewCMap
  160847. #define jpeg_consume_input jConsumeInput
  160848. #define jpeg_calc_output_dimensions jCalcDimensions
  160849. #define jpeg_save_markers jSaveMarkers
  160850. #define jpeg_set_marker_processor jSetMarker
  160851. #define jpeg_read_coefficients jReadCoefs
  160852. #define jpeg_write_coefficients jWrtCoefs
  160853. #define jpeg_copy_critical_parameters jCopyCrit
  160854. #define jpeg_abort_compress jAbrtCompress
  160855. #define jpeg_abort_decompress jAbrtDecompress
  160856. #define jpeg_abort jAbort
  160857. #define jpeg_destroy jDestroy
  160858. #define jpeg_resync_to_restart jResyncRestart
  160859. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160860. /* Default error-management setup */
  160861. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160862. JPP((struct jpeg_error_mgr * err));
  160863. /* Initialization of JPEG compression objects.
  160864. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160865. * names that applications should call. These expand to calls on
  160866. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160867. * passed for version mismatch checking.
  160868. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160869. */
  160870. #define jpeg_create_compress(cinfo) \
  160871. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160872. (size_t) sizeof(struct jpeg_compress_struct))
  160873. #define jpeg_create_decompress(cinfo) \
  160874. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160875. (size_t) sizeof(struct jpeg_decompress_struct))
  160876. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160877. int version, size_t structsize));
  160878. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160879. int version, size_t structsize));
  160880. /* Destruction of JPEG compression objects */
  160881. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160882. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160883. /* Standard data source and destination managers: stdio streams. */
  160884. /* Caller is responsible for opening the file before and closing after. */
  160885. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160886. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160887. /* Default parameter setup for compression */
  160888. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160889. /* Compression parameter setup aids */
  160890. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160891. J_COLOR_SPACE colorspace));
  160892. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160893. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160894. boolean force_baseline));
  160895. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160896. int scale_factor,
  160897. boolean force_baseline));
  160898. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160899. const unsigned int *basic_table,
  160900. int scale_factor,
  160901. boolean force_baseline));
  160902. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160903. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160904. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160905. boolean suppress));
  160906. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160907. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160908. /* Main entry points for compression */
  160909. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160910. boolean write_all_tables));
  160911. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160912. JSAMPARRAY scanlines,
  160913. JDIMENSION num_lines));
  160914. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160915. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160916. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160917. JSAMPIMAGE data,
  160918. JDIMENSION num_lines));
  160919. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160920. EXTERN(void) jpeg_write_marker
  160921. JPP((j_compress_ptr cinfo, int marker,
  160922. const JOCTET * dataptr, unsigned int datalen));
  160923. /* Same, but piecemeal. */
  160924. EXTERN(void) jpeg_write_m_header
  160925. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160926. EXTERN(void) jpeg_write_m_byte
  160927. JPP((j_compress_ptr cinfo, int val));
  160928. /* Alternate compression function: just write an abbreviated table file */
  160929. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160930. /* Decompression startup: read start of JPEG datastream to see what's there */
  160931. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160932. boolean require_image));
  160933. /* Return value is one of: */
  160934. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160935. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160936. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160937. /* If you pass require_image = TRUE (normal case), you need not check for
  160938. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160939. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160940. * give a suspension return (the stdio source module doesn't).
  160941. */
  160942. /* Main entry points for decompression */
  160943. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160944. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160945. JSAMPARRAY scanlines,
  160946. JDIMENSION max_lines));
  160947. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160948. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160949. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160950. JSAMPIMAGE data,
  160951. JDIMENSION max_lines));
  160952. /* Additional entry points for buffered-image mode. */
  160953. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160954. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160955. int scan_number));
  160956. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160957. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160958. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160959. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160960. /* Return value is one of: */
  160961. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160962. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160963. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160964. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160965. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160966. /* Precalculate output dimensions for current decompression parameters. */
  160967. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160968. /* Control saving of COM and APPn markers into marker_list. */
  160969. EXTERN(void) jpeg_save_markers
  160970. JPP((j_decompress_ptr cinfo, int marker_code,
  160971. unsigned int length_limit));
  160972. /* Install a special processing method for COM or APPn markers. */
  160973. EXTERN(void) jpeg_set_marker_processor
  160974. JPP((j_decompress_ptr cinfo, int marker_code,
  160975. jpeg_marker_parser_method routine));
  160976. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160977. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160978. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160979. jvirt_barray_ptr * coef_arrays));
  160980. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160981. j_compress_ptr dstinfo));
  160982. /* If you choose to abort compression or decompression before completing
  160983. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160984. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160985. * if you're done with the JPEG object, but if you want to clean it up and
  160986. * reuse it, call this:
  160987. */
  160988. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160989. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160990. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160991. * flavor of JPEG object. These may be more convenient in some places.
  160992. */
  160993. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160994. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160995. /* Default restart-marker-resync procedure for use by data source modules */
  160996. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160997. int desired));
  160998. /* These marker codes are exported since applications and data source modules
  160999. * are likely to want to use them.
  161000. */
  161001. #define JPEG_RST0 0xD0 /* RST0 marker code */
  161002. #define JPEG_EOI 0xD9 /* EOI marker code */
  161003. #define JPEG_APP0 0xE0 /* APP0 marker code */
  161004. #define JPEG_COM 0xFE /* COM marker code */
  161005. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  161006. * for structure definitions that are never filled in, keep it quiet by
  161007. * supplying dummy definitions for the various substructures.
  161008. */
  161009. #ifdef INCOMPLETE_TYPES_BROKEN
  161010. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  161011. struct jvirt_sarray_control { long dummy; };
  161012. struct jvirt_barray_control { long dummy; };
  161013. struct jpeg_comp_master { long dummy; };
  161014. struct jpeg_c_main_controller { long dummy; };
  161015. struct jpeg_c_prep_controller { long dummy; };
  161016. struct jpeg_c_coef_controller { long dummy; };
  161017. struct jpeg_marker_writer { long dummy; };
  161018. struct jpeg_color_converter { long dummy; };
  161019. struct jpeg_downsampler { long dummy; };
  161020. struct jpeg_forward_dct { long dummy; };
  161021. struct jpeg_entropy_encoder { long dummy; };
  161022. struct jpeg_decomp_master { long dummy; };
  161023. struct jpeg_d_main_controller { long dummy; };
  161024. struct jpeg_d_coef_controller { long dummy; };
  161025. struct jpeg_d_post_controller { long dummy; };
  161026. struct jpeg_input_controller { long dummy; };
  161027. struct jpeg_marker_reader { long dummy; };
  161028. struct jpeg_entropy_decoder { long dummy; };
  161029. struct jpeg_inverse_dct { long dummy; };
  161030. struct jpeg_upsampler { long dummy; };
  161031. struct jpeg_color_deconverter { long dummy; };
  161032. struct jpeg_color_quantizer { long dummy; };
  161033. #endif /* JPEG_INTERNALS */
  161034. #endif /* INCOMPLETE_TYPES_BROKEN */
  161035. /*
  161036. * The JPEG library modules define JPEG_INTERNALS before including this file.
  161037. * The internal structure declarations are read only when that is true.
  161038. * Applications using the library should not include jpegint.h, but may wish
  161039. * to include jerror.h.
  161040. */
  161041. #ifdef JPEG_INTERNALS
  161042. /*** Start of inlined file: jpegint.h ***/
  161043. /* Declarations for both compression & decompression */
  161044. typedef enum { /* Operating modes for buffer controllers */
  161045. JBUF_PASS_THRU, /* Plain stripwise operation */
  161046. /* Remaining modes require a full-image buffer to have been created */
  161047. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  161048. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  161049. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  161050. } J_BUF_MODE;
  161051. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  161052. #define CSTATE_START 100 /* after create_compress */
  161053. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  161054. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  161055. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  161056. #define DSTATE_START 200 /* after create_decompress */
  161057. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  161058. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  161059. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  161060. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  161061. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  161062. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  161063. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  161064. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  161065. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  161066. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  161067. /* Declarations for compression modules */
  161068. /* Master control module */
  161069. struct jpeg_comp_master {
  161070. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  161071. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  161072. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161073. /* State variables made visible to other modules */
  161074. boolean call_pass_startup; /* True if pass_startup must be called */
  161075. boolean is_last_pass; /* True during last pass */
  161076. };
  161077. /* Main buffer control (downsampled-data buffer) */
  161078. struct jpeg_c_main_controller {
  161079. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161080. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  161081. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161082. JDIMENSION in_rows_avail));
  161083. };
  161084. /* Compression preprocessing (downsampling input buffer control) */
  161085. struct jpeg_c_prep_controller {
  161086. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161087. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  161088. JSAMPARRAY input_buf,
  161089. JDIMENSION *in_row_ctr,
  161090. JDIMENSION in_rows_avail,
  161091. JSAMPIMAGE output_buf,
  161092. JDIMENSION *out_row_group_ctr,
  161093. JDIMENSION out_row_groups_avail));
  161094. };
  161095. /* Coefficient buffer control */
  161096. struct jpeg_c_coef_controller {
  161097. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161098. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  161099. JSAMPIMAGE input_buf));
  161100. };
  161101. /* Colorspace conversion */
  161102. struct jpeg_color_converter {
  161103. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161104. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  161105. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161106. JDIMENSION output_row, int num_rows));
  161107. };
  161108. /* Downsampling */
  161109. struct jpeg_downsampler {
  161110. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161111. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  161112. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161113. JSAMPIMAGE output_buf,
  161114. JDIMENSION out_row_group_index));
  161115. boolean need_context_rows; /* TRUE if need rows above & below */
  161116. };
  161117. /* Forward DCT (also controls coefficient quantization) */
  161118. struct jpeg_forward_dct {
  161119. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161120. /* perhaps this should be an array??? */
  161121. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  161122. jpeg_component_info * compptr,
  161123. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161124. JDIMENSION start_row, JDIMENSION start_col,
  161125. JDIMENSION num_blocks));
  161126. };
  161127. /* Entropy encoding */
  161128. struct jpeg_entropy_encoder {
  161129. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161130. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161131. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161132. };
  161133. /* Marker writing */
  161134. struct jpeg_marker_writer {
  161135. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161136. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161137. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161138. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161139. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161140. /* These routines are exported to allow insertion of extra markers */
  161141. /* Probably only COM and APPn markers should be written this way */
  161142. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161143. unsigned int datalen));
  161144. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161145. };
  161146. /* Declarations for decompression modules */
  161147. /* Master control module */
  161148. struct jpeg_decomp_master {
  161149. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161150. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161151. /* State variables made visible to other modules */
  161152. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161153. };
  161154. /* Input control module */
  161155. struct jpeg_input_controller {
  161156. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161157. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161158. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161159. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161160. /* State variables made visible to other modules */
  161161. boolean has_multiple_scans; /* True if file has multiple scans */
  161162. boolean eoi_reached; /* True when EOI has been consumed */
  161163. };
  161164. /* Main buffer control (downsampled-data buffer) */
  161165. struct jpeg_d_main_controller {
  161166. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161167. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161168. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161169. JDIMENSION out_rows_avail));
  161170. };
  161171. /* Coefficient buffer control */
  161172. struct jpeg_d_coef_controller {
  161173. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161174. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161175. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161176. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161177. JSAMPIMAGE output_buf));
  161178. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161179. jvirt_barray_ptr *coef_arrays;
  161180. };
  161181. /* Decompression postprocessing (color quantization buffer control) */
  161182. struct jpeg_d_post_controller {
  161183. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161184. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161185. JSAMPIMAGE input_buf,
  161186. JDIMENSION *in_row_group_ctr,
  161187. JDIMENSION in_row_groups_avail,
  161188. JSAMPARRAY output_buf,
  161189. JDIMENSION *out_row_ctr,
  161190. JDIMENSION out_rows_avail));
  161191. };
  161192. /* Marker reading & parsing */
  161193. struct jpeg_marker_reader {
  161194. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161195. /* Read markers until SOS or EOI.
  161196. * Returns same codes as are defined for jpeg_consume_input:
  161197. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161198. */
  161199. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161200. /* Read a restart marker --- exported for use by entropy decoder only */
  161201. jpeg_marker_parser_method read_restart_marker;
  161202. /* State of marker reader --- nominally internal, but applications
  161203. * supplying COM or APPn handlers might like to know the state.
  161204. */
  161205. boolean saw_SOI; /* found SOI? */
  161206. boolean saw_SOF; /* found SOF? */
  161207. int next_restart_num; /* next restart number expected (0-7) */
  161208. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161209. };
  161210. /* Entropy decoding */
  161211. struct jpeg_entropy_decoder {
  161212. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161213. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161214. JBLOCKROW *MCU_data));
  161215. /* This is here to share code between baseline and progressive decoders; */
  161216. /* other modules probably should not use it */
  161217. boolean insufficient_data; /* set TRUE after emitting warning */
  161218. };
  161219. /* Inverse DCT (also performs dequantization) */
  161220. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161221. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161222. JCOEFPTR coef_block,
  161223. JSAMPARRAY output_buf, JDIMENSION output_col));
  161224. struct jpeg_inverse_dct {
  161225. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161226. /* It is useful to allow each component to have a separate IDCT method. */
  161227. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161228. };
  161229. /* Upsampling (note that upsampler must also call color converter) */
  161230. struct jpeg_upsampler {
  161231. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161232. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161233. JSAMPIMAGE input_buf,
  161234. JDIMENSION *in_row_group_ctr,
  161235. JDIMENSION in_row_groups_avail,
  161236. JSAMPARRAY output_buf,
  161237. JDIMENSION *out_row_ctr,
  161238. JDIMENSION out_rows_avail));
  161239. boolean need_context_rows; /* TRUE if need rows above & below */
  161240. };
  161241. /* Colorspace conversion */
  161242. struct jpeg_color_deconverter {
  161243. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161244. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161245. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161246. JSAMPARRAY output_buf, int num_rows));
  161247. };
  161248. /* Color quantization or color precision reduction */
  161249. struct jpeg_color_quantizer {
  161250. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161251. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161252. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161253. int num_rows));
  161254. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161255. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161256. };
  161257. /* Miscellaneous useful macros */
  161258. #undef MAX
  161259. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161260. #undef MIN
  161261. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161262. /* We assume that right shift corresponds to signed division by 2 with
  161263. * rounding towards minus infinity. This is correct for typical "arithmetic
  161264. * shift" instructions that shift in copies of the sign bit. But some
  161265. * C compilers implement >> with an unsigned shift. For these machines you
  161266. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161267. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161268. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161269. * included in the variables of any routine using RIGHT_SHIFT.
  161270. */
  161271. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161272. #define SHIFT_TEMPS INT32 shift_temp;
  161273. #define RIGHT_SHIFT(x,shft) \
  161274. ((shift_temp = (x)) < 0 ? \
  161275. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161276. (shift_temp >> (shft)))
  161277. #else
  161278. #define SHIFT_TEMPS
  161279. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161280. #endif
  161281. /* Short forms of external names for systems with brain-damaged linkers. */
  161282. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161283. #define jinit_compress_master jICompress
  161284. #define jinit_c_master_control jICMaster
  161285. #define jinit_c_main_controller jICMainC
  161286. #define jinit_c_prep_controller jICPrepC
  161287. #define jinit_c_coef_controller jICCoefC
  161288. #define jinit_color_converter jICColor
  161289. #define jinit_downsampler jIDownsampler
  161290. #define jinit_forward_dct jIFDCT
  161291. #define jinit_huff_encoder jIHEncoder
  161292. #define jinit_phuff_encoder jIPHEncoder
  161293. #define jinit_marker_writer jIMWriter
  161294. #define jinit_master_decompress jIDMaster
  161295. #define jinit_d_main_controller jIDMainC
  161296. #define jinit_d_coef_controller jIDCoefC
  161297. #define jinit_d_post_controller jIDPostC
  161298. #define jinit_input_controller jIInCtlr
  161299. #define jinit_marker_reader jIMReader
  161300. #define jinit_huff_decoder jIHDecoder
  161301. #define jinit_phuff_decoder jIPHDecoder
  161302. #define jinit_inverse_dct jIIDCT
  161303. #define jinit_upsampler jIUpsampler
  161304. #define jinit_color_deconverter jIDColor
  161305. #define jinit_1pass_quantizer jI1Quant
  161306. #define jinit_2pass_quantizer jI2Quant
  161307. #define jinit_merged_upsampler jIMUpsampler
  161308. #define jinit_memory_mgr jIMemMgr
  161309. #define jdiv_round_up jDivRound
  161310. #define jround_up jRound
  161311. #define jcopy_sample_rows jCopySamples
  161312. #define jcopy_block_row jCopyBlocks
  161313. #define jzero_far jZeroFar
  161314. #define jpeg_zigzag_order jZIGTable
  161315. #define jpeg_natural_order jZAGTable
  161316. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161317. /* Compression module initialization routines */
  161318. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161319. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161320. boolean transcode_only));
  161321. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161322. boolean need_full_buffer));
  161323. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161324. boolean need_full_buffer));
  161325. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161326. boolean need_full_buffer));
  161327. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161328. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161329. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161330. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161331. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161332. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161333. /* Decompression module initialization routines */
  161334. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161335. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161336. boolean need_full_buffer));
  161337. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161338. boolean need_full_buffer));
  161339. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161340. boolean need_full_buffer));
  161341. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161342. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161343. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161344. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161345. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161346. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161347. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161348. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161349. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161350. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161351. /* Memory manager initialization */
  161352. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161353. /* Utility routines in jutils.c */
  161354. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161355. EXTERN(long) jround_up JPP((long a, long b));
  161356. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161357. JSAMPARRAY output_array, int dest_row,
  161358. int num_rows, JDIMENSION num_cols));
  161359. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161360. JDIMENSION num_blocks));
  161361. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161362. /* Constant tables in jutils.c */
  161363. #if 0 /* This table is not actually needed in v6a */
  161364. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161365. #endif
  161366. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161367. /* Suppress undefined-structure complaints if necessary. */
  161368. #ifdef INCOMPLETE_TYPES_BROKEN
  161369. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161370. struct jvirt_sarray_control { long dummy; };
  161371. struct jvirt_barray_control { long dummy; };
  161372. #endif
  161373. #endif /* INCOMPLETE_TYPES_BROKEN */
  161374. /*** End of inlined file: jpegint.h ***/
  161375. /* fetch private declarations */
  161376. /*** Start of inlined file: jerror.h ***/
  161377. /*
  161378. * To define the enum list of message codes, include this file without
  161379. * defining macro JMESSAGE. To create a message string table, include it
  161380. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161381. */
  161382. #ifndef JMESSAGE
  161383. #ifndef JERROR_H
  161384. /* First time through, define the enum list */
  161385. #define JMAKE_ENUM_LIST
  161386. #else
  161387. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161388. #define JMESSAGE(code,string)
  161389. #endif /* JERROR_H */
  161390. #endif /* JMESSAGE */
  161391. #ifdef JMAKE_ENUM_LIST
  161392. typedef enum {
  161393. #define JMESSAGE(code,string) code ,
  161394. #endif /* JMAKE_ENUM_LIST */
  161395. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161396. /* For maintenance convenience, list is alphabetical by message code name */
  161397. JMESSAGE(JERR_ARITH_NOTIMPL,
  161398. "Sorry, there are legal restrictions on arithmetic coding")
  161399. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161400. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161401. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161402. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161403. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161404. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161405. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161406. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161407. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161408. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161409. JMESSAGE(JERR_BAD_LIB_VERSION,
  161410. "Wrong JPEG library version: library is %d, caller expects %d")
  161411. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161412. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161413. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161414. JMESSAGE(JERR_BAD_PROGRESSION,
  161415. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161416. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161417. "Invalid progressive parameters at scan script entry %d")
  161418. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161419. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161420. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161421. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161422. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161423. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161424. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161425. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161426. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161427. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161428. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161429. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161430. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161431. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161432. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161433. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161434. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161435. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161436. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161437. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161438. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161439. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161440. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161441. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161442. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161443. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161444. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161445. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161446. "Cannot transcode due to multiple use of quantization table %d")
  161447. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161448. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161449. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161450. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161451. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161452. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161453. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161454. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161455. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161456. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161457. JMESSAGE(JERR_QUANT_COMPONENTS,
  161458. "Cannot quantize more than %d color components")
  161459. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161460. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161461. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161462. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161463. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161464. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161465. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161466. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161467. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161468. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161469. JMESSAGE(JERR_TFILE_WRITE,
  161470. "Write failed on temporary file --- out of disk space?")
  161471. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161472. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161473. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161474. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161475. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161476. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161477. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161478. JMESSAGE(JMSG_VERSION, JVERSION)
  161479. JMESSAGE(JTRC_16BIT_TABLES,
  161480. "Caution: quantization tables are too coarse for baseline JPEG")
  161481. JMESSAGE(JTRC_ADOBE,
  161482. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161483. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161484. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161485. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161486. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161487. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161488. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161489. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161490. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161491. JMESSAGE(JTRC_EOI, "End Of Image")
  161492. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161493. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161494. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161495. "Warning: thumbnail image size does not match data length %u")
  161496. JMESSAGE(JTRC_JFIF_EXTENSION,
  161497. "JFIF extension marker: type 0x%02x, length %u")
  161498. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161499. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161500. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161501. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161502. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161503. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161504. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161505. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161506. JMESSAGE(JTRC_RST, "RST%d")
  161507. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161508. "Smoothing not supported with nonstandard sampling ratios")
  161509. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161510. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161511. JMESSAGE(JTRC_SOI, "Start of Image")
  161512. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161513. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161514. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161515. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161516. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161517. JMESSAGE(JTRC_THUMB_JPEG,
  161518. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161519. JMESSAGE(JTRC_THUMB_PALETTE,
  161520. "JFIF extension marker: palette thumbnail image, length %u")
  161521. JMESSAGE(JTRC_THUMB_RGB,
  161522. "JFIF extension marker: RGB thumbnail image, length %u")
  161523. JMESSAGE(JTRC_UNKNOWN_IDS,
  161524. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161525. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161526. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161527. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161528. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161529. "Inconsistent progression sequence for component %d coefficient %d")
  161530. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161531. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161532. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161533. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161534. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161535. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161536. JMESSAGE(JWRN_MUST_RESYNC,
  161537. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161538. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161539. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161540. #ifdef JMAKE_ENUM_LIST
  161541. JMSG_LASTMSGCODE
  161542. } J_MESSAGE_CODE;
  161543. #undef JMAKE_ENUM_LIST
  161544. #endif /* JMAKE_ENUM_LIST */
  161545. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161546. #undef JMESSAGE
  161547. #ifndef JERROR_H
  161548. #define JERROR_H
  161549. /* Macros to simplify using the error and trace message stuff */
  161550. /* The first parameter is either type of cinfo pointer */
  161551. /* Fatal errors (print message and exit) */
  161552. #define ERREXIT(cinfo,code) \
  161553. ((cinfo)->err->msg_code = (code), \
  161554. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161555. #define ERREXIT1(cinfo,code,p1) \
  161556. ((cinfo)->err->msg_code = (code), \
  161557. (cinfo)->err->msg_parm.i[0] = (p1), \
  161558. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161559. #define ERREXIT2(cinfo,code,p1,p2) \
  161560. ((cinfo)->err->msg_code = (code), \
  161561. (cinfo)->err->msg_parm.i[0] = (p1), \
  161562. (cinfo)->err->msg_parm.i[1] = (p2), \
  161563. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161564. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161565. ((cinfo)->err->msg_code = (code), \
  161566. (cinfo)->err->msg_parm.i[0] = (p1), \
  161567. (cinfo)->err->msg_parm.i[1] = (p2), \
  161568. (cinfo)->err->msg_parm.i[2] = (p3), \
  161569. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161570. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161571. ((cinfo)->err->msg_code = (code), \
  161572. (cinfo)->err->msg_parm.i[0] = (p1), \
  161573. (cinfo)->err->msg_parm.i[1] = (p2), \
  161574. (cinfo)->err->msg_parm.i[2] = (p3), \
  161575. (cinfo)->err->msg_parm.i[3] = (p4), \
  161576. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161577. #define ERREXITS(cinfo,code,str) \
  161578. ((cinfo)->err->msg_code = (code), \
  161579. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161580. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161581. #define MAKESTMT(stuff) do { stuff } while (0)
  161582. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161583. #define WARNMS(cinfo,code) \
  161584. ((cinfo)->err->msg_code = (code), \
  161585. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161586. #define WARNMS1(cinfo,code,p1) \
  161587. ((cinfo)->err->msg_code = (code), \
  161588. (cinfo)->err->msg_parm.i[0] = (p1), \
  161589. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161590. #define WARNMS2(cinfo,code,p1,p2) \
  161591. ((cinfo)->err->msg_code = (code), \
  161592. (cinfo)->err->msg_parm.i[0] = (p1), \
  161593. (cinfo)->err->msg_parm.i[1] = (p2), \
  161594. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161595. /* Informational/debugging messages */
  161596. #define TRACEMS(cinfo,lvl,code) \
  161597. ((cinfo)->err->msg_code = (code), \
  161598. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161599. #define TRACEMS1(cinfo,lvl,code,p1) \
  161600. ((cinfo)->err->msg_code = (code), \
  161601. (cinfo)->err->msg_parm.i[0] = (p1), \
  161602. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161603. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161604. ((cinfo)->err->msg_code = (code), \
  161605. (cinfo)->err->msg_parm.i[0] = (p1), \
  161606. (cinfo)->err->msg_parm.i[1] = (p2), \
  161607. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161608. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161609. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161610. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161611. (cinfo)->err->msg_code = (code); \
  161612. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161613. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161614. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161615. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161616. (cinfo)->err->msg_code = (code); \
  161617. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161618. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161619. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161620. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161621. _mp[4] = (p5); \
  161622. (cinfo)->err->msg_code = (code); \
  161623. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161624. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161625. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161626. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161627. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161628. (cinfo)->err->msg_code = (code); \
  161629. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161630. #define TRACEMSS(cinfo,lvl,code,str) \
  161631. ((cinfo)->err->msg_code = (code), \
  161632. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161633. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161634. #endif /* JERROR_H */
  161635. /*** End of inlined file: jerror.h ***/
  161636. /* fetch error codes too */
  161637. #endif
  161638. #endif /* JPEGLIB_H */
  161639. /*** End of inlined file: jpeglib.h ***/
  161640. /*** Start of inlined file: jcapimin.c ***/
  161641. #define JPEG_INTERNALS
  161642. /*** Start of inlined file: jinclude.h ***/
  161643. /* Include auto-config file to find out which system include files we need. */
  161644. #ifndef __jinclude_h__
  161645. #define __jinclude_h__
  161646. /*** Start of inlined file: jconfig.h ***/
  161647. /* see jconfig.doc for explanations */
  161648. // disable all the warnings under MSVC
  161649. #ifdef _MSC_VER
  161650. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161651. #endif
  161652. #ifdef __BORLANDC__
  161653. #pragma warn -8057
  161654. #pragma warn -8019
  161655. #pragma warn -8004
  161656. #pragma warn -8008
  161657. #endif
  161658. #define HAVE_PROTOTYPES
  161659. #define HAVE_UNSIGNED_CHAR
  161660. #define HAVE_UNSIGNED_SHORT
  161661. /* #define void char */
  161662. /* #define const */
  161663. #undef CHAR_IS_UNSIGNED
  161664. #define HAVE_STDDEF_H
  161665. #define HAVE_STDLIB_H
  161666. #undef NEED_BSD_STRINGS
  161667. #undef NEED_SYS_TYPES_H
  161668. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161669. #undef NEED_SHORT_EXTERNAL_NAMES
  161670. #undef INCOMPLETE_TYPES_BROKEN
  161671. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161672. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161673. typedef unsigned char boolean;
  161674. #endif
  161675. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161676. #ifdef JPEG_INTERNALS
  161677. #undef RIGHT_SHIFT_IS_UNSIGNED
  161678. #endif /* JPEG_INTERNALS */
  161679. #ifdef JPEG_CJPEG_DJPEG
  161680. #define BMP_SUPPORTED /* BMP image file format */
  161681. #define GIF_SUPPORTED /* GIF image file format */
  161682. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161683. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161684. #define TARGA_SUPPORTED /* Targa image file format */
  161685. #define TWO_FILE_COMMANDLINE /* optional */
  161686. #define USE_SETMODE /* Microsoft has setmode() */
  161687. #undef NEED_SIGNAL_CATCHER
  161688. #undef DONT_USE_B_MODE
  161689. #undef PROGRESS_REPORT /* optional */
  161690. #endif /* JPEG_CJPEG_DJPEG */
  161691. /*** End of inlined file: jconfig.h ***/
  161692. /* auto configuration options */
  161693. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161694. /*
  161695. * We need the NULL macro and size_t typedef.
  161696. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161697. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161698. * pull in <sys/types.h> as well.
  161699. * Note that the core JPEG library does not require <stdio.h>;
  161700. * only the default error handler and data source/destination modules do.
  161701. * But we must pull it in because of the references to FILE in jpeglib.h.
  161702. * You can remove those references if you want to compile without <stdio.h>.
  161703. */
  161704. #ifdef HAVE_STDDEF_H
  161705. #include <stddef.h>
  161706. #endif
  161707. #ifdef HAVE_STDLIB_H
  161708. #include <stdlib.h>
  161709. #endif
  161710. #ifdef NEED_SYS_TYPES_H
  161711. #include <sys/types.h>
  161712. #endif
  161713. #include <stdio.h>
  161714. /*
  161715. * We need memory copying and zeroing functions, plus strncpy().
  161716. * ANSI and System V implementations declare these in <string.h>.
  161717. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161718. * Some systems may declare memset and memcpy in <memory.h>.
  161719. *
  161720. * NOTE: we assume the size parameters to these functions are of type size_t.
  161721. * Change the casts in these macros if not!
  161722. */
  161723. #ifdef NEED_BSD_STRINGS
  161724. #include <strings.h>
  161725. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161726. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161727. #else /* not BSD, assume ANSI/SysV string lib */
  161728. #include <string.h>
  161729. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161730. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161731. #endif
  161732. /*
  161733. * In ANSI C, and indeed any rational implementation, size_t is also the
  161734. * type returned by sizeof(). However, it seems there are some irrational
  161735. * implementations out there, in which sizeof() returns an int even though
  161736. * size_t is defined as long or unsigned long. To ensure consistent results
  161737. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161738. */
  161739. #define SIZEOF(object) ((size_t) sizeof(object))
  161740. /*
  161741. * The modules that use fread() and fwrite() always invoke them through
  161742. * these macros. On some systems you may need to twiddle the argument casts.
  161743. * CAUTION: argument order is different from underlying functions!
  161744. */
  161745. #define JFREAD(file,buf,sizeofbuf) \
  161746. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161747. #define JFWRITE(file,buf,sizeofbuf) \
  161748. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161749. typedef enum { /* JPEG marker codes */
  161750. M_SOF0 = 0xc0,
  161751. M_SOF1 = 0xc1,
  161752. M_SOF2 = 0xc2,
  161753. M_SOF3 = 0xc3,
  161754. M_SOF5 = 0xc5,
  161755. M_SOF6 = 0xc6,
  161756. M_SOF7 = 0xc7,
  161757. M_JPG = 0xc8,
  161758. M_SOF9 = 0xc9,
  161759. M_SOF10 = 0xca,
  161760. M_SOF11 = 0xcb,
  161761. M_SOF13 = 0xcd,
  161762. M_SOF14 = 0xce,
  161763. M_SOF15 = 0xcf,
  161764. M_DHT = 0xc4,
  161765. M_DAC = 0xcc,
  161766. M_RST0 = 0xd0,
  161767. M_RST1 = 0xd1,
  161768. M_RST2 = 0xd2,
  161769. M_RST3 = 0xd3,
  161770. M_RST4 = 0xd4,
  161771. M_RST5 = 0xd5,
  161772. M_RST6 = 0xd6,
  161773. M_RST7 = 0xd7,
  161774. M_SOI = 0xd8,
  161775. M_EOI = 0xd9,
  161776. M_SOS = 0xda,
  161777. M_DQT = 0xdb,
  161778. M_DNL = 0xdc,
  161779. M_DRI = 0xdd,
  161780. M_DHP = 0xde,
  161781. M_EXP = 0xdf,
  161782. M_APP0 = 0xe0,
  161783. M_APP1 = 0xe1,
  161784. M_APP2 = 0xe2,
  161785. M_APP3 = 0xe3,
  161786. M_APP4 = 0xe4,
  161787. M_APP5 = 0xe5,
  161788. M_APP6 = 0xe6,
  161789. M_APP7 = 0xe7,
  161790. M_APP8 = 0xe8,
  161791. M_APP9 = 0xe9,
  161792. M_APP10 = 0xea,
  161793. M_APP11 = 0xeb,
  161794. M_APP12 = 0xec,
  161795. M_APP13 = 0xed,
  161796. M_APP14 = 0xee,
  161797. M_APP15 = 0xef,
  161798. M_JPG0 = 0xf0,
  161799. M_JPG13 = 0xfd,
  161800. M_COM = 0xfe,
  161801. M_TEM = 0x01,
  161802. M_ERROR = 0x100
  161803. } JPEG_MARKER;
  161804. /*
  161805. * Figure F.12: extend sign bit.
  161806. * On some machines, a shift and add will be faster than a table lookup.
  161807. */
  161808. #ifdef AVOID_TABLES
  161809. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161810. #else
  161811. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161812. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161813. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161814. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161815. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161816. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161817. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161818. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161819. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161820. #endif /* AVOID_TABLES */
  161821. #endif
  161822. /*** End of inlined file: jinclude.h ***/
  161823. /*
  161824. * Initialization of a JPEG compression object.
  161825. * The error manager must already be set up (in case memory manager fails).
  161826. */
  161827. GLOBAL(void)
  161828. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161829. {
  161830. int i;
  161831. /* Guard against version mismatches between library and caller. */
  161832. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161833. if (version != JPEG_LIB_VERSION)
  161834. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161835. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161836. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161837. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161838. /* For debugging purposes, we zero the whole master structure.
  161839. * But the application has already set the err pointer, and may have set
  161840. * client_data, so we have to save and restore those fields.
  161841. * Note: if application hasn't set client_data, tools like Purify may
  161842. * complain here.
  161843. */
  161844. {
  161845. struct jpeg_error_mgr * err = cinfo->err;
  161846. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161847. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161848. cinfo->err = err;
  161849. cinfo->client_data = client_data;
  161850. }
  161851. cinfo->is_decompressor = FALSE;
  161852. /* Initialize a memory manager instance for this object */
  161853. jinit_memory_mgr((j_common_ptr) cinfo);
  161854. /* Zero out pointers to permanent structures. */
  161855. cinfo->progress = NULL;
  161856. cinfo->dest = NULL;
  161857. cinfo->comp_info = NULL;
  161858. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161859. cinfo->quant_tbl_ptrs[i] = NULL;
  161860. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161861. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161862. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161863. }
  161864. cinfo->script_space = NULL;
  161865. cinfo->input_gamma = 1.0; /* in case application forgets */
  161866. /* OK, I'm ready */
  161867. cinfo->global_state = CSTATE_START;
  161868. }
  161869. /*
  161870. * Destruction of a JPEG compression object
  161871. */
  161872. GLOBAL(void)
  161873. jpeg_destroy_compress (j_compress_ptr cinfo)
  161874. {
  161875. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161876. }
  161877. /*
  161878. * Abort processing of a JPEG compression operation,
  161879. * but don't destroy the object itself.
  161880. */
  161881. GLOBAL(void)
  161882. jpeg_abort_compress (j_compress_ptr cinfo)
  161883. {
  161884. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161885. }
  161886. /*
  161887. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161888. * Marks all currently defined tables as already written (if suppress)
  161889. * or not written (if !suppress). This will control whether they get emitted
  161890. * by a subsequent jpeg_start_compress call.
  161891. *
  161892. * This routine is exported for use by applications that want to produce
  161893. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161894. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161895. * jcparam.o would be linked whether the application used it or not.
  161896. */
  161897. GLOBAL(void)
  161898. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161899. {
  161900. int i;
  161901. JQUANT_TBL * qtbl;
  161902. JHUFF_TBL * htbl;
  161903. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161904. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161905. qtbl->sent_table = suppress;
  161906. }
  161907. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161908. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161909. htbl->sent_table = suppress;
  161910. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161911. htbl->sent_table = suppress;
  161912. }
  161913. }
  161914. /*
  161915. * Finish JPEG compression.
  161916. *
  161917. * If a multipass operating mode was selected, this may do a great deal of
  161918. * work including most of the actual output.
  161919. */
  161920. GLOBAL(void)
  161921. jpeg_finish_compress (j_compress_ptr cinfo)
  161922. {
  161923. JDIMENSION iMCU_row;
  161924. if (cinfo->global_state == CSTATE_SCANNING ||
  161925. cinfo->global_state == CSTATE_RAW_OK) {
  161926. /* Terminate first pass */
  161927. if (cinfo->next_scanline < cinfo->image_height)
  161928. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161929. (*cinfo->master->finish_pass) (cinfo);
  161930. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161931. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161932. /* Perform any remaining passes */
  161933. while (! cinfo->master->is_last_pass) {
  161934. (*cinfo->master->prepare_for_pass) (cinfo);
  161935. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161936. if (cinfo->progress != NULL) {
  161937. cinfo->progress->pass_counter = (long) iMCU_row;
  161938. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161939. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161940. }
  161941. /* We bypass the main controller and invoke coef controller directly;
  161942. * all work is being done from the coefficient buffer.
  161943. */
  161944. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161945. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161946. }
  161947. (*cinfo->master->finish_pass) (cinfo);
  161948. }
  161949. /* Write EOI, do final cleanup */
  161950. (*cinfo->marker->write_file_trailer) (cinfo);
  161951. (*cinfo->dest->term_destination) (cinfo);
  161952. /* We can use jpeg_abort to release memory and reset global_state */
  161953. jpeg_abort((j_common_ptr) cinfo);
  161954. }
  161955. /*
  161956. * Write a special marker.
  161957. * This is only recommended for writing COM or APPn markers.
  161958. * Must be called after jpeg_start_compress() and before
  161959. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161960. */
  161961. GLOBAL(void)
  161962. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161963. const JOCTET *dataptr, unsigned int datalen)
  161964. {
  161965. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161966. if (cinfo->next_scanline != 0 ||
  161967. (cinfo->global_state != CSTATE_SCANNING &&
  161968. cinfo->global_state != CSTATE_RAW_OK &&
  161969. cinfo->global_state != CSTATE_WRCOEFS))
  161970. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161971. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161972. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161973. while (datalen--) {
  161974. (*write_marker_byte) (cinfo, *dataptr);
  161975. dataptr++;
  161976. }
  161977. }
  161978. /* Same, but piecemeal. */
  161979. GLOBAL(void)
  161980. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161981. {
  161982. if (cinfo->next_scanline != 0 ||
  161983. (cinfo->global_state != CSTATE_SCANNING &&
  161984. cinfo->global_state != CSTATE_RAW_OK &&
  161985. cinfo->global_state != CSTATE_WRCOEFS))
  161986. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161987. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161988. }
  161989. GLOBAL(void)
  161990. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161991. {
  161992. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161993. }
  161994. /*
  161995. * Alternate compression function: just write an abbreviated table file.
  161996. * Before calling this, all parameters and a data destination must be set up.
  161997. *
  161998. * To produce a pair of files containing abbreviated tables and abbreviated
  161999. * image data, one would proceed as follows:
  162000. *
  162001. * initialize JPEG object
  162002. * set JPEG parameters
  162003. * set destination to table file
  162004. * jpeg_write_tables(cinfo);
  162005. * set destination to image file
  162006. * jpeg_start_compress(cinfo, FALSE);
  162007. * write data...
  162008. * jpeg_finish_compress(cinfo);
  162009. *
  162010. * jpeg_write_tables has the side effect of marking all tables written
  162011. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  162012. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  162013. */
  162014. GLOBAL(void)
  162015. jpeg_write_tables (j_compress_ptr cinfo)
  162016. {
  162017. if (cinfo->global_state != CSTATE_START)
  162018. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162019. /* (Re)initialize error mgr and destination modules */
  162020. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162021. (*cinfo->dest->init_destination) (cinfo);
  162022. /* Initialize the marker writer ... bit of a crock to do it here. */
  162023. jinit_marker_writer(cinfo);
  162024. /* Write them tables! */
  162025. (*cinfo->marker->write_tables_only) (cinfo);
  162026. /* And clean up. */
  162027. (*cinfo->dest->term_destination) (cinfo);
  162028. /*
  162029. * In library releases up through v6a, we called jpeg_abort() here to free
  162030. * any working memory allocated by the destination manager and marker
  162031. * writer. Some applications had a problem with that: they allocated space
  162032. * of their own from the library memory manager, and didn't want it to go
  162033. * away during write_tables. So now we do nothing. This will cause a
  162034. * memory leak if an app calls write_tables repeatedly without doing a full
  162035. * compression cycle or otherwise resetting the JPEG object. However, that
  162036. * seems less bad than unexpectedly freeing memory in the normal case.
  162037. * An app that prefers the old behavior can call jpeg_abort for itself after
  162038. * each call to jpeg_write_tables().
  162039. */
  162040. }
  162041. /*** End of inlined file: jcapimin.c ***/
  162042. /*** Start of inlined file: jcapistd.c ***/
  162043. #define JPEG_INTERNALS
  162044. /*
  162045. * Compression initialization.
  162046. * Before calling this, all parameters and a data destination must be set up.
  162047. *
  162048. * We require a write_all_tables parameter as a failsafe check when writing
  162049. * multiple datastreams from the same compression object. Since prior runs
  162050. * will have left all the tables marked sent_table=TRUE, a subsequent run
  162051. * would emit an abbreviated stream (no tables) by default. This may be what
  162052. * is wanted, but for safety's sake it should not be the default behavior:
  162053. * programmers should have to make a deliberate choice to emit abbreviated
  162054. * images. Therefore the documentation and examples should encourage people
  162055. * to pass write_all_tables=TRUE; then it will take active thought to do the
  162056. * wrong thing.
  162057. */
  162058. GLOBAL(void)
  162059. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  162060. {
  162061. if (cinfo->global_state != CSTATE_START)
  162062. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162063. if (write_all_tables)
  162064. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  162065. /* (Re)initialize error mgr and destination modules */
  162066. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162067. (*cinfo->dest->init_destination) (cinfo);
  162068. /* Perform master selection of active modules */
  162069. jinit_compress_master(cinfo);
  162070. /* Set up for the first pass */
  162071. (*cinfo->master->prepare_for_pass) (cinfo);
  162072. /* Ready for application to drive first pass through jpeg_write_scanlines
  162073. * or jpeg_write_raw_data.
  162074. */
  162075. cinfo->next_scanline = 0;
  162076. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  162077. }
  162078. /*
  162079. * Write some scanlines of data to the JPEG compressor.
  162080. *
  162081. * The return value will be the number of lines actually written.
  162082. * This should be less than the supplied num_lines only in case that
  162083. * the data destination module has requested suspension of the compressor,
  162084. * or if more than image_height scanlines are passed in.
  162085. *
  162086. * Note: we warn about excess calls to jpeg_write_scanlines() since
  162087. * this likely signals an application programmer error. However,
  162088. * excess scanlines passed in the last valid call are *silently* ignored,
  162089. * so that the application need not adjust num_lines for end-of-image
  162090. * when using a multiple-scanline buffer.
  162091. */
  162092. GLOBAL(JDIMENSION)
  162093. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  162094. JDIMENSION num_lines)
  162095. {
  162096. JDIMENSION row_ctr, rows_left;
  162097. if (cinfo->global_state != CSTATE_SCANNING)
  162098. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162099. if (cinfo->next_scanline >= cinfo->image_height)
  162100. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162101. /* Call progress monitor hook if present */
  162102. if (cinfo->progress != NULL) {
  162103. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162104. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162105. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162106. }
  162107. /* Give master control module another chance if this is first call to
  162108. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  162109. * delayed so that application can write COM, etc, markers between
  162110. * jpeg_start_compress and jpeg_write_scanlines.
  162111. */
  162112. if (cinfo->master->call_pass_startup)
  162113. (*cinfo->master->pass_startup) (cinfo);
  162114. /* Ignore any extra scanlines at bottom of image. */
  162115. rows_left = cinfo->image_height - cinfo->next_scanline;
  162116. if (num_lines > rows_left)
  162117. num_lines = rows_left;
  162118. row_ctr = 0;
  162119. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  162120. cinfo->next_scanline += row_ctr;
  162121. return row_ctr;
  162122. }
  162123. /*
  162124. * Alternate entry point to write raw data.
  162125. * Processes exactly one iMCU row per call, unless suspended.
  162126. */
  162127. GLOBAL(JDIMENSION)
  162128. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162129. JDIMENSION num_lines)
  162130. {
  162131. JDIMENSION lines_per_iMCU_row;
  162132. if (cinfo->global_state != CSTATE_RAW_OK)
  162133. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162134. if (cinfo->next_scanline >= cinfo->image_height) {
  162135. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162136. return 0;
  162137. }
  162138. /* Call progress monitor hook if present */
  162139. if (cinfo->progress != NULL) {
  162140. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162141. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162142. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162143. }
  162144. /* Give master control module another chance if this is first call to
  162145. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162146. * delayed so that application can write COM, etc, markers between
  162147. * jpeg_start_compress and jpeg_write_raw_data.
  162148. */
  162149. if (cinfo->master->call_pass_startup)
  162150. (*cinfo->master->pass_startup) (cinfo);
  162151. /* Verify that at least one iMCU row has been passed. */
  162152. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162153. if (num_lines < lines_per_iMCU_row)
  162154. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162155. /* Directly compress the row. */
  162156. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162157. /* If compressor did not consume the whole row, suspend processing. */
  162158. return 0;
  162159. }
  162160. /* OK, we processed one iMCU row. */
  162161. cinfo->next_scanline += lines_per_iMCU_row;
  162162. return lines_per_iMCU_row;
  162163. }
  162164. /*** End of inlined file: jcapistd.c ***/
  162165. /*** Start of inlined file: jccoefct.c ***/
  162166. #define JPEG_INTERNALS
  162167. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162168. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162169. * step is run during the first pass, and subsequent passes need only read
  162170. * the buffered coefficients.
  162171. */
  162172. #ifdef ENTROPY_OPT_SUPPORTED
  162173. #define FULL_COEF_BUFFER_SUPPORTED
  162174. #else
  162175. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162176. #define FULL_COEF_BUFFER_SUPPORTED
  162177. #endif
  162178. #endif
  162179. /* Private buffer controller object */
  162180. typedef struct {
  162181. struct jpeg_c_coef_controller pub; /* public fields */
  162182. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162183. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162184. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162185. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162186. /* For single-pass compression, it's sufficient to buffer just one MCU
  162187. * (although this may prove a bit slow in practice). We allocate a
  162188. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162189. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162190. * it's not really very big; this is to keep the module interfaces unchanged
  162191. * when a large coefficient buffer is necessary.)
  162192. * In multi-pass modes, this array points to the current MCU's blocks
  162193. * within the virtual arrays.
  162194. */
  162195. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162196. /* In multi-pass modes, we need a virtual block array for each component. */
  162197. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162198. } my_coef_controller;
  162199. typedef my_coef_controller * my_coef_ptr;
  162200. /* Forward declarations */
  162201. METHODDEF(boolean) compress_data
  162202. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162203. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162204. METHODDEF(boolean) compress_first_pass
  162205. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162206. METHODDEF(boolean) compress_output
  162207. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162208. #endif
  162209. LOCAL(void)
  162210. start_iMCU_row (j_compress_ptr cinfo)
  162211. /* Reset within-iMCU-row counters for a new row */
  162212. {
  162213. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162214. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162215. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162216. * But at the bottom of the image, process only what's left.
  162217. */
  162218. if (cinfo->comps_in_scan > 1) {
  162219. coef->MCU_rows_per_iMCU_row = 1;
  162220. } else {
  162221. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162222. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162223. else
  162224. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162225. }
  162226. coef->mcu_ctr = 0;
  162227. coef->MCU_vert_offset = 0;
  162228. }
  162229. /*
  162230. * Initialize for a processing pass.
  162231. */
  162232. METHODDEF(void)
  162233. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162234. {
  162235. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162236. coef->iMCU_row_num = 0;
  162237. start_iMCU_row(cinfo);
  162238. switch (pass_mode) {
  162239. case JBUF_PASS_THRU:
  162240. if (coef->whole_image[0] != NULL)
  162241. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162242. coef->pub.compress_data = compress_data;
  162243. break;
  162244. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162245. case JBUF_SAVE_AND_PASS:
  162246. if (coef->whole_image[0] == NULL)
  162247. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162248. coef->pub.compress_data = compress_first_pass;
  162249. break;
  162250. case JBUF_CRANK_DEST:
  162251. if (coef->whole_image[0] == NULL)
  162252. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162253. coef->pub.compress_data = compress_output;
  162254. break;
  162255. #endif
  162256. default:
  162257. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162258. break;
  162259. }
  162260. }
  162261. /*
  162262. * Process some data in the single-pass case.
  162263. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162264. * per call, ie, v_samp_factor block rows for each component in the image.
  162265. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162266. *
  162267. * NB: input_buf contains a plane for each component in image,
  162268. * which we index according to the component's SOF position.
  162269. */
  162270. METHODDEF(boolean)
  162271. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162272. {
  162273. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162274. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162275. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162276. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162277. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162278. JDIMENSION ypos, xpos;
  162279. jpeg_component_info *compptr;
  162280. /* Loop to write as much as one whole iMCU row */
  162281. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162282. yoffset++) {
  162283. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162284. MCU_col_num++) {
  162285. /* Determine where data comes from in input_buf and do the DCT thing.
  162286. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162287. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162288. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162289. * specially. The data in them does not matter for image reconstruction,
  162290. * so we fill them with values that will encode to the smallest amount of
  162291. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162292. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162293. */
  162294. blkn = 0;
  162295. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162296. compptr = cinfo->cur_comp_info[ci];
  162297. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162298. : compptr->last_col_width;
  162299. xpos = MCU_col_num * compptr->MCU_sample_width;
  162300. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162301. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162302. if (coef->iMCU_row_num < last_iMCU_row ||
  162303. yoffset+yindex < compptr->last_row_height) {
  162304. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162305. input_buf[compptr->component_index],
  162306. coef->MCU_buffer[blkn],
  162307. ypos, xpos, (JDIMENSION) blockcnt);
  162308. if (blockcnt < compptr->MCU_width) {
  162309. /* Create some dummy blocks at the right edge of the image. */
  162310. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162311. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162312. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162313. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162314. }
  162315. }
  162316. } else {
  162317. /* Create a row of dummy blocks at the bottom of the image. */
  162318. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162319. compptr->MCU_width * SIZEOF(JBLOCK));
  162320. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162321. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162322. }
  162323. }
  162324. blkn += compptr->MCU_width;
  162325. ypos += DCTSIZE;
  162326. }
  162327. }
  162328. /* Try to write the MCU. In event of a suspension failure, we will
  162329. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162330. */
  162331. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162332. /* Suspension forced; update state counters and exit */
  162333. coef->MCU_vert_offset = yoffset;
  162334. coef->mcu_ctr = MCU_col_num;
  162335. return FALSE;
  162336. }
  162337. }
  162338. /* Completed an MCU row, but perhaps not an iMCU row */
  162339. coef->mcu_ctr = 0;
  162340. }
  162341. /* Completed the iMCU row, advance counters for next one */
  162342. coef->iMCU_row_num++;
  162343. start_iMCU_row(cinfo);
  162344. return TRUE;
  162345. }
  162346. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162347. /*
  162348. * Process some data in the first pass of a multi-pass case.
  162349. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162350. * per call, ie, v_samp_factor block rows for each component in the image.
  162351. * This amount of data is read from the source buffer, DCT'd and quantized,
  162352. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162353. * as needed at the right and lower edges. (The dummy blocks are constructed
  162354. * in the virtual arrays, which have been padded appropriately.) This makes
  162355. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162356. *
  162357. * We must also emit the data to the entropy encoder. This is conveniently
  162358. * done by calling compress_output() after we've loaded the current strip
  162359. * of the virtual arrays.
  162360. *
  162361. * NB: input_buf contains a plane for each component in image. All
  162362. * components are DCT'd and loaded into the virtual arrays in this pass.
  162363. * However, it may be that only a subset of the components are emitted to
  162364. * the entropy encoder during this first pass; be careful about looking
  162365. * at the scan-dependent variables (MCU dimensions, etc).
  162366. */
  162367. METHODDEF(boolean)
  162368. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162369. {
  162370. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162371. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162372. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162373. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162374. JCOEF lastDC;
  162375. jpeg_component_info *compptr;
  162376. JBLOCKARRAY buffer;
  162377. JBLOCKROW thisblockrow, lastblockrow;
  162378. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162379. ci++, compptr++) {
  162380. /* Align the virtual buffer for this component. */
  162381. buffer = (*cinfo->mem->access_virt_barray)
  162382. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162383. coef->iMCU_row_num * compptr->v_samp_factor,
  162384. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162385. /* Count non-dummy DCT block rows in this iMCU row. */
  162386. if (coef->iMCU_row_num < last_iMCU_row)
  162387. block_rows = compptr->v_samp_factor;
  162388. else {
  162389. /* NB: can't use last_row_height here, since may not be set! */
  162390. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162391. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162392. }
  162393. blocks_across = compptr->width_in_blocks;
  162394. h_samp_factor = compptr->h_samp_factor;
  162395. /* Count number of dummy blocks to be added at the right margin. */
  162396. ndummy = (int) (blocks_across % h_samp_factor);
  162397. if (ndummy > 0)
  162398. ndummy = h_samp_factor - ndummy;
  162399. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162400. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162401. */
  162402. for (block_row = 0; block_row < block_rows; block_row++) {
  162403. thisblockrow = buffer[block_row];
  162404. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162405. input_buf[ci], thisblockrow,
  162406. (JDIMENSION) (block_row * DCTSIZE),
  162407. (JDIMENSION) 0, blocks_across);
  162408. if (ndummy > 0) {
  162409. /* Create dummy blocks at the right edge of the image. */
  162410. thisblockrow += blocks_across; /* => first dummy block */
  162411. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162412. lastDC = thisblockrow[-1][0];
  162413. for (bi = 0; bi < ndummy; bi++) {
  162414. thisblockrow[bi][0] = lastDC;
  162415. }
  162416. }
  162417. }
  162418. /* If at end of image, create dummy block rows as needed.
  162419. * The tricky part here is that within each MCU, we want the DC values
  162420. * of the dummy blocks to match the last real block's DC value.
  162421. * This squeezes a few more bytes out of the resulting file...
  162422. */
  162423. if (coef->iMCU_row_num == last_iMCU_row) {
  162424. blocks_across += ndummy; /* include lower right corner */
  162425. MCUs_across = blocks_across / h_samp_factor;
  162426. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162427. block_row++) {
  162428. thisblockrow = buffer[block_row];
  162429. lastblockrow = buffer[block_row-1];
  162430. jzero_far((void FAR *) thisblockrow,
  162431. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162432. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162433. lastDC = lastblockrow[h_samp_factor-1][0];
  162434. for (bi = 0; bi < h_samp_factor; bi++) {
  162435. thisblockrow[bi][0] = lastDC;
  162436. }
  162437. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162438. lastblockrow += h_samp_factor;
  162439. }
  162440. }
  162441. }
  162442. }
  162443. /* NB: compress_output will increment iMCU_row_num if successful.
  162444. * A suspension return will result in redoing all the work above next time.
  162445. */
  162446. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162447. return compress_output(cinfo, input_buf);
  162448. }
  162449. /*
  162450. * Process some data in subsequent passes of a multi-pass case.
  162451. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162452. * per call, ie, v_samp_factor block rows for each component in the scan.
  162453. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162454. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162455. *
  162456. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162457. */
  162458. METHODDEF(boolean)
  162459. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162460. {
  162461. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162462. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162463. int blkn, ci, xindex, yindex, yoffset;
  162464. JDIMENSION start_col;
  162465. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162466. JBLOCKROW buffer_ptr;
  162467. jpeg_component_info *compptr;
  162468. /* Align the virtual buffers for the components used in this scan.
  162469. * NB: during first pass, this is safe only because the buffers will
  162470. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162471. */
  162472. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162473. compptr = cinfo->cur_comp_info[ci];
  162474. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162475. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162476. coef->iMCU_row_num * compptr->v_samp_factor,
  162477. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162478. }
  162479. /* Loop to process one whole iMCU row */
  162480. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162481. yoffset++) {
  162482. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162483. MCU_col_num++) {
  162484. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162485. blkn = 0; /* index of current DCT block within MCU */
  162486. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162487. compptr = cinfo->cur_comp_info[ci];
  162488. start_col = MCU_col_num * compptr->MCU_width;
  162489. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162490. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162491. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162492. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162493. }
  162494. }
  162495. }
  162496. /* Try to write the MCU. */
  162497. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162498. /* Suspension forced; update state counters and exit */
  162499. coef->MCU_vert_offset = yoffset;
  162500. coef->mcu_ctr = MCU_col_num;
  162501. return FALSE;
  162502. }
  162503. }
  162504. /* Completed an MCU row, but perhaps not an iMCU row */
  162505. coef->mcu_ctr = 0;
  162506. }
  162507. /* Completed the iMCU row, advance counters for next one */
  162508. coef->iMCU_row_num++;
  162509. start_iMCU_row(cinfo);
  162510. return TRUE;
  162511. }
  162512. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162513. /*
  162514. * Initialize coefficient buffer controller.
  162515. */
  162516. GLOBAL(void)
  162517. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162518. {
  162519. my_coef_ptr coef;
  162520. coef = (my_coef_ptr)
  162521. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162522. SIZEOF(my_coef_controller));
  162523. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162524. coef->pub.start_pass = start_pass_coef;
  162525. /* Create the coefficient buffer. */
  162526. if (need_full_buffer) {
  162527. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162528. /* Allocate a full-image virtual array for each component, */
  162529. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162530. int ci;
  162531. jpeg_component_info *compptr;
  162532. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162533. ci++, compptr++) {
  162534. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162535. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162536. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162537. (long) compptr->h_samp_factor),
  162538. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162539. (long) compptr->v_samp_factor),
  162540. (JDIMENSION) compptr->v_samp_factor);
  162541. }
  162542. #else
  162543. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162544. #endif
  162545. } else {
  162546. /* We only need a single-MCU buffer. */
  162547. JBLOCKROW buffer;
  162548. int i;
  162549. buffer = (JBLOCKROW)
  162550. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162551. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162552. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162553. coef->MCU_buffer[i] = buffer + i;
  162554. }
  162555. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162556. }
  162557. }
  162558. /*** End of inlined file: jccoefct.c ***/
  162559. /*** Start of inlined file: jccolor.c ***/
  162560. #define JPEG_INTERNALS
  162561. /* Private subobject */
  162562. typedef struct {
  162563. struct jpeg_color_converter pub; /* public fields */
  162564. /* Private state for RGB->YCC conversion */
  162565. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162566. } my_color_converter;
  162567. typedef my_color_converter * my_cconvert_ptr;
  162568. /**************** RGB -> YCbCr conversion: most common case **************/
  162569. /*
  162570. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162571. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162572. * The conversion equations to be implemented are therefore
  162573. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162574. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162575. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162576. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162577. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162578. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162579. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162580. * were not represented exactly. Now we sacrifice exact representation of
  162581. * maximum red and maximum blue in order to get exact grayscales.
  162582. *
  162583. * To avoid floating-point arithmetic, we represent the fractional constants
  162584. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162585. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162586. *
  162587. * For even more speed, we avoid doing any multiplications in the inner loop
  162588. * by precalculating the constants times R,G,B for all possible values.
  162589. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162590. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162591. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162592. * colorspace anyway.
  162593. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162594. * in the tables to save adding them separately in the inner loop.
  162595. */
  162596. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162597. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162598. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162599. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162600. /* We allocate one big table and divide it up into eight parts, instead of
  162601. * doing eight alloc_small requests. This lets us use a single table base
  162602. * address, which can be held in a register in the inner loops on many
  162603. * machines (more than can hold all eight addresses, anyway).
  162604. */
  162605. #define R_Y_OFF 0 /* offset to R => Y section */
  162606. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162607. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162608. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162609. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162610. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162611. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162612. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162613. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162614. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162615. /*
  162616. * Initialize for RGB->YCC colorspace conversion.
  162617. */
  162618. METHODDEF(void)
  162619. rgb_ycc_start (j_compress_ptr cinfo)
  162620. {
  162621. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162622. INT32 * rgb_ycc_tab;
  162623. INT32 i;
  162624. /* Allocate and fill in the conversion tables. */
  162625. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162626. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162627. (TABLE_SIZE * SIZEOF(INT32)));
  162628. for (i = 0; i <= MAXJSAMPLE; i++) {
  162629. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162630. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162631. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162632. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162633. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162634. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162635. * This ensures that the maximum output will round to MAXJSAMPLE
  162636. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162637. */
  162638. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162639. /* B=>Cb and R=>Cr tables are the same
  162640. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162641. */
  162642. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162643. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162644. }
  162645. }
  162646. /*
  162647. * Convert some rows of samples to the JPEG colorspace.
  162648. *
  162649. * Note that we change from the application's interleaved-pixel format
  162650. * to our internal noninterleaved, one-plane-per-component format.
  162651. * The input buffer is therefore three times as wide as the output buffer.
  162652. *
  162653. * A starting row offset is provided only for the output buffer. The caller
  162654. * can easily adjust the passed input_buf value to accommodate any row
  162655. * offset required on that side.
  162656. */
  162657. METHODDEF(void)
  162658. rgb_ycc_convert (j_compress_ptr cinfo,
  162659. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162660. JDIMENSION output_row, int num_rows)
  162661. {
  162662. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162663. register int r, g, b;
  162664. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162665. register JSAMPROW inptr;
  162666. register JSAMPROW outptr0, outptr1, outptr2;
  162667. register JDIMENSION col;
  162668. JDIMENSION num_cols = cinfo->image_width;
  162669. while (--num_rows >= 0) {
  162670. inptr = *input_buf++;
  162671. outptr0 = output_buf[0][output_row];
  162672. outptr1 = output_buf[1][output_row];
  162673. outptr2 = output_buf[2][output_row];
  162674. output_row++;
  162675. for (col = 0; col < num_cols; col++) {
  162676. r = GETJSAMPLE(inptr[RGB_RED]);
  162677. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162678. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162679. inptr += RGB_PIXELSIZE;
  162680. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162681. * must be too; we do not need an explicit range-limiting operation.
  162682. * Hence the value being shifted is never negative, and we don't
  162683. * need the general RIGHT_SHIFT macro.
  162684. */
  162685. /* Y */
  162686. outptr0[col] = (JSAMPLE)
  162687. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162688. >> SCALEBITS);
  162689. /* Cb */
  162690. outptr1[col] = (JSAMPLE)
  162691. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162692. >> SCALEBITS);
  162693. /* Cr */
  162694. outptr2[col] = (JSAMPLE)
  162695. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162696. >> SCALEBITS);
  162697. }
  162698. }
  162699. }
  162700. /**************** Cases other than RGB -> YCbCr **************/
  162701. /*
  162702. * Convert some rows of samples to the JPEG colorspace.
  162703. * This version handles RGB->grayscale conversion, which is the same
  162704. * as the RGB->Y portion of RGB->YCbCr.
  162705. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162706. */
  162707. METHODDEF(void)
  162708. rgb_gray_convert (j_compress_ptr cinfo,
  162709. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162710. JDIMENSION output_row, int num_rows)
  162711. {
  162712. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162713. register int r, g, b;
  162714. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162715. register JSAMPROW inptr;
  162716. register JSAMPROW outptr;
  162717. register JDIMENSION col;
  162718. JDIMENSION num_cols = cinfo->image_width;
  162719. while (--num_rows >= 0) {
  162720. inptr = *input_buf++;
  162721. outptr = output_buf[0][output_row];
  162722. output_row++;
  162723. for (col = 0; col < num_cols; col++) {
  162724. r = GETJSAMPLE(inptr[RGB_RED]);
  162725. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162726. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162727. inptr += RGB_PIXELSIZE;
  162728. /* Y */
  162729. outptr[col] = (JSAMPLE)
  162730. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162731. >> SCALEBITS);
  162732. }
  162733. }
  162734. }
  162735. /*
  162736. * Convert some rows of samples to the JPEG colorspace.
  162737. * This version handles Adobe-style CMYK->YCCK conversion,
  162738. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162739. * conversion as above, while passing K (black) unchanged.
  162740. * We assume rgb_ycc_start has been called.
  162741. */
  162742. METHODDEF(void)
  162743. cmyk_ycck_convert (j_compress_ptr cinfo,
  162744. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162745. JDIMENSION output_row, int num_rows)
  162746. {
  162747. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162748. register int r, g, b;
  162749. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162750. register JSAMPROW inptr;
  162751. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162752. register JDIMENSION col;
  162753. JDIMENSION num_cols = cinfo->image_width;
  162754. while (--num_rows >= 0) {
  162755. inptr = *input_buf++;
  162756. outptr0 = output_buf[0][output_row];
  162757. outptr1 = output_buf[1][output_row];
  162758. outptr2 = output_buf[2][output_row];
  162759. outptr3 = output_buf[3][output_row];
  162760. output_row++;
  162761. for (col = 0; col < num_cols; col++) {
  162762. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162763. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162764. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162765. /* K passes through as-is */
  162766. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162767. inptr += 4;
  162768. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162769. * must be too; we do not need an explicit range-limiting operation.
  162770. * Hence the value being shifted is never negative, and we don't
  162771. * need the general RIGHT_SHIFT macro.
  162772. */
  162773. /* Y */
  162774. outptr0[col] = (JSAMPLE)
  162775. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162776. >> SCALEBITS);
  162777. /* Cb */
  162778. outptr1[col] = (JSAMPLE)
  162779. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162780. >> SCALEBITS);
  162781. /* Cr */
  162782. outptr2[col] = (JSAMPLE)
  162783. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162784. >> SCALEBITS);
  162785. }
  162786. }
  162787. }
  162788. /*
  162789. * Convert some rows of samples to the JPEG colorspace.
  162790. * This version handles grayscale output with no conversion.
  162791. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162792. */
  162793. METHODDEF(void)
  162794. grayscale_convert (j_compress_ptr cinfo,
  162795. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162796. JDIMENSION output_row, int num_rows)
  162797. {
  162798. register JSAMPROW inptr;
  162799. register JSAMPROW outptr;
  162800. register JDIMENSION col;
  162801. JDIMENSION num_cols = cinfo->image_width;
  162802. int instride = cinfo->input_components;
  162803. while (--num_rows >= 0) {
  162804. inptr = *input_buf++;
  162805. outptr = output_buf[0][output_row];
  162806. output_row++;
  162807. for (col = 0; col < num_cols; col++) {
  162808. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162809. inptr += instride;
  162810. }
  162811. }
  162812. }
  162813. /*
  162814. * Convert some rows of samples to the JPEG colorspace.
  162815. * This version handles multi-component colorspaces without conversion.
  162816. * We assume input_components == num_components.
  162817. */
  162818. METHODDEF(void)
  162819. null_convert (j_compress_ptr cinfo,
  162820. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162821. JDIMENSION output_row, int num_rows)
  162822. {
  162823. register JSAMPROW inptr;
  162824. register JSAMPROW outptr;
  162825. register JDIMENSION col;
  162826. register int ci;
  162827. int nc = cinfo->num_components;
  162828. JDIMENSION num_cols = cinfo->image_width;
  162829. while (--num_rows >= 0) {
  162830. /* It seems fastest to make a separate pass for each component. */
  162831. for (ci = 0; ci < nc; ci++) {
  162832. inptr = *input_buf;
  162833. outptr = output_buf[ci][output_row];
  162834. for (col = 0; col < num_cols; col++) {
  162835. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162836. inptr += nc;
  162837. }
  162838. }
  162839. input_buf++;
  162840. output_row++;
  162841. }
  162842. }
  162843. /*
  162844. * Empty method for start_pass.
  162845. */
  162846. METHODDEF(void)
  162847. null_method (j_compress_ptr)
  162848. {
  162849. /* no work needed */
  162850. }
  162851. /*
  162852. * Module initialization routine for input colorspace conversion.
  162853. */
  162854. GLOBAL(void)
  162855. jinit_color_converter (j_compress_ptr cinfo)
  162856. {
  162857. my_cconvert_ptr cconvert;
  162858. cconvert = (my_cconvert_ptr)
  162859. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162860. SIZEOF(my_color_converter));
  162861. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162862. /* set start_pass to null method until we find out differently */
  162863. cconvert->pub.start_pass = null_method;
  162864. /* Make sure input_components agrees with in_color_space */
  162865. switch (cinfo->in_color_space) {
  162866. case JCS_GRAYSCALE:
  162867. if (cinfo->input_components != 1)
  162868. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162869. break;
  162870. case JCS_RGB:
  162871. #if RGB_PIXELSIZE != 3
  162872. if (cinfo->input_components != RGB_PIXELSIZE)
  162873. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162874. break;
  162875. #endif /* else share code with YCbCr */
  162876. case JCS_YCbCr:
  162877. if (cinfo->input_components != 3)
  162878. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162879. break;
  162880. case JCS_CMYK:
  162881. case JCS_YCCK:
  162882. if (cinfo->input_components != 4)
  162883. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162884. break;
  162885. default: /* JCS_UNKNOWN can be anything */
  162886. if (cinfo->input_components < 1)
  162887. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162888. break;
  162889. }
  162890. /* Check num_components, set conversion method based on requested space */
  162891. switch (cinfo->jpeg_color_space) {
  162892. case JCS_GRAYSCALE:
  162893. if (cinfo->num_components != 1)
  162894. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162895. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162896. cconvert->pub.color_convert = grayscale_convert;
  162897. else if (cinfo->in_color_space == JCS_RGB) {
  162898. cconvert->pub.start_pass = rgb_ycc_start;
  162899. cconvert->pub.color_convert = rgb_gray_convert;
  162900. } else if (cinfo->in_color_space == JCS_YCbCr)
  162901. cconvert->pub.color_convert = grayscale_convert;
  162902. else
  162903. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162904. break;
  162905. case JCS_RGB:
  162906. if (cinfo->num_components != 3)
  162907. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162908. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162909. cconvert->pub.color_convert = null_convert;
  162910. else
  162911. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162912. break;
  162913. case JCS_YCbCr:
  162914. if (cinfo->num_components != 3)
  162915. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162916. if (cinfo->in_color_space == JCS_RGB) {
  162917. cconvert->pub.start_pass = rgb_ycc_start;
  162918. cconvert->pub.color_convert = rgb_ycc_convert;
  162919. } else if (cinfo->in_color_space == JCS_YCbCr)
  162920. cconvert->pub.color_convert = null_convert;
  162921. else
  162922. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162923. break;
  162924. case JCS_CMYK:
  162925. if (cinfo->num_components != 4)
  162926. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162927. if (cinfo->in_color_space == JCS_CMYK)
  162928. cconvert->pub.color_convert = null_convert;
  162929. else
  162930. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162931. break;
  162932. case JCS_YCCK:
  162933. if (cinfo->num_components != 4)
  162934. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162935. if (cinfo->in_color_space == JCS_CMYK) {
  162936. cconvert->pub.start_pass = rgb_ycc_start;
  162937. cconvert->pub.color_convert = cmyk_ycck_convert;
  162938. } else if (cinfo->in_color_space == JCS_YCCK)
  162939. cconvert->pub.color_convert = null_convert;
  162940. else
  162941. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162942. break;
  162943. default: /* allow null conversion of JCS_UNKNOWN */
  162944. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162945. cinfo->num_components != cinfo->input_components)
  162946. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162947. cconvert->pub.color_convert = null_convert;
  162948. break;
  162949. }
  162950. }
  162951. /*** End of inlined file: jccolor.c ***/
  162952. #undef FIX
  162953. /*** Start of inlined file: jcdctmgr.c ***/
  162954. #define JPEG_INTERNALS
  162955. /*** Start of inlined file: jdct.h ***/
  162956. /*
  162957. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162958. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162959. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162960. * implementations use an array of type FAST_FLOAT, instead.)
  162961. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162962. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162963. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162964. * convention improves accuracy in integer implementations and saves some
  162965. * work in floating-point ones.
  162966. * Quantization of the output coefficients is done by jcdctmgr.c.
  162967. */
  162968. #ifndef __jdct_h__
  162969. #define __jdct_h__
  162970. #if BITS_IN_JSAMPLE == 8
  162971. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162972. #else
  162973. typedef INT32 DCTELEM; /* must have 32 bits */
  162974. #endif
  162975. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162976. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162977. /*
  162978. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162979. * to an output sample array. The routine must dequantize the input data as
  162980. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162981. * pointed to by compptr->dct_table. The output data is to be placed into the
  162982. * sample array starting at a specified column. (Any row offset needed will
  162983. * be applied to the array pointer before it is passed to the IDCT code.)
  162984. * Note that the number of samples emitted by the IDCT routine is
  162985. * DCT_scaled_size * DCT_scaled_size.
  162986. */
  162987. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162988. /*
  162989. * Each IDCT routine has its own ideas about the best dct_table element type.
  162990. */
  162991. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162992. #if BITS_IN_JSAMPLE == 8
  162993. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162994. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162995. #else
  162996. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162997. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162998. #endif
  162999. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  163000. /*
  163001. * Each IDCT routine is responsible for range-limiting its results and
  163002. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  163003. * be quite far out of range if the input data is corrupt, so a bulletproof
  163004. * range-limiting step is required. We use a mask-and-table-lookup method
  163005. * to do the combined operations quickly. See the comments with
  163006. * prepare_range_limit_table (in jdmaster.c) for more info.
  163007. */
  163008. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  163009. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  163010. /* Short forms of external names for systems with brain-damaged linkers. */
  163011. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163012. #define jpeg_fdct_islow jFDislow
  163013. #define jpeg_fdct_ifast jFDifast
  163014. #define jpeg_fdct_float jFDfloat
  163015. #define jpeg_idct_islow jRDislow
  163016. #define jpeg_idct_ifast jRDifast
  163017. #define jpeg_idct_float jRDfloat
  163018. #define jpeg_idct_4x4 jRD4x4
  163019. #define jpeg_idct_2x2 jRD2x2
  163020. #define jpeg_idct_1x1 jRD1x1
  163021. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163022. /* Extern declarations for the forward and inverse DCT routines. */
  163023. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  163024. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  163025. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  163026. EXTERN(void) jpeg_idct_islow
  163027. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163028. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163029. EXTERN(void) jpeg_idct_ifast
  163030. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163031. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163032. EXTERN(void) jpeg_idct_float
  163033. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163034. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163035. EXTERN(void) jpeg_idct_4x4
  163036. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163037. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163038. EXTERN(void) jpeg_idct_2x2
  163039. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163040. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163041. EXTERN(void) jpeg_idct_1x1
  163042. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163043. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163044. /*
  163045. * Macros for handling fixed-point arithmetic; these are used by many
  163046. * but not all of the DCT/IDCT modules.
  163047. *
  163048. * All values are expected to be of type INT32.
  163049. * Fractional constants are scaled left by CONST_BITS bits.
  163050. * CONST_BITS is defined within each module using these macros,
  163051. * and may differ from one module to the next.
  163052. */
  163053. #define ONE ((INT32) 1)
  163054. #define CONST_SCALE (ONE << CONST_BITS)
  163055. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  163056. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  163057. * thus causing a lot of useless floating-point operations at run time.
  163058. */
  163059. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  163060. /* Descale and correctly round an INT32 value that's scaled by N bits.
  163061. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  163062. * the fudge factor is correct for either sign of X.
  163063. */
  163064. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  163065. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  163066. * This macro is used only when the two inputs will actually be no more than
  163067. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  163068. * full 32x32 multiply. This provides a useful speedup on many machines.
  163069. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  163070. * in C, but some C compilers will do the right thing if you provide the
  163071. * correct combination of casts.
  163072. */
  163073. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163074. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  163075. #endif
  163076. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  163077. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  163078. #endif
  163079. #ifndef MULTIPLY16C16 /* default definition */
  163080. #define MULTIPLY16C16(var,const) ((var) * (const))
  163081. #endif
  163082. /* Same except both inputs are variables. */
  163083. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163084. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  163085. #endif
  163086. #ifndef MULTIPLY16V16 /* default definition */
  163087. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  163088. #endif
  163089. #endif
  163090. /*** End of inlined file: jdct.h ***/
  163091. /* Private declarations for DCT subsystem */
  163092. /* Private subobject for this module */
  163093. typedef struct {
  163094. struct jpeg_forward_dct pub; /* public fields */
  163095. /* Pointer to the DCT routine actually in use */
  163096. forward_DCT_method_ptr do_dct;
  163097. /* The actual post-DCT divisors --- not identical to the quant table
  163098. * entries, because of scaling (especially for an unnormalized DCT).
  163099. * Each table is given in normal array order.
  163100. */
  163101. DCTELEM * divisors[NUM_QUANT_TBLS];
  163102. #ifdef DCT_FLOAT_SUPPORTED
  163103. /* Same as above for the floating-point case. */
  163104. float_DCT_method_ptr do_float_dct;
  163105. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  163106. #endif
  163107. } my_fdct_controller;
  163108. typedef my_fdct_controller * my_fdct_ptr;
  163109. /*
  163110. * Initialize for a processing pass.
  163111. * Verify that all referenced Q-tables are present, and set up
  163112. * the divisor table for each one.
  163113. * In the current implementation, DCT of all components is done during
  163114. * the first pass, even if only some components will be output in the
  163115. * first scan. Hence all components should be examined here.
  163116. */
  163117. METHODDEF(void)
  163118. start_pass_fdctmgr (j_compress_ptr cinfo)
  163119. {
  163120. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163121. int ci, qtblno, i;
  163122. jpeg_component_info *compptr;
  163123. JQUANT_TBL * qtbl;
  163124. DCTELEM * dtbl;
  163125. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163126. ci++, compptr++) {
  163127. qtblno = compptr->quant_tbl_no;
  163128. /* Make sure specified quantization table is present */
  163129. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163130. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163131. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163132. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163133. /* Compute divisors for this quant table */
  163134. /* We may do this more than once for same table, but it's not a big deal */
  163135. switch (cinfo->dct_method) {
  163136. #ifdef DCT_ISLOW_SUPPORTED
  163137. case JDCT_ISLOW:
  163138. /* For LL&M IDCT method, divisors are equal to raw quantization
  163139. * coefficients multiplied by 8 (to counteract scaling).
  163140. */
  163141. if (fdct->divisors[qtblno] == NULL) {
  163142. fdct->divisors[qtblno] = (DCTELEM *)
  163143. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163144. DCTSIZE2 * SIZEOF(DCTELEM));
  163145. }
  163146. dtbl = fdct->divisors[qtblno];
  163147. for (i = 0; i < DCTSIZE2; i++) {
  163148. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163149. }
  163150. break;
  163151. #endif
  163152. #ifdef DCT_IFAST_SUPPORTED
  163153. case JDCT_IFAST:
  163154. {
  163155. /* For AA&N IDCT method, divisors are equal to quantization
  163156. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163157. * scalefactor[0] = 1
  163158. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163159. * We apply a further scale factor of 8.
  163160. */
  163161. #define CONST_BITS 14
  163162. static const INT16 aanscales[DCTSIZE2] = {
  163163. /* precomputed values scaled up by 14 bits */
  163164. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163165. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163166. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163167. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163168. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163169. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163170. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163171. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163172. };
  163173. SHIFT_TEMPS
  163174. if (fdct->divisors[qtblno] == NULL) {
  163175. fdct->divisors[qtblno] = (DCTELEM *)
  163176. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163177. DCTSIZE2 * SIZEOF(DCTELEM));
  163178. }
  163179. dtbl = fdct->divisors[qtblno];
  163180. for (i = 0; i < DCTSIZE2; i++) {
  163181. dtbl[i] = (DCTELEM)
  163182. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163183. (INT32) aanscales[i]),
  163184. CONST_BITS-3);
  163185. }
  163186. }
  163187. break;
  163188. #endif
  163189. #ifdef DCT_FLOAT_SUPPORTED
  163190. case JDCT_FLOAT:
  163191. {
  163192. /* For float AA&N IDCT method, divisors are equal to quantization
  163193. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163194. * scalefactor[0] = 1
  163195. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163196. * We apply a further scale factor of 8.
  163197. * What's actually stored is 1/divisor so that the inner loop can
  163198. * use a multiplication rather than a division.
  163199. */
  163200. FAST_FLOAT * fdtbl;
  163201. int row, col;
  163202. static const double aanscalefactor[DCTSIZE] = {
  163203. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163204. 1.0, 0.785694958, 0.541196100, 0.275899379
  163205. };
  163206. if (fdct->float_divisors[qtblno] == NULL) {
  163207. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163208. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163209. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163210. }
  163211. fdtbl = fdct->float_divisors[qtblno];
  163212. i = 0;
  163213. for (row = 0; row < DCTSIZE; row++) {
  163214. for (col = 0; col < DCTSIZE; col++) {
  163215. fdtbl[i] = (FAST_FLOAT)
  163216. (1.0 / (((double) qtbl->quantval[i] *
  163217. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163218. i++;
  163219. }
  163220. }
  163221. }
  163222. break;
  163223. #endif
  163224. default:
  163225. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163226. break;
  163227. }
  163228. }
  163229. }
  163230. /*
  163231. * Perform forward DCT on one or more blocks of a component.
  163232. *
  163233. * The input samples are taken from the sample_data[] array starting at
  163234. * position start_row/start_col, and moving to the right for any additional
  163235. * blocks. The quantized coefficients are returned in coef_blocks[].
  163236. */
  163237. METHODDEF(void)
  163238. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163239. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163240. JDIMENSION start_row, JDIMENSION start_col,
  163241. JDIMENSION num_blocks)
  163242. /* This version is used for integer DCT implementations. */
  163243. {
  163244. /* This routine is heavily used, so it's worth coding it tightly. */
  163245. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163246. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163247. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163248. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163249. JDIMENSION bi;
  163250. sample_data += start_row; /* fold in the vertical offset once */
  163251. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163252. /* Load data into workspace, applying unsigned->signed conversion */
  163253. { register DCTELEM *workspaceptr;
  163254. register JSAMPROW elemptr;
  163255. register int elemr;
  163256. workspaceptr = workspace;
  163257. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163258. elemptr = sample_data[elemr] + start_col;
  163259. #if DCTSIZE == 8 /* unroll the inner loop */
  163260. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163261. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163262. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163263. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163264. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163265. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163266. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163267. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163268. #else
  163269. { register int elemc;
  163270. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163271. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163272. }
  163273. }
  163274. #endif
  163275. }
  163276. }
  163277. /* Perform the DCT */
  163278. (*do_dct) (workspace);
  163279. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163280. { register DCTELEM temp, qval;
  163281. register int i;
  163282. register JCOEFPTR output_ptr = coef_blocks[bi];
  163283. for (i = 0; i < DCTSIZE2; i++) {
  163284. qval = divisors[i];
  163285. temp = workspace[i];
  163286. /* Divide the coefficient value by qval, ensuring proper rounding.
  163287. * Since C does not specify the direction of rounding for negative
  163288. * quotients, we have to force the dividend positive for portability.
  163289. *
  163290. * In most files, at least half of the output values will be zero
  163291. * (at default quantization settings, more like three-quarters...)
  163292. * so we should ensure that this case is fast. On many machines,
  163293. * a comparison is enough cheaper than a divide to make a special test
  163294. * a win. Since both inputs will be nonnegative, we need only test
  163295. * for a < b to discover whether a/b is 0.
  163296. * If your machine's division is fast enough, define FAST_DIVIDE.
  163297. */
  163298. #ifdef FAST_DIVIDE
  163299. #define DIVIDE_BY(a,b) a /= b
  163300. #else
  163301. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163302. #endif
  163303. if (temp < 0) {
  163304. temp = -temp;
  163305. temp += qval>>1; /* for rounding */
  163306. DIVIDE_BY(temp, qval);
  163307. temp = -temp;
  163308. } else {
  163309. temp += qval>>1; /* for rounding */
  163310. DIVIDE_BY(temp, qval);
  163311. }
  163312. output_ptr[i] = (JCOEF) temp;
  163313. }
  163314. }
  163315. }
  163316. }
  163317. #ifdef DCT_FLOAT_SUPPORTED
  163318. METHODDEF(void)
  163319. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163320. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163321. JDIMENSION start_row, JDIMENSION start_col,
  163322. JDIMENSION num_blocks)
  163323. /* This version is used for floating-point DCT implementations. */
  163324. {
  163325. /* This routine is heavily used, so it's worth coding it tightly. */
  163326. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163327. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163328. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163329. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163330. JDIMENSION bi;
  163331. sample_data += start_row; /* fold in the vertical offset once */
  163332. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163333. /* Load data into workspace, applying unsigned->signed conversion */
  163334. { register FAST_FLOAT *workspaceptr;
  163335. register JSAMPROW elemptr;
  163336. register int elemr;
  163337. workspaceptr = workspace;
  163338. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163339. elemptr = sample_data[elemr] + start_col;
  163340. #if DCTSIZE == 8 /* unroll the inner loop */
  163341. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163342. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163343. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163344. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163345. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163346. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163347. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163348. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163349. #else
  163350. { register int elemc;
  163351. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163352. *workspaceptr++ = (FAST_FLOAT)
  163353. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163354. }
  163355. }
  163356. #endif
  163357. }
  163358. }
  163359. /* Perform the DCT */
  163360. (*do_dct) (workspace);
  163361. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163362. { register FAST_FLOAT temp;
  163363. register int i;
  163364. register JCOEFPTR output_ptr = coef_blocks[bi];
  163365. for (i = 0; i < DCTSIZE2; i++) {
  163366. /* Apply the quantization and scaling factor */
  163367. temp = workspace[i] * divisors[i];
  163368. /* Round to nearest integer.
  163369. * Since C does not specify the direction of rounding for negative
  163370. * quotients, we have to force the dividend positive for portability.
  163371. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163372. * code should work for either 16-bit or 32-bit ints.
  163373. */
  163374. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163375. }
  163376. }
  163377. }
  163378. }
  163379. #endif /* DCT_FLOAT_SUPPORTED */
  163380. /*
  163381. * Initialize FDCT manager.
  163382. */
  163383. GLOBAL(void)
  163384. jinit_forward_dct (j_compress_ptr cinfo)
  163385. {
  163386. my_fdct_ptr fdct;
  163387. int i;
  163388. fdct = (my_fdct_ptr)
  163389. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163390. SIZEOF(my_fdct_controller));
  163391. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163392. fdct->pub.start_pass = start_pass_fdctmgr;
  163393. switch (cinfo->dct_method) {
  163394. #ifdef DCT_ISLOW_SUPPORTED
  163395. case JDCT_ISLOW:
  163396. fdct->pub.forward_DCT = forward_DCT;
  163397. fdct->do_dct = jpeg_fdct_islow;
  163398. break;
  163399. #endif
  163400. #ifdef DCT_IFAST_SUPPORTED
  163401. case JDCT_IFAST:
  163402. fdct->pub.forward_DCT = forward_DCT;
  163403. fdct->do_dct = jpeg_fdct_ifast;
  163404. break;
  163405. #endif
  163406. #ifdef DCT_FLOAT_SUPPORTED
  163407. case JDCT_FLOAT:
  163408. fdct->pub.forward_DCT = forward_DCT_float;
  163409. fdct->do_float_dct = jpeg_fdct_float;
  163410. break;
  163411. #endif
  163412. default:
  163413. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163414. break;
  163415. }
  163416. /* Mark divisor tables unallocated */
  163417. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163418. fdct->divisors[i] = NULL;
  163419. #ifdef DCT_FLOAT_SUPPORTED
  163420. fdct->float_divisors[i] = NULL;
  163421. #endif
  163422. }
  163423. }
  163424. /*** End of inlined file: jcdctmgr.c ***/
  163425. #undef CONST_BITS
  163426. /*** Start of inlined file: jchuff.c ***/
  163427. #define JPEG_INTERNALS
  163428. /*** Start of inlined file: jchuff.h ***/
  163429. /* The legal range of a DCT coefficient is
  163430. * -1024 .. +1023 for 8-bit data;
  163431. * -16384 .. +16383 for 12-bit data.
  163432. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163433. */
  163434. #ifndef _jchuff_h_
  163435. #define _jchuff_h_
  163436. #if BITS_IN_JSAMPLE == 8
  163437. #define MAX_COEF_BITS 10
  163438. #else
  163439. #define MAX_COEF_BITS 14
  163440. #endif
  163441. /* Derived data constructed for each Huffman table */
  163442. typedef struct {
  163443. unsigned int ehufco[256]; /* code for each symbol */
  163444. char ehufsi[256]; /* length of code for each symbol */
  163445. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163446. } c_derived_tbl;
  163447. /* Short forms of external names for systems with brain-damaged linkers. */
  163448. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163449. #define jpeg_make_c_derived_tbl jMkCDerived
  163450. #define jpeg_gen_optimal_table jGenOptTbl
  163451. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163452. /* Expand a Huffman table definition into the derived format */
  163453. EXTERN(void) jpeg_make_c_derived_tbl
  163454. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163455. c_derived_tbl ** pdtbl));
  163456. /* Generate an optimal table definition given the specified counts */
  163457. EXTERN(void) jpeg_gen_optimal_table
  163458. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163459. #endif
  163460. /*** End of inlined file: jchuff.h ***/
  163461. /* Declarations shared with jcphuff.c */
  163462. /* Expanded entropy encoder object for Huffman encoding.
  163463. *
  163464. * The savable_state subrecord contains fields that change within an MCU,
  163465. * but must not be updated permanently until we complete the MCU.
  163466. */
  163467. typedef struct {
  163468. INT32 put_buffer; /* current bit-accumulation buffer */
  163469. int put_bits; /* # of bits now in it */
  163470. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163471. } savable_state;
  163472. /* This macro is to work around compilers with missing or broken
  163473. * structure assignment. You'll need to fix this code if you have
  163474. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163475. */
  163476. #ifndef NO_STRUCT_ASSIGN
  163477. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163478. #else
  163479. #if MAX_COMPS_IN_SCAN == 4
  163480. #define ASSIGN_STATE(dest,src) \
  163481. ((dest).put_buffer = (src).put_buffer, \
  163482. (dest).put_bits = (src).put_bits, \
  163483. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163484. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163485. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163486. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163487. #endif
  163488. #endif
  163489. typedef struct {
  163490. struct jpeg_entropy_encoder pub; /* public fields */
  163491. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163492. /* These fields are NOT loaded into local working state. */
  163493. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163494. int next_restart_num; /* next restart number to write (0-7) */
  163495. /* Pointers to derived tables (these workspaces have image lifespan) */
  163496. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163497. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163498. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163499. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163500. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163501. #endif
  163502. } huff_entropy_encoder;
  163503. typedef huff_entropy_encoder * huff_entropy_ptr;
  163504. /* Working state while writing an MCU.
  163505. * This struct contains all the fields that are needed by subroutines.
  163506. */
  163507. typedef struct {
  163508. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163509. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163510. savable_state cur; /* Current bit buffer & DC state */
  163511. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163512. } working_state;
  163513. /* Forward declarations */
  163514. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163515. JBLOCKROW *MCU_data));
  163516. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163517. #ifdef ENTROPY_OPT_SUPPORTED
  163518. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163519. JBLOCKROW *MCU_data));
  163520. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163521. #endif
  163522. /*
  163523. * Initialize for a Huffman-compressed scan.
  163524. * If gather_statistics is TRUE, we do not output anything during the scan,
  163525. * just count the Huffman symbols used and generate Huffman code tables.
  163526. */
  163527. METHODDEF(void)
  163528. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163529. {
  163530. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163531. int ci, dctbl, actbl;
  163532. jpeg_component_info * compptr;
  163533. if (gather_statistics) {
  163534. #ifdef ENTROPY_OPT_SUPPORTED
  163535. entropy->pub.encode_mcu = encode_mcu_gather;
  163536. entropy->pub.finish_pass = finish_pass_gather;
  163537. #else
  163538. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163539. #endif
  163540. } else {
  163541. entropy->pub.encode_mcu = encode_mcu_huff;
  163542. entropy->pub.finish_pass = finish_pass_huff;
  163543. }
  163544. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163545. compptr = cinfo->cur_comp_info[ci];
  163546. dctbl = compptr->dc_tbl_no;
  163547. actbl = compptr->ac_tbl_no;
  163548. if (gather_statistics) {
  163549. #ifdef ENTROPY_OPT_SUPPORTED
  163550. /* Check for invalid table indexes */
  163551. /* (make_c_derived_tbl does this in the other path) */
  163552. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163553. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163554. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163555. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163556. /* Allocate and zero the statistics tables */
  163557. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163558. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163559. entropy->dc_count_ptrs[dctbl] = (long *)
  163560. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163561. 257 * SIZEOF(long));
  163562. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163563. if (entropy->ac_count_ptrs[actbl] == NULL)
  163564. entropy->ac_count_ptrs[actbl] = (long *)
  163565. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163566. 257 * SIZEOF(long));
  163567. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163568. #endif
  163569. } else {
  163570. /* Compute derived values for Huffman tables */
  163571. /* We may do this more than once for a table, but it's not expensive */
  163572. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163573. & entropy->dc_derived_tbls[dctbl]);
  163574. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163575. & entropy->ac_derived_tbls[actbl]);
  163576. }
  163577. /* Initialize DC predictions to 0 */
  163578. entropy->saved.last_dc_val[ci] = 0;
  163579. }
  163580. /* Initialize bit buffer to empty */
  163581. entropy->saved.put_buffer = 0;
  163582. entropy->saved.put_bits = 0;
  163583. /* Initialize restart stuff */
  163584. entropy->restarts_to_go = cinfo->restart_interval;
  163585. entropy->next_restart_num = 0;
  163586. }
  163587. /*
  163588. * Compute the derived values for a Huffman table.
  163589. * This routine also performs some validation checks on the table.
  163590. *
  163591. * Note this is also used by jcphuff.c.
  163592. */
  163593. GLOBAL(void)
  163594. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163595. c_derived_tbl ** pdtbl)
  163596. {
  163597. JHUFF_TBL *htbl;
  163598. c_derived_tbl *dtbl;
  163599. int p, i, l, lastp, si, maxsymbol;
  163600. char huffsize[257];
  163601. unsigned int huffcode[257];
  163602. unsigned int code;
  163603. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163604. * paralleling the order of the symbols themselves in htbl->huffval[].
  163605. */
  163606. /* Find the input Huffman table */
  163607. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163608. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163609. htbl =
  163610. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163611. if (htbl == NULL)
  163612. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163613. /* Allocate a workspace if we haven't already done so. */
  163614. if (*pdtbl == NULL)
  163615. *pdtbl = (c_derived_tbl *)
  163616. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163617. SIZEOF(c_derived_tbl));
  163618. dtbl = *pdtbl;
  163619. /* Figure C.1: make table of Huffman code length for each symbol */
  163620. p = 0;
  163621. for (l = 1; l <= 16; l++) {
  163622. i = (int) htbl->bits[l];
  163623. if (i < 0 || p + i > 256) /* protect against table overrun */
  163624. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163625. while (i--)
  163626. huffsize[p++] = (char) l;
  163627. }
  163628. huffsize[p] = 0;
  163629. lastp = p;
  163630. /* Figure C.2: generate the codes themselves */
  163631. /* We also validate that the counts represent a legal Huffman code tree. */
  163632. code = 0;
  163633. si = huffsize[0];
  163634. p = 0;
  163635. while (huffsize[p]) {
  163636. while (((int) huffsize[p]) == si) {
  163637. huffcode[p++] = code;
  163638. code++;
  163639. }
  163640. /* code is now 1 more than the last code used for codelength si; but
  163641. * it must still fit in si bits, since no code is allowed to be all ones.
  163642. */
  163643. if (((INT32) code) >= (((INT32) 1) << si))
  163644. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163645. code <<= 1;
  163646. si++;
  163647. }
  163648. /* Figure C.3: generate encoding tables */
  163649. /* These are code and size indexed by symbol value */
  163650. /* Set all codeless symbols to have code length 0;
  163651. * this lets us detect duplicate VAL entries here, and later
  163652. * allows emit_bits to detect any attempt to emit such symbols.
  163653. */
  163654. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163655. /* This is also a convenient place to check for out-of-range
  163656. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163657. * but only 0..15 for DC. (We could constrain them further
  163658. * based on data depth and mode, but this seems enough.)
  163659. */
  163660. maxsymbol = isDC ? 15 : 255;
  163661. for (p = 0; p < lastp; p++) {
  163662. i = htbl->huffval[p];
  163663. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163664. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163665. dtbl->ehufco[i] = huffcode[p];
  163666. dtbl->ehufsi[i] = huffsize[p];
  163667. }
  163668. }
  163669. /* Outputting bytes to the file */
  163670. /* Emit a byte, taking 'action' if must suspend. */
  163671. #define emit_byte(state,val,action) \
  163672. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163673. if (--(state)->free_in_buffer == 0) \
  163674. if (! dump_buffer(state)) \
  163675. { action; } }
  163676. LOCAL(boolean)
  163677. dump_buffer (working_state * state)
  163678. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163679. {
  163680. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163681. if (! (*dest->empty_output_buffer) (state->cinfo))
  163682. return FALSE;
  163683. /* After a successful buffer dump, must reset buffer pointers */
  163684. state->next_output_byte = dest->next_output_byte;
  163685. state->free_in_buffer = dest->free_in_buffer;
  163686. return TRUE;
  163687. }
  163688. /* Outputting bits to the file */
  163689. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163690. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163691. * in one call, and we never retain more than 7 bits in put_buffer
  163692. * between calls, so 24 bits are sufficient.
  163693. */
  163694. INLINE
  163695. LOCAL(boolean)
  163696. emit_bits (working_state * state, unsigned int code, int size)
  163697. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163698. {
  163699. /* This routine is heavily used, so it's worth coding tightly. */
  163700. register INT32 put_buffer = (INT32) code;
  163701. register int put_bits = state->cur.put_bits;
  163702. /* if size is 0, caller used an invalid Huffman table entry */
  163703. if (size == 0)
  163704. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163705. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163706. put_bits += size; /* new number of bits in buffer */
  163707. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163708. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163709. while (put_bits >= 8) {
  163710. int c = (int) ((put_buffer >> 16) & 0xFF);
  163711. emit_byte(state, c, return FALSE);
  163712. if (c == 0xFF) { /* need to stuff a zero byte? */
  163713. emit_byte(state, 0, return FALSE);
  163714. }
  163715. put_buffer <<= 8;
  163716. put_bits -= 8;
  163717. }
  163718. state->cur.put_buffer = put_buffer; /* update state variables */
  163719. state->cur.put_bits = put_bits;
  163720. return TRUE;
  163721. }
  163722. LOCAL(boolean)
  163723. flush_bits (working_state * state)
  163724. {
  163725. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163726. return FALSE;
  163727. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163728. state->cur.put_bits = 0;
  163729. return TRUE;
  163730. }
  163731. /* Encode a single block's worth of coefficients */
  163732. LOCAL(boolean)
  163733. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163734. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163735. {
  163736. register int temp, temp2;
  163737. register int nbits;
  163738. register int k, r, i;
  163739. /* Encode the DC coefficient difference per section F.1.2.1 */
  163740. temp = temp2 = block[0] - last_dc_val;
  163741. if (temp < 0) {
  163742. temp = -temp; /* temp is abs value of input */
  163743. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163744. /* This code assumes we are on a two's complement machine */
  163745. temp2--;
  163746. }
  163747. /* Find the number of bits needed for the magnitude of the coefficient */
  163748. nbits = 0;
  163749. while (temp) {
  163750. nbits++;
  163751. temp >>= 1;
  163752. }
  163753. /* Check for out-of-range coefficient values.
  163754. * Since we're encoding a difference, the range limit is twice as much.
  163755. */
  163756. if (nbits > MAX_COEF_BITS+1)
  163757. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163758. /* Emit the Huffman-coded symbol for the number of bits */
  163759. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163760. return FALSE;
  163761. /* Emit that number of bits of the value, if positive, */
  163762. /* or the complement of its magnitude, if negative. */
  163763. if (nbits) /* emit_bits rejects calls with size 0 */
  163764. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163765. return FALSE;
  163766. /* Encode the AC coefficients per section F.1.2.2 */
  163767. r = 0; /* r = run length of zeros */
  163768. for (k = 1; k < DCTSIZE2; k++) {
  163769. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163770. r++;
  163771. } else {
  163772. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163773. while (r > 15) {
  163774. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163775. return FALSE;
  163776. r -= 16;
  163777. }
  163778. temp2 = temp;
  163779. if (temp < 0) {
  163780. temp = -temp; /* temp is abs value of input */
  163781. /* This code assumes we are on a two's complement machine */
  163782. temp2--;
  163783. }
  163784. /* Find the number of bits needed for the magnitude of the coefficient */
  163785. nbits = 1; /* there must be at least one 1 bit */
  163786. while ((temp >>= 1))
  163787. nbits++;
  163788. /* Check for out-of-range coefficient values */
  163789. if (nbits > MAX_COEF_BITS)
  163790. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163791. /* Emit Huffman symbol for run length / number of bits */
  163792. i = (r << 4) + nbits;
  163793. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163794. return FALSE;
  163795. /* Emit that number of bits of the value, if positive, */
  163796. /* or the complement of its magnitude, if negative. */
  163797. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163798. return FALSE;
  163799. r = 0;
  163800. }
  163801. }
  163802. /* If the last coef(s) were zero, emit an end-of-block code */
  163803. if (r > 0)
  163804. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163805. return FALSE;
  163806. return TRUE;
  163807. }
  163808. /*
  163809. * Emit a restart marker & resynchronize predictions.
  163810. */
  163811. LOCAL(boolean)
  163812. emit_restart (working_state * state, int restart_num)
  163813. {
  163814. int ci;
  163815. if (! flush_bits(state))
  163816. return FALSE;
  163817. emit_byte(state, 0xFF, return FALSE);
  163818. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163819. /* Re-initialize DC predictions to 0 */
  163820. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163821. state->cur.last_dc_val[ci] = 0;
  163822. /* The restart counter is not updated until we successfully write the MCU. */
  163823. return TRUE;
  163824. }
  163825. /*
  163826. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163827. */
  163828. METHODDEF(boolean)
  163829. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163830. {
  163831. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163832. working_state state;
  163833. int blkn, ci;
  163834. jpeg_component_info * compptr;
  163835. /* Load up working state */
  163836. state.next_output_byte = cinfo->dest->next_output_byte;
  163837. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163838. ASSIGN_STATE(state.cur, entropy->saved);
  163839. state.cinfo = cinfo;
  163840. /* Emit restart marker if needed */
  163841. if (cinfo->restart_interval) {
  163842. if (entropy->restarts_to_go == 0)
  163843. if (! emit_restart(&state, entropy->next_restart_num))
  163844. return FALSE;
  163845. }
  163846. /* Encode the MCU data blocks */
  163847. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163848. ci = cinfo->MCU_membership[blkn];
  163849. compptr = cinfo->cur_comp_info[ci];
  163850. if (! encode_one_block(&state,
  163851. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163852. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163853. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163854. return FALSE;
  163855. /* Update last_dc_val */
  163856. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163857. }
  163858. /* Completed MCU, so update state */
  163859. cinfo->dest->next_output_byte = state.next_output_byte;
  163860. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163861. ASSIGN_STATE(entropy->saved, state.cur);
  163862. /* Update restart-interval state too */
  163863. if (cinfo->restart_interval) {
  163864. if (entropy->restarts_to_go == 0) {
  163865. entropy->restarts_to_go = cinfo->restart_interval;
  163866. entropy->next_restart_num++;
  163867. entropy->next_restart_num &= 7;
  163868. }
  163869. entropy->restarts_to_go--;
  163870. }
  163871. return TRUE;
  163872. }
  163873. /*
  163874. * Finish up at the end of a Huffman-compressed scan.
  163875. */
  163876. METHODDEF(void)
  163877. finish_pass_huff (j_compress_ptr cinfo)
  163878. {
  163879. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163880. working_state state;
  163881. /* Load up working state ... flush_bits needs it */
  163882. state.next_output_byte = cinfo->dest->next_output_byte;
  163883. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163884. ASSIGN_STATE(state.cur, entropy->saved);
  163885. state.cinfo = cinfo;
  163886. /* Flush out the last data */
  163887. if (! flush_bits(&state))
  163888. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163889. /* Update state */
  163890. cinfo->dest->next_output_byte = state.next_output_byte;
  163891. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163892. ASSIGN_STATE(entropy->saved, state.cur);
  163893. }
  163894. /*
  163895. * Huffman coding optimization.
  163896. *
  163897. * We first scan the supplied data and count the number of uses of each symbol
  163898. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163899. * Then we build a Huffman coding tree for the observed counts.
  163900. * Symbols which are not needed at all for the particular image are not
  163901. * assigned any code, which saves space in the DHT marker as well as in
  163902. * the compressed data.
  163903. */
  163904. #ifdef ENTROPY_OPT_SUPPORTED
  163905. /* Process a single block's worth of coefficients */
  163906. LOCAL(void)
  163907. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163908. long dc_counts[], long ac_counts[])
  163909. {
  163910. register int temp;
  163911. register int nbits;
  163912. register int k, r;
  163913. /* Encode the DC coefficient difference per section F.1.2.1 */
  163914. temp = block[0] - last_dc_val;
  163915. if (temp < 0)
  163916. temp = -temp;
  163917. /* Find the number of bits needed for the magnitude of the coefficient */
  163918. nbits = 0;
  163919. while (temp) {
  163920. nbits++;
  163921. temp >>= 1;
  163922. }
  163923. /* Check for out-of-range coefficient values.
  163924. * Since we're encoding a difference, the range limit is twice as much.
  163925. */
  163926. if (nbits > MAX_COEF_BITS+1)
  163927. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163928. /* Count the Huffman symbol for the number of bits */
  163929. dc_counts[nbits]++;
  163930. /* Encode the AC coefficients per section F.1.2.2 */
  163931. r = 0; /* r = run length of zeros */
  163932. for (k = 1; k < DCTSIZE2; k++) {
  163933. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163934. r++;
  163935. } else {
  163936. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163937. while (r > 15) {
  163938. ac_counts[0xF0]++;
  163939. r -= 16;
  163940. }
  163941. /* Find the number of bits needed for the magnitude of the coefficient */
  163942. if (temp < 0)
  163943. temp = -temp;
  163944. /* Find the number of bits needed for the magnitude of the coefficient */
  163945. nbits = 1; /* there must be at least one 1 bit */
  163946. while ((temp >>= 1))
  163947. nbits++;
  163948. /* Check for out-of-range coefficient values */
  163949. if (nbits > MAX_COEF_BITS)
  163950. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163951. /* Count Huffman symbol for run length / number of bits */
  163952. ac_counts[(r << 4) + nbits]++;
  163953. r = 0;
  163954. }
  163955. }
  163956. /* If the last coef(s) were zero, emit an end-of-block code */
  163957. if (r > 0)
  163958. ac_counts[0]++;
  163959. }
  163960. /*
  163961. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163962. * No data is actually output, so no suspension return is possible.
  163963. */
  163964. METHODDEF(boolean)
  163965. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163966. {
  163967. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163968. int blkn, ci;
  163969. jpeg_component_info * compptr;
  163970. /* Take care of restart intervals if needed */
  163971. if (cinfo->restart_interval) {
  163972. if (entropy->restarts_to_go == 0) {
  163973. /* Re-initialize DC predictions to 0 */
  163974. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163975. entropy->saved.last_dc_val[ci] = 0;
  163976. /* Update restart state */
  163977. entropy->restarts_to_go = cinfo->restart_interval;
  163978. }
  163979. entropy->restarts_to_go--;
  163980. }
  163981. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163982. ci = cinfo->MCU_membership[blkn];
  163983. compptr = cinfo->cur_comp_info[ci];
  163984. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163985. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163986. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163987. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163988. }
  163989. return TRUE;
  163990. }
  163991. /*
  163992. * Generate the best Huffman code table for the given counts, fill htbl.
  163993. * Note this is also used by jcphuff.c.
  163994. *
  163995. * The JPEG standard requires that no symbol be assigned a codeword of all
  163996. * one bits (so that padding bits added at the end of a compressed segment
  163997. * can't look like a valid code). Because of the canonical ordering of
  163998. * codewords, this just means that there must be an unused slot in the
  163999. * longest codeword length category. Section K.2 of the JPEG spec suggests
  164000. * reserving such a slot by pretending that symbol 256 is a valid symbol
  164001. * with count 1. In theory that's not optimal; giving it count zero but
  164002. * including it in the symbol set anyway should give a better Huffman code.
  164003. * But the theoretically better code actually seems to come out worse in
  164004. * practice, because it produces more all-ones bytes (which incur stuffed
  164005. * zero bytes in the final file). In any case the difference is tiny.
  164006. *
  164007. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  164008. * If some symbols have a very small but nonzero probability, the Huffman tree
  164009. * must be adjusted to meet the code length restriction. We currently use
  164010. * the adjustment method suggested in JPEG section K.2. This method is *not*
  164011. * optimal; it may not choose the best possible limited-length code. But
  164012. * typically only very-low-frequency symbols will be given less-than-optimal
  164013. * lengths, so the code is almost optimal. Experimental comparisons against
  164014. * an optimal limited-length-code algorithm indicate that the difference is
  164015. * microscopic --- usually less than a hundredth of a percent of total size.
  164016. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  164017. */
  164018. GLOBAL(void)
  164019. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  164020. {
  164021. #define MAX_CLEN 32 /* assumed maximum initial code length */
  164022. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  164023. int codesize[257]; /* codesize[k] = code length of symbol k */
  164024. int others[257]; /* next symbol in current branch of tree */
  164025. int c1, c2;
  164026. int p, i, j;
  164027. long v;
  164028. /* This algorithm is explained in section K.2 of the JPEG standard */
  164029. MEMZERO(bits, SIZEOF(bits));
  164030. MEMZERO(codesize, SIZEOF(codesize));
  164031. for (i = 0; i < 257; i++)
  164032. others[i] = -1; /* init links to empty */
  164033. freq[256] = 1; /* make sure 256 has a nonzero count */
  164034. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  164035. * that no real symbol is given code-value of all ones, because 256
  164036. * will be placed last in the largest codeword category.
  164037. */
  164038. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  164039. for (;;) {
  164040. /* Find the smallest nonzero frequency, set c1 = its symbol */
  164041. /* In case of ties, take the larger symbol number */
  164042. c1 = -1;
  164043. v = 1000000000L;
  164044. for (i = 0; i <= 256; i++) {
  164045. if (freq[i] && freq[i] <= v) {
  164046. v = freq[i];
  164047. c1 = i;
  164048. }
  164049. }
  164050. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  164051. /* In case of ties, take the larger symbol number */
  164052. c2 = -1;
  164053. v = 1000000000L;
  164054. for (i = 0; i <= 256; i++) {
  164055. if (freq[i] && freq[i] <= v && i != c1) {
  164056. v = freq[i];
  164057. c2 = i;
  164058. }
  164059. }
  164060. /* Done if we've merged everything into one frequency */
  164061. if (c2 < 0)
  164062. break;
  164063. /* Else merge the two counts/trees */
  164064. freq[c1] += freq[c2];
  164065. freq[c2] = 0;
  164066. /* Increment the codesize of everything in c1's tree branch */
  164067. codesize[c1]++;
  164068. while (others[c1] >= 0) {
  164069. c1 = others[c1];
  164070. codesize[c1]++;
  164071. }
  164072. others[c1] = c2; /* chain c2 onto c1's tree branch */
  164073. /* Increment the codesize of everything in c2's tree branch */
  164074. codesize[c2]++;
  164075. while (others[c2] >= 0) {
  164076. c2 = others[c2];
  164077. codesize[c2]++;
  164078. }
  164079. }
  164080. /* Now count the number of symbols of each code length */
  164081. for (i = 0; i <= 256; i++) {
  164082. if (codesize[i]) {
  164083. /* The JPEG standard seems to think that this can't happen, */
  164084. /* but I'm paranoid... */
  164085. if (codesize[i] > MAX_CLEN)
  164086. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  164087. bits[codesize[i]]++;
  164088. }
  164089. }
  164090. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  164091. * Huffman procedure assigned any such lengths, we must adjust the coding.
  164092. * Here is what the JPEG spec says about how this next bit works:
  164093. * Since symbols are paired for the longest Huffman code, the symbols are
  164094. * removed from this length category two at a time. The prefix for the pair
  164095. * (which is one bit shorter) is allocated to one of the pair; then,
  164096. * skipping the BITS entry for that prefix length, a code word from the next
  164097. * shortest nonzero BITS entry is converted into a prefix for two code words
  164098. * one bit longer.
  164099. */
  164100. for (i = MAX_CLEN; i > 16; i--) {
  164101. while (bits[i] > 0) {
  164102. j = i - 2; /* find length of new prefix to be used */
  164103. while (bits[j] == 0)
  164104. j--;
  164105. bits[i] -= 2; /* remove two symbols */
  164106. bits[i-1]++; /* one goes in this length */
  164107. bits[j+1] += 2; /* two new symbols in this length */
  164108. bits[j]--; /* symbol of this length is now a prefix */
  164109. }
  164110. }
  164111. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  164112. while (bits[i] == 0) /* find largest codelength still in use */
  164113. i--;
  164114. bits[i]--;
  164115. /* Return final symbol counts (only for lengths 0..16) */
  164116. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  164117. /* Return a list of the symbols sorted by code length */
  164118. /* It's not real clear to me why we don't need to consider the codelength
  164119. * changes made above, but the JPEG spec seems to think this works.
  164120. */
  164121. p = 0;
  164122. for (i = 1; i <= MAX_CLEN; i++) {
  164123. for (j = 0; j <= 255; j++) {
  164124. if (codesize[j] == i) {
  164125. htbl->huffval[p] = (UINT8) j;
  164126. p++;
  164127. }
  164128. }
  164129. }
  164130. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164131. htbl->sent_table = FALSE;
  164132. }
  164133. /*
  164134. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164135. */
  164136. METHODDEF(void)
  164137. finish_pass_gather (j_compress_ptr cinfo)
  164138. {
  164139. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164140. int ci, dctbl, actbl;
  164141. jpeg_component_info * compptr;
  164142. JHUFF_TBL **htblptr;
  164143. boolean did_dc[NUM_HUFF_TBLS];
  164144. boolean did_ac[NUM_HUFF_TBLS];
  164145. /* It's important not to apply jpeg_gen_optimal_table more than once
  164146. * per table, because it clobbers the input frequency counts!
  164147. */
  164148. MEMZERO(did_dc, SIZEOF(did_dc));
  164149. MEMZERO(did_ac, SIZEOF(did_ac));
  164150. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164151. compptr = cinfo->cur_comp_info[ci];
  164152. dctbl = compptr->dc_tbl_no;
  164153. actbl = compptr->ac_tbl_no;
  164154. if (! did_dc[dctbl]) {
  164155. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164156. if (*htblptr == NULL)
  164157. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164158. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164159. did_dc[dctbl] = TRUE;
  164160. }
  164161. if (! did_ac[actbl]) {
  164162. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164163. if (*htblptr == NULL)
  164164. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164165. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164166. did_ac[actbl] = TRUE;
  164167. }
  164168. }
  164169. }
  164170. #endif /* ENTROPY_OPT_SUPPORTED */
  164171. /*
  164172. * Module initialization routine for Huffman entropy encoding.
  164173. */
  164174. GLOBAL(void)
  164175. jinit_huff_encoder (j_compress_ptr cinfo)
  164176. {
  164177. huff_entropy_ptr entropy;
  164178. int i;
  164179. entropy = (huff_entropy_ptr)
  164180. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164181. SIZEOF(huff_entropy_encoder));
  164182. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164183. entropy->pub.start_pass = start_pass_huff;
  164184. /* Mark tables unallocated */
  164185. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164186. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164187. #ifdef ENTROPY_OPT_SUPPORTED
  164188. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164189. #endif
  164190. }
  164191. }
  164192. /*** End of inlined file: jchuff.c ***/
  164193. #undef emit_byte
  164194. /*** Start of inlined file: jcinit.c ***/
  164195. #define JPEG_INTERNALS
  164196. /*
  164197. * Master selection of compression modules.
  164198. * This is done once at the start of processing an image. We determine
  164199. * which modules will be used and give them appropriate initialization calls.
  164200. */
  164201. GLOBAL(void)
  164202. jinit_compress_master (j_compress_ptr cinfo)
  164203. {
  164204. /* Initialize master control (includes parameter checking/processing) */
  164205. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164206. /* Preprocessing */
  164207. if (! cinfo->raw_data_in) {
  164208. jinit_color_converter(cinfo);
  164209. jinit_downsampler(cinfo);
  164210. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164211. }
  164212. /* Forward DCT */
  164213. jinit_forward_dct(cinfo);
  164214. /* Entropy encoding: either Huffman or arithmetic coding. */
  164215. if (cinfo->arith_code) {
  164216. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164217. } else {
  164218. if (cinfo->progressive_mode) {
  164219. #ifdef C_PROGRESSIVE_SUPPORTED
  164220. jinit_phuff_encoder(cinfo);
  164221. #else
  164222. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164223. #endif
  164224. } else
  164225. jinit_huff_encoder(cinfo);
  164226. }
  164227. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164228. jinit_c_coef_controller(cinfo,
  164229. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164230. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164231. jinit_marker_writer(cinfo);
  164232. /* We can now tell the memory manager to allocate virtual arrays. */
  164233. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164234. /* Write the datastream header (SOI) immediately.
  164235. * Frame and scan headers are postponed till later.
  164236. * This lets application insert special markers after the SOI.
  164237. */
  164238. (*cinfo->marker->write_file_header) (cinfo);
  164239. }
  164240. /*** End of inlined file: jcinit.c ***/
  164241. /*** Start of inlined file: jcmainct.c ***/
  164242. #define JPEG_INTERNALS
  164243. /* Note: currently, there is no operating mode in which a full-image buffer
  164244. * is needed at this step. If there were, that mode could not be used with
  164245. * "raw data" input, since this module is bypassed in that case. However,
  164246. * we've left the code here for possible use in special applications.
  164247. */
  164248. #undef FULL_MAIN_BUFFER_SUPPORTED
  164249. /* Private buffer controller object */
  164250. typedef struct {
  164251. struct jpeg_c_main_controller pub; /* public fields */
  164252. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164253. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164254. boolean suspended; /* remember if we suspended output */
  164255. J_BUF_MODE pass_mode; /* current operating mode */
  164256. /* If using just a strip buffer, this points to the entire set of buffers
  164257. * (we allocate one for each component). In the full-image case, this
  164258. * points to the currently accessible strips of the virtual arrays.
  164259. */
  164260. JSAMPARRAY buffer[MAX_COMPONENTS];
  164261. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164262. /* If using full-image storage, this array holds pointers to virtual-array
  164263. * control blocks for each component. Unused if not full-image storage.
  164264. */
  164265. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164266. #endif
  164267. } my_main_controller;
  164268. typedef my_main_controller * my_main_ptr;
  164269. /* Forward declarations */
  164270. METHODDEF(void) process_data_simple_main
  164271. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164272. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164273. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164274. METHODDEF(void) process_data_buffer_main
  164275. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164276. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164277. #endif
  164278. /*
  164279. * Initialize for a processing pass.
  164280. */
  164281. METHODDEF(void)
  164282. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164283. {
  164284. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164285. /* Do nothing in raw-data mode. */
  164286. if (cinfo->raw_data_in)
  164287. return;
  164288. main_->cur_iMCU_row = 0; /* initialize counters */
  164289. main_->rowgroup_ctr = 0;
  164290. main_->suspended = FALSE;
  164291. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164292. switch (pass_mode) {
  164293. case JBUF_PASS_THRU:
  164294. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164295. if (main_->whole_image[0] != NULL)
  164296. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164297. #endif
  164298. main_->pub.process_data = process_data_simple_main;
  164299. break;
  164300. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164301. case JBUF_SAVE_SOURCE:
  164302. case JBUF_CRANK_DEST:
  164303. case JBUF_SAVE_AND_PASS:
  164304. if (main_->whole_image[0] == NULL)
  164305. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164306. main_->pub.process_data = process_data_buffer_main;
  164307. break;
  164308. #endif
  164309. default:
  164310. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164311. break;
  164312. }
  164313. }
  164314. /*
  164315. * Process some data.
  164316. * This routine handles the simple pass-through mode,
  164317. * where we have only a strip buffer.
  164318. */
  164319. METHODDEF(void)
  164320. process_data_simple_main (j_compress_ptr cinfo,
  164321. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164322. JDIMENSION in_rows_avail)
  164323. {
  164324. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164325. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164326. /* Read input data if we haven't filled the main buffer yet */
  164327. if (main_->rowgroup_ctr < DCTSIZE)
  164328. (*cinfo->prep->pre_process_data) (cinfo,
  164329. input_buf, in_row_ctr, in_rows_avail,
  164330. main_->buffer, &main_->rowgroup_ctr,
  164331. (JDIMENSION) DCTSIZE);
  164332. /* If we don't have a full iMCU row buffered, return to application for
  164333. * more data. Note that preprocessor will always pad to fill the iMCU row
  164334. * at the bottom of the image.
  164335. */
  164336. if (main_->rowgroup_ctr != DCTSIZE)
  164337. return;
  164338. /* Send the completed row to the compressor */
  164339. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164340. /* If compressor did not consume the whole row, then we must need to
  164341. * suspend processing and return to the application. In this situation
  164342. * we pretend we didn't yet consume the last input row; otherwise, if
  164343. * it happened to be the last row of the image, the application would
  164344. * think we were done.
  164345. */
  164346. if (! main_->suspended) {
  164347. (*in_row_ctr)--;
  164348. main_->suspended = TRUE;
  164349. }
  164350. return;
  164351. }
  164352. /* We did finish the row. Undo our little suspension hack if a previous
  164353. * call suspended; then mark the main buffer empty.
  164354. */
  164355. if (main_->suspended) {
  164356. (*in_row_ctr)++;
  164357. main_->suspended = FALSE;
  164358. }
  164359. main_->rowgroup_ctr = 0;
  164360. main_->cur_iMCU_row++;
  164361. }
  164362. }
  164363. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164364. /*
  164365. * Process some data.
  164366. * This routine handles all of the modes that use a full-size buffer.
  164367. */
  164368. METHODDEF(void)
  164369. process_data_buffer_main (j_compress_ptr cinfo,
  164370. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164371. JDIMENSION in_rows_avail)
  164372. {
  164373. my_main_ptr main = (my_main_ptr) cinfo->main;
  164374. int ci;
  164375. jpeg_component_info *compptr;
  164376. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164377. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164378. /* Realign the virtual buffers if at the start of an iMCU row. */
  164379. if (main->rowgroup_ctr == 0) {
  164380. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164381. ci++, compptr++) {
  164382. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164383. ((j_common_ptr) cinfo, main->whole_image[ci],
  164384. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164385. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164386. }
  164387. /* In a read pass, pretend we just read some source data. */
  164388. if (! writing) {
  164389. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164390. main->rowgroup_ctr = DCTSIZE;
  164391. }
  164392. }
  164393. /* If a write pass, read input data until the current iMCU row is full. */
  164394. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164395. if (writing) {
  164396. (*cinfo->prep->pre_process_data) (cinfo,
  164397. input_buf, in_row_ctr, in_rows_avail,
  164398. main->buffer, &main->rowgroup_ctr,
  164399. (JDIMENSION) DCTSIZE);
  164400. /* Return to application if we need more data to fill the iMCU row. */
  164401. if (main->rowgroup_ctr < DCTSIZE)
  164402. return;
  164403. }
  164404. /* Emit data, unless this is a sink-only pass. */
  164405. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164406. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164407. /* If compressor did not consume the whole row, then we must need to
  164408. * suspend processing and return to the application. In this situation
  164409. * we pretend we didn't yet consume the last input row; otherwise, if
  164410. * it happened to be the last row of the image, the application would
  164411. * think we were done.
  164412. */
  164413. if (! main->suspended) {
  164414. (*in_row_ctr)--;
  164415. main->suspended = TRUE;
  164416. }
  164417. return;
  164418. }
  164419. /* We did finish the row. Undo our little suspension hack if a previous
  164420. * call suspended; then mark the main buffer empty.
  164421. */
  164422. if (main->suspended) {
  164423. (*in_row_ctr)++;
  164424. main->suspended = FALSE;
  164425. }
  164426. }
  164427. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164428. main->rowgroup_ctr = 0;
  164429. main->cur_iMCU_row++;
  164430. }
  164431. }
  164432. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164433. /*
  164434. * Initialize main buffer controller.
  164435. */
  164436. GLOBAL(void)
  164437. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164438. {
  164439. my_main_ptr main_;
  164440. int ci;
  164441. jpeg_component_info *compptr;
  164442. main_ = (my_main_ptr)
  164443. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164444. SIZEOF(my_main_controller));
  164445. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164446. main_->pub.start_pass = start_pass_main;
  164447. /* We don't need to create a buffer in raw-data mode. */
  164448. if (cinfo->raw_data_in)
  164449. return;
  164450. /* Create the buffer. It holds downsampled data, so each component
  164451. * may be of a different size.
  164452. */
  164453. if (need_full_buffer) {
  164454. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164455. /* Allocate a full-image virtual array for each component */
  164456. /* Note we pad the bottom to a multiple of the iMCU height */
  164457. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164458. ci++, compptr++) {
  164459. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164460. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164461. compptr->width_in_blocks * DCTSIZE,
  164462. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164463. (long) compptr->v_samp_factor) * DCTSIZE,
  164464. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164465. }
  164466. #else
  164467. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164468. #endif
  164469. } else {
  164470. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164471. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164472. #endif
  164473. /* Allocate a strip buffer for each component */
  164474. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164475. ci++, compptr++) {
  164476. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164477. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164478. compptr->width_in_blocks * DCTSIZE,
  164479. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164480. }
  164481. }
  164482. }
  164483. /*** End of inlined file: jcmainct.c ***/
  164484. /*** Start of inlined file: jcmarker.c ***/
  164485. #define JPEG_INTERNALS
  164486. /* Private state */
  164487. typedef struct {
  164488. struct jpeg_marker_writer pub; /* public fields */
  164489. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164490. } my_marker_writer;
  164491. typedef my_marker_writer * my_marker_ptr;
  164492. /*
  164493. * Basic output routines.
  164494. *
  164495. * Note that we do not support suspension while writing a marker.
  164496. * Therefore, an application using suspension must ensure that there is
  164497. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164498. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164499. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164500. * modes are not supported at all with suspension, so those two are the only
  164501. * points where markers will be written.
  164502. */
  164503. LOCAL(void)
  164504. emit_byte (j_compress_ptr cinfo, int val)
  164505. /* Emit a byte */
  164506. {
  164507. struct jpeg_destination_mgr * dest = cinfo->dest;
  164508. *(dest->next_output_byte)++ = (JOCTET) val;
  164509. if (--dest->free_in_buffer == 0) {
  164510. if (! (*dest->empty_output_buffer) (cinfo))
  164511. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164512. }
  164513. }
  164514. LOCAL(void)
  164515. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164516. /* Emit a marker code */
  164517. {
  164518. emit_byte(cinfo, 0xFF);
  164519. emit_byte(cinfo, (int) mark);
  164520. }
  164521. LOCAL(void)
  164522. emit_2bytes (j_compress_ptr cinfo, int value)
  164523. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164524. {
  164525. emit_byte(cinfo, (value >> 8) & 0xFF);
  164526. emit_byte(cinfo, value & 0xFF);
  164527. }
  164528. /*
  164529. * Routines to write specific marker types.
  164530. */
  164531. LOCAL(int)
  164532. emit_dqt (j_compress_ptr cinfo, int index)
  164533. /* Emit a DQT marker */
  164534. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164535. {
  164536. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164537. int prec;
  164538. int i;
  164539. if (qtbl == NULL)
  164540. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164541. prec = 0;
  164542. for (i = 0; i < DCTSIZE2; i++) {
  164543. if (qtbl->quantval[i] > 255)
  164544. prec = 1;
  164545. }
  164546. if (! qtbl->sent_table) {
  164547. emit_marker(cinfo, M_DQT);
  164548. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164549. emit_byte(cinfo, index + (prec<<4));
  164550. for (i = 0; i < DCTSIZE2; i++) {
  164551. /* The table entries must be emitted in zigzag order. */
  164552. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164553. if (prec)
  164554. emit_byte(cinfo, (int) (qval >> 8));
  164555. emit_byte(cinfo, (int) (qval & 0xFF));
  164556. }
  164557. qtbl->sent_table = TRUE;
  164558. }
  164559. return prec;
  164560. }
  164561. LOCAL(void)
  164562. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164563. /* Emit a DHT marker */
  164564. {
  164565. JHUFF_TBL * htbl;
  164566. int length, i;
  164567. if (is_ac) {
  164568. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164569. index += 0x10; /* output index has AC bit set */
  164570. } else {
  164571. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164572. }
  164573. if (htbl == NULL)
  164574. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164575. if (! htbl->sent_table) {
  164576. emit_marker(cinfo, M_DHT);
  164577. length = 0;
  164578. for (i = 1; i <= 16; i++)
  164579. length += htbl->bits[i];
  164580. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164581. emit_byte(cinfo, index);
  164582. for (i = 1; i <= 16; i++)
  164583. emit_byte(cinfo, htbl->bits[i]);
  164584. for (i = 0; i < length; i++)
  164585. emit_byte(cinfo, htbl->huffval[i]);
  164586. htbl->sent_table = TRUE;
  164587. }
  164588. }
  164589. LOCAL(void)
  164590. emit_dac (j_compress_ptr)
  164591. /* Emit a DAC marker */
  164592. /* Since the useful info is so small, we want to emit all the tables in */
  164593. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164594. {
  164595. #ifdef C_ARITH_CODING_SUPPORTED
  164596. char dc_in_use[NUM_ARITH_TBLS];
  164597. char ac_in_use[NUM_ARITH_TBLS];
  164598. int length, i;
  164599. jpeg_component_info *compptr;
  164600. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164601. dc_in_use[i] = ac_in_use[i] = 0;
  164602. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164603. compptr = cinfo->cur_comp_info[i];
  164604. dc_in_use[compptr->dc_tbl_no] = 1;
  164605. ac_in_use[compptr->ac_tbl_no] = 1;
  164606. }
  164607. length = 0;
  164608. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164609. length += dc_in_use[i] + ac_in_use[i];
  164610. emit_marker(cinfo, M_DAC);
  164611. emit_2bytes(cinfo, length*2 + 2);
  164612. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164613. if (dc_in_use[i]) {
  164614. emit_byte(cinfo, i);
  164615. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164616. }
  164617. if (ac_in_use[i]) {
  164618. emit_byte(cinfo, i + 0x10);
  164619. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164620. }
  164621. }
  164622. #endif /* C_ARITH_CODING_SUPPORTED */
  164623. }
  164624. LOCAL(void)
  164625. emit_dri (j_compress_ptr cinfo)
  164626. /* Emit a DRI marker */
  164627. {
  164628. emit_marker(cinfo, M_DRI);
  164629. emit_2bytes(cinfo, 4); /* fixed length */
  164630. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164631. }
  164632. LOCAL(void)
  164633. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164634. /* Emit a SOF marker */
  164635. {
  164636. int ci;
  164637. jpeg_component_info *compptr;
  164638. emit_marker(cinfo, code);
  164639. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164640. /* Make sure image isn't bigger than SOF field can handle */
  164641. if ((long) cinfo->image_height > 65535L ||
  164642. (long) cinfo->image_width > 65535L)
  164643. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164644. emit_byte(cinfo, cinfo->data_precision);
  164645. emit_2bytes(cinfo, (int) cinfo->image_height);
  164646. emit_2bytes(cinfo, (int) cinfo->image_width);
  164647. emit_byte(cinfo, cinfo->num_components);
  164648. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164649. ci++, compptr++) {
  164650. emit_byte(cinfo, compptr->component_id);
  164651. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164652. emit_byte(cinfo, compptr->quant_tbl_no);
  164653. }
  164654. }
  164655. LOCAL(void)
  164656. emit_sos (j_compress_ptr cinfo)
  164657. /* Emit a SOS marker */
  164658. {
  164659. int i, td, ta;
  164660. jpeg_component_info *compptr;
  164661. emit_marker(cinfo, M_SOS);
  164662. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164663. emit_byte(cinfo, cinfo->comps_in_scan);
  164664. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164665. compptr = cinfo->cur_comp_info[i];
  164666. emit_byte(cinfo, compptr->component_id);
  164667. td = compptr->dc_tbl_no;
  164668. ta = compptr->ac_tbl_no;
  164669. if (cinfo->progressive_mode) {
  164670. /* Progressive mode: only DC or only AC tables are used in one scan;
  164671. * furthermore, Huffman coding of DC refinement uses no table at all.
  164672. * We emit 0 for unused field(s); this is recommended by the P&M text
  164673. * but does not seem to be specified in the standard.
  164674. */
  164675. if (cinfo->Ss == 0) {
  164676. ta = 0; /* DC scan */
  164677. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164678. td = 0; /* no DC table either */
  164679. } else {
  164680. td = 0; /* AC scan */
  164681. }
  164682. }
  164683. emit_byte(cinfo, (td << 4) + ta);
  164684. }
  164685. emit_byte(cinfo, cinfo->Ss);
  164686. emit_byte(cinfo, cinfo->Se);
  164687. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164688. }
  164689. LOCAL(void)
  164690. emit_jfif_app0 (j_compress_ptr cinfo)
  164691. /* Emit a JFIF-compliant APP0 marker */
  164692. {
  164693. /*
  164694. * Length of APP0 block (2 bytes)
  164695. * Block ID (4 bytes - ASCII "JFIF")
  164696. * Zero byte (1 byte to terminate the ID string)
  164697. * Version Major, Minor (2 bytes - major first)
  164698. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164699. * Xdpu (2 bytes - dots per unit horizontal)
  164700. * Ydpu (2 bytes - dots per unit vertical)
  164701. * Thumbnail X size (1 byte)
  164702. * Thumbnail Y size (1 byte)
  164703. */
  164704. emit_marker(cinfo, M_APP0);
  164705. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164706. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164707. emit_byte(cinfo, 0x46);
  164708. emit_byte(cinfo, 0x49);
  164709. emit_byte(cinfo, 0x46);
  164710. emit_byte(cinfo, 0);
  164711. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164712. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164713. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164714. emit_2bytes(cinfo, (int) cinfo->X_density);
  164715. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164716. emit_byte(cinfo, 0); /* No thumbnail image */
  164717. emit_byte(cinfo, 0);
  164718. }
  164719. LOCAL(void)
  164720. emit_adobe_app14 (j_compress_ptr cinfo)
  164721. /* Emit an Adobe APP14 marker */
  164722. {
  164723. /*
  164724. * Length of APP14 block (2 bytes)
  164725. * Block ID (5 bytes - ASCII "Adobe")
  164726. * Version Number (2 bytes - currently 100)
  164727. * Flags0 (2 bytes - currently 0)
  164728. * Flags1 (2 bytes - currently 0)
  164729. * Color transform (1 byte)
  164730. *
  164731. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164732. * now in circulation seem to use Version = 100, so that's what we write.
  164733. *
  164734. * We write the color transform byte as 1 if the JPEG color space is
  164735. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164736. * whether the encoder performed a transformation, which is pretty useless.
  164737. */
  164738. emit_marker(cinfo, M_APP14);
  164739. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164740. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164741. emit_byte(cinfo, 0x64);
  164742. emit_byte(cinfo, 0x6F);
  164743. emit_byte(cinfo, 0x62);
  164744. emit_byte(cinfo, 0x65);
  164745. emit_2bytes(cinfo, 100); /* Version */
  164746. emit_2bytes(cinfo, 0); /* Flags0 */
  164747. emit_2bytes(cinfo, 0); /* Flags1 */
  164748. switch (cinfo->jpeg_color_space) {
  164749. case JCS_YCbCr:
  164750. emit_byte(cinfo, 1); /* Color transform = 1 */
  164751. break;
  164752. case JCS_YCCK:
  164753. emit_byte(cinfo, 2); /* Color transform = 2 */
  164754. break;
  164755. default:
  164756. emit_byte(cinfo, 0); /* Color transform = 0 */
  164757. break;
  164758. }
  164759. }
  164760. /*
  164761. * These routines allow writing an arbitrary marker with parameters.
  164762. * The only intended use is to emit COM or APPn markers after calling
  164763. * write_file_header and before calling write_frame_header.
  164764. * Other uses are not guaranteed to produce desirable results.
  164765. * Counting the parameter bytes properly is the caller's responsibility.
  164766. */
  164767. METHODDEF(void)
  164768. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164769. /* Emit an arbitrary marker header */
  164770. {
  164771. if (datalen > (unsigned int) 65533) /* safety check */
  164772. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164773. emit_marker(cinfo, (JPEG_MARKER) marker);
  164774. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164775. }
  164776. METHODDEF(void)
  164777. write_marker_byte (j_compress_ptr cinfo, int val)
  164778. /* Emit one byte of marker parameters following write_marker_header */
  164779. {
  164780. emit_byte(cinfo, val);
  164781. }
  164782. /*
  164783. * Write datastream header.
  164784. * This consists of an SOI and optional APPn markers.
  164785. * We recommend use of the JFIF marker, but not the Adobe marker,
  164786. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164787. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164788. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164789. * Note that an application can write additional header markers after
  164790. * jpeg_start_compress returns.
  164791. */
  164792. METHODDEF(void)
  164793. write_file_header (j_compress_ptr cinfo)
  164794. {
  164795. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164796. emit_marker(cinfo, M_SOI); /* first the SOI */
  164797. /* SOI is defined to reset restart interval to 0 */
  164798. marker->last_restart_interval = 0;
  164799. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164800. emit_jfif_app0(cinfo);
  164801. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164802. emit_adobe_app14(cinfo);
  164803. }
  164804. /*
  164805. * Write frame header.
  164806. * This consists of DQT and SOFn markers.
  164807. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164808. * This avoids compatibility problems with incorrect implementations that
  164809. * try to error-check the quant table numbers as soon as they see the SOF.
  164810. */
  164811. METHODDEF(void)
  164812. write_frame_header (j_compress_ptr cinfo)
  164813. {
  164814. int ci, prec;
  164815. boolean is_baseline;
  164816. jpeg_component_info *compptr;
  164817. /* Emit DQT for each quantization table.
  164818. * Note that emit_dqt() suppresses any duplicate tables.
  164819. */
  164820. prec = 0;
  164821. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164822. ci++, compptr++) {
  164823. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164824. }
  164825. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164826. /* Check for a non-baseline specification.
  164827. * Note we assume that Huffman table numbers won't be changed later.
  164828. */
  164829. if (cinfo->arith_code || cinfo->progressive_mode ||
  164830. cinfo->data_precision != 8) {
  164831. is_baseline = FALSE;
  164832. } else {
  164833. is_baseline = TRUE;
  164834. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164835. ci++, compptr++) {
  164836. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164837. is_baseline = FALSE;
  164838. }
  164839. if (prec && is_baseline) {
  164840. is_baseline = FALSE;
  164841. /* If it's baseline except for quantizer size, warn the user */
  164842. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164843. }
  164844. }
  164845. /* Emit the proper SOF marker */
  164846. if (cinfo->arith_code) {
  164847. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164848. } else {
  164849. if (cinfo->progressive_mode)
  164850. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164851. else if (is_baseline)
  164852. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164853. else
  164854. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164855. }
  164856. }
  164857. /*
  164858. * Write scan header.
  164859. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164860. * Compressed data will be written following the SOS.
  164861. */
  164862. METHODDEF(void)
  164863. write_scan_header (j_compress_ptr cinfo)
  164864. {
  164865. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164866. int i;
  164867. jpeg_component_info *compptr;
  164868. if (cinfo->arith_code) {
  164869. /* Emit arith conditioning info. We may have some duplication
  164870. * if the file has multiple scans, but it's so small it's hardly
  164871. * worth worrying about.
  164872. */
  164873. emit_dac(cinfo);
  164874. } else {
  164875. /* Emit Huffman tables.
  164876. * Note that emit_dht() suppresses any duplicate tables.
  164877. */
  164878. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164879. compptr = cinfo->cur_comp_info[i];
  164880. if (cinfo->progressive_mode) {
  164881. /* Progressive mode: only DC or only AC tables are used in one scan */
  164882. if (cinfo->Ss == 0) {
  164883. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164884. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164885. } else {
  164886. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164887. }
  164888. } else {
  164889. /* Sequential mode: need both DC and AC tables */
  164890. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164891. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164892. }
  164893. }
  164894. }
  164895. /* Emit DRI if required --- note that DRI value could change for each scan.
  164896. * We avoid wasting space with unnecessary DRIs, however.
  164897. */
  164898. if (cinfo->restart_interval != marker->last_restart_interval) {
  164899. emit_dri(cinfo);
  164900. marker->last_restart_interval = cinfo->restart_interval;
  164901. }
  164902. emit_sos(cinfo);
  164903. }
  164904. /*
  164905. * Write datastream trailer.
  164906. */
  164907. METHODDEF(void)
  164908. write_file_trailer (j_compress_ptr cinfo)
  164909. {
  164910. emit_marker(cinfo, M_EOI);
  164911. }
  164912. /*
  164913. * Write an abbreviated table-specification datastream.
  164914. * This consists of SOI, DQT and DHT tables, and EOI.
  164915. * Any table that is defined and not marked sent_table = TRUE will be
  164916. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164917. */
  164918. METHODDEF(void)
  164919. write_tables_only (j_compress_ptr cinfo)
  164920. {
  164921. int i;
  164922. emit_marker(cinfo, M_SOI);
  164923. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164924. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164925. (void) emit_dqt(cinfo, i);
  164926. }
  164927. if (! cinfo->arith_code) {
  164928. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164929. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164930. emit_dht(cinfo, i, FALSE);
  164931. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164932. emit_dht(cinfo, i, TRUE);
  164933. }
  164934. }
  164935. emit_marker(cinfo, M_EOI);
  164936. }
  164937. /*
  164938. * Initialize the marker writer module.
  164939. */
  164940. GLOBAL(void)
  164941. jinit_marker_writer (j_compress_ptr cinfo)
  164942. {
  164943. my_marker_ptr marker;
  164944. /* Create the subobject */
  164945. marker = (my_marker_ptr)
  164946. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164947. SIZEOF(my_marker_writer));
  164948. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164949. /* Initialize method pointers */
  164950. marker->pub.write_file_header = write_file_header;
  164951. marker->pub.write_frame_header = write_frame_header;
  164952. marker->pub.write_scan_header = write_scan_header;
  164953. marker->pub.write_file_trailer = write_file_trailer;
  164954. marker->pub.write_tables_only = write_tables_only;
  164955. marker->pub.write_marker_header = write_marker_header;
  164956. marker->pub.write_marker_byte = write_marker_byte;
  164957. /* Initialize private state */
  164958. marker->last_restart_interval = 0;
  164959. }
  164960. /*** End of inlined file: jcmarker.c ***/
  164961. /*** Start of inlined file: jcmaster.c ***/
  164962. #define JPEG_INTERNALS
  164963. /* Private state */
  164964. typedef enum {
  164965. main_pass, /* input data, also do first output step */
  164966. huff_opt_pass, /* Huffman code optimization pass */
  164967. output_pass /* data output pass */
  164968. } c_pass_type;
  164969. typedef struct {
  164970. struct jpeg_comp_master pub; /* public fields */
  164971. c_pass_type pass_type; /* the type of the current pass */
  164972. int pass_number; /* # of passes completed */
  164973. int total_passes; /* total # of passes needed */
  164974. int scan_number; /* current index in scan_info[] */
  164975. } my_comp_master;
  164976. typedef my_comp_master * my_master_ptr;
  164977. /*
  164978. * Support routines that do various essential calculations.
  164979. */
  164980. LOCAL(void)
  164981. initial_setup (j_compress_ptr cinfo)
  164982. /* Do computations that are needed before master selection phase */
  164983. {
  164984. int ci;
  164985. jpeg_component_info *compptr;
  164986. long samplesperrow;
  164987. JDIMENSION jd_samplesperrow;
  164988. /* Sanity check on image dimensions */
  164989. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164990. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164991. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164992. /* Make sure image isn't bigger than I can handle */
  164993. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164994. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164995. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164996. /* Width of an input scanline must be representable as JDIMENSION. */
  164997. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164998. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164999. if ((long) jd_samplesperrow != samplesperrow)
  165000. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  165001. /* For now, precision must match compiled-in value... */
  165002. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  165003. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  165004. /* Check that number of components won't exceed internal array sizes */
  165005. if (cinfo->num_components > MAX_COMPONENTS)
  165006. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165007. MAX_COMPONENTS);
  165008. /* Compute maximum sampling factors; check factor validity */
  165009. cinfo->max_h_samp_factor = 1;
  165010. cinfo->max_v_samp_factor = 1;
  165011. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165012. ci++, compptr++) {
  165013. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  165014. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  165015. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  165016. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  165017. compptr->h_samp_factor);
  165018. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  165019. compptr->v_samp_factor);
  165020. }
  165021. /* Compute dimensions of components */
  165022. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165023. ci++, compptr++) {
  165024. /* Fill in the correct component_index value; don't rely on application */
  165025. compptr->component_index = ci;
  165026. /* For compression, we never do DCT scaling. */
  165027. compptr->DCT_scaled_size = DCTSIZE;
  165028. /* Size in DCT blocks */
  165029. compptr->width_in_blocks = (JDIMENSION)
  165030. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165031. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  165032. compptr->height_in_blocks = (JDIMENSION)
  165033. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165034. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  165035. /* Size in samples */
  165036. compptr->downsampled_width = (JDIMENSION)
  165037. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165038. (long) cinfo->max_h_samp_factor);
  165039. compptr->downsampled_height = (JDIMENSION)
  165040. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165041. (long) cinfo->max_v_samp_factor);
  165042. /* Mark component needed (this flag isn't actually used for compression) */
  165043. compptr->component_needed = TRUE;
  165044. }
  165045. /* Compute number of fully interleaved MCU rows (number of times that
  165046. * main controller will call coefficient controller).
  165047. */
  165048. cinfo->total_iMCU_rows = (JDIMENSION)
  165049. jdiv_round_up((long) cinfo->image_height,
  165050. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165051. }
  165052. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165053. LOCAL(void)
  165054. validate_script (j_compress_ptr cinfo)
  165055. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  165056. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  165057. */
  165058. {
  165059. const jpeg_scan_info * scanptr;
  165060. int scanno, ncomps, ci, coefi, thisi;
  165061. int Ss, Se, Ah, Al;
  165062. boolean component_sent[MAX_COMPONENTS];
  165063. #ifdef C_PROGRESSIVE_SUPPORTED
  165064. int * last_bitpos_ptr;
  165065. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  165066. /* -1 until that coefficient has been seen; then last Al for it */
  165067. #endif
  165068. if (cinfo->num_scans <= 0)
  165069. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  165070. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  165071. * for progressive JPEG, no scan can have this.
  165072. */
  165073. scanptr = cinfo->scan_info;
  165074. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  165075. #ifdef C_PROGRESSIVE_SUPPORTED
  165076. cinfo->progressive_mode = TRUE;
  165077. last_bitpos_ptr = & last_bitpos[0][0];
  165078. for (ci = 0; ci < cinfo->num_components; ci++)
  165079. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  165080. *last_bitpos_ptr++ = -1;
  165081. #else
  165082. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165083. #endif
  165084. } else {
  165085. cinfo->progressive_mode = FALSE;
  165086. for (ci = 0; ci < cinfo->num_components; ci++)
  165087. component_sent[ci] = FALSE;
  165088. }
  165089. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  165090. /* Validate component indexes */
  165091. ncomps = scanptr->comps_in_scan;
  165092. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  165093. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  165094. for (ci = 0; ci < ncomps; ci++) {
  165095. thisi = scanptr->component_index[ci];
  165096. if (thisi < 0 || thisi >= cinfo->num_components)
  165097. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165098. /* Components must appear in SOF order within each scan */
  165099. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  165100. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165101. }
  165102. /* Validate progression parameters */
  165103. Ss = scanptr->Ss;
  165104. Se = scanptr->Se;
  165105. Ah = scanptr->Ah;
  165106. Al = scanptr->Al;
  165107. if (cinfo->progressive_mode) {
  165108. #ifdef C_PROGRESSIVE_SUPPORTED
  165109. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  165110. * seems wrong: the upper bound ought to depend on data precision.
  165111. * Perhaps they really meant 0..N+1 for N-bit precision.
  165112. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  165113. * out-of-range reconstructed DC values during the first DC scan,
  165114. * which might cause problems for some decoders.
  165115. */
  165116. #if BITS_IN_JSAMPLE == 8
  165117. #define MAX_AH_AL 10
  165118. #else
  165119. #define MAX_AH_AL 13
  165120. #endif
  165121. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  165122. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165123. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165124. if (Ss == 0) {
  165125. if (Se != 0) /* DC and AC together not OK */
  165126. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165127. } else {
  165128. if (ncomps != 1) /* AC scans must be for only one component */
  165129. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165130. }
  165131. for (ci = 0; ci < ncomps; ci++) {
  165132. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165133. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165134. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165135. for (coefi = Ss; coefi <= Se; coefi++) {
  165136. if (last_bitpos_ptr[coefi] < 0) {
  165137. /* first scan of this coefficient */
  165138. if (Ah != 0)
  165139. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165140. } else {
  165141. /* not first scan */
  165142. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165143. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165144. }
  165145. last_bitpos_ptr[coefi] = Al;
  165146. }
  165147. }
  165148. #endif
  165149. } else {
  165150. /* For sequential JPEG, all progression parameters must be these: */
  165151. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165152. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165153. /* Make sure components are not sent twice */
  165154. for (ci = 0; ci < ncomps; ci++) {
  165155. thisi = scanptr->component_index[ci];
  165156. if (component_sent[thisi])
  165157. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165158. component_sent[thisi] = TRUE;
  165159. }
  165160. }
  165161. }
  165162. /* Now verify that everything got sent. */
  165163. if (cinfo->progressive_mode) {
  165164. #ifdef C_PROGRESSIVE_SUPPORTED
  165165. /* For progressive mode, we only check that at least some DC data
  165166. * got sent for each component; the spec does not require that all bits
  165167. * of all coefficients be transmitted. Would it be wiser to enforce
  165168. * transmission of all coefficient bits??
  165169. */
  165170. for (ci = 0; ci < cinfo->num_components; ci++) {
  165171. if (last_bitpos[ci][0] < 0)
  165172. ERREXIT(cinfo, JERR_MISSING_DATA);
  165173. }
  165174. #endif
  165175. } else {
  165176. for (ci = 0; ci < cinfo->num_components; ci++) {
  165177. if (! component_sent[ci])
  165178. ERREXIT(cinfo, JERR_MISSING_DATA);
  165179. }
  165180. }
  165181. }
  165182. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165183. LOCAL(void)
  165184. select_scan_parameters (j_compress_ptr cinfo)
  165185. /* Set up the scan parameters for the current scan */
  165186. {
  165187. int ci;
  165188. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165189. if (cinfo->scan_info != NULL) {
  165190. /* Prepare for current scan --- the script is already validated */
  165191. my_master_ptr master = (my_master_ptr) cinfo->master;
  165192. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165193. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165194. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165195. cinfo->cur_comp_info[ci] =
  165196. &cinfo->comp_info[scanptr->component_index[ci]];
  165197. }
  165198. cinfo->Ss = scanptr->Ss;
  165199. cinfo->Se = scanptr->Se;
  165200. cinfo->Ah = scanptr->Ah;
  165201. cinfo->Al = scanptr->Al;
  165202. }
  165203. else
  165204. #endif
  165205. {
  165206. /* Prepare for single sequential-JPEG scan containing all components */
  165207. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165208. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165209. MAX_COMPS_IN_SCAN);
  165210. cinfo->comps_in_scan = cinfo->num_components;
  165211. for (ci = 0; ci < cinfo->num_components; ci++) {
  165212. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165213. }
  165214. cinfo->Ss = 0;
  165215. cinfo->Se = DCTSIZE2-1;
  165216. cinfo->Ah = 0;
  165217. cinfo->Al = 0;
  165218. }
  165219. }
  165220. LOCAL(void)
  165221. per_scan_setup (j_compress_ptr cinfo)
  165222. /* Do computations that are needed before processing a JPEG scan */
  165223. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165224. {
  165225. int ci, mcublks, tmp;
  165226. jpeg_component_info *compptr;
  165227. if (cinfo->comps_in_scan == 1) {
  165228. /* Noninterleaved (single-component) scan */
  165229. compptr = cinfo->cur_comp_info[0];
  165230. /* Overall image size in MCUs */
  165231. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165232. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165233. /* For noninterleaved scan, always one block per MCU */
  165234. compptr->MCU_width = 1;
  165235. compptr->MCU_height = 1;
  165236. compptr->MCU_blocks = 1;
  165237. compptr->MCU_sample_width = DCTSIZE;
  165238. compptr->last_col_width = 1;
  165239. /* For noninterleaved scans, it is convenient to define last_row_height
  165240. * as the number of block rows present in the last iMCU row.
  165241. */
  165242. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165243. if (tmp == 0) tmp = compptr->v_samp_factor;
  165244. compptr->last_row_height = tmp;
  165245. /* Prepare array describing MCU composition */
  165246. cinfo->blocks_in_MCU = 1;
  165247. cinfo->MCU_membership[0] = 0;
  165248. } else {
  165249. /* Interleaved (multi-component) scan */
  165250. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165251. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165252. MAX_COMPS_IN_SCAN);
  165253. /* Overall image size in MCUs */
  165254. cinfo->MCUs_per_row = (JDIMENSION)
  165255. jdiv_round_up((long) cinfo->image_width,
  165256. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165257. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165258. jdiv_round_up((long) cinfo->image_height,
  165259. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165260. cinfo->blocks_in_MCU = 0;
  165261. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165262. compptr = cinfo->cur_comp_info[ci];
  165263. /* Sampling factors give # of blocks of component in each MCU */
  165264. compptr->MCU_width = compptr->h_samp_factor;
  165265. compptr->MCU_height = compptr->v_samp_factor;
  165266. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165267. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165268. /* Figure number of non-dummy blocks in last MCU column & row */
  165269. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165270. if (tmp == 0) tmp = compptr->MCU_width;
  165271. compptr->last_col_width = tmp;
  165272. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165273. if (tmp == 0) tmp = compptr->MCU_height;
  165274. compptr->last_row_height = tmp;
  165275. /* Prepare array describing MCU composition */
  165276. mcublks = compptr->MCU_blocks;
  165277. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165278. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165279. while (mcublks-- > 0) {
  165280. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165281. }
  165282. }
  165283. }
  165284. /* Convert restart specified in rows to actual MCU count. */
  165285. /* Note that count must fit in 16 bits, so we provide limiting. */
  165286. if (cinfo->restart_in_rows > 0) {
  165287. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165288. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165289. }
  165290. }
  165291. /*
  165292. * Per-pass setup.
  165293. * This is called at the beginning of each pass. We determine which modules
  165294. * will be active during this pass and give them appropriate start_pass calls.
  165295. * We also set is_last_pass to indicate whether any more passes will be
  165296. * required.
  165297. */
  165298. METHODDEF(void)
  165299. prepare_for_pass (j_compress_ptr cinfo)
  165300. {
  165301. my_master_ptr master = (my_master_ptr) cinfo->master;
  165302. switch (master->pass_type) {
  165303. case main_pass:
  165304. /* Initial pass: will collect input data, and do either Huffman
  165305. * optimization or data output for the first scan.
  165306. */
  165307. select_scan_parameters(cinfo);
  165308. per_scan_setup(cinfo);
  165309. if (! cinfo->raw_data_in) {
  165310. (*cinfo->cconvert->start_pass) (cinfo);
  165311. (*cinfo->downsample->start_pass) (cinfo);
  165312. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165313. }
  165314. (*cinfo->fdct->start_pass) (cinfo);
  165315. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165316. (*cinfo->coef->start_pass) (cinfo,
  165317. (master->total_passes > 1 ?
  165318. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165319. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165320. if (cinfo->optimize_coding) {
  165321. /* No immediate data output; postpone writing frame/scan headers */
  165322. master->pub.call_pass_startup = FALSE;
  165323. } else {
  165324. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165325. master->pub.call_pass_startup = TRUE;
  165326. }
  165327. break;
  165328. #ifdef ENTROPY_OPT_SUPPORTED
  165329. case huff_opt_pass:
  165330. /* Do Huffman optimization for a scan after the first one. */
  165331. select_scan_parameters(cinfo);
  165332. per_scan_setup(cinfo);
  165333. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165334. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165335. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165336. master->pub.call_pass_startup = FALSE;
  165337. break;
  165338. }
  165339. /* Special case: Huffman DC refinement scans need no Huffman table
  165340. * and therefore we can skip the optimization pass for them.
  165341. */
  165342. master->pass_type = output_pass;
  165343. master->pass_number++;
  165344. /*FALLTHROUGH*/
  165345. #endif
  165346. case output_pass:
  165347. /* Do a data-output pass. */
  165348. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165349. if (! cinfo->optimize_coding) {
  165350. select_scan_parameters(cinfo);
  165351. per_scan_setup(cinfo);
  165352. }
  165353. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165354. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165355. /* We emit frame/scan headers now */
  165356. if (master->scan_number == 0)
  165357. (*cinfo->marker->write_frame_header) (cinfo);
  165358. (*cinfo->marker->write_scan_header) (cinfo);
  165359. master->pub.call_pass_startup = FALSE;
  165360. break;
  165361. default:
  165362. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165363. }
  165364. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165365. /* Set up progress monitor's pass info if present */
  165366. if (cinfo->progress != NULL) {
  165367. cinfo->progress->completed_passes = master->pass_number;
  165368. cinfo->progress->total_passes = master->total_passes;
  165369. }
  165370. }
  165371. /*
  165372. * Special start-of-pass hook.
  165373. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165374. * In single-pass processing, we need this hook because we don't want to
  165375. * write frame/scan headers during jpeg_start_compress; we want to let the
  165376. * application write COM markers etc. between jpeg_start_compress and the
  165377. * jpeg_write_scanlines loop.
  165378. * In multi-pass processing, this routine is not used.
  165379. */
  165380. METHODDEF(void)
  165381. pass_startup (j_compress_ptr cinfo)
  165382. {
  165383. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165384. (*cinfo->marker->write_frame_header) (cinfo);
  165385. (*cinfo->marker->write_scan_header) (cinfo);
  165386. }
  165387. /*
  165388. * Finish up at end of pass.
  165389. */
  165390. METHODDEF(void)
  165391. finish_pass_master (j_compress_ptr cinfo)
  165392. {
  165393. my_master_ptr master = (my_master_ptr) cinfo->master;
  165394. /* The entropy coder always needs an end-of-pass call,
  165395. * either to analyze statistics or to flush its output buffer.
  165396. */
  165397. (*cinfo->entropy->finish_pass) (cinfo);
  165398. /* Update state for next pass */
  165399. switch (master->pass_type) {
  165400. case main_pass:
  165401. /* next pass is either output of scan 0 (after optimization)
  165402. * or output of scan 1 (if no optimization).
  165403. */
  165404. master->pass_type = output_pass;
  165405. if (! cinfo->optimize_coding)
  165406. master->scan_number++;
  165407. break;
  165408. case huff_opt_pass:
  165409. /* next pass is always output of current scan */
  165410. master->pass_type = output_pass;
  165411. break;
  165412. case output_pass:
  165413. /* next pass is either optimization or output of next scan */
  165414. if (cinfo->optimize_coding)
  165415. master->pass_type = huff_opt_pass;
  165416. master->scan_number++;
  165417. break;
  165418. }
  165419. master->pass_number++;
  165420. }
  165421. /*
  165422. * Initialize master compression control.
  165423. */
  165424. GLOBAL(void)
  165425. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165426. {
  165427. my_master_ptr master;
  165428. master = (my_master_ptr)
  165429. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165430. SIZEOF(my_comp_master));
  165431. cinfo->master = (struct jpeg_comp_master *) master;
  165432. master->pub.prepare_for_pass = prepare_for_pass;
  165433. master->pub.pass_startup = pass_startup;
  165434. master->pub.finish_pass = finish_pass_master;
  165435. master->pub.is_last_pass = FALSE;
  165436. /* Validate parameters, determine derived values */
  165437. initial_setup(cinfo);
  165438. if (cinfo->scan_info != NULL) {
  165439. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165440. validate_script(cinfo);
  165441. #else
  165442. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165443. #endif
  165444. } else {
  165445. cinfo->progressive_mode = FALSE;
  165446. cinfo->num_scans = 1;
  165447. }
  165448. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165449. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165450. /* Initialize my private state */
  165451. if (transcode_only) {
  165452. /* no main pass in transcoding */
  165453. if (cinfo->optimize_coding)
  165454. master->pass_type = huff_opt_pass;
  165455. else
  165456. master->pass_type = output_pass;
  165457. } else {
  165458. /* for normal compression, first pass is always this type: */
  165459. master->pass_type = main_pass;
  165460. }
  165461. master->scan_number = 0;
  165462. master->pass_number = 0;
  165463. if (cinfo->optimize_coding)
  165464. master->total_passes = cinfo->num_scans * 2;
  165465. else
  165466. master->total_passes = cinfo->num_scans;
  165467. }
  165468. /*** End of inlined file: jcmaster.c ***/
  165469. /*** Start of inlined file: jcomapi.c ***/
  165470. #define JPEG_INTERNALS
  165471. /*
  165472. * Abort processing of a JPEG compression or decompression operation,
  165473. * but don't destroy the object itself.
  165474. *
  165475. * For this, we merely clean up all the nonpermanent memory pools.
  165476. * Note that temp files (virtual arrays) are not allowed to belong to
  165477. * the permanent pool, so we will be able to close all temp files here.
  165478. * Closing a data source or destination, if necessary, is the application's
  165479. * responsibility.
  165480. */
  165481. GLOBAL(void)
  165482. jpeg_abort (j_common_ptr cinfo)
  165483. {
  165484. int pool;
  165485. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165486. if (cinfo->mem == NULL)
  165487. return;
  165488. /* Releasing pools in reverse order might help avoid fragmentation
  165489. * with some (brain-damaged) malloc libraries.
  165490. */
  165491. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165492. (*cinfo->mem->free_pool) (cinfo, pool);
  165493. }
  165494. /* Reset overall state for possible reuse of object */
  165495. if (cinfo->is_decompressor) {
  165496. cinfo->global_state = DSTATE_START;
  165497. /* Try to keep application from accessing now-deleted marker list.
  165498. * A bit kludgy to do it here, but this is the most central place.
  165499. */
  165500. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165501. } else {
  165502. cinfo->global_state = CSTATE_START;
  165503. }
  165504. }
  165505. /*
  165506. * Destruction of a JPEG object.
  165507. *
  165508. * Everything gets deallocated except the master jpeg_compress_struct itself
  165509. * and the error manager struct. Both of these are supplied by the application
  165510. * and must be freed, if necessary, by the application. (Often they are on
  165511. * the stack and so don't need to be freed anyway.)
  165512. * Closing a data source or destination, if necessary, is the application's
  165513. * responsibility.
  165514. */
  165515. GLOBAL(void)
  165516. jpeg_destroy (j_common_ptr cinfo)
  165517. {
  165518. /* We need only tell the memory manager to release everything. */
  165519. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165520. if (cinfo->mem != NULL)
  165521. (*cinfo->mem->self_destruct) (cinfo);
  165522. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165523. cinfo->global_state = 0; /* mark it destroyed */
  165524. }
  165525. /*
  165526. * Convenience routines for allocating quantization and Huffman tables.
  165527. * (Would jutils.c be a more reasonable place to put these?)
  165528. */
  165529. GLOBAL(JQUANT_TBL *)
  165530. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165531. {
  165532. JQUANT_TBL *tbl;
  165533. tbl = (JQUANT_TBL *)
  165534. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165535. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165536. return tbl;
  165537. }
  165538. GLOBAL(JHUFF_TBL *)
  165539. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165540. {
  165541. JHUFF_TBL *tbl;
  165542. tbl = (JHUFF_TBL *)
  165543. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165544. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165545. return tbl;
  165546. }
  165547. /*** End of inlined file: jcomapi.c ***/
  165548. /*** Start of inlined file: jcparam.c ***/
  165549. #define JPEG_INTERNALS
  165550. /*
  165551. * Quantization table setup routines
  165552. */
  165553. GLOBAL(void)
  165554. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165555. const unsigned int *basic_table,
  165556. int scale_factor, boolean force_baseline)
  165557. /* Define a quantization table equal to the basic_table times
  165558. * a scale factor (given as a percentage).
  165559. * If force_baseline is TRUE, the computed quantization table entries
  165560. * are limited to 1..255 for JPEG baseline compatibility.
  165561. */
  165562. {
  165563. JQUANT_TBL ** qtblptr;
  165564. int i;
  165565. long temp;
  165566. /* Safety check to ensure start_compress not called yet. */
  165567. if (cinfo->global_state != CSTATE_START)
  165568. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165569. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165570. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165571. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165572. if (*qtblptr == NULL)
  165573. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165574. for (i = 0; i < DCTSIZE2; i++) {
  165575. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165576. /* limit the values to the valid range */
  165577. if (temp <= 0L) temp = 1L;
  165578. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165579. if (force_baseline && temp > 255L)
  165580. temp = 255L; /* limit to baseline range if requested */
  165581. (*qtblptr)->quantval[i] = (UINT16) temp;
  165582. }
  165583. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165584. (*qtblptr)->sent_table = FALSE;
  165585. }
  165586. GLOBAL(void)
  165587. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165588. boolean force_baseline)
  165589. /* Set or change the 'quality' (quantization) setting, using default tables
  165590. * and a straight percentage-scaling quality scale. In most cases it's better
  165591. * to use jpeg_set_quality (below); this entry point is provided for
  165592. * applications that insist on a linear percentage scaling.
  165593. */
  165594. {
  165595. /* These are the sample quantization tables given in JPEG spec section K.1.
  165596. * The spec says that the values given produce "good" quality, and
  165597. * when divided by 2, "very good" quality.
  165598. */
  165599. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165600. 16, 11, 10, 16, 24, 40, 51, 61,
  165601. 12, 12, 14, 19, 26, 58, 60, 55,
  165602. 14, 13, 16, 24, 40, 57, 69, 56,
  165603. 14, 17, 22, 29, 51, 87, 80, 62,
  165604. 18, 22, 37, 56, 68, 109, 103, 77,
  165605. 24, 35, 55, 64, 81, 104, 113, 92,
  165606. 49, 64, 78, 87, 103, 121, 120, 101,
  165607. 72, 92, 95, 98, 112, 100, 103, 99
  165608. };
  165609. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165610. 17, 18, 24, 47, 99, 99, 99, 99,
  165611. 18, 21, 26, 66, 99, 99, 99, 99,
  165612. 24, 26, 56, 99, 99, 99, 99, 99,
  165613. 47, 66, 99, 99, 99, 99, 99, 99,
  165614. 99, 99, 99, 99, 99, 99, 99, 99,
  165615. 99, 99, 99, 99, 99, 99, 99, 99,
  165616. 99, 99, 99, 99, 99, 99, 99, 99,
  165617. 99, 99, 99, 99, 99, 99, 99, 99
  165618. };
  165619. /* Set up two quantization tables using the specified scaling */
  165620. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165621. scale_factor, force_baseline);
  165622. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165623. scale_factor, force_baseline);
  165624. }
  165625. GLOBAL(int)
  165626. jpeg_quality_scaling (int quality)
  165627. /* Convert a user-specified quality rating to a percentage scaling factor
  165628. * for an underlying quantization table, using our recommended scaling curve.
  165629. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165630. */
  165631. {
  165632. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165633. if (quality <= 0) quality = 1;
  165634. if (quality > 100) quality = 100;
  165635. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165636. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165637. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165638. * to make all the table entries 1 (hence, minimum quantization loss).
  165639. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165640. */
  165641. if (quality < 50)
  165642. quality = 5000 / quality;
  165643. else
  165644. quality = 200 - quality*2;
  165645. return quality;
  165646. }
  165647. GLOBAL(void)
  165648. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165649. /* Set or change the 'quality' (quantization) setting, using default tables.
  165650. * This is the standard quality-adjusting entry point for typical user
  165651. * interfaces; only those who want detailed control over quantization tables
  165652. * would use the preceding three routines directly.
  165653. */
  165654. {
  165655. /* Convert user 0-100 rating to percentage scaling */
  165656. quality = jpeg_quality_scaling(quality);
  165657. /* Set up standard quality tables */
  165658. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165659. }
  165660. /*
  165661. * Huffman table setup routines
  165662. */
  165663. LOCAL(void)
  165664. add_huff_table (j_compress_ptr cinfo,
  165665. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165666. /* Define a Huffman table */
  165667. {
  165668. int nsymbols, len;
  165669. if (*htblptr == NULL)
  165670. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165671. /* Copy the number-of-symbols-of-each-code-length counts */
  165672. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165673. /* Validate the counts. We do this here mainly so we can copy the right
  165674. * number of symbols from the val[] array, without risking marching off
  165675. * the end of memory. jchuff.c will do a more thorough test later.
  165676. */
  165677. nsymbols = 0;
  165678. for (len = 1; len <= 16; len++)
  165679. nsymbols += bits[len];
  165680. if (nsymbols < 1 || nsymbols > 256)
  165681. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165682. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165683. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165684. (*htblptr)->sent_table = FALSE;
  165685. }
  165686. LOCAL(void)
  165687. std_huff_tables (j_compress_ptr cinfo)
  165688. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165689. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165690. {
  165691. static const UINT8 bits_dc_luminance[17] =
  165692. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165693. static const UINT8 val_dc_luminance[] =
  165694. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165695. static const UINT8 bits_dc_chrominance[17] =
  165696. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165697. static const UINT8 val_dc_chrominance[] =
  165698. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165699. static const UINT8 bits_ac_luminance[17] =
  165700. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165701. static const UINT8 val_ac_luminance[] =
  165702. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165703. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165704. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165705. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165706. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165707. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165708. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165709. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165710. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165711. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165712. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165713. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165714. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165715. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165716. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165717. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165718. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165719. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165720. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165721. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165722. 0xf9, 0xfa };
  165723. static const UINT8 bits_ac_chrominance[17] =
  165724. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165725. static const UINT8 val_ac_chrominance[] =
  165726. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165727. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165728. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165729. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165730. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165731. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165732. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165733. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165734. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165735. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165736. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165737. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165738. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165739. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165740. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165741. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165742. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165743. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165744. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165745. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165746. 0xf9, 0xfa };
  165747. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165748. bits_dc_luminance, val_dc_luminance);
  165749. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165750. bits_ac_luminance, val_ac_luminance);
  165751. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165752. bits_dc_chrominance, val_dc_chrominance);
  165753. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165754. bits_ac_chrominance, val_ac_chrominance);
  165755. }
  165756. /*
  165757. * Default parameter setup for compression.
  165758. *
  165759. * Applications that don't choose to use this routine must do their
  165760. * own setup of all these parameters. Alternately, you can call this
  165761. * to establish defaults and then alter parameters selectively. This
  165762. * is the recommended approach since, if we add any new parameters,
  165763. * your code will still work (they'll be set to reasonable defaults).
  165764. */
  165765. GLOBAL(void)
  165766. jpeg_set_defaults (j_compress_ptr cinfo)
  165767. {
  165768. int i;
  165769. /* Safety check to ensure start_compress not called yet. */
  165770. if (cinfo->global_state != CSTATE_START)
  165771. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165772. /* Allocate comp_info array large enough for maximum component count.
  165773. * Array is made permanent in case application wants to compress
  165774. * multiple images at same param settings.
  165775. */
  165776. if (cinfo->comp_info == NULL)
  165777. cinfo->comp_info = (jpeg_component_info *)
  165778. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165779. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165780. /* Initialize everything not dependent on the color space */
  165781. cinfo->data_precision = BITS_IN_JSAMPLE;
  165782. /* Set up two quantization tables using default quality of 75 */
  165783. jpeg_set_quality(cinfo, 75, TRUE);
  165784. /* Set up two Huffman tables */
  165785. std_huff_tables(cinfo);
  165786. /* Initialize default arithmetic coding conditioning */
  165787. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165788. cinfo->arith_dc_L[i] = 0;
  165789. cinfo->arith_dc_U[i] = 1;
  165790. cinfo->arith_ac_K[i] = 5;
  165791. }
  165792. /* Default is no multiple-scan output */
  165793. cinfo->scan_info = NULL;
  165794. cinfo->num_scans = 0;
  165795. /* Expect normal source image, not raw downsampled data */
  165796. cinfo->raw_data_in = FALSE;
  165797. /* Use Huffman coding, not arithmetic coding, by default */
  165798. cinfo->arith_code = FALSE;
  165799. /* By default, don't do extra passes to optimize entropy coding */
  165800. cinfo->optimize_coding = FALSE;
  165801. /* The standard Huffman tables are only valid for 8-bit data precision.
  165802. * If the precision is higher, force optimization on so that usable
  165803. * tables will be computed. This test can be removed if default tables
  165804. * are supplied that are valid for the desired precision.
  165805. */
  165806. if (cinfo->data_precision > 8)
  165807. cinfo->optimize_coding = TRUE;
  165808. /* By default, use the simpler non-cosited sampling alignment */
  165809. cinfo->CCIR601_sampling = FALSE;
  165810. /* No input smoothing */
  165811. cinfo->smoothing_factor = 0;
  165812. /* DCT algorithm preference */
  165813. cinfo->dct_method = JDCT_DEFAULT;
  165814. /* No restart markers */
  165815. cinfo->restart_interval = 0;
  165816. cinfo->restart_in_rows = 0;
  165817. /* Fill in default JFIF marker parameters. Note that whether the marker
  165818. * will actually be written is determined by jpeg_set_colorspace.
  165819. *
  165820. * By default, the library emits JFIF version code 1.01.
  165821. * An application that wants to emit JFIF 1.02 extension markers should set
  165822. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165823. * to 1.02, but there may still be some decoders in use that will complain
  165824. * about that; saying 1.01 should minimize compatibility problems.
  165825. */
  165826. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165827. cinfo->JFIF_minor_version = 1;
  165828. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165829. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165830. cinfo->Y_density = 1;
  165831. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165832. jpeg_default_colorspace(cinfo);
  165833. }
  165834. /*
  165835. * Select an appropriate JPEG colorspace for in_color_space.
  165836. */
  165837. GLOBAL(void)
  165838. jpeg_default_colorspace (j_compress_ptr cinfo)
  165839. {
  165840. switch (cinfo->in_color_space) {
  165841. case JCS_GRAYSCALE:
  165842. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165843. break;
  165844. case JCS_RGB:
  165845. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165846. break;
  165847. case JCS_YCbCr:
  165848. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165849. break;
  165850. case JCS_CMYK:
  165851. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165852. break;
  165853. case JCS_YCCK:
  165854. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165855. break;
  165856. case JCS_UNKNOWN:
  165857. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165858. break;
  165859. default:
  165860. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165861. }
  165862. }
  165863. /*
  165864. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165865. */
  165866. GLOBAL(void)
  165867. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165868. {
  165869. jpeg_component_info * compptr;
  165870. int ci;
  165871. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165872. (compptr = &cinfo->comp_info[index], \
  165873. compptr->component_id = (id), \
  165874. compptr->h_samp_factor = (hsamp), \
  165875. compptr->v_samp_factor = (vsamp), \
  165876. compptr->quant_tbl_no = (quant), \
  165877. compptr->dc_tbl_no = (dctbl), \
  165878. compptr->ac_tbl_no = (actbl) )
  165879. /* Safety check to ensure start_compress not called yet. */
  165880. if (cinfo->global_state != CSTATE_START)
  165881. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165882. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165883. * tables 1 for chrominance components.
  165884. */
  165885. cinfo->jpeg_color_space = colorspace;
  165886. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165887. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165888. switch (colorspace) {
  165889. case JCS_GRAYSCALE:
  165890. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165891. cinfo->num_components = 1;
  165892. /* JFIF specifies component ID 1 */
  165893. SET_COMP(0, 1, 1,1, 0, 0,0);
  165894. break;
  165895. case JCS_RGB:
  165896. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165897. cinfo->num_components = 3;
  165898. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165899. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165900. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165901. break;
  165902. case JCS_YCbCr:
  165903. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165904. cinfo->num_components = 3;
  165905. /* JFIF specifies component IDs 1,2,3 */
  165906. /* We default to 2x2 subsamples of chrominance */
  165907. SET_COMP(0, 1, 2,2, 0, 0,0);
  165908. SET_COMP(1, 2, 1,1, 1, 1,1);
  165909. SET_COMP(2, 3, 1,1, 1, 1,1);
  165910. break;
  165911. case JCS_CMYK:
  165912. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165913. cinfo->num_components = 4;
  165914. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165915. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165916. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165917. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165918. break;
  165919. case JCS_YCCK:
  165920. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165921. cinfo->num_components = 4;
  165922. SET_COMP(0, 1, 2,2, 0, 0,0);
  165923. SET_COMP(1, 2, 1,1, 1, 1,1);
  165924. SET_COMP(2, 3, 1,1, 1, 1,1);
  165925. SET_COMP(3, 4, 2,2, 0, 0,0);
  165926. break;
  165927. case JCS_UNKNOWN:
  165928. cinfo->num_components = cinfo->input_components;
  165929. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165930. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165931. MAX_COMPONENTS);
  165932. for (ci = 0; ci < cinfo->num_components; ci++) {
  165933. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165934. }
  165935. break;
  165936. default:
  165937. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165938. }
  165939. }
  165940. #ifdef C_PROGRESSIVE_SUPPORTED
  165941. LOCAL(jpeg_scan_info *)
  165942. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165943. int Ss, int Se, int Ah, int Al)
  165944. /* Support routine: generate one scan for specified component */
  165945. {
  165946. scanptr->comps_in_scan = 1;
  165947. scanptr->component_index[0] = ci;
  165948. scanptr->Ss = Ss;
  165949. scanptr->Se = Se;
  165950. scanptr->Ah = Ah;
  165951. scanptr->Al = Al;
  165952. scanptr++;
  165953. return scanptr;
  165954. }
  165955. LOCAL(jpeg_scan_info *)
  165956. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165957. int Ss, int Se, int Ah, int Al)
  165958. /* Support routine: generate one scan for each component */
  165959. {
  165960. int ci;
  165961. for (ci = 0; ci < ncomps; ci++) {
  165962. scanptr->comps_in_scan = 1;
  165963. scanptr->component_index[0] = ci;
  165964. scanptr->Ss = Ss;
  165965. scanptr->Se = Se;
  165966. scanptr->Ah = Ah;
  165967. scanptr->Al = Al;
  165968. scanptr++;
  165969. }
  165970. return scanptr;
  165971. }
  165972. LOCAL(jpeg_scan_info *)
  165973. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165974. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165975. {
  165976. int ci;
  165977. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165978. /* Single interleaved DC scan */
  165979. scanptr->comps_in_scan = ncomps;
  165980. for (ci = 0; ci < ncomps; ci++)
  165981. scanptr->component_index[ci] = ci;
  165982. scanptr->Ss = scanptr->Se = 0;
  165983. scanptr->Ah = Ah;
  165984. scanptr->Al = Al;
  165985. scanptr++;
  165986. } else {
  165987. /* Noninterleaved DC scan for each component */
  165988. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165989. }
  165990. return scanptr;
  165991. }
  165992. /*
  165993. * Create a recommended progressive-JPEG script.
  165994. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165995. */
  165996. GLOBAL(void)
  165997. jpeg_simple_progression (j_compress_ptr cinfo)
  165998. {
  165999. int ncomps = cinfo->num_components;
  166000. int nscans;
  166001. jpeg_scan_info * scanptr;
  166002. /* Safety check to ensure start_compress not called yet. */
  166003. if (cinfo->global_state != CSTATE_START)
  166004. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166005. /* Figure space needed for script. Calculation must match code below! */
  166006. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  166007. /* Custom script for YCbCr color images. */
  166008. nscans = 10;
  166009. } else {
  166010. /* All-purpose script for other color spaces. */
  166011. if (ncomps > MAX_COMPS_IN_SCAN)
  166012. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  166013. else
  166014. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  166015. }
  166016. /* Allocate space for script.
  166017. * We need to put it in the permanent pool in case the application performs
  166018. * multiple compressions without changing the settings. To avoid a memory
  166019. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  166020. * object, we try to re-use previously allocated space, and we allocate
  166021. * enough space to handle YCbCr even if initially asked for grayscale.
  166022. */
  166023. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  166024. cinfo->script_space_size = MAX(nscans, 10);
  166025. cinfo->script_space = (jpeg_scan_info *)
  166026. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166027. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  166028. }
  166029. scanptr = cinfo->script_space;
  166030. cinfo->scan_info = scanptr;
  166031. cinfo->num_scans = nscans;
  166032. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  166033. /* Custom script for YCbCr color images. */
  166034. /* Initial DC scan */
  166035. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  166036. /* Initial AC scan: get some luma data out in a hurry */
  166037. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  166038. /* Chroma data is too small to be worth expending many scans on */
  166039. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  166040. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  166041. /* Complete spectral selection for luma AC */
  166042. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  166043. /* Refine next bit of luma AC */
  166044. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  166045. /* Finish DC successive approximation */
  166046. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  166047. /* Finish AC successive approximation */
  166048. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  166049. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  166050. /* Luma bottom bit comes last since it's usually largest scan */
  166051. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  166052. } else {
  166053. /* All-purpose script for other color spaces. */
  166054. /* Successive approximation first pass */
  166055. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  166056. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  166057. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  166058. /* Successive approximation second pass */
  166059. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  166060. /* Successive approximation final pass */
  166061. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  166062. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  166063. }
  166064. }
  166065. #endif /* C_PROGRESSIVE_SUPPORTED */
  166066. /*** End of inlined file: jcparam.c ***/
  166067. /*** Start of inlined file: jcphuff.c ***/
  166068. #define JPEG_INTERNALS
  166069. #ifdef C_PROGRESSIVE_SUPPORTED
  166070. /* Expanded entropy encoder object for progressive Huffman encoding. */
  166071. typedef struct {
  166072. struct jpeg_entropy_encoder pub; /* public fields */
  166073. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  166074. boolean gather_statistics;
  166075. /* Bit-level coding status.
  166076. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  166077. */
  166078. JOCTET * next_output_byte; /* => next byte to write in buffer */
  166079. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  166080. INT32 put_buffer; /* current bit-accumulation buffer */
  166081. int put_bits; /* # of bits now in it */
  166082. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  166083. /* Coding status for DC components */
  166084. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166085. /* Coding status for AC components */
  166086. int ac_tbl_no; /* the table number of the single component */
  166087. unsigned int EOBRUN; /* run length of EOBs */
  166088. unsigned int BE; /* # of buffered correction bits before MCU */
  166089. char * bit_buffer; /* buffer for correction bits (1 per char) */
  166090. /* packing correction bits tightly would save some space but cost time... */
  166091. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166092. int next_restart_num; /* next restart number to write (0-7) */
  166093. /* Pointers to derived tables (these workspaces have image lifespan).
  166094. * Since any one scan codes only DC or only AC, we only need one set
  166095. * of tables, not one for DC and one for AC.
  166096. */
  166097. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166098. /* Statistics tables for optimization; again, one set is enough */
  166099. long * count_ptrs[NUM_HUFF_TBLS];
  166100. } phuff_entropy_encoder;
  166101. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  166102. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  166103. * buffer can hold. Larger sizes may slightly improve compression, but
  166104. * 1000 is already well into the realm of overkill.
  166105. * The minimum safe size is 64 bits.
  166106. */
  166107. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  166108. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  166109. * We assume that int right shift is unsigned if INT32 right shift is,
  166110. * which should be safe.
  166111. */
  166112. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  166113. #define ISHIFT_TEMPS int ishift_temp;
  166114. #define IRIGHT_SHIFT(x,shft) \
  166115. ((ishift_temp = (x)) < 0 ? \
  166116. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  166117. (ishift_temp >> (shft)))
  166118. #else
  166119. #define ISHIFT_TEMPS
  166120. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  166121. #endif
  166122. /* Forward declarations */
  166123. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166124. JBLOCKROW *MCU_data));
  166125. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166126. JBLOCKROW *MCU_data));
  166127. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166128. JBLOCKROW *MCU_data));
  166129. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166130. JBLOCKROW *MCU_data));
  166131. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166132. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166133. /*
  166134. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166135. */
  166136. METHODDEF(void)
  166137. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166138. {
  166139. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166140. boolean is_DC_band;
  166141. int ci, tbl;
  166142. jpeg_component_info * compptr;
  166143. entropy->cinfo = cinfo;
  166144. entropy->gather_statistics = gather_statistics;
  166145. is_DC_band = (cinfo->Ss == 0);
  166146. /* We assume jcmaster.c already validated the scan parameters. */
  166147. /* Select execution routines */
  166148. if (cinfo->Ah == 0) {
  166149. if (is_DC_band)
  166150. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166151. else
  166152. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166153. } else {
  166154. if (is_DC_band)
  166155. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166156. else {
  166157. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166158. /* AC refinement needs a correction bit buffer */
  166159. if (entropy->bit_buffer == NULL)
  166160. entropy->bit_buffer = (char *)
  166161. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166162. MAX_CORR_BITS * SIZEOF(char));
  166163. }
  166164. }
  166165. if (gather_statistics)
  166166. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166167. else
  166168. entropy->pub.finish_pass = finish_pass_phuff;
  166169. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166170. * for AC coefficients.
  166171. */
  166172. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166173. compptr = cinfo->cur_comp_info[ci];
  166174. /* Initialize DC predictions to 0 */
  166175. entropy->last_dc_val[ci] = 0;
  166176. /* Get table index */
  166177. if (is_DC_band) {
  166178. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166179. continue;
  166180. tbl = compptr->dc_tbl_no;
  166181. } else {
  166182. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166183. }
  166184. if (gather_statistics) {
  166185. /* Check for invalid table index */
  166186. /* (make_c_derived_tbl does this in the other path) */
  166187. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166188. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166189. /* Allocate and zero the statistics tables */
  166190. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166191. if (entropy->count_ptrs[tbl] == NULL)
  166192. entropy->count_ptrs[tbl] = (long *)
  166193. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166194. 257 * SIZEOF(long));
  166195. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166196. } else {
  166197. /* Compute derived values for Huffman table */
  166198. /* We may do this more than once for a table, but it's not expensive */
  166199. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166200. & entropy->derived_tbls[tbl]);
  166201. }
  166202. }
  166203. /* Initialize AC stuff */
  166204. entropy->EOBRUN = 0;
  166205. entropy->BE = 0;
  166206. /* Initialize bit buffer to empty */
  166207. entropy->put_buffer = 0;
  166208. entropy->put_bits = 0;
  166209. /* Initialize restart stuff */
  166210. entropy->restarts_to_go = cinfo->restart_interval;
  166211. entropy->next_restart_num = 0;
  166212. }
  166213. /* Outputting bytes to the file.
  166214. * NB: these must be called only when actually outputting,
  166215. * that is, entropy->gather_statistics == FALSE.
  166216. */
  166217. /* Emit a byte */
  166218. #define emit_byte(entropy,val) \
  166219. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166220. if (--(entropy)->free_in_buffer == 0) \
  166221. dump_buffer_p(entropy); }
  166222. LOCAL(void)
  166223. dump_buffer_p (phuff_entropy_ptr entropy)
  166224. /* Empty the output buffer; we do not support suspension in this module. */
  166225. {
  166226. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166227. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166228. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166229. /* After a successful buffer dump, must reset buffer pointers */
  166230. entropy->next_output_byte = dest->next_output_byte;
  166231. entropy->free_in_buffer = dest->free_in_buffer;
  166232. }
  166233. /* Outputting bits to the file */
  166234. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166235. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166236. * in one call, and we never retain more than 7 bits in put_buffer
  166237. * between calls, so 24 bits are sufficient.
  166238. */
  166239. INLINE
  166240. LOCAL(void)
  166241. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166242. /* Emit some bits, unless we are in gather mode */
  166243. {
  166244. /* This routine is heavily used, so it's worth coding tightly. */
  166245. register INT32 put_buffer = (INT32) code;
  166246. register int put_bits = entropy->put_bits;
  166247. /* if size is 0, caller used an invalid Huffman table entry */
  166248. if (size == 0)
  166249. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166250. if (entropy->gather_statistics)
  166251. return; /* do nothing if we're only getting stats */
  166252. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166253. put_bits += size; /* new number of bits in buffer */
  166254. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166255. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166256. while (put_bits >= 8) {
  166257. int c = (int) ((put_buffer >> 16) & 0xFF);
  166258. emit_byte(entropy, c);
  166259. if (c == 0xFF) { /* need to stuff a zero byte? */
  166260. emit_byte(entropy, 0);
  166261. }
  166262. put_buffer <<= 8;
  166263. put_bits -= 8;
  166264. }
  166265. entropy->put_buffer = put_buffer; /* update variables */
  166266. entropy->put_bits = put_bits;
  166267. }
  166268. LOCAL(void)
  166269. flush_bits_p (phuff_entropy_ptr entropy)
  166270. {
  166271. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166272. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166273. entropy->put_bits = 0;
  166274. }
  166275. /*
  166276. * Emit (or just count) a Huffman symbol.
  166277. */
  166278. INLINE
  166279. LOCAL(void)
  166280. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166281. {
  166282. if (entropy->gather_statistics)
  166283. entropy->count_ptrs[tbl_no][symbol]++;
  166284. else {
  166285. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166286. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166287. }
  166288. }
  166289. /*
  166290. * Emit bits from a correction bit buffer.
  166291. */
  166292. LOCAL(void)
  166293. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166294. unsigned int nbits)
  166295. {
  166296. if (entropy->gather_statistics)
  166297. return; /* no real work */
  166298. while (nbits > 0) {
  166299. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166300. bufstart++;
  166301. nbits--;
  166302. }
  166303. }
  166304. /*
  166305. * Emit any pending EOBRUN symbol.
  166306. */
  166307. LOCAL(void)
  166308. emit_eobrun (phuff_entropy_ptr entropy)
  166309. {
  166310. register int temp, nbits;
  166311. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166312. temp = entropy->EOBRUN;
  166313. nbits = 0;
  166314. while ((temp >>= 1))
  166315. nbits++;
  166316. /* safety check: shouldn't happen given limited correction-bit buffer */
  166317. if (nbits > 14)
  166318. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166319. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166320. if (nbits)
  166321. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166322. entropy->EOBRUN = 0;
  166323. /* Emit any buffered correction bits */
  166324. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166325. entropy->BE = 0;
  166326. }
  166327. }
  166328. /*
  166329. * Emit a restart marker & resynchronize predictions.
  166330. */
  166331. LOCAL(void)
  166332. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166333. {
  166334. int ci;
  166335. emit_eobrun(entropy);
  166336. if (! entropy->gather_statistics) {
  166337. flush_bits_p(entropy);
  166338. emit_byte(entropy, 0xFF);
  166339. emit_byte(entropy, JPEG_RST0 + restart_num);
  166340. }
  166341. if (entropy->cinfo->Ss == 0) {
  166342. /* Re-initialize DC predictions to 0 */
  166343. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166344. entropy->last_dc_val[ci] = 0;
  166345. } else {
  166346. /* Re-initialize all AC-related fields to 0 */
  166347. entropy->EOBRUN = 0;
  166348. entropy->BE = 0;
  166349. }
  166350. }
  166351. /*
  166352. * MCU encoding for DC initial scan (either spectral selection,
  166353. * or first pass of successive approximation).
  166354. */
  166355. METHODDEF(boolean)
  166356. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166357. {
  166358. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166359. register int temp, temp2;
  166360. register int nbits;
  166361. int blkn, ci;
  166362. int Al = cinfo->Al;
  166363. JBLOCKROW block;
  166364. jpeg_component_info * compptr;
  166365. ISHIFT_TEMPS
  166366. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166367. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166368. /* Emit restart marker if needed */
  166369. if (cinfo->restart_interval)
  166370. if (entropy->restarts_to_go == 0)
  166371. emit_restart_p(entropy, entropy->next_restart_num);
  166372. /* Encode the MCU data blocks */
  166373. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166374. block = MCU_data[blkn];
  166375. ci = cinfo->MCU_membership[blkn];
  166376. compptr = cinfo->cur_comp_info[ci];
  166377. /* Compute the DC value after the required point transform by Al.
  166378. * This is simply an arithmetic right shift.
  166379. */
  166380. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166381. /* DC differences are figured on the point-transformed values. */
  166382. temp = temp2 - entropy->last_dc_val[ci];
  166383. entropy->last_dc_val[ci] = temp2;
  166384. /* Encode the DC coefficient difference per section G.1.2.1 */
  166385. temp2 = temp;
  166386. if (temp < 0) {
  166387. temp = -temp; /* temp is abs value of input */
  166388. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166389. /* This code assumes we are on a two's complement machine */
  166390. temp2--;
  166391. }
  166392. /* Find the number of bits needed for the magnitude of the coefficient */
  166393. nbits = 0;
  166394. while (temp) {
  166395. nbits++;
  166396. temp >>= 1;
  166397. }
  166398. /* Check for out-of-range coefficient values.
  166399. * Since we're encoding a difference, the range limit is twice as much.
  166400. */
  166401. if (nbits > MAX_COEF_BITS+1)
  166402. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166403. /* Count/emit the Huffman-coded symbol for the number of bits */
  166404. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166405. /* Emit that number of bits of the value, if positive, */
  166406. /* or the complement of its magnitude, if negative. */
  166407. if (nbits) /* emit_bits rejects calls with size 0 */
  166408. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166409. }
  166410. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166411. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166412. /* Update restart-interval state too */
  166413. if (cinfo->restart_interval) {
  166414. if (entropy->restarts_to_go == 0) {
  166415. entropy->restarts_to_go = cinfo->restart_interval;
  166416. entropy->next_restart_num++;
  166417. entropy->next_restart_num &= 7;
  166418. }
  166419. entropy->restarts_to_go--;
  166420. }
  166421. return TRUE;
  166422. }
  166423. /*
  166424. * MCU encoding for AC initial scan (either spectral selection,
  166425. * or first pass of successive approximation).
  166426. */
  166427. METHODDEF(boolean)
  166428. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166429. {
  166430. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166431. register int temp, temp2;
  166432. register int nbits;
  166433. register int r, k;
  166434. int Se = cinfo->Se;
  166435. int Al = cinfo->Al;
  166436. JBLOCKROW block;
  166437. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166438. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166439. /* Emit restart marker if needed */
  166440. if (cinfo->restart_interval)
  166441. if (entropy->restarts_to_go == 0)
  166442. emit_restart_p(entropy, entropy->next_restart_num);
  166443. /* Encode the MCU data block */
  166444. block = MCU_data[0];
  166445. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166446. r = 0; /* r = run length of zeros */
  166447. for (k = cinfo->Ss; k <= Se; k++) {
  166448. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166449. r++;
  166450. continue;
  166451. }
  166452. /* We must apply the point transform by Al. For AC coefficients this
  166453. * is an integer division with rounding towards 0. To do this portably
  166454. * in C, we shift after obtaining the absolute value; so the code is
  166455. * interwoven with finding the abs value (temp) and output bits (temp2).
  166456. */
  166457. if (temp < 0) {
  166458. temp = -temp; /* temp is abs value of input */
  166459. temp >>= Al; /* apply the point transform */
  166460. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166461. temp2 = ~temp;
  166462. } else {
  166463. temp >>= Al; /* apply the point transform */
  166464. temp2 = temp;
  166465. }
  166466. /* Watch out for case that nonzero coef is zero after point transform */
  166467. if (temp == 0) {
  166468. r++;
  166469. continue;
  166470. }
  166471. /* Emit any pending EOBRUN */
  166472. if (entropy->EOBRUN > 0)
  166473. emit_eobrun(entropy);
  166474. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166475. while (r > 15) {
  166476. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166477. r -= 16;
  166478. }
  166479. /* Find the number of bits needed for the magnitude of the coefficient */
  166480. nbits = 1; /* there must be at least one 1 bit */
  166481. while ((temp >>= 1))
  166482. nbits++;
  166483. /* Check for out-of-range coefficient values */
  166484. if (nbits > MAX_COEF_BITS)
  166485. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166486. /* Count/emit Huffman symbol for run length / number of bits */
  166487. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166488. /* Emit that number of bits of the value, if positive, */
  166489. /* or the complement of its magnitude, if negative. */
  166490. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166491. r = 0; /* reset zero run length */
  166492. }
  166493. if (r > 0) { /* If there are trailing zeroes, */
  166494. entropy->EOBRUN++; /* count an EOB */
  166495. if (entropy->EOBRUN == 0x7FFF)
  166496. emit_eobrun(entropy); /* force it out to avoid overflow */
  166497. }
  166498. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166499. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166500. /* Update restart-interval state too */
  166501. if (cinfo->restart_interval) {
  166502. if (entropy->restarts_to_go == 0) {
  166503. entropy->restarts_to_go = cinfo->restart_interval;
  166504. entropy->next_restart_num++;
  166505. entropy->next_restart_num &= 7;
  166506. }
  166507. entropy->restarts_to_go--;
  166508. }
  166509. return TRUE;
  166510. }
  166511. /*
  166512. * MCU encoding for DC successive approximation refinement scan.
  166513. * Note: we assume such scans can be multi-component, although the spec
  166514. * is not very clear on the point.
  166515. */
  166516. METHODDEF(boolean)
  166517. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166518. {
  166519. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166520. register int temp;
  166521. int blkn;
  166522. int Al = cinfo->Al;
  166523. JBLOCKROW block;
  166524. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166525. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166526. /* Emit restart marker if needed */
  166527. if (cinfo->restart_interval)
  166528. if (entropy->restarts_to_go == 0)
  166529. emit_restart_p(entropy, entropy->next_restart_num);
  166530. /* Encode the MCU data blocks */
  166531. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166532. block = MCU_data[blkn];
  166533. /* We simply emit the Al'th bit of the DC coefficient value. */
  166534. temp = (*block)[0];
  166535. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166536. }
  166537. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166538. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166539. /* Update restart-interval state too */
  166540. if (cinfo->restart_interval) {
  166541. if (entropy->restarts_to_go == 0) {
  166542. entropy->restarts_to_go = cinfo->restart_interval;
  166543. entropy->next_restart_num++;
  166544. entropy->next_restart_num &= 7;
  166545. }
  166546. entropy->restarts_to_go--;
  166547. }
  166548. return TRUE;
  166549. }
  166550. /*
  166551. * MCU encoding for AC successive approximation refinement scan.
  166552. */
  166553. METHODDEF(boolean)
  166554. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166555. {
  166556. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166557. register int temp;
  166558. register int r, k;
  166559. int EOB;
  166560. char *BR_buffer;
  166561. unsigned int BR;
  166562. int Se = cinfo->Se;
  166563. int Al = cinfo->Al;
  166564. JBLOCKROW block;
  166565. int absvalues[DCTSIZE2];
  166566. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166567. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166568. /* Emit restart marker if needed */
  166569. if (cinfo->restart_interval)
  166570. if (entropy->restarts_to_go == 0)
  166571. emit_restart_p(entropy, entropy->next_restart_num);
  166572. /* Encode the MCU data block */
  166573. block = MCU_data[0];
  166574. /* It is convenient to make a pre-pass to determine the transformed
  166575. * coefficients' absolute values and the EOB position.
  166576. */
  166577. EOB = 0;
  166578. for (k = cinfo->Ss; k <= Se; k++) {
  166579. temp = (*block)[jpeg_natural_order[k]];
  166580. /* We must apply the point transform by Al. For AC coefficients this
  166581. * is an integer division with rounding towards 0. To do this portably
  166582. * in C, we shift after obtaining the absolute value.
  166583. */
  166584. if (temp < 0)
  166585. temp = -temp; /* temp is abs value of input */
  166586. temp >>= Al; /* apply the point transform */
  166587. absvalues[k] = temp; /* save abs value for main pass */
  166588. if (temp == 1)
  166589. EOB = k; /* EOB = index of last newly-nonzero coef */
  166590. }
  166591. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166592. r = 0; /* r = run length of zeros */
  166593. BR = 0; /* BR = count of buffered bits added now */
  166594. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166595. for (k = cinfo->Ss; k <= Se; k++) {
  166596. if ((temp = absvalues[k]) == 0) {
  166597. r++;
  166598. continue;
  166599. }
  166600. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166601. while (r > 15 && k <= EOB) {
  166602. /* emit any pending EOBRUN and the BE correction bits */
  166603. emit_eobrun(entropy);
  166604. /* Emit ZRL */
  166605. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166606. r -= 16;
  166607. /* Emit buffered correction bits that must be associated with ZRL */
  166608. emit_buffered_bits(entropy, BR_buffer, BR);
  166609. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166610. BR = 0;
  166611. }
  166612. /* If the coef was previously nonzero, it only needs a correction bit.
  166613. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166614. * that we also need to test r > 15. But if r > 15, we can only get here
  166615. * if k > EOB, which implies that this coefficient is not 1.
  166616. */
  166617. if (temp > 1) {
  166618. /* The correction bit is the next bit of the absolute value. */
  166619. BR_buffer[BR++] = (char) (temp & 1);
  166620. continue;
  166621. }
  166622. /* Emit any pending EOBRUN and the BE correction bits */
  166623. emit_eobrun(entropy);
  166624. /* Count/emit Huffman symbol for run length / number of bits */
  166625. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166626. /* Emit output bit for newly-nonzero coef */
  166627. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166628. emit_bits_p(entropy, (unsigned int) temp, 1);
  166629. /* Emit buffered correction bits that must be associated with this code */
  166630. emit_buffered_bits(entropy, BR_buffer, BR);
  166631. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166632. BR = 0;
  166633. r = 0; /* reset zero run length */
  166634. }
  166635. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166636. entropy->EOBRUN++; /* count an EOB */
  166637. entropy->BE += BR; /* concat my correction bits to older ones */
  166638. /* We force out the EOB if we risk either:
  166639. * 1. overflow of the EOB counter;
  166640. * 2. overflow of the correction bit buffer during the next MCU.
  166641. */
  166642. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166643. emit_eobrun(entropy);
  166644. }
  166645. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166646. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166647. /* Update restart-interval state too */
  166648. if (cinfo->restart_interval) {
  166649. if (entropy->restarts_to_go == 0) {
  166650. entropy->restarts_to_go = cinfo->restart_interval;
  166651. entropy->next_restart_num++;
  166652. entropy->next_restart_num &= 7;
  166653. }
  166654. entropy->restarts_to_go--;
  166655. }
  166656. return TRUE;
  166657. }
  166658. /*
  166659. * Finish up at the end of a Huffman-compressed progressive scan.
  166660. */
  166661. METHODDEF(void)
  166662. finish_pass_phuff (j_compress_ptr cinfo)
  166663. {
  166664. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166665. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166666. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166667. /* Flush out any buffered data */
  166668. emit_eobrun(entropy);
  166669. flush_bits_p(entropy);
  166670. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166671. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166672. }
  166673. /*
  166674. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166675. */
  166676. METHODDEF(void)
  166677. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166678. {
  166679. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166680. boolean is_DC_band;
  166681. int ci, tbl;
  166682. jpeg_component_info * compptr;
  166683. JHUFF_TBL **htblptr;
  166684. boolean did[NUM_HUFF_TBLS];
  166685. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166686. emit_eobrun(entropy);
  166687. is_DC_band = (cinfo->Ss == 0);
  166688. /* It's important not to apply jpeg_gen_optimal_table more than once
  166689. * per table, because it clobbers the input frequency counts!
  166690. */
  166691. MEMZERO(did, SIZEOF(did));
  166692. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166693. compptr = cinfo->cur_comp_info[ci];
  166694. if (is_DC_band) {
  166695. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166696. continue;
  166697. tbl = compptr->dc_tbl_no;
  166698. } else {
  166699. tbl = compptr->ac_tbl_no;
  166700. }
  166701. if (! did[tbl]) {
  166702. if (is_DC_band)
  166703. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166704. else
  166705. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166706. if (*htblptr == NULL)
  166707. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166708. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166709. did[tbl] = TRUE;
  166710. }
  166711. }
  166712. }
  166713. /*
  166714. * Module initialization routine for progressive Huffman entropy encoding.
  166715. */
  166716. GLOBAL(void)
  166717. jinit_phuff_encoder (j_compress_ptr cinfo)
  166718. {
  166719. phuff_entropy_ptr entropy;
  166720. int i;
  166721. entropy = (phuff_entropy_ptr)
  166722. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166723. SIZEOF(phuff_entropy_encoder));
  166724. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166725. entropy->pub.start_pass = start_pass_phuff;
  166726. /* Mark tables unallocated */
  166727. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166728. entropy->derived_tbls[i] = NULL;
  166729. entropy->count_ptrs[i] = NULL;
  166730. }
  166731. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166732. }
  166733. #endif /* C_PROGRESSIVE_SUPPORTED */
  166734. /*** End of inlined file: jcphuff.c ***/
  166735. /*** Start of inlined file: jcprepct.c ***/
  166736. #define JPEG_INTERNALS
  166737. /* At present, jcsample.c can request context rows only for smoothing.
  166738. * In the future, we might also need context rows for CCIR601 sampling
  166739. * or other more-complex downsampling procedures. The code to support
  166740. * context rows should be compiled only if needed.
  166741. */
  166742. #ifdef INPUT_SMOOTHING_SUPPORTED
  166743. #define CONTEXT_ROWS_SUPPORTED
  166744. #endif
  166745. /*
  166746. * For the simple (no-context-row) case, we just need to buffer one
  166747. * row group's worth of pixels for the downsampling step. At the bottom of
  166748. * the image, we pad to a full row group by replicating the last pixel row.
  166749. * The downsampler's last output row is then replicated if needed to pad
  166750. * out to a full iMCU row.
  166751. *
  166752. * When providing context rows, we must buffer three row groups' worth of
  166753. * pixels. Three row groups are physically allocated, but the row pointer
  166754. * arrays are made five row groups high, with the extra pointers above and
  166755. * below "wrapping around" to point to the last and first real row groups.
  166756. * This allows the downsampler to access the proper context rows.
  166757. * At the top and bottom of the image, we create dummy context rows by
  166758. * copying the first or last real pixel row. This copying could be avoided
  166759. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166760. * trouble on the compression side.
  166761. */
  166762. /* Private buffer controller object */
  166763. typedef struct {
  166764. struct jpeg_c_prep_controller pub; /* public fields */
  166765. /* Downsampling input buffer. This buffer holds color-converted data
  166766. * until we have enough to do a downsample step.
  166767. */
  166768. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166769. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166770. int next_buf_row; /* index of next row to store in color_buf */
  166771. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166772. int this_row_group; /* starting row index of group to process */
  166773. int next_buf_stop; /* downsample when we reach this index */
  166774. #endif
  166775. } my_prep_controller;
  166776. typedef my_prep_controller * my_prep_ptr;
  166777. /*
  166778. * Initialize for a processing pass.
  166779. */
  166780. METHODDEF(void)
  166781. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166782. {
  166783. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166784. if (pass_mode != JBUF_PASS_THRU)
  166785. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166786. /* Initialize total-height counter for detecting bottom of image */
  166787. prep->rows_to_go = cinfo->image_height;
  166788. /* Mark the conversion buffer empty */
  166789. prep->next_buf_row = 0;
  166790. #ifdef CONTEXT_ROWS_SUPPORTED
  166791. /* Preset additional state variables for context mode.
  166792. * These aren't used in non-context mode, so we needn't test which mode.
  166793. */
  166794. prep->this_row_group = 0;
  166795. /* Set next_buf_stop to stop after two row groups have been read in. */
  166796. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166797. #endif
  166798. }
  166799. /*
  166800. * Expand an image vertically from height input_rows to height output_rows,
  166801. * by duplicating the bottom row.
  166802. */
  166803. LOCAL(void)
  166804. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166805. int input_rows, int output_rows)
  166806. {
  166807. register int row;
  166808. for (row = input_rows; row < output_rows; row++) {
  166809. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166810. 1, num_cols);
  166811. }
  166812. }
  166813. /*
  166814. * Process some data in the simple no-context case.
  166815. *
  166816. * Preprocessor output data is counted in "row groups". A row group
  166817. * is defined to be v_samp_factor sample rows of each component.
  166818. * Downsampling will produce this much data from each max_v_samp_factor
  166819. * input rows.
  166820. */
  166821. METHODDEF(void)
  166822. pre_process_data (j_compress_ptr cinfo,
  166823. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166824. JDIMENSION in_rows_avail,
  166825. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166826. JDIMENSION out_row_groups_avail)
  166827. {
  166828. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166829. int numrows, ci;
  166830. JDIMENSION inrows;
  166831. jpeg_component_info * compptr;
  166832. while (*in_row_ctr < in_rows_avail &&
  166833. *out_row_group_ctr < out_row_groups_avail) {
  166834. /* Do color conversion to fill the conversion buffer. */
  166835. inrows = in_rows_avail - *in_row_ctr;
  166836. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166837. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166838. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166839. prep->color_buf,
  166840. (JDIMENSION) prep->next_buf_row,
  166841. numrows);
  166842. *in_row_ctr += numrows;
  166843. prep->next_buf_row += numrows;
  166844. prep->rows_to_go -= numrows;
  166845. /* If at bottom of image, pad to fill the conversion buffer. */
  166846. if (prep->rows_to_go == 0 &&
  166847. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166848. for (ci = 0; ci < cinfo->num_components; ci++) {
  166849. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166850. prep->next_buf_row, cinfo->max_v_samp_factor);
  166851. }
  166852. prep->next_buf_row = cinfo->max_v_samp_factor;
  166853. }
  166854. /* If we've filled the conversion buffer, empty it. */
  166855. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166856. (*cinfo->downsample->downsample) (cinfo,
  166857. prep->color_buf, (JDIMENSION) 0,
  166858. output_buf, *out_row_group_ctr);
  166859. prep->next_buf_row = 0;
  166860. (*out_row_group_ctr)++;
  166861. }
  166862. /* If at bottom of image, pad the output to a full iMCU height.
  166863. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166864. */
  166865. if (prep->rows_to_go == 0 &&
  166866. *out_row_group_ctr < out_row_groups_avail) {
  166867. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166868. ci++, compptr++) {
  166869. expand_bottom_edge(output_buf[ci],
  166870. compptr->width_in_blocks * DCTSIZE,
  166871. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166872. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166873. }
  166874. *out_row_group_ctr = out_row_groups_avail;
  166875. break; /* can exit outer loop without test */
  166876. }
  166877. }
  166878. }
  166879. #ifdef CONTEXT_ROWS_SUPPORTED
  166880. /*
  166881. * Process some data in the context case.
  166882. */
  166883. METHODDEF(void)
  166884. pre_process_context (j_compress_ptr cinfo,
  166885. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166886. JDIMENSION in_rows_avail,
  166887. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166888. JDIMENSION out_row_groups_avail)
  166889. {
  166890. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166891. int numrows, ci;
  166892. int buf_height = cinfo->max_v_samp_factor * 3;
  166893. JDIMENSION inrows;
  166894. while (*out_row_group_ctr < out_row_groups_avail) {
  166895. if (*in_row_ctr < in_rows_avail) {
  166896. /* Do color conversion to fill the conversion buffer. */
  166897. inrows = in_rows_avail - *in_row_ctr;
  166898. numrows = prep->next_buf_stop - prep->next_buf_row;
  166899. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166900. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166901. prep->color_buf,
  166902. (JDIMENSION) prep->next_buf_row,
  166903. numrows);
  166904. /* Pad at top of image, if first time through */
  166905. if (prep->rows_to_go == cinfo->image_height) {
  166906. for (ci = 0; ci < cinfo->num_components; ci++) {
  166907. int row;
  166908. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166909. jcopy_sample_rows(prep->color_buf[ci], 0,
  166910. prep->color_buf[ci], -row,
  166911. 1, cinfo->image_width);
  166912. }
  166913. }
  166914. }
  166915. *in_row_ctr += numrows;
  166916. prep->next_buf_row += numrows;
  166917. prep->rows_to_go -= numrows;
  166918. } else {
  166919. /* Return for more data, unless we are at the bottom of the image. */
  166920. if (prep->rows_to_go != 0)
  166921. break;
  166922. /* When at bottom of image, pad to fill the conversion buffer. */
  166923. if (prep->next_buf_row < prep->next_buf_stop) {
  166924. for (ci = 0; ci < cinfo->num_components; ci++) {
  166925. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166926. prep->next_buf_row, prep->next_buf_stop);
  166927. }
  166928. prep->next_buf_row = prep->next_buf_stop;
  166929. }
  166930. }
  166931. /* If we've gotten enough data, downsample a row group. */
  166932. if (prep->next_buf_row == prep->next_buf_stop) {
  166933. (*cinfo->downsample->downsample) (cinfo,
  166934. prep->color_buf,
  166935. (JDIMENSION) prep->this_row_group,
  166936. output_buf, *out_row_group_ctr);
  166937. (*out_row_group_ctr)++;
  166938. /* Advance pointers with wraparound as necessary. */
  166939. prep->this_row_group += cinfo->max_v_samp_factor;
  166940. if (prep->this_row_group >= buf_height)
  166941. prep->this_row_group = 0;
  166942. if (prep->next_buf_row >= buf_height)
  166943. prep->next_buf_row = 0;
  166944. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166945. }
  166946. }
  166947. }
  166948. /*
  166949. * Create the wrapped-around downsampling input buffer needed for context mode.
  166950. */
  166951. LOCAL(void)
  166952. create_context_buffer (j_compress_ptr cinfo)
  166953. {
  166954. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166955. int rgroup_height = cinfo->max_v_samp_factor;
  166956. int ci, i;
  166957. jpeg_component_info * compptr;
  166958. JSAMPARRAY true_buffer, fake_buffer;
  166959. /* Grab enough space for fake row pointers for all the components;
  166960. * we need five row groups' worth of pointers for each component.
  166961. */
  166962. fake_buffer = (JSAMPARRAY)
  166963. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166964. (cinfo->num_components * 5 * rgroup_height) *
  166965. SIZEOF(JSAMPROW));
  166966. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166967. ci++, compptr++) {
  166968. /* Allocate the actual buffer space (3 row groups) for this component.
  166969. * We make the buffer wide enough to allow the downsampler to edge-expand
  166970. * horizontally within the buffer, if it so chooses.
  166971. */
  166972. true_buffer = (*cinfo->mem->alloc_sarray)
  166973. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166974. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166975. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166976. (JDIMENSION) (3 * rgroup_height));
  166977. /* Copy true buffer row pointers into the middle of the fake row array */
  166978. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166979. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166980. /* Fill in the above and below wraparound pointers */
  166981. for (i = 0; i < rgroup_height; i++) {
  166982. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166983. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166984. }
  166985. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166986. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166987. }
  166988. }
  166989. #endif /* CONTEXT_ROWS_SUPPORTED */
  166990. /*
  166991. * Initialize preprocessing controller.
  166992. */
  166993. GLOBAL(void)
  166994. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166995. {
  166996. my_prep_ptr prep;
  166997. int ci;
  166998. jpeg_component_info * compptr;
  166999. if (need_full_buffer) /* safety check */
  167000. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167001. prep = (my_prep_ptr)
  167002. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167003. SIZEOF(my_prep_controller));
  167004. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  167005. prep->pub.start_pass = start_pass_prep;
  167006. /* Allocate the color conversion buffer.
  167007. * We make the buffer wide enough to allow the downsampler to edge-expand
  167008. * horizontally within the buffer, if it so chooses.
  167009. */
  167010. if (cinfo->downsample->need_context_rows) {
  167011. /* Set up to provide context rows */
  167012. #ifdef CONTEXT_ROWS_SUPPORTED
  167013. prep->pub.pre_process_data = pre_process_context;
  167014. create_context_buffer(cinfo);
  167015. #else
  167016. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167017. #endif
  167018. } else {
  167019. /* No context, just make it tall enough for one row group */
  167020. prep->pub.pre_process_data = pre_process_data;
  167021. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167022. ci++, compptr++) {
  167023. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  167024. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167025. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  167026. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  167027. (JDIMENSION) cinfo->max_v_samp_factor);
  167028. }
  167029. }
  167030. }
  167031. /*** End of inlined file: jcprepct.c ***/
  167032. /*** Start of inlined file: jcsample.c ***/
  167033. #define JPEG_INTERNALS
  167034. /* Pointer to routine to downsample a single component */
  167035. typedef JMETHOD(void, downsample1_ptr,
  167036. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167037. JSAMPARRAY input_data, JSAMPARRAY output_data));
  167038. /* Private subobject */
  167039. typedef struct {
  167040. struct jpeg_downsampler pub; /* public fields */
  167041. /* Downsampling method pointers, one per component */
  167042. downsample1_ptr methods[MAX_COMPONENTS];
  167043. } my_downsampler;
  167044. typedef my_downsampler * my_downsample_ptr;
  167045. /*
  167046. * Initialize for a downsampling pass.
  167047. */
  167048. METHODDEF(void)
  167049. start_pass_downsample (j_compress_ptr)
  167050. {
  167051. /* no work for now */
  167052. }
  167053. /*
  167054. * Expand a component horizontally from width input_cols to width output_cols,
  167055. * by duplicating the rightmost samples.
  167056. */
  167057. LOCAL(void)
  167058. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  167059. JDIMENSION input_cols, JDIMENSION output_cols)
  167060. {
  167061. register JSAMPROW ptr;
  167062. register JSAMPLE pixval;
  167063. register int count;
  167064. int row;
  167065. int numcols = (int) (output_cols - input_cols);
  167066. if (numcols > 0) {
  167067. for (row = 0; row < num_rows; row++) {
  167068. ptr = image_data[row] + input_cols;
  167069. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  167070. for (count = numcols; count > 0; count--)
  167071. *ptr++ = pixval;
  167072. }
  167073. }
  167074. }
  167075. /*
  167076. * Do downsampling for a whole row group (all components).
  167077. *
  167078. * In this version we simply downsample each component independently.
  167079. */
  167080. METHODDEF(void)
  167081. sep_downsample (j_compress_ptr cinfo,
  167082. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  167083. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  167084. {
  167085. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  167086. int ci;
  167087. jpeg_component_info * compptr;
  167088. JSAMPARRAY in_ptr, out_ptr;
  167089. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167090. ci++, compptr++) {
  167091. in_ptr = input_buf[ci] + in_row_index;
  167092. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  167093. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  167094. }
  167095. }
  167096. /*
  167097. * Downsample pixel values of a single component.
  167098. * One row group is processed per call.
  167099. * This version handles arbitrary integral sampling ratios, without smoothing.
  167100. * Note that this version is not actually used for customary sampling ratios.
  167101. */
  167102. METHODDEF(void)
  167103. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167104. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167105. {
  167106. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  167107. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  167108. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167109. JSAMPROW inptr, outptr;
  167110. INT32 outvalue;
  167111. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  167112. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  167113. numpix = h_expand * v_expand;
  167114. numpix2 = numpix/2;
  167115. /* Expand input data enough to let all the output samples be generated
  167116. * by the standard loop. Special-casing padded output would be more
  167117. * efficient.
  167118. */
  167119. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167120. cinfo->image_width, output_cols * h_expand);
  167121. inrow = 0;
  167122. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167123. outptr = output_data[outrow];
  167124. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167125. outcol++, outcol_h += h_expand) {
  167126. outvalue = 0;
  167127. for (v = 0; v < v_expand; v++) {
  167128. inptr = input_data[inrow+v] + outcol_h;
  167129. for (h = 0; h < h_expand; h++) {
  167130. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167131. }
  167132. }
  167133. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167134. }
  167135. inrow += v_expand;
  167136. }
  167137. }
  167138. /*
  167139. * Downsample pixel values of a single component.
  167140. * This version handles the special case of a full-size component,
  167141. * without smoothing.
  167142. */
  167143. METHODDEF(void)
  167144. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167145. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167146. {
  167147. /* Copy the data */
  167148. jcopy_sample_rows(input_data, 0, output_data, 0,
  167149. cinfo->max_v_samp_factor, cinfo->image_width);
  167150. /* Edge-expand */
  167151. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167152. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167153. }
  167154. /*
  167155. * Downsample pixel values of a single component.
  167156. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167157. * without smoothing.
  167158. *
  167159. * A note about the "bias" calculations: when rounding fractional values to
  167160. * integer, we do not want to always round 0.5 up to the next integer.
  167161. * If we did that, we'd introduce a noticeable bias towards larger values.
  167162. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167163. * alternate pixel locations (a simple ordered dither pattern).
  167164. */
  167165. METHODDEF(void)
  167166. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167167. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167168. {
  167169. int outrow;
  167170. JDIMENSION outcol;
  167171. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167172. register JSAMPROW inptr, outptr;
  167173. register int bias;
  167174. /* Expand input data enough to let all the output samples be generated
  167175. * by the standard loop. Special-casing padded output would be more
  167176. * efficient.
  167177. */
  167178. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167179. cinfo->image_width, output_cols * 2);
  167180. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167181. outptr = output_data[outrow];
  167182. inptr = input_data[outrow];
  167183. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167184. for (outcol = 0; outcol < output_cols; outcol++) {
  167185. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167186. + bias) >> 1);
  167187. bias ^= 1; /* 0=>1, 1=>0 */
  167188. inptr += 2;
  167189. }
  167190. }
  167191. }
  167192. /*
  167193. * Downsample pixel values of a single component.
  167194. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167195. * without smoothing.
  167196. */
  167197. METHODDEF(void)
  167198. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167199. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167200. {
  167201. int inrow, outrow;
  167202. JDIMENSION outcol;
  167203. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167204. register JSAMPROW inptr0, inptr1, outptr;
  167205. register int bias;
  167206. /* Expand input data enough to let all the output samples be generated
  167207. * by the standard loop. Special-casing padded output would be more
  167208. * efficient.
  167209. */
  167210. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167211. cinfo->image_width, output_cols * 2);
  167212. inrow = 0;
  167213. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167214. outptr = output_data[outrow];
  167215. inptr0 = input_data[inrow];
  167216. inptr1 = input_data[inrow+1];
  167217. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167218. for (outcol = 0; outcol < output_cols; outcol++) {
  167219. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167220. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167221. + bias) >> 2);
  167222. bias ^= 3; /* 1=>2, 2=>1 */
  167223. inptr0 += 2; inptr1 += 2;
  167224. }
  167225. inrow += 2;
  167226. }
  167227. }
  167228. #ifdef INPUT_SMOOTHING_SUPPORTED
  167229. /*
  167230. * Downsample pixel values of a single component.
  167231. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167232. * with smoothing. One row of context is required.
  167233. */
  167234. METHODDEF(void)
  167235. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167236. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167237. {
  167238. int inrow, outrow;
  167239. JDIMENSION colctr;
  167240. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167241. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167242. INT32 membersum, neighsum, memberscale, neighscale;
  167243. /* Expand input data enough to let all the output samples be generated
  167244. * by the standard loop. Special-casing padded output would be more
  167245. * efficient.
  167246. */
  167247. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167248. cinfo->image_width, output_cols * 2);
  167249. /* We don't bother to form the individual "smoothed" input pixel values;
  167250. * we can directly compute the output which is the average of the four
  167251. * smoothed values. Each of the four member pixels contributes a fraction
  167252. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167253. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167254. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167255. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167256. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167257. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167258. * factors are scaled by 2^16 = 65536.
  167259. * Also recall that SF = smoothing_factor / 1024.
  167260. */
  167261. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167262. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167263. inrow = 0;
  167264. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167265. outptr = output_data[outrow];
  167266. inptr0 = input_data[inrow];
  167267. inptr1 = input_data[inrow+1];
  167268. above_ptr = input_data[inrow-1];
  167269. below_ptr = input_data[inrow+2];
  167270. /* Special case for first column: pretend column -1 is same as column 0 */
  167271. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167272. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167273. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167274. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167275. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167276. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167277. neighsum += neighsum;
  167278. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167279. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167280. membersum = membersum * memberscale + neighsum * neighscale;
  167281. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167282. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167283. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167284. /* sum of pixels directly mapped to this output element */
  167285. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167286. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167287. /* sum of edge-neighbor pixels */
  167288. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167289. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167290. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167291. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167292. /* The edge-neighbors count twice as much as corner-neighbors */
  167293. neighsum += neighsum;
  167294. /* Add in the corner-neighbors */
  167295. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167296. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167297. /* form final output scaled up by 2^16 */
  167298. membersum = membersum * memberscale + neighsum * neighscale;
  167299. /* round, descale and output it */
  167300. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167301. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167302. }
  167303. /* Special case for last column */
  167304. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167305. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167306. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167307. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167308. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167309. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167310. neighsum += neighsum;
  167311. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167312. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167313. membersum = membersum * memberscale + neighsum * neighscale;
  167314. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167315. inrow += 2;
  167316. }
  167317. }
  167318. /*
  167319. * Downsample pixel values of a single component.
  167320. * This version handles the special case of a full-size component,
  167321. * with smoothing. One row of context is required.
  167322. */
  167323. METHODDEF(void)
  167324. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167325. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167326. {
  167327. int outrow;
  167328. JDIMENSION colctr;
  167329. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167330. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167331. INT32 membersum, neighsum, memberscale, neighscale;
  167332. int colsum, lastcolsum, nextcolsum;
  167333. /* Expand input data enough to let all the output samples be generated
  167334. * by the standard loop. Special-casing padded output would be more
  167335. * efficient.
  167336. */
  167337. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167338. cinfo->image_width, output_cols);
  167339. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167340. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167341. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167342. * Also recall that SF = smoothing_factor / 1024.
  167343. */
  167344. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167345. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167346. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167347. outptr = output_data[outrow];
  167348. inptr = input_data[outrow];
  167349. above_ptr = input_data[outrow-1];
  167350. below_ptr = input_data[outrow+1];
  167351. /* Special case for first column */
  167352. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167353. GETJSAMPLE(*inptr);
  167354. membersum = GETJSAMPLE(*inptr++);
  167355. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167356. GETJSAMPLE(*inptr);
  167357. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167358. membersum = membersum * memberscale + neighsum * neighscale;
  167359. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167360. lastcolsum = colsum; colsum = nextcolsum;
  167361. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167362. membersum = GETJSAMPLE(*inptr++);
  167363. above_ptr++; below_ptr++;
  167364. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167365. GETJSAMPLE(*inptr);
  167366. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167367. membersum = membersum * memberscale + neighsum * neighscale;
  167368. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167369. lastcolsum = colsum; colsum = nextcolsum;
  167370. }
  167371. /* Special case for last column */
  167372. membersum = GETJSAMPLE(*inptr);
  167373. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167374. membersum = membersum * memberscale + neighsum * neighscale;
  167375. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167376. }
  167377. }
  167378. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167379. /*
  167380. * Module initialization routine for downsampling.
  167381. * Note that we must select a routine for each component.
  167382. */
  167383. GLOBAL(void)
  167384. jinit_downsampler (j_compress_ptr cinfo)
  167385. {
  167386. my_downsample_ptr downsample;
  167387. int ci;
  167388. jpeg_component_info * compptr;
  167389. boolean smoothok = TRUE;
  167390. downsample = (my_downsample_ptr)
  167391. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167392. SIZEOF(my_downsampler));
  167393. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167394. downsample->pub.start_pass = start_pass_downsample;
  167395. downsample->pub.downsample = sep_downsample;
  167396. downsample->pub.need_context_rows = FALSE;
  167397. if (cinfo->CCIR601_sampling)
  167398. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167399. /* Verify we can handle the sampling factors, and set up method pointers */
  167400. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167401. ci++, compptr++) {
  167402. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167403. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167404. #ifdef INPUT_SMOOTHING_SUPPORTED
  167405. if (cinfo->smoothing_factor) {
  167406. downsample->methods[ci] = fullsize_smooth_downsample;
  167407. downsample->pub.need_context_rows = TRUE;
  167408. } else
  167409. #endif
  167410. downsample->methods[ci] = fullsize_downsample;
  167411. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167412. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167413. smoothok = FALSE;
  167414. downsample->methods[ci] = h2v1_downsample;
  167415. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167416. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167417. #ifdef INPUT_SMOOTHING_SUPPORTED
  167418. if (cinfo->smoothing_factor) {
  167419. downsample->methods[ci] = h2v2_smooth_downsample;
  167420. downsample->pub.need_context_rows = TRUE;
  167421. } else
  167422. #endif
  167423. downsample->methods[ci] = h2v2_downsample;
  167424. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167425. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167426. smoothok = FALSE;
  167427. downsample->methods[ci] = int_downsample;
  167428. } else
  167429. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167430. }
  167431. #ifdef INPUT_SMOOTHING_SUPPORTED
  167432. if (cinfo->smoothing_factor && !smoothok)
  167433. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167434. #endif
  167435. }
  167436. /*** End of inlined file: jcsample.c ***/
  167437. /*** Start of inlined file: jctrans.c ***/
  167438. #define JPEG_INTERNALS
  167439. /* Forward declarations */
  167440. LOCAL(void) transencode_master_selection
  167441. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167442. LOCAL(void) transencode_coef_controller
  167443. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167444. /*
  167445. * Compression initialization for writing raw-coefficient data.
  167446. * Before calling this, all parameters and a data destination must be set up.
  167447. * Call jpeg_finish_compress() to actually write the data.
  167448. *
  167449. * The number of passed virtual arrays must match cinfo->num_components.
  167450. * Note that the virtual arrays need not be filled or even realized at
  167451. * the time write_coefficients is called; indeed, if the virtual arrays
  167452. * were requested from this compression object's memory manager, they
  167453. * typically will be realized during this routine and filled afterwards.
  167454. */
  167455. GLOBAL(void)
  167456. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167457. {
  167458. if (cinfo->global_state != CSTATE_START)
  167459. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167460. /* Mark all tables to be written */
  167461. jpeg_suppress_tables(cinfo, FALSE);
  167462. /* (Re)initialize error mgr and destination modules */
  167463. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167464. (*cinfo->dest->init_destination) (cinfo);
  167465. /* Perform master selection of active modules */
  167466. transencode_master_selection(cinfo, coef_arrays);
  167467. /* Wait for jpeg_finish_compress() call */
  167468. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167469. cinfo->global_state = CSTATE_WRCOEFS;
  167470. }
  167471. /*
  167472. * Initialize the compression object with default parameters,
  167473. * then copy from the source object all parameters needed for lossless
  167474. * transcoding. Parameters that can be varied without loss (such as
  167475. * scan script and Huffman optimization) are left in their default states.
  167476. */
  167477. GLOBAL(void)
  167478. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167479. j_compress_ptr dstinfo)
  167480. {
  167481. JQUANT_TBL ** qtblptr;
  167482. jpeg_component_info *incomp, *outcomp;
  167483. JQUANT_TBL *c_quant, *slot_quant;
  167484. int tblno, ci, coefi;
  167485. /* Safety check to ensure start_compress not called yet. */
  167486. if (dstinfo->global_state != CSTATE_START)
  167487. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167488. /* Copy fundamental image dimensions */
  167489. dstinfo->image_width = srcinfo->image_width;
  167490. dstinfo->image_height = srcinfo->image_height;
  167491. dstinfo->input_components = srcinfo->num_components;
  167492. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167493. /* Initialize all parameters to default values */
  167494. jpeg_set_defaults(dstinfo);
  167495. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167496. * Fix it to get the right header markers for the image colorspace.
  167497. */
  167498. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167499. dstinfo->data_precision = srcinfo->data_precision;
  167500. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167501. /* Copy the source's quantization tables. */
  167502. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167503. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167504. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167505. if (*qtblptr == NULL)
  167506. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167507. MEMCOPY((*qtblptr)->quantval,
  167508. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167509. SIZEOF((*qtblptr)->quantval));
  167510. (*qtblptr)->sent_table = FALSE;
  167511. }
  167512. }
  167513. /* Copy the source's per-component info.
  167514. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167515. */
  167516. dstinfo->num_components = srcinfo->num_components;
  167517. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167518. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167519. MAX_COMPONENTS);
  167520. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167521. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167522. outcomp->component_id = incomp->component_id;
  167523. outcomp->h_samp_factor = incomp->h_samp_factor;
  167524. outcomp->v_samp_factor = incomp->v_samp_factor;
  167525. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167526. /* Make sure saved quantization table for component matches the qtable
  167527. * slot. If not, the input file re-used this qtable slot.
  167528. * IJG encoder currently cannot duplicate this.
  167529. */
  167530. tblno = outcomp->quant_tbl_no;
  167531. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167532. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167533. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167534. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167535. c_quant = incomp->quant_table;
  167536. if (c_quant != NULL) {
  167537. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167538. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167539. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167540. }
  167541. }
  167542. /* Note: we do not copy the source's Huffman table assignments;
  167543. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167544. */
  167545. }
  167546. /* Also copy JFIF version and resolution information, if available.
  167547. * Strictly speaking this isn't "critical" info, but it's nearly
  167548. * always appropriate to copy it if available. In particular,
  167549. * if the application chooses to copy JFIF 1.02 extension markers from
  167550. * the source file, we need to copy the version to make sure we don't
  167551. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167552. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167553. */
  167554. if (srcinfo->saw_JFIF_marker) {
  167555. if (srcinfo->JFIF_major_version == 1) {
  167556. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167557. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167558. }
  167559. dstinfo->density_unit = srcinfo->density_unit;
  167560. dstinfo->X_density = srcinfo->X_density;
  167561. dstinfo->Y_density = srcinfo->Y_density;
  167562. }
  167563. }
  167564. /*
  167565. * Master selection of compression modules for transcoding.
  167566. * This substitutes for jcinit.c's initialization of the full compressor.
  167567. */
  167568. LOCAL(void)
  167569. transencode_master_selection (j_compress_ptr cinfo,
  167570. jvirt_barray_ptr * coef_arrays)
  167571. {
  167572. /* Although we don't actually use input_components for transcoding,
  167573. * jcmaster.c's initial_setup will complain if input_components is 0.
  167574. */
  167575. cinfo->input_components = 1;
  167576. /* Initialize master control (includes parameter checking/processing) */
  167577. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167578. /* Entropy encoding: either Huffman or arithmetic coding. */
  167579. if (cinfo->arith_code) {
  167580. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167581. } else {
  167582. if (cinfo->progressive_mode) {
  167583. #ifdef C_PROGRESSIVE_SUPPORTED
  167584. jinit_phuff_encoder(cinfo);
  167585. #else
  167586. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167587. #endif
  167588. } else
  167589. jinit_huff_encoder(cinfo);
  167590. }
  167591. /* We need a special coefficient buffer controller. */
  167592. transencode_coef_controller(cinfo, coef_arrays);
  167593. jinit_marker_writer(cinfo);
  167594. /* We can now tell the memory manager to allocate virtual arrays. */
  167595. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167596. /* Write the datastream header (SOI, JFIF) immediately.
  167597. * Frame and scan headers are postponed till later.
  167598. * This lets application insert special markers after the SOI.
  167599. */
  167600. (*cinfo->marker->write_file_header) (cinfo);
  167601. }
  167602. /*
  167603. * The rest of this file is a special implementation of the coefficient
  167604. * buffer controller. This is similar to jccoefct.c, but it handles only
  167605. * output from presupplied virtual arrays. Furthermore, we generate any
  167606. * dummy padding blocks on-the-fly rather than expecting them to be present
  167607. * in the arrays.
  167608. */
  167609. /* Private buffer controller object */
  167610. typedef struct {
  167611. struct jpeg_c_coef_controller pub; /* public fields */
  167612. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167613. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167614. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167615. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167616. /* Virtual block array for each component. */
  167617. jvirt_barray_ptr * whole_image;
  167618. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167619. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167620. } my_coef_controller2;
  167621. typedef my_coef_controller2 * my_coef_ptr2;
  167622. LOCAL(void)
  167623. start_iMCU_row2 (j_compress_ptr cinfo)
  167624. /* Reset within-iMCU-row counters for a new row */
  167625. {
  167626. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167627. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167628. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167629. * But at the bottom of the image, process only what's left.
  167630. */
  167631. if (cinfo->comps_in_scan > 1) {
  167632. coef->MCU_rows_per_iMCU_row = 1;
  167633. } else {
  167634. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167635. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167636. else
  167637. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167638. }
  167639. coef->mcu_ctr = 0;
  167640. coef->MCU_vert_offset = 0;
  167641. }
  167642. /*
  167643. * Initialize for a processing pass.
  167644. */
  167645. METHODDEF(void)
  167646. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167647. {
  167648. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167649. if (pass_mode != JBUF_CRANK_DEST)
  167650. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167651. coef->iMCU_row_num = 0;
  167652. start_iMCU_row2(cinfo);
  167653. }
  167654. /*
  167655. * Process some data.
  167656. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167657. * per call, ie, v_samp_factor block rows for each component in the scan.
  167658. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167659. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167660. *
  167661. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167662. */
  167663. METHODDEF(boolean)
  167664. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167665. {
  167666. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167667. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167668. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167669. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167670. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167671. JDIMENSION start_col;
  167672. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167673. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167674. JBLOCKROW buffer_ptr;
  167675. jpeg_component_info *compptr;
  167676. /* Align the virtual buffers for the components used in this scan. */
  167677. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167678. compptr = cinfo->cur_comp_info[ci];
  167679. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167680. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167681. coef->iMCU_row_num * compptr->v_samp_factor,
  167682. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167683. }
  167684. /* Loop to process one whole iMCU row */
  167685. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167686. yoffset++) {
  167687. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167688. MCU_col_num++) {
  167689. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167690. blkn = 0; /* index of current DCT block within MCU */
  167691. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167692. compptr = cinfo->cur_comp_info[ci];
  167693. start_col = MCU_col_num * compptr->MCU_width;
  167694. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167695. : compptr->last_col_width;
  167696. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167697. if (coef->iMCU_row_num < last_iMCU_row ||
  167698. yindex+yoffset < compptr->last_row_height) {
  167699. /* Fill in pointers to real blocks in this row */
  167700. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167701. for (xindex = 0; xindex < blockcnt; xindex++)
  167702. MCU_buffer[blkn++] = buffer_ptr++;
  167703. } else {
  167704. /* At bottom of image, need a whole row of dummy blocks */
  167705. xindex = 0;
  167706. }
  167707. /* Fill in any dummy blocks needed in this row.
  167708. * Dummy blocks are filled in the same way as in jccoefct.c:
  167709. * all zeroes in the AC entries, DC entries equal to previous
  167710. * block's DC value. The init routine has already zeroed the
  167711. * AC entries, so we need only set the DC entries correctly.
  167712. */
  167713. for (; xindex < compptr->MCU_width; xindex++) {
  167714. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167715. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167716. blkn++;
  167717. }
  167718. }
  167719. }
  167720. /* Try to write the MCU. */
  167721. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167722. /* Suspension forced; update state counters and exit */
  167723. coef->MCU_vert_offset = yoffset;
  167724. coef->mcu_ctr = MCU_col_num;
  167725. return FALSE;
  167726. }
  167727. }
  167728. /* Completed an MCU row, but perhaps not an iMCU row */
  167729. coef->mcu_ctr = 0;
  167730. }
  167731. /* Completed the iMCU row, advance counters for next one */
  167732. coef->iMCU_row_num++;
  167733. start_iMCU_row2(cinfo);
  167734. return TRUE;
  167735. }
  167736. /*
  167737. * Initialize coefficient buffer controller.
  167738. *
  167739. * Each passed coefficient array must be the right size for that
  167740. * coefficient: width_in_blocks wide and height_in_blocks high,
  167741. * with unitheight at least v_samp_factor.
  167742. */
  167743. LOCAL(void)
  167744. transencode_coef_controller (j_compress_ptr cinfo,
  167745. jvirt_barray_ptr * coef_arrays)
  167746. {
  167747. my_coef_ptr2 coef;
  167748. JBLOCKROW buffer;
  167749. int i;
  167750. coef = (my_coef_ptr2)
  167751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167752. SIZEOF(my_coef_controller2));
  167753. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167754. coef->pub.start_pass = start_pass_coef2;
  167755. coef->pub.compress_data = compress_output2;
  167756. /* Save pointer to virtual arrays */
  167757. coef->whole_image = coef_arrays;
  167758. /* Allocate and pre-zero space for dummy DCT blocks. */
  167759. buffer = (JBLOCKROW)
  167760. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167761. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167762. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167763. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167764. coef->dummy_buffer[i] = buffer + i;
  167765. }
  167766. }
  167767. /*** End of inlined file: jctrans.c ***/
  167768. /*** Start of inlined file: jdapistd.c ***/
  167769. #define JPEG_INTERNALS
  167770. /* Forward declarations */
  167771. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167772. /*
  167773. * Decompression initialization.
  167774. * jpeg_read_header must be completed before calling this.
  167775. *
  167776. * If a multipass operating mode was selected, this will do all but the
  167777. * last pass, and thus may take a great deal of time.
  167778. *
  167779. * Returns FALSE if suspended. The return value need be inspected only if
  167780. * a suspending data source is used.
  167781. */
  167782. GLOBAL(boolean)
  167783. jpeg_start_decompress (j_decompress_ptr cinfo)
  167784. {
  167785. if (cinfo->global_state == DSTATE_READY) {
  167786. /* First call: initialize master control, select active modules */
  167787. jinit_master_decompress(cinfo);
  167788. if (cinfo->buffered_image) {
  167789. /* No more work here; expecting jpeg_start_output next */
  167790. cinfo->global_state = DSTATE_BUFIMAGE;
  167791. return TRUE;
  167792. }
  167793. cinfo->global_state = DSTATE_PRELOAD;
  167794. }
  167795. if (cinfo->global_state == DSTATE_PRELOAD) {
  167796. /* If file has multiple scans, absorb them all into the coef buffer */
  167797. if (cinfo->inputctl->has_multiple_scans) {
  167798. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167799. for (;;) {
  167800. int retcode;
  167801. /* Call progress monitor hook if present */
  167802. if (cinfo->progress != NULL)
  167803. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167804. /* Absorb some more input */
  167805. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167806. if (retcode == JPEG_SUSPENDED)
  167807. return FALSE;
  167808. if (retcode == JPEG_REACHED_EOI)
  167809. break;
  167810. /* Advance progress counter if appropriate */
  167811. if (cinfo->progress != NULL &&
  167812. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167813. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167814. /* jdmaster underestimated number of scans; ratchet up one scan */
  167815. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167816. }
  167817. }
  167818. }
  167819. #else
  167820. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167821. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167822. }
  167823. cinfo->output_scan_number = cinfo->input_scan_number;
  167824. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167825. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167826. /* Perform any dummy output passes, and set up for the final pass */
  167827. return output_pass_setup(cinfo);
  167828. }
  167829. /*
  167830. * Set up for an output pass, and perform any dummy pass(es) needed.
  167831. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167832. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167833. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167834. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167835. */
  167836. LOCAL(boolean)
  167837. output_pass_setup (j_decompress_ptr cinfo)
  167838. {
  167839. if (cinfo->global_state != DSTATE_PRESCAN) {
  167840. /* First call: do pass setup */
  167841. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167842. cinfo->output_scanline = 0;
  167843. cinfo->global_state = DSTATE_PRESCAN;
  167844. }
  167845. /* Loop over any required dummy passes */
  167846. while (cinfo->master->is_dummy_pass) {
  167847. #ifdef QUANT_2PASS_SUPPORTED
  167848. /* Crank through the dummy pass */
  167849. while (cinfo->output_scanline < cinfo->output_height) {
  167850. JDIMENSION last_scanline;
  167851. /* Call progress monitor hook if present */
  167852. if (cinfo->progress != NULL) {
  167853. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167854. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167855. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167856. }
  167857. /* Process some data */
  167858. last_scanline = cinfo->output_scanline;
  167859. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167860. &cinfo->output_scanline, (JDIMENSION) 0);
  167861. if (cinfo->output_scanline == last_scanline)
  167862. return FALSE; /* No progress made, must suspend */
  167863. }
  167864. /* Finish up dummy pass, and set up for another one */
  167865. (*cinfo->master->finish_output_pass) (cinfo);
  167866. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167867. cinfo->output_scanline = 0;
  167868. #else
  167869. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167870. #endif /* QUANT_2PASS_SUPPORTED */
  167871. }
  167872. /* Ready for application to drive output pass through
  167873. * jpeg_read_scanlines or jpeg_read_raw_data.
  167874. */
  167875. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167876. return TRUE;
  167877. }
  167878. /*
  167879. * Read some scanlines of data from the JPEG decompressor.
  167880. *
  167881. * The return value will be the number of lines actually read.
  167882. * This may be less than the number requested in several cases,
  167883. * including bottom of image, data source suspension, and operating
  167884. * modes that emit multiple scanlines at a time.
  167885. *
  167886. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167887. * this likely signals an application programmer error. However,
  167888. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167889. */
  167890. GLOBAL(JDIMENSION)
  167891. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167892. JDIMENSION max_lines)
  167893. {
  167894. JDIMENSION row_ctr;
  167895. if (cinfo->global_state != DSTATE_SCANNING)
  167896. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167897. if (cinfo->output_scanline >= cinfo->output_height) {
  167898. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167899. return 0;
  167900. }
  167901. /* Call progress monitor hook if present */
  167902. if (cinfo->progress != NULL) {
  167903. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167904. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167905. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167906. }
  167907. /* Process some data */
  167908. row_ctr = 0;
  167909. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167910. cinfo->output_scanline += row_ctr;
  167911. return row_ctr;
  167912. }
  167913. /*
  167914. * Alternate entry point to read raw data.
  167915. * Processes exactly one iMCU row per call, unless suspended.
  167916. */
  167917. GLOBAL(JDIMENSION)
  167918. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167919. JDIMENSION max_lines)
  167920. {
  167921. JDIMENSION lines_per_iMCU_row;
  167922. if (cinfo->global_state != DSTATE_RAW_OK)
  167923. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167924. if (cinfo->output_scanline >= cinfo->output_height) {
  167925. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167926. return 0;
  167927. }
  167928. /* Call progress monitor hook if present */
  167929. if (cinfo->progress != NULL) {
  167930. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167931. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167932. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167933. }
  167934. /* Verify that at least one iMCU row can be returned. */
  167935. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167936. if (max_lines < lines_per_iMCU_row)
  167937. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167938. /* Decompress directly into user's buffer. */
  167939. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167940. return 0; /* suspension forced, can do nothing more */
  167941. /* OK, we processed one iMCU row. */
  167942. cinfo->output_scanline += lines_per_iMCU_row;
  167943. return lines_per_iMCU_row;
  167944. }
  167945. /* Additional entry points for buffered-image mode. */
  167946. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167947. /*
  167948. * Initialize for an output pass in buffered-image mode.
  167949. */
  167950. GLOBAL(boolean)
  167951. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167952. {
  167953. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167954. cinfo->global_state != DSTATE_PRESCAN)
  167955. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167956. /* Limit scan number to valid range */
  167957. if (scan_number <= 0)
  167958. scan_number = 1;
  167959. if (cinfo->inputctl->eoi_reached &&
  167960. scan_number > cinfo->input_scan_number)
  167961. scan_number = cinfo->input_scan_number;
  167962. cinfo->output_scan_number = scan_number;
  167963. /* Perform any dummy output passes, and set up for the real pass */
  167964. return output_pass_setup(cinfo);
  167965. }
  167966. /*
  167967. * Finish up after an output pass in buffered-image mode.
  167968. *
  167969. * Returns FALSE if suspended. The return value need be inspected only if
  167970. * a suspending data source is used.
  167971. */
  167972. GLOBAL(boolean)
  167973. jpeg_finish_output (j_decompress_ptr cinfo)
  167974. {
  167975. if ((cinfo->global_state == DSTATE_SCANNING ||
  167976. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167977. /* Terminate this pass. */
  167978. /* We do not require the whole pass to have been completed. */
  167979. (*cinfo->master->finish_output_pass) (cinfo);
  167980. cinfo->global_state = DSTATE_BUFPOST;
  167981. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167982. /* BUFPOST = repeat call after a suspension, anything else is error */
  167983. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167984. }
  167985. /* Read markers looking for SOS or EOI */
  167986. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167987. ! cinfo->inputctl->eoi_reached) {
  167988. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167989. return FALSE; /* Suspend, come back later */
  167990. }
  167991. cinfo->global_state = DSTATE_BUFIMAGE;
  167992. return TRUE;
  167993. }
  167994. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167995. /*** End of inlined file: jdapistd.c ***/
  167996. /*** Start of inlined file: jdapimin.c ***/
  167997. #define JPEG_INTERNALS
  167998. /*
  167999. * Initialization of a JPEG decompression object.
  168000. * The error manager must already be set up (in case memory manager fails).
  168001. */
  168002. GLOBAL(void)
  168003. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  168004. {
  168005. int i;
  168006. /* Guard against version mismatches between library and caller. */
  168007. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  168008. if (version != JPEG_LIB_VERSION)
  168009. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  168010. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  168011. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  168012. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  168013. /* For debugging purposes, we zero the whole master structure.
  168014. * But the application has already set the err pointer, and may have set
  168015. * client_data, so we have to save and restore those fields.
  168016. * Note: if application hasn't set client_data, tools like Purify may
  168017. * complain here.
  168018. */
  168019. {
  168020. struct jpeg_error_mgr * err = cinfo->err;
  168021. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  168022. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  168023. cinfo->err = err;
  168024. cinfo->client_data = client_data;
  168025. }
  168026. cinfo->is_decompressor = TRUE;
  168027. /* Initialize a memory manager instance for this object */
  168028. jinit_memory_mgr((j_common_ptr) cinfo);
  168029. /* Zero out pointers to permanent structures. */
  168030. cinfo->progress = NULL;
  168031. cinfo->src = NULL;
  168032. for (i = 0; i < NUM_QUANT_TBLS; i++)
  168033. cinfo->quant_tbl_ptrs[i] = NULL;
  168034. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  168035. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  168036. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  168037. }
  168038. /* Initialize marker processor so application can override methods
  168039. * for COM, APPn markers before calling jpeg_read_header.
  168040. */
  168041. cinfo->marker_list = NULL;
  168042. jinit_marker_reader(cinfo);
  168043. /* And initialize the overall input controller. */
  168044. jinit_input_controller(cinfo);
  168045. /* OK, I'm ready */
  168046. cinfo->global_state = DSTATE_START;
  168047. }
  168048. /*
  168049. * Destruction of a JPEG decompression object
  168050. */
  168051. GLOBAL(void)
  168052. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  168053. {
  168054. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  168055. }
  168056. /*
  168057. * Abort processing of a JPEG decompression operation,
  168058. * but don't destroy the object itself.
  168059. */
  168060. GLOBAL(void)
  168061. jpeg_abort_decompress (j_decompress_ptr cinfo)
  168062. {
  168063. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  168064. }
  168065. /*
  168066. * Set default decompression parameters.
  168067. */
  168068. LOCAL(void)
  168069. default_decompress_parms (j_decompress_ptr cinfo)
  168070. {
  168071. /* Guess the input colorspace, and set output colorspace accordingly. */
  168072. /* (Wish JPEG committee had provided a real way to specify this...) */
  168073. /* Note application may override our guesses. */
  168074. switch (cinfo->num_components) {
  168075. case 1:
  168076. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  168077. cinfo->out_color_space = JCS_GRAYSCALE;
  168078. break;
  168079. case 3:
  168080. if (cinfo->saw_JFIF_marker) {
  168081. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  168082. } else if (cinfo->saw_Adobe_marker) {
  168083. switch (cinfo->Adobe_transform) {
  168084. case 0:
  168085. cinfo->jpeg_color_space = JCS_RGB;
  168086. break;
  168087. case 1:
  168088. cinfo->jpeg_color_space = JCS_YCbCr;
  168089. break;
  168090. default:
  168091. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168092. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168093. break;
  168094. }
  168095. } else {
  168096. /* Saw no special markers, try to guess from the component IDs */
  168097. int cid0 = cinfo->comp_info[0].component_id;
  168098. int cid1 = cinfo->comp_info[1].component_id;
  168099. int cid2 = cinfo->comp_info[2].component_id;
  168100. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  168101. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  168102. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  168103. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  168104. else {
  168105. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  168106. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168107. }
  168108. }
  168109. /* Always guess RGB is proper output colorspace. */
  168110. cinfo->out_color_space = JCS_RGB;
  168111. break;
  168112. case 4:
  168113. if (cinfo->saw_Adobe_marker) {
  168114. switch (cinfo->Adobe_transform) {
  168115. case 0:
  168116. cinfo->jpeg_color_space = JCS_CMYK;
  168117. break;
  168118. case 2:
  168119. cinfo->jpeg_color_space = JCS_YCCK;
  168120. break;
  168121. default:
  168122. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168123. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168124. break;
  168125. }
  168126. } else {
  168127. /* No special markers, assume straight CMYK. */
  168128. cinfo->jpeg_color_space = JCS_CMYK;
  168129. }
  168130. cinfo->out_color_space = JCS_CMYK;
  168131. break;
  168132. default:
  168133. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168134. cinfo->out_color_space = JCS_UNKNOWN;
  168135. break;
  168136. }
  168137. /* Set defaults for other decompression parameters. */
  168138. cinfo->scale_num = 1; /* 1:1 scaling */
  168139. cinfo->scale_denom = 1;
  168140. cinfo->output_gamma = 1.0;
  168141. cinfo->buffered_image = FALSE;
  168142. cinfo->raw_data_out = FALSE;
  168143. cinfo->dct_method = JDCT_DEFAULT;
  168144. cinfo->do_fancy_upsampling = TRUE;
  168145. cinfo->do_block_smoothing = TRUE;
  168146. cinfo->quantize_colors = FALSE;
  168147. /* We set these in case application only sets quantize_colors. */
  168148. cinfo->dither_mode = JDITHER_FS;
  168149. #ifdef QUANT_2PASS_SUPPORTED
  168150. cinfo->two_pass_quantize = TRUE;
  168151. #else
  168152. cinfo->two_pass_quantize = FALSE;
  168153. #endif
  168154. cinfo->desired_number_of_colors = 256;
  168155. cinfo->colormap = NULL;
  168156. /* Initialize for no mode change in buffered-image mode. */
  168157. cinfo->enable_1pass_quant = FALSE;
  168158. cinfo->enable_external_quant = FALSE;
  168159. cinfo->enable_2pass_quant = FALSE;
  168160. }
  168161. /*
  168162. * Decompression startup: read start of JPEG datastream to see what's there.
  168163. * Need only initialize JPEG object and supply a data source before calling.
  168164. *
  168165. * This routine will read as far as the first SOS marker (ie, actual start of
  168166. * compressed data), and will save all tables and parameters in the JPEG
  168167. * object. It will also initialize the decompression parameters to default
  168168. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168169. * adjust the decompression parameters and then call jpeg_start_decompress.
  168170. * (Or, if the application only wanted to determine the image parameters,
  168171. * the data need not be decompressed. In that case, call jpeg_abort or
  168172. * jpeg_destroy to release any temporary space.)
  168173. * If an abbreviated (tables only) datastream is presented, the routine will
  168174. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168175. * re-use the JPEG object to read the abbreviated image datastream(s).
  168176. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168177. * The JPEG_SUSPENDED return code only occurs if the data source module
  168178. * requests suspension of the decompressor. In this case the application
  168179. * should load more source data and then re-call jpeg_read_header to resume
  168180. * processing.
  168181. * If a non-suspending data source is used and require_image is TRUE, then the
  168182. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168183. *
  168184. * This routine is now just a front end to jpeg_consume_input, with some
  168185. * extra error checking.
  168186. */
  168187. GLOBAL(int)
  168188. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168189. {
  168190. int retcode;
  168191. if (cinfo->global_state != DSTATE_START &&
  168192. cinfo->global_state != DSTATE_INHEADER)
  168193. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168194. retcode = jpeg_consume_input(cinfo);
  168195. switch (retcode) {
  168196. case JPEG_REACHED_SOS:
  168197. retcode = JPEG_HEADER_OK;
  168198. break;
  168199. case JPEG_REACHED_EOI:
  168200. if (require_image) /* Complain if application wanted an image */
  168201. ERREXIT(cinfo, JERR_NO_IMAGE);
  168202. /* Reset to start state; it would be safer to require the application to
  168203. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168204. * A side effect is to free any temporary memory (there shouldn't be any).
  168205. */
  168206. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168207. retcode = JPEG_HEADER_TABLES_ONLY;
  168208. break;
  168209. case JPEG_SUSPENDED:
  168210. /* no work */
  168211. break;
  168212. }
  168213. return retcode;
  168214. }
  168215. /*
  168216. * Consume data in advance of what the decompressor requires.
  168217. * This can be called at any time once the decompressor object has
  168218. * been created and a data source has been set up.
  168219. *
  168220. * This routine is essentially a state machine that handles a couple
  168221. * of critical state-transition actions, namely initial setup and
  168222. * transition from header scanning to ready-for-start_decompress.
  168223. * All the actual input is done via the input controller's consume_input
  168224. * method.
  168225. */
  168226. GLOBAL(int)
  168227. jpeg_consume_input (j_decompress_ptr cinfo)
  168228. {
  168229. int retcode = JPEG_SUSPENDED;
  168230. /* NB: every possible DSTATE value should be listed in this switch */
  168231. switch (cinfo->global_state) {
  168232. case DSTATE_START:
  168233. /* Start-of-datastream actions: reset appropriate modules */
  168234. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168235. /* Initialize application's data source module */
  168236. (*cinfo->src->init_source) (cinfo);
  168237. cinfo->global_state = DSTATE_INHEADER;
  168238. /*FALLTHROUGH*/
  168239. case DSTATE_INHEADER:
  168240. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168241. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168242. /* Set up default parameters based on header data */
  168243. default_decompress_parms(cinfo);
  168244. /* Set global state: ready for start_decompress */
  168245. cinfo->global_state = DSTATE_READY;
  168246. }
  168247. break;
  168248. case DSTATE_READY:
  168249. /* Can't advance past first SOS until start_decompress is called */
  168250. retcode = JPEG_REACHED_SOS;
  168251. break;
  168252. case DSTATE_PRELOAD:
  168253. case DSTATE_PRESCAN:
  168254. case DSTATE_SCANNING:
  168255. case DSTATE_RAW_OK:
  168256. case DSTATE_BUFIMAGE:
  168257. case DSTATE_BUFPOST:
  168258. case DSTATE_STOPPING:
  168259. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168260. break;
  168261. default:
  168262. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168263. }
  168264. return retcode;
  168265. }
  168266. /*
  168267. * Have we finished reading the input file?
  168268. */
  168269. GLOBAL(boolean)
  168270. jpeg_input_complete (j_decompress_ptr cinfo)
  168271. {
  168272. /* Check for valid jpeg object */
  168273. if (cinfo->global_state < DSTATE_START ||
  168274. cinfo->global_state > DSTATE_STOPPING)
  168275. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168276. return cinfo->inputctl->eoi_reached;
  168277. }
  168278. /*
  168279. * Is there more than one scan?
  168280. */
  168281. GLOBAL(boolean)
  168282. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168283. {
  168284. /* Only valid after jpeg_read_header completes */
  168285. if (cinfo->global_state < DSTATE_READY ||
  168286. cinfo->global_state > DSTATE_STOPPING)
  168287. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168288. return cinfo->inputctl->has_multiple_scans;
  168289. }
  168290. /*
  168291. * Finish JPEG decompression.
  168292. *
  168293. * This will normally just verify the file trailer and release temp storage.
  168294. *
  168295. * Returns FALSE if suspended. The return value need be inspected only if
  168296. * a suspending data source is used.
  168297. */
  168298. GLOBAL(boolean)
  168299. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168300. {
  168301. if ((cinfo->global_state == DSTATE_SCANNING ||
  168302. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168303. /* Terminate final pass of non-buffered mode */
  168304. if (cinfo->output_scanline < cinfo->output_height)
  168305. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168306. (*cinfo->master->finish_output_pass) (cinfo);
  168307. cinfo->global_state = DSTATE_STOPPING;
  168308. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168309. /* Finishing after a buffered-image operation */
  168310. cinfo->global_state = DSTATE_STOPPING;
  168311. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168312. /* STOPPING = repeat call after a suspension, anything else is error */
  168313. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168314. }
  168315. /* Read until EOI */
  168316. while (! cinfo->inputctl->eoi_reached) {
  168317. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168318. return FALSE; /* Suspend, come back later */
  168319. }
  168320. /* Do final cleanup */
  168321. (*cinfo->src->term_source) (cinfo);
  168322. /* We can use jpeg_abort to release memory and reset global_state */
  168323. jpeg_abort((j_common_ptr) cinfo);
  168324. return TRUE;
  168325. }
  168326. /*** End of inlined file: jdapimin.c ***/
  168327. /*** Start of inlined file: jdatasrc.c ***/
  168328. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168329. /*** Start of inlined file: jerror.h ***/
  168330. /*
  168331. * To define the enum list of message codes, include this file without
  168332. * defining macro JMESSAGE. To create a message string table, include it
  168333. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168334. */
  168335. #ifndef JMESSAGE
  168336. #ifndef JERROR_H
  168337. /* First time through, define the enum list */
  168338. #define JMAKE_ENUM_LIST
  168339. #else
  168340. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168341. #define JMESSAGE(code,string)
  168342. #endif /* JERROR_H */
  168343. #endif /* JMESSAGE */
  168344. #ifdef JMAKE_ENUM_LIST
  168345. typedef enum {
  168346. #define JMESSAGE(code,string) code ,
  168347. #endif /* JMAKE_ENUM_LIST */
  168348. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168349. /* For maintenance convenience, list is alphabetical by message code name */
  168350. JMESSAGE(JERR_ARITH_NOTIMPL,
  168351. "Sorry, there are legal restrictions on arithmetic coding")
  168352. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168353. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168354. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168355. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168356. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168357. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168358. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168359. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168360. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168361. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168362. JMESSAGE(JERR_BAD_LIB_VERSION,
  168363. "Wrong JPEG library version: library is %d, caller expects %d")
  168364. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168365. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168366. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168367. JMESSAGE(JERR_BAD_PROGRESSION,
  168368. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168369. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168370. "Invalid progressive parameters at scan script entry %d")
  168371. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168372. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168373. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168374. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168375. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168376. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168377. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168378. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168379. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168380. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168381. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168382. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168383. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168384. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168385. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168386. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168387. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168388. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168389. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168390. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168391. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168392. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168393. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168394. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168395. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168396. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168397. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168398. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168399. "Cannot transcode due to multiple use of quantization table %d")
  168400. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168401. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168402. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168403. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168404. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168405. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168406. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168407. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168408. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168409. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168410. JMESSAGE(JERR_QUANT_COMPONENTS,
  168411. "Cannot quantize more than %d color components")
  168412. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168413. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168414. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168415. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168416. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168417. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168418. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168419. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168420. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168421. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168422. JMESSAGE(JERR_TFILE_WRITE,
  168423. "Write failed on temporary file --- out of disk space?")
  168424. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168425. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168426. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168427. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168428. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168429. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168430. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168431. JMESSAGE(JMSG_VERSION, JVERSION)
  168432. JMESSAGE(JTRC_16BIT_TABLES,
  168433. "Caution: quantization tables are too coarse for baseline JPEG")
  168434. JMESSAGE(JTRC_ADOBE,
  168435. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168436. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168437. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168438. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168439. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168440. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168441. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168442. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168443. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168444. JMESSAGE(JTRC_EOI, "End Of Image")
  168445. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168446. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168447. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168448. "Warning: thumbnail image size does not match data length %u")
  168449. JMESSAGE(JTRC_JFIF_EXTENSION,
  168450. "JFIF extension marker: type 0x%02x, length %u")
  168451. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168452. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168453. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168454. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168455. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168456. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168457. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168458. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168459. JMESSAGE(JTRC_RST, "RST%d")
  168460. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168461. "Smoothing not supported with nonstandard sampling ratios")
  168462. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168463. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168464. JMESSAGE(JTRC_SOI, "Start of Image")
  168465. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168466. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168467. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168468. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168469. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168470. JMESSAGE(JTRC_THUMB_JPEG,
  168471. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168472. JMESSAGE(JTRC_THUMB_PALETTE,
  168473. "JFIF extension marker: palette thumbnail image, length %u")
  168474. JMESSAGE(JTRC_THUMB_RGB,
  168475. "JFIF extension marker: RGB thumbnail image, length %u")
  168476. JMESSAGE(JTRC_UNKNOWN_IDS,
  168477. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168478. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168479. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168480. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168481. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168482. "Inconsistent progression sequence for component %d coefficient %d")
  168483. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168484. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168485. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168486. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168487. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168488. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168489. JMESSAGE(JWRN_MUST_RESYNC,
  168490. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168491. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168492. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168493. #ifdef JMAKE_ENUM_LIST
  168494. JMSG_LASTMSGCODE
  168495. } J_MESSAGE_CODE;
  168496. #undef JMAKE_ENUM_LIST
  168497. #endif /* JMAKE_ENUM_LIST */
  168498. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168499. #undef JMESSAGE
  168500. #ifndef JERROR_H
  168501. #define JERROR_H
  168502. /* Macros to simplify using the error and trace message stuff */
  168503. /* The first parameter is either type of cinfo pointer */
  168504. /* Fatal errors (print message and exit) */
  168505. #define ERREXIT(cinfo,code) \
  168506. ((cinfo)->err->msg_code = (code), \
  168507. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168508. #define ERREXIT1(cinfo,code,p1) \
  168509. ((cinfo)->err->msg_code = (code), \
  168510. (cinfo)->err->msg_parm.i[0] = (p1), \
  168511. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168512. #define ERREXIT2(cinfo,code,p1,p2) \
  168513. ((cinfo)->err->msg_code = (code), \
  168514. (cinfo)->err->msg_parm.i[0] = (p1), \
  168515. (cinfo)->err->msg_parm.i[1] = (p2), \
  168516. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168517. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168518. ((cinfo)->err->msg_code = (code), \
  168519. (cinfo)->err->msg_parm.i[0] = (p1), \
  168520. (cinfo)->err->msg_parm.i[1] = (p2), \
  168521. (cinfo)->err->msg_parm.i[2] = (p3), \
  168522. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168523. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168524. ((cinfo)->err->msg_code = (code), \
  168525. (cinfo)->err->msg_parm.i[0] = (p1), \
  168526. (cinfo)->err->msg_parm.i[1] = (p2), \
  168527. (cinfo)->err->msg_parm.i[2] = (p3), \
  168528. (cinfo)->err->msg_parm.i[3] = (p4), \
  168529. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168530. #define ERREXITS(cinfo,code,str) \
  168531. ((cinfo)->err->msg_code = (code), \
  168532. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168533. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168534. #define MAKESTMT(stuff) do { stuff } while (0)
  168535. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168536. #define WARNMS(cinfo,code) \
  168537. ((cinfo)->err->msg_code = (code), \
  168538. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168539. #define WARNMS1(cinfo,code,p1) \
  168540. ((cinfo)->err->msg_code = (code), \
  168541. (cinfo)->err->msg_parm.i[0] = (p1), \
  168542. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168543. #define WARNMS2(cinfo,code,p1,p2) \
  168544. ((cinfo)->err->msg_code = (code), \
  168545. (cinfo)->err->msg_parm.i[0] = (p1), \
  168546. (cinfo)->err->msg_parm.i[1] = (p2), \
  168547. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168548. /* Informational/debugging messages */
  168549. #define TRACEMS(cinfo,lvl,code) \
  168550. ((cinfo)->err->msg_code = (code), \
  168551. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168552. #define TRACEMS1(cinfo,lvl,code,p1) \
  168553. ((cinfo)->err->msg_code = (code), \
  168554. (cinfo)->err->msg_parm.i[0] = (p1), \
  168555. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168556. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168557. ((cinfo)->err->msg_code = (code), \
  168558. (cinfo)->err->msg_parm.i[0] = (p1), \
  168559. (cinfo)->err->msg_parm.i[1] = (p2), \
  168560. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168561. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168562. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168563. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168564. (cinfo)->err->msg_code = (code); \
  168565. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168566. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168567. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168568. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168569. (cinfo)->err->msg_code = (code); \
  168570. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168571. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168572. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168573. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168574. _mp[4] = (p5); \
  168575. (cinfo)->err->msg_code = (code); \
  168576. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168577. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168578. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168579. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168580. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168581. (cinfo)->err->msg_code = (code); \
  168582. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168583. #define TRACEMSS(cinfo,lvl,code,str) \
  168584. ((cinfo)->err->msg_code = (code), \
  168585. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168586. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168587. #endif /* JERROR_H */
  168588. /*** End of inlined file: jerror.h ***/
  168589. /* Expanded data source object for stdio input */
  168590. typedef struct {
  168591. struct jpeg_source_mgr pub; /* public fields */
  168592. FILE * infile; /* source stream */
  168593. JOCTET * buffer; /* start of buffer */
  168594. boolean start_of_file; /* have we gotten any data yet? */
  168595. } my_source_mgr;
  168596. typedef my_source_mgr * my_src_ptr;
  168597. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168598. /*
  168599. * Initialize source --- called by jpeg_read_header
  168600. * before any data is actually read.
  168601. */
  168602. METHODDEF(void)
  168603. init_source (j_decompress_ptr cinfo)
  168604. {
  168605. my_src_ptr src = (my_src_ptr) cinfo->src;
  168606. /* We reset the empty-input-file flag for each image,
  168607. * but we don't clear the input buffer.
  168608. * This is correct behavior for reading a series of images from one source.
  168609. */
  168610. src->start_of_file = TRUE;
  168611. }
  168612. /*
  168613. * Fill the input buffer --- called whenever buffer is emptied.
  168614. *
  168615. * In typical applications, this should read fresh data into the buffer
  168616. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168617. * reset the pointer & count to the start of the buffer, and return TRUE
  168618. * indicating that the buffer has been reloaded. It is not necessary to
  168619. * fill the buffer entirely, only to obtain at least one more byte.
  168620. *
  168621. * There is no such thing as an EOF return. If the end of the file has been
  168622. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168623. * the buffer. In most cases, generating a warning message and inserting a
  168624. * fake EOI marker is the best course of action --- this will allow the
  168625. * decompressor to output however much of the image is there. However,
  168626. * the resulting error message is misleading if the real problem is an empty
  168627. * input file, so we handle that case specially.
  168628. *
  168629. * In applications that need to be able to suspend compression due to input
  168630. * not being available yet, a FALSE return indicates that no more data can be
  168631. * obtained right now, but more may be forthcoming later. In this situation,
  168632. * the decompressor will return to its caller (with an indication of the
  168633. * number of scanlines it has read, if any). The application should resume
  168634. * decompression after it has loaded more data into the input buffer. Note
  168635. * that there are substantial restrictions on the use of suspension --- see
  168636. * the documentation.
  168637. *
  168638. * When suspending, the decompressor will back up to a convenient restart point
  168639. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168640. * indicate where the restart point will be if the current call returns FALSE.
  168641. * Data beyond this point must be rescanned after resumption, so move it to
  168642. * the front of the buffer rather than discarding it.
  168643. */
  168644. METHODDEF(boolean)
  168645. fill_input_buffer (j_decompress_ptr cinfo)
  168646. {
  168647. my_src_ptr src = (my_src_ptr) cinfo->src;
  168648. size_t nbytes;
  168649. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168650. if (nbytes <= 0) {
  168651. if (src->start_of_file) /* Treat empty input file as fatal error */
  168652. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168653. WARNMS(cinfo, JWRN_JPEG_EOF);
  168654. /* Insert a fake EOI marker */
  168655. src->buffer[0] = (JOCTET) 0xFF;
  168656. src->buffer[1] = (JOCTET) JPEG_EOI;
  168657. nbytes = 2;
  168658. }
  168659. src->pub.next_input_byte = src->buffer;
  168660. src->pub.bytes_in_buffer = nbytes;
  168661. src->start_of_file = FALSE;
  168662. return TRUE;
  168663. }
  168664. /*
  168665. * Skip data --- used to skip over a potentially large amount of
  168666. * uninteresting data (such as an APPn marker).
  168667. *
  168668. * Writers of suspendable-input applications must note that skip_input_data
  168669. * is not granted the right to give a suspension return. If the skip extends
  168670. * beyond the data currently in the buffer, the buffer can be marked empty so
  168671. * that the next read will cause a fill_input_buffer call that can suspend.
  168672. * Arranging for additional bytes to be discarded before reloading the input
  168673. * buffer is the application writer's problem.
  168674. */
  168675. METHODDEF(void)
  168676. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168677. {
  168678. my_src_ptr src = (my_src_ptr) cinfo->src;
  168679. /* Just a dumb implementation for now. Could use fseek() except
  168680. * it doesn't work on pipes. Not clear that being smart is worth
  168681. * any trouble anyway --- large skips are infrequent.
  168682. */
  168683. if (num_bytes > 0) {
  168684. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168685. num_bytes -= (long) src->pub.bytes_in_buffer;
  168686. (void) fill_input_buffer(cinfo);
  168687. /* note we assume that fill_input_buffer will never return FALSE,
  168688. * so suspension need not be handled.
  168689. */
  168690. }
  168691. src->pub.next_input_byte += (size_t) num_bytes;
  168692. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168693. }
  168694. }
  168695. /*
  168696. * An additional method that can be provided by data source modules is the
  168697. * resync_to_restart method for error recovery in the presence of RST markers.
  168698. * For the moment, this source module just uses the default resync method
  168699. * provided by the JPEG library. That method assumes that no backtracking
  168700. * is possible.
  168701. */
  168702. /*
  168703. * Terminate source --- called by jpeg_finish_decompress
  168704. * after all data has been read. Often a no-op.
  168705. *
  168706. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168707. * application must deal with any cleanup that should happen even
  168708. * for error exit.
  168709. */
  168710. METHODDEF(void)
  168711. term_source (j_decompress_ptr)
  168712. {
  168713. /* no work necessary here */
  168714. }
  168715. /*
  168716. * Prepare for input from a stdio stream.
  168717. * The caller must have already opened the stream, and is responsible
  168718. * for closing it after finishing decompression.
  168719. */
  168720. GLOBAL(void)
  168721. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168722. {
  168723. my_src_ptr src;
  168724. /* The source object and input buffer are made permanent so that a series
  168725. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168726. * only before the first one. (If we discarded the buffer at the end of
  168727. * one image, we'd likely lose the start of the next one.)
  168728. * This makes it unsafe to use this manager and a different source
  168729. * manager serially with the same JPEG object. Caveat programmer.
  168730. */
  168731. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168732. cinfo->src = (struct jpeg_source_mgr *)
  168733. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168734. SIZEOF(my_source_mgr));
  168735. src = (my_src_ptr) cinfo->src;
  168736. src->buffer = (JOCTET *)
  168737. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168738. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168739. }
  168740. src = (my_src_ptr) cinfo->src;
  168741. src->pub.init_source = init_source;
  168742. src->pub.fill_input_buffer = fill_input_buffer;
  168743. src->pub.skip_input_data = skip_input_data;
  168744. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168745. src->pub.term_source = term_source;
  168746. src->infile = infile;
  168747. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168748. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168749. }
  168750. /*** End of inlined file: jdatasrc.c ***/
  168751. /*** Start of inlined file: jdcoefct.c ***/
  168752. #define JPEG_INTERNALS
  168753. /* Block smoothing is only applicable for progressive JPEG, so: */
  168754. #ifndef D_PROGRESSIVE_SUPPORTED
  168755. #undef BLOCK_SMOOTHING_SUPPORTED
  168756. #endif
  168757. /* Private buffer controller object */
  168758. typedef struct {
  168759. struct jpeg_d_coef_controller pub; /* public fields */
  168760. /* These variables keep track of the current location of the input side. */
  168761. /* cinfo->input_iMCU_row is also used for this. */
  168762. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168763. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168764. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168765. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168766. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168767. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168768. * and let the entropy decoder write into that workspace each time.
  168769. * (On 80x86, the workspace is FAR even though it's not really very big;
  168770. * this is to keep the module interfaces unchanged when a large coefficient
  168771. * buffer is necessary.)
  168772. * In multi-pass modes, this array points to the current MCU's blocks
  168773. * within the virtual arrays; it is used only by the input side.
  168774. */
  168775. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168776. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168777. /* In multi-pass modes, we need a virtual block array for each component. */
  168778. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168779. #endif
  168780. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168781. /* When doing block smoothing, we latch coefficient Al values here */
  168782. int * coef_bits_latch;
  168783. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168784. #endif
  168785. } my_coef_controller3;
  168786. typedef my_coef_controller3 * my_coef_ptr3;
  168787. /* Forward declarations */
  168788. METHODDEF(int) decompress_onepass
  168789. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168790. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168791. METHODDEF(int) decompress_data
  168792. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168793. #endif
  168794. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168795. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168796. METHODDEF(int) decompress_smooth_data
  168797. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168798. #endif
  168799. LOCAL(void)
  168800. start_iMCU_row3 (j_decompress_ptr cinfo)
  168801. /* Reset within-iMCU-row counters for a new row (input side) */
  168802. {
  168803. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168804. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168805. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168806. * But at the bottom of the image, process only what's left.
  168807. */
  168808. if (cinfo->comps_in_scan > 1) {
  168809. coef->MCU_rows_per_iMCU_row = 1;
  168810. } else {
  168811. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168812. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168813. else
  168814. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168815. }
  168816. coef->MCU_ctr = 0;
  168817. coef->MCU_vert_offset = 0;
  168818. }
  168819. /*
  168820. * Initialize for an input processing pass.
  168821. */
  168822. METHODDEF(void)
  168823. start_input_pass (j_decompress_ptr cinfo)
  168824. {
  168825. cinfo->input_iMCU_row = 0;
  168826. start_iMCU_row3(cinfo);
  168827. }
  168828. /*
  168829. * Initialize for an output processing pass.
  168830. */
  168831. METHODDEF(void)
  168832. start_output_pass (j_decompress_ptr cinfo)
  168833. {
  168834. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168835. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168836. /* If multipass, check to see whether to use block smoothing on this pass */
  168837. if (coef->pub.coef_arrays != NULL) {
  168838. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168839. coef->pub.decompress_data = decompress_smooth_data;
  168840. else
  168841. coef->pub.decompress_data = decompress_data;
  168842. }
  168843. #endif
  168844. cinfo->output_iMCU_row = 0;
  168845. }
  168846. /*
  168847. * Decompress and return some data in the single-pass case.
  168848. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168849. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168850. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168851. *
  168852. * NB: output_buf contains a plane for each component in image,
  168853. * which we index according to the component's SOF position.
  168854. */
  168855. METHODDEF(int)
  168856. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168857. {
  168858. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168859. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168860. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168861. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168862. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168863. JSAMPARRAY output_ptr;
  168864. JDIMENSION start_col, output_col;
  168865. jpeg_component_info *compptr;
  168866. inverse_DCT_method_ptr inverse_DCT;
  168867. /* Loop to process as much as one whole iMCU row */
  168868. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168869. yoffset++) {
  168870. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168871. MCU_col_num++) {
  168872. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168873. jzero_far((void FAR *) coef->MCU_buffer[0],
  168874. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168875. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168876. /* Suspension forced; update state counters and exit */
  168877. coef->MCU_vert_offset = yoffset;
  168878. coef->MCU_ctr = MCU_col_num;
  168879. return JPEG_SUSPENDED;
  168880. }
  168881. /* Determine where data should go in output_buf and do the IDCT thing.
  168882. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168883. * incremented past them!). Note the inner loop relies on having
  168884. * allocated the MCU_buffer[] blocks sequentially.
  168885. */
  168886. blkn = 0; /* index of current DCT block within MCU */
  168887. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168888. compptr = cinfo->cur_comp_info[ci];
  168889. /* Don't bother to IDCT an uninteresting component. */
  168890. if (! compptr->component_needed) {
  168891. blkn += compptr->MCU_blocks;
  168892. continue;
  168893. }
  168894. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168895. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168896. : compptr->last_col_width;
  168897. output_ptr = output_buf[compptr->component_index] +
  168898. yoffset * compptr->DCT_scaled_size;
  168899. start_col = MCU_col_num * compptr->MCU_sample_width;
  168900. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168901. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168902. yoffset+yindex < compptr->last_row_height) {
  168903. output_col = start_col;
  168904. for (xindex = 0; xindex < useful_width; xindex++) {
  168905. (*inverse_DCT) (cinfo, compptr,
  168906. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168907. output_ptr, output_col);
  168908. output_col += compptr->DCT_scaled_size;
  168909. }
  168910. }
  168911. blkn += compptr->MCU_width;
  168912. output_ptr += compptr->DCT_scaled_size;
  168913. }
  168914. }
  168915. }
  168916. /* Completed an MCU row, but perhaps not an iMCU row */
  168917. coef->MCU_ctr = 0;
  168918. }
  168919. /* Completed the iMCU row, advance counters for next one */
  168920. cinfo->output_iMCU_row++;
  168921. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168922. start_iMCU_row3(cinfo);
  168923. return JPEG_ROW_COMPLETED;
  168924. }
  168925. /* Completed the scan */
  168926. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168927. return JPEG_SCAN_COMPLETED;
  168928. }
  168929. /*
  168930. * Dummy consume-input routine for single-pass operation.
  168931. */
  168932. METHODDEF(int)
  168933. dummy_consume_data (j_decompress_ptr)
  168934. {
  168935. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168936. }
  168937. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168938. /*
  168939. * Consume input data and store it in the full-image coefficient buffer.
  168940. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168941. * ie, v_samp_factor block rows for each component in the scan.
  168942. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168943. */
  168944. METHODDEF(int)
  168945. consume_data (j_decompress_ptr cinfo)
  168946. {
  168947. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168948. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168949. int blkn, ci, xindex, yindex, yoffset;
  168950. JDIMENSION start_col;
  168951. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168952. JBLOCKROW buffer_ptr;
  168953. jpeg_component_info *compptr;
  168954. /* Align the virtual buffers for the components used in this scan. */
  168955. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168956. compptr = cinfo->cur_comp_info[ci];
  168957. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168958. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168959. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168960. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168961. /* Note: entropy decoder expects buffer to be zeroed,
  168962. * but this is handled automatically by the memory manager
  168963. * because we requested a pre-zeroed array.
  168964. */
  168965. }
  168966. /* Loop to process one whole iMCU row */
  168967. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168968. yoffset++) {
  168969. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168970. MCU_col_num++) {
  168971. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168972. blkn = 0; /* index of current DCT block within MCU */
  168973. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168974. compptr = cinfo->cur_comp_info[ci];
  168975. start_col = MCU_col_num * compptr->MCU_width;
  168976. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168977. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168978. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168979. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168980. }
  168981. }
  168982. }
  168983. /* Try to fetch the MCU. */
  168984. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168985. /* Suspension forced; update state counters and exit */
  168986. coef->MCU_vert_offset = yoffset;
  168987. coef->MCU_ctr = MCU_col_num;
  168988. return JPEG_SUSPENDED;
  168989. }
  168990. }
  168991. /* Completed an MCU row, but perhaps not an iMCU row */
  168992. coef->MCU_ctr = 0;
  168993. }
  168994. /* Completed the iMCU row, advance counters for next one */
  168995. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168996. start_iMCU_row3(cinfo);
  168997. return JPEG_ROW_COMPLETED;
  168998. }
  168999. /* Completed the scan */
  169000. (*cinfo->inputctl->finish_input_pass) (cinfo);
  169001. return JPEG_SCAN_COMPLETED;
  169002. }
  169003. /*
  169004. * Decompress and return some data in the multi-pass case.
  169005. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  169006. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  169007. *
  169008. * NB: output_buf contains a plane for each component in image.
  169009. */
  169010. METHODDEF(int)
  169011. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169012. {
  169013. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169014. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169015. JDIMENSION block_num;
  169016. int ci, block_row, block_rows;
  169017. JBLOCKARRAY buffer;
  169018. JBLOCKROW buffer_ptr;
  169019. JSAMPARRAY output_ptr;
  169020. JDIMENSION output_col;
  169021. jpeg_component_info *compptr;
  169022. inverse_DCT_method_ptr inverse_DCT;
  169023. /* Force some input to be done if we are getting ahead of the input. */
  169024. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  169025. (cinfo->input_scan_number == cinfo->output_scan_number &&
  169026. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  169027. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169028. return JPEG_SUSPENDED;
  169029. }
  169030. /* OK, output from the virtual arrays. */
  169031. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169032. ci++, compptr++) {
  169033. /* Don't bother to IDCT an uninteresting component. */
  169034. if (! compptr->component_needed)
  169035. continue;
  169036. /* Align the virtual buffer for this component. */
  169037. buffer = (*cinfo->mem->access_virt_barray)
  169038. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169039. cinfo->output_iMCU_row * compptr->v_samp_factor,
  169040. (JDIMENSION) compptr->v_samp_factor, FALSE);
  169041. /* Count non-dummy DCT block rows in this iMCU row. */
  169042. if (cinfo->output_iMCU_row < last_iMCU_row)
  169043. block_rows = compptr->v_samp_factor;
  169044. else {
  169045. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169046. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169047. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169048. }
  169049. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169050. output_ptr = output_buf[ci];
  169051. /* Loop over all DCT blocks to be processed. */
  169052. for (block_row = 0; block_row < block_rows; block_row++) {
  169053. buffer_ptr = buffer[block_row];
  169054. output_col = 0;
  169055. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  169056. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  169057. output_ptr, output_col);
  169058. buffer_ptr++;
  169059. output_col += compptr->DCT_scaled_size;
  169060. }
  169061. output_ptr += compptr->DCT_scaled_size;
  169062. }
  169063. }
  169064. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169065. return JPEG_ROW_COMPLETED;
  169066. return JPEG_SCAN_COMPLETED;
  169067. }
  169068. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169069. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169070. /*
  169071. * This code applies interblock smoothing as described by section K.8
  169072. * of the JPEG standard: the first 5 AC coefficients are estimated from
  169073. * the DC values of a DCT block and its 8 neighboring blocks.
  169074. * We apply smoothing only for progressive JPEG decoding, and only if
  169075. * the coefficients it can estimate are not yet known to full precision.
  169076. */
  169077. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  169078. #define Q01_POS 1
  169079. #define Q10_POS 8
  169080. #define Q20_POS 16
  169081. #define Q11_POS 9
  169082. #define Q02_POS 2
  169083. /*
  169084. * Determine whether block smoothing is applicable and safe.
  169085. * We also latch the current states of the coef_bits[] entries for the
  169086. * AC coefficients; otherwise, if the input side of the decompressor
  169087. * advances into a new scan, we might think the coefficients are known
  169088. * more accurately than they really are.
  169089. */
  169090. LOCAL(boolean)
  169091. smoothing_ok (j_decompress_ptr cinfo)
  169092. {
  169093. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169094. boolean smoothing_useful = FALSE;
  169095. int ci, coefi;
  169096. jpeg_component_info *compptr;
  169097. JQUANT_TBL * qtable;
  169098. int * coef_bits;
  169099. int * coef_bits_latch;
  169100. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  169101. return FALSE;
  169102. /* Allocate latch area if not already done */
  169103. if (coef->coef_bits_latch == NULL)
  169104. coef->coef_bits_latch = (int *)
  169105. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169106. cinfo->num_components *
  169107. (SAVED_COEFS * SIZEOF(int)));
  169108. coef_bits_latch = coef->coef_bits_latch;
  169109. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169110. ci++, compptr++) {
  169111. /* All components' quantization values must already be latched. */
  169112. if ((qtable = compptr->quant_table) == NULL)
  169113. return FALSE;
  169114. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  169115. if (qtable->quantval[0] == 0 ||
  169116. qtable->quantval[Q01_POS] == 0 ||
  169117. qtable->quantval[Q10_POS] == 0 ||
  169118. qtable->quantval[Q20_POS] == 0 ||
  169119. qtable->quantval[Q11_POS] == 0 ||
  169120. qtable->quantval[Q02_POS] == 0)
  169121. return FALSE;
  169122. /* DC values must be at least partly known for all components. */
  169123. coef_bits = cinfo->coef_bits[ci];
  169124. if (coef_bits[0] < 0)
  169125. return FALSE;
  169126. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169127. for (coefi = 1; coefi <= 5; coefi++) {
  169128. coef_bits_latch[coefi] = coef_bits[coefi];
  169129. if (coef_bits[coefi] != 0)
  169130. smoothing_useful = TRUE;
  169131. }
  169132. coef_bits_latch += SAVED_COEFS;
  169133. }
  169134. return smoothing_useful;
  169135. }
  169136. /*
  169137. * Variant of decompress_data for use when doing block smoothing.
  169138. */
  169139. METHODDEF(int)
  169140. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169141. {
  169142. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169143. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169144. JDIMENSION block_num, last_block_column;
  169145. int ci, block_row, block_rows, access_rows;
  169146. JBLOCKARRAY buffer;
  169147. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169148. JSAMPARRAY output_ptr;
  169149. JDIMENSION output_col;
  169150. jpeg_component_info *compptr;
  169151. inverse_DCT_method_ptr inverse_DCT;
  169152. boolean first_row, last_row;
  169153. JBLOCK workspace;
  169154. int *coef_bits;
  169155. JQUANT_TBL *quanttbl;
  169156. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169157. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169158. int Al, pred;
  169159. /* Force some input to be done if we are getting ahead of the input. */
  169160. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169161. ! cinfo->inputctl->eoi_reached) {
  169162. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169163. /* If input is working on current scan, we ordinarily want it to
  169164. * have completed the current row. But if input scan is DC,
  169165. * we want it to keep one row ahead so that next block row's DC
  169166. * values are up to date.
  169167. */
  169168. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169169. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169170. break;
  169171. }
  169172. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169173. return JPEG_SUSPENDED;
  169174. }
  169175. /* OK, output from the virtual arrays. */
  169176. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169177. ci++, compptr++) {
  169178. /* Don't bother to IDCT an uninteresting component. */
  169179. if (! compptr->component_needed)
  169180. continue;
  169181. /* Count non-dummy DCT block rows in this iMCU row. */
  169182. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169183. block_rows = compptr->v_samp_factor;
  169184. access_rows = block_rows * 2; /* this and next iMCU row */
  169185. last_row = FALSE;
  169186. } else {
  169187. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169188. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169189. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169190. access_rows = block_rows; /* this iMCU row only */
  169191. last_row = TRUE;
  169192. }
  169193. /* Align the virtual buffer for this component. */
  169194. if (cinfo->output_iMCU_row > 0) {
  169195. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169196. buffer = (*cinfo->mem->access_virt_barray)
  169197. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169198. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169199. (JDIMENSION) access_rows, FALSE);
  169200. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169201. first_row = FALSE;
  169202. } else {
  169203. buffer = (*cinfo->mem->access_virt_barray)
  169204. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169205. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169206. first_row = TRUE;
  169207. }
  169208. /* Fetch component-dependent info */
  169209. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169210. quanttbl = compptr->quant_table;
  169211. Q00 = quanttbl->quantval[0];
  169212. Q01 = quanttbl->quantval[Q01_POS];
  169213. Q10 = quanttbl->quantval[Q10_POS];
  169214. Q20 = quanttbl->quantval[Q20_POS];
  169215. Q11 = quanttbl->quantval[Q11_POS];
  169216. Q02 = quanttbl->quantval[Q02_POS];
  169217. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169218. output_ptr = output_buf[ci];
  169219. /* Loop over all DCT blocks to be processed. */
  169220. for (block_row = 0; block_row < block_rows; block_row++) {
  169221. buffer_ptr = buffer[block_row];
  169222. if (first_row && block_row == 0)
  169223. prev_block_row = buffer_ptr;
  169224. else
  169225. prev_block_row = buffer[block_row-1];
  169226. if (last_row && block_row == block_rows-1)
  169227. next_block_row = buffer_ptr;
  169228. else
  169229. next_block_row = buffer[block_row+1];
  169230. /* We fetch the surrounding DC values using a sliding-register approach.
  169231. * Initialize all nine here so as to do the right thing on narrow pics.
  169232. */
  169233. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169234. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169235. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169236. output_col = 0;
  169237. last_block_column = compptr->width_in_blocks - 1;
  169238. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169239. /* Fetch current DCT block into workspace so we can modify it. */
  169240. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169241. /* Update DC values */
  169242. if (block_num < last_block_column) {
  169243. DC3 = (int) prev_block_row[1][0];
  169244. DC6 = (int) buffer_ptr[1][0];
  169245. DC9 = (int) next_block_row[1][0];
  169246. }
  169247. /* Compute coefficient estimates per K.8.
  169248. * An estimate is applied only if coefficient is still zero,
  169249. * and is not known to be fully accurate.
  169250. */
  169251. /* AC01 */
  169252. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169253. num = 36 * Q00 * (DC4 - DC6);
  169254. if (num >= 0) {
  169255. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169256. if (Al > 0 && pred >= (1<<Al))
  169257. pred = (1<<Al)-1;
  169258. } else {
  169259. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169260. if (Al > 0 && pred >= (1<<Al))
  169261. pred = (1<<Al)-1;
  169262. pred = -pred;
  169263. }
  169264. workspace[1] = (JCOEF) pred;
  169265. }
  169266. /* AC10 */
  169267. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169268. num = 36 * Q00 * (DC2 - DC8);
  169269. if (num >= 0) {
  169270. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169271. if (Al > 0 && pred >= (1<<Al))
  169272. pred = (1<<Al)-1;
  169273. } else {
  169274. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169275. if (Al > 0 && pred >= (1<<Al))
  169276. pred = (1<<Al)-1;
  169277. pred = -pred;
  169278. }
  169279. workspace[8] = (JCOEF) pred;
  169280. }
  169281. /* AC20 */
  169282. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169283. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169284. if (num >= 0) {
  169285. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169286. if (Al > 0 && pred >= (1<<Al))
  169287. pred = (1<<Al)-1;
  169288. } else {
  169289. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169290. if (Al > 0 && pred >= (1<<Al))
  169291. pred = (1<<Al)-1;
  169292. pred = -pred;
  169293. }
  169294. workspace[16] = (JCOEF) pred;
  169295. }
  169296. /* AC11 */
  169297. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169298. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169299. if (num >= 0) {
  169300. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169301. if (Al > 0 && pred >= (1<<Al))
  169302. pred = (1<<Al)-1;
  169303. } else {
  169304. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169305. if (Al > 0 && pred >= (1<<Al))
  169306. pred = (1<<Al)-1;
  169307. pred = -pred;
  169308. }
  169309. workspace[9] = (JCOEF) pred;
  169310. }
  169311. /* AC02 */
  169312. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169313. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169314. if (num >= 0) {
  169315. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169316. if (Al > 0 && pred >= (1<<Al))
  169317. pred = (1<<Al)-1;
  169318. } else {
  169319. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169320. if (Al > 0 && pred >= (1<<Al))
  169321. pred = (1<<Al)-1;
  169322. pred = -pred;
  169323. }
  169324. workspace[2] = (JCOEF) pred;
  169325. }
  169326. /* OK, do the IDCT */
  169327. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169328. output_ptr, output_col);
  169329. /* Advance for next column */
  169330. DC1 = DC2; DC2 = DC3;
  169331. DC4 = DC5; DC5 = DC6;
  169332. DC7 = DC8; DC8 = DC9;
  169333. buffer_ptr++, prev_block_row++, next_block_row++;
  169334. output_col += compptr->DCT_scaled_size;
  169335. }
  169336. output_ptr += compptr->DCT_scaled_size;
  169337. }
  169338. }
  169339. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169340. return JPEG_ROW_COMPLETED;
  169341. return JPEG_SCAN_COMPLETED;
  169342. }
  169343. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169344. /*
  169345. * Initialize coefficient buffer controller.
  169346. */
  169347. GLOBAL(void)
  169348. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169349. {
  169350. my_coef_ptr3 coef;
  169351. coef = (my_coef_ptr3)
  169352. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169353. SIZEOF(my_coef_controller3));
  169354. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169355. coef->pub.start_input_pass = start_input_pass;
  169356. coef->pub.start_output_pass = start_output_pass;
  169357. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169358. coef->coef_bits_latch = NULL;
  169359. #endif
  169360. /* Create the coefficient buffer. */
  169361. if (need_full_buffer) {
  169362. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169363. /* Allocate a full-image virtual array for each component, */
  169364. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169365. /* Note we ask for a pre-zeroed array. */
  169366. int ci, access_rows;
  169367. jpeg_component_info *compptr;
  169368. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169369. ci++, compptr++) {
  169370. access_rows = compptr->v_samp_factor;
  169371. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169372. /* If block smoothing could be used, need a bigger window */
  169373. if (cinfo->progressive_mode)
  169374. access_rows *= 3;
  169375. #endif
  169376. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169377. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169378. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169379. (long) compptr->h_samp_factor),
  169380. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169381. (long) compptr->v_samp_factor),
  169382. (JDIMENSION) access_rows);
  169383. }
  169384. coef->pub.consume_data = consume_data;
  169385. coef->pub.decompress_data = decompress_data;
  169386. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169387. #else
  169388. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169389. #endif
  169390. } else {
  169391. /* We only need a single-MCU buffer. */
  169392. JBLOCKROW buffer;
  169393. int i;
  169394. buffer = (JBLOCKROW)
  169395. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169396. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169397. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169398. coef->MCU_buffer[i] = buffer + i;
  169399. }
  169400. coef->pub.consume_data = dummy_consume_data;
  169401. coef->pub.decompress_data = decompress_onepass;
  169402. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169403. }
  169404. }
  169405. /*** End of inlined file: jdcoefct.c ***/
  169406. #undef FIX
  169407. /*** Start of inlined file: jdcolor.c ***/
  169408. #define JPEG_INTERNALS
  169409. /* Private subobject */
  169410. typedef struct {
  169411. struct jpeg_color_deconverter pub; /* public fields */
  169412. /* Private state for YCC->RGB conversion */
  169413. int * Cr_r_tab; /* => table for Cr to R conversion */
  169414. int * Cb_b_tab; /* => table for Cb to B conversion */
  169415. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169416. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169417. } my_color_deconverter2;
  169418. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169419. /**************** YCbCr -> RGB conversion: most common case **************/
  169420. /*
  169421. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169422. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169423. * The conversion equations to be implemented are therefore
  169424. * R = Y + 1.40200 * Cr
  169425. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169426. * B = Y + 1.77200 * Cb
  169427. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169428. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169429. *
  169430. * To avoid floating-point arithmetic, we represent the fractional constants
  169431. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169432. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169433. * Notice that Y, being an integral input, does not contribute any fraction
  169434. * so it need not participate in the rounding.
  169435. *
  169436. * For even more speed, we avoid doing any multiplications in the inner loop
  169437. * by precalculating the constants times Cb and Cr for all possible values.
  169438. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169439. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169440. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169441. * colorspace anyway.
  169442. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169443. * values for the G calculation are left scaled up, since we must add them
  169444. * together before rounding.
  169445. */
  169446. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169447. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169448. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169449. /*
  169450. * Initialize tables for YCC->RGB colorspace conversion.
  169451. */
  169452. LOCAL(void)
  169453. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169454. {
  169455. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169456. int i;
  169457. INT32 x;
  169458. SHIFT_TEMPS
  169459. cconvert->Cr_r_tab = (int *)
  169460. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169461. (MAXJSAMPLE+1) * SIZEOF(int));
  169462. cconvert->Cb_b_tab = (int *)
  169463. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169464. (MAXJSAMPLE+1) * SIZEOF(int));
  169465. cconvert->Cr_g_tab = (INT32 *)
  169466. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169467. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169468. cconvert->Cb_g_tab = (INT32 *)
  169469. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169470. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169471. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169472. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169473. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169474. /* Cr=>R value is nearest int to 1.40200 * x */
  169475. cconvert->Cr_r_tab[i] = (int)
  169476. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169477. /* Cb=>B value is nearest int to 1.77200 * x */
  169478. cconvert->Cb_b_tab[i] = (int)
  169479. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169480. /* Cr=>G value is scaled-up -0.71414 * x */
  169481. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169482. /* Cb=>G value is scaled-up -0.34414 * x */
  169483. /* We also add in ONE_HALF so that need not do it in inner loop */
  169484. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169485. }
  169486. }
  169487. /*
  169488. * Convert some rows of samples to the output colorspace.
  169489. *
  169490. * Note that we change from noninterleaved, one-plane-per-component format
  169491. * to interleaved-pixel format. The output buffer is therefore three times
  169492. * as wide as the input buffer.
  169493. * A starting row offset is provided only for the input buffer. The caller
  169494. * can easily adjust the passed output_buf value to accommodate any row
  169495. * offset required on that side.
  169496. */
  169497. METHODDEF(void)
  169498. ycc_rgb_convert (j_decompress_ptr cinfo,
  169499. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169500. JSAMPARRAY output_buf, int num_rows)
  169501. {
  169502. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169503. register int y, cb, cr;
  169504. register JSAMPROW outptr;
  169505. register JSAMPROW inptr0, inptr1, inptr2;
  169506. register JDIMENSION col;
  169507. JDIMENSION num_cols = cinfo->output_width;
  169508. /* copy these pointers into registers if possible */
  169509. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169510. register int * Crrtab = cconvert->Cr_r_tab;
  169511. register int * Cbbtab = cconvert->Cb_b_tab;
  169512. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169513. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169514. SHIFT_TEMPS
  169515. while (--num_rows >= 0) {
  169516. inptr0 = input_buf[0][input_row];
  169517. inptr1 = input_buf[1][input_row];
  169518. inptr2 = input_buf[2][input_row];
  169519. input_row++;
  169520. outptr = *output_buf++;
  169521. for (col = 0; col < num_cols; col++) {
  169522. y = GETJSAMPLE(inptr0[col]);
  169523. cb = GETJSAMPLE(inptr1[col]);
  169524. cr = GETJSAMPLE(inptr2[col]);
  169525. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169526. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169527. outptr[RGB_GREEN] = range_limit[y +
  169528. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169529. SCALEBITS))];
  169530. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169531. outptr += RGB_PIXELSIZE;
  169532. }
  169533. }
  169534. }
  169535. /**************** Cases other than YCbCr -> RGB **************/
  169536. /*
  169537. * Color conversion for no colorspace change: just copy the data,
  169538. * converting from separate-planes to interleaved representation.
  169539. */
  169540. METHODDEF(void)
  169541. null_convert2 (j_decompress_ptr cinfo,
  169542. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169543. JSAMPARRAY output_buf, int num_rows)
  169544. {
  169545. register JSAMPROW inptr, outptr;
  169546. register JDIMENSION count;
  169547. register int num_components = cinfo->num_components;
  169548. JDIMENSION num_cols = cinfo->output_width;
  169549. int ci;
  169550. while (--num_rows >= 0) {
  169551. for (ci = 0; ci < num_components; ci++) {
  169552. inptr = input_buf[ci][input_row];
  169553. outptr = output_buf[0] + ci;
  169554. for (count = num_cols; count > 0; count--) {
  169555. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169556. outptr += num_components;
  169557. }
  169558. }
  169559. input_row++;
  169560. output_buf++;
  169561. }
  169562. }
  169563. /*
  169564. * Color conversion for grayscale: just copy the data.
  169565. * This also works for YCbCr -> grayscale conversion, in which
  169566. * we just copy the Y (luminance) component and ignore chrominance.
  169567. */
  169568. METHODDEF(void)
  169569. grayscale_convert2 (j_decompress_ptr cinfo,
  169570. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169571. JSAMPARRAY output_buf, int num_rows)
  169572. {
  169573. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169574. num_rows, cinfo->output_width);
  169575. }
  169576. /*
  169577. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169578. * This is provided to support applications that don't want to cope
  169579. * with grayscale as a separate case.
  169580. */
  169581. METHODDEF(void)
  169582. gray_rgb_convert (j_decompress_ptr cinfo,
  169583. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169584. JSAMPARRAY output_buf, int num_rows)
  169585. {
  169586. register JSAMPROW inptr, outptr;
  169587. register JDIMENSION col;
  169588. JDIMENSION num_cols = cinfo->output_width;
  169589. while (--num_rows >= 0) {
  169590. inptr = input_buf[0][input_row++];
  169591. outptr = *output_buf++;
  169592. for (col = 0; col < num_cols; col++) {
  169593. /* We can dispense with GETJSAMPLE() here */
  169594. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169595. outptr += RGB_PIXELSIZE;
  169596. }
  169597. }
  169598. }
  169599. /*
  169600. * Adobe-style YCCK->CMYK conversion.
  169601. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169602. * conversion as above, while passing K (black) unchanged.
  169603. * We assume build_ycc_rgb_table has been called.
  169604. */
  169605. METHODDEF(void)
  169606. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169607. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169608. JSAMPARRAY output_buf, int num_rows)
  169609. {
  169610. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169611. register int y, cb, cr;
  169612. register JSAMPROW outptr;
  169613. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169614. register JDIMENSION col;
  169615. JDIMENSION num_cols = cinfo->output_width;
  169616. /* copy these pointers into registers if possible */
  169617. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169618. register int * Crrtab = cconvert->Cr_r_tab;
  169619. register int * Cbbtab = cconvert->Cb_b_tab;
  169620. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169621. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169622. SHIFT_TEMPS
  169623. while (--num_rows >= 0) {
  169624. inptr0 = input_buf[0][input_row];
  169625. inptr1 = input_buf[1][input_row];
  169626. inptr2 = input_buf[2][input_row];
  169627. inptr3 = input_buf[3][input_row];
  169628. input_row++;
  169629. outptr = *output_buf++;
  169630. for (col = 0; col < num_cols; col++) {
  169631. y = GETJSAMPLE(inptr0[col]);
  169632. cb = GETJSAMPLE(inptr1[col]);
  169633. cr = GETJSAMPLE(inptr2[col]);
  169634. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169635. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169636. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169637. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169638. SCALEBITS)))];
  169639. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169640. /* K passes through unchanged */
  169641. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169642. outptr += 4;
  169643. }
  169644. }
  169645. }
  169646. /*
  169647. * Empty method for start_pass.
  169648. */
  169649. METHODDEF(void)
  169650. start_pass_dcolor (j_decompress_ptr)
  169651. {
  169652. /* no work needed */
  169653. }
  169654. /*
  169655. * Module initialization routine for output colorspace conversion.
  169656. */
  169657. GLOBAL(void)
  169658. jinit_color_deconverter (j_decompress_ptr cinfo)
  169659. {
  169660. my_cconvert_ptr2 cconvert;
  169661. int ci;
  169662. cconvert = (my_cconvert_ptr2)
  169663. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169664. SIZEOF(my_color_deconverter2));
  169665. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169666. cconvert->pub.start_pass = start_pass_dcolor;
  169667. /* Make sure num_components agrees with jpeg_color_space */
  169668. switch (cinfo->jpeg_color_space) {
  169669. case JCS_GRAYSCALE:
  169670. if (cinfo->num_components != 1)
  169671. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169672. break;
  169673. case JCS_RGB:
  169674. case JCS_YCbCr:
  169675. if (cinfo->num_components != 3)
  169676. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169677. break;
  169678. case JCS_CMYK:
  169679. case JCS_YCCK:
  169680. if (cinfo->num_components != 4)
  169681. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169682. break;
  169683. default: /* JCS_UNKNOWN can be anything */
  169684. if (cinfo->num_components < 1)
  169685. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169686. break;
  169687. }
  169688. /* Set out_color_components and conversion method based on requested space.
  169689. * Also clear the component_needed flags for any unused components,
  169690. * so that earlier pipeline stages can avoid useless computation.
  169691. */
  169692. switch (cinfo->out_color_space) {
  169693. case JCS_GRAYSCALE:
  169694. cinfo->out_color_components = 1;
  169695. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169696. cinfo->jpeg_color_space == JCS_YCbCr) {
  169697. cconvert->pub.color_convert = grayscale_convert2;
  169698. /* For color->grayscale conversion, only the Y (0) component is needed */
  169699. for (ci = 1; ci < cinfo->num_components; ci++)
  169700. cinfo->comp_info[ci].component_needed = FALSE;
  169701. } else
  169702. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169703. break;
  169704. case JCS_RGB:
  169705. cinfo->out_color_components = RGB_PIXELSIZE;
  169706. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169707. cconvert->pub.color_convert = ycc_rgb_convert;
  169708. build_ycc_rgb_table(cinfo);
  169709. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169710. cconvert->pub.color_convert = gray_rgb_convert;
  169711. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169712. cconvert->pub.color_convert = null_convert2;
  169713. } else
  169714. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169715. break;
  169716. case JCS_CMYK:
  169717. cinfo->out_color_components = 4;
  169718. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169719. cconvert->pub.color_convert = ycck_cmyk_convert;
  169720. build_ycc_rgb_table(cinfo);
  169721. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169722. cconvert->pub.color_convert = null_convert2;
  169723. } else
  169724. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169725. break;
  169726. default:
  169727. /* Permit null conversion to same output space */
  169728. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169729. cinfo->out_color_components = cinfo->num_components;
  169730. cconvert->pub.color_convert = null_convert2;
  169731. } else /* unsupported non-null conversion */
  169732. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169733. break;
  169734. }
  169735. if (cinfo->quantize_colors)
  169736. cinfo->output_components = 1; /* single colormapped output component */
  169737. else
  169738. cinfo->output_components = cinfo->out_color_components;
  169739. }
  169740. /*** End of inlined file: jdcolor.c ***/
  169741. #undef FIX
  169742. /*** Start of inlined file: jddctmgr.c ***/
  169743. #define JPEG_INTERNALS
  169744. /*
  169745. * The decompressor input side (jdinput.c) saves away the appropriate
  169746. * quantization table for each component at the start of the first scan
  169747. * involving that component. (This is necessary in order to correctly
  169748. * decode files that reuse Q-table slots.)
  169749. * When we are ready to make an output pass, the saved Q-table is converted
  169750. * to a multiplier table that will actually be used by the IDCT routine.
  169751. * The multiplier table contents are IDCT-method-dependent. To support
  169752. * application changes in IDCT method between scans, we can remake the
  169753. * multiplier tables if necessary.
  169754. * In buffered-image mode, the first output pass may occur before any data
  169755. * has been seen for some components, and thus before their Q-tables have
  169756. * been saved away. To handle this case, multiplier tables are preset
  169757. * to zeroes; the result of the IDCT will be a neutral gray level.
  169758. */
  169759. /* Private subobject for this module */
  169760. typedef struct {
  169761. struct jpeg_inverse_dct pub; /* public fields */
  169762. /* This array contains the IDCT method code that each multiplier table
  169763. * is currently set up for, or -1 if it's not yet set up.
  169764. * The actual multiplier tables are pointed to by dct_table in the
  169765. * per-component comp_info structures.
  169766. */
  169767. int cur_method[MAX_COMPONENTS];
  169768. } my_idct_controller;
  169769. typedef my_idct_controller * my_idct_ptr;
  169770. /* Allocated multiplier tables: big enough for any supported variant */
  169771. typedef union {
  169772. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169773. #ifdef DCT_IFAST_SUPPORTED
  169774. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169775. #endif
  169776. #ifdef DCT_FLOAT_SUPPORTED
  169777. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169778. #endif
  169779. } multiplier_table;
  169780. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169781. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169782. */
  169783. #ifdef DCT_ISLOW_SUPPORTED
  169784. #define PROVIDE_ISLOW_TABLES
  169785. #else
  169786. #ifdef IDCT_SCALING_SUPPORTED
  169787. #define PROVIDE_ISLOW_TABLES
  169788. #endif
  169789. #endif
  169790. /*
  169791. * Prepare for an output pass.
  169792. * Here we select the proper IDCT routine for each component and build
  169793. * a matching multiplier table.
  169794. */
  169795. METHODDEF(void)
  169796. start_pass (j_decompress_ptr cinfo)
  169797. {
  169798. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169799. int ci, i;
  169800. jpeg_component_info *compptr;
  169801. int method = 0;
  169802. inverse_DCT_method_ptr method_ptr = NULL;
  169803. JQUANT_TBL * qtbl;
  169804. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169805. ci++, compptr++) {
  169806. /* Select the proper IDCT routine for this component's scaling */
  169807. switch (compptr->DCT_scaled_size) {
  169808. #ifdef IDCT_SCALING_SUPPORTED
  169809. case 1:
  169810. method_ptr = jpeg_idct_1x1;
  169811. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169812. break;
  169813. case 2:
  169814. method_ptr = jpeg_idct_2x2;
  169815. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169816. break;
  169817. case 4:
  169818. method_ptr = jpeg_idct_4x4;
  169819. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169820. break;
  169821. #endif
  169822. case DCTSIZE:
  169823. switch (cinfo->dct_method) {
  169824. #ifdef DCT_ISLOW_SUPPORTED
  169825. case JDCT_ISLOW:
  169826. method_ptr = jpeg_idct_islow;
  169827. method = JDCT_ISLOW;
  169828. break;
  169829. #endif
  169830. #ifdef DCT_IFAST_SUPPORTED
  169831. case JDCT_IFAST:
  169832. method_ptr = jpeg_idct_ifast;
  169833. method = JDCT_IFAST;
  169834. break;
  169835. #endif
  169836. #ifdef DCT_FLOAT_SUPPORTED
  169837. case JDCT_FLOAT:
  169838. method_ptr = jpeg_idct_float;
  169839. method = JDCT_FLOAT;
  169840. break;
  169841. #endif
  169842. default:
  169843. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169844. break;
  169845. }
  169846. break;
  169847. default:
  169848. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169849. break;
  169850. }
  169851. idct->pub.inverse_DCT[ci] = method_ptr;
  169852. /* Create multiplier table from quant table.
  169853. * However, we can skip this if the component is uninteresting
  169854. * or if we already built the table. Also, if no quant table
  169855. * has yet been saved for the component, we leave the
  169856. * multiplier table all-zero; we'll be reading zeroes from the
  169857. * coefficient controller's buffer anyway.
  169858. */
  169859. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169860. continue;
  169861. qtbl = compptr->quant_table;
  169862. if (qtbl == NULL) /* happens if no data yet for component */
  169863. continue;
  169864. idct->cur_method[ci] = method;
  169865. switch (method) {
  169866. #ifdef PROVIDE_ISLOW_TABLES
  169867. case JDCT_ISLOW:
  169868. {
  169869. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169870. * coefficients, but are stored as ints to ensure access efficiency.
  169871. */
  169872. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169873. for (i = 0; i < DCTSIZE2; i++) {
  169874. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169875. }
  169876. }
  169877. break;
  169878. #endif
  169879. #ifdef DCT_IFAST_SUPPORTED
  169880. case JDCT_IFAST:
  169881. {
  169882. /* For AA&N IDCT method, multipliers are equal to quantization
  169883. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169884. * scalefactor[0] = 1
  169885. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169886. * For integer operation, the multiplier table is to be scaled by
  169887. * IFAST_SCALE_BITS.
  169888. */
  169889. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169890. #define CONST_BITS 14
  169891. static const INT16 aanscales[DCTSIZE2] = {
  169892. /* precomputed values scaled up by 14 bits */
  169893. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169894. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169895. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169896. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169897. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169898. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169899. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169900. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169901. };
  169902. SHIFT_TEMPS
  169903. for (i = 0; i < DCTSIZE2; i++) {
  169904. ifmtbl[i] = (IFAST_MULT_TYPE)
  169905. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169906. (INT32) aanscales[i]),
  169907. CONST_BITS-IFAST_SCALE_BITS);
  169908. }
  169909. }
  169910. break;
  169911. #endif
  169912. #ifdef DCT_FLOAT_SUPPORTED
  169913. case JDCT_FLOAT:
  169914. {
  169915. /* For float AA&N IDCT method, multipliers are equal to quantization
  169916. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169917. * scalefactor[0] = 1
  169918. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169919. */
  169920. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169921. int row, col;
  169922. static const double aanscalefactor[DCTSIZE] = {
  169923. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169924. 1.0, 0.785694958, 0.541196100, 0.275899379
  169925. };
  169926. i = 0;
  169927. for (row = 0; row < DCTSIZE; row++) {
  169928. for (col = 0; col < DCTSIZE; col++) {
  169929. fmtbl[i] = (FLOAT_MULT_TYPE)
  169930. ((double) qtbl->quantval[i] *
  169931. aanscalefactor[row] * aanscalefactor[col]);
  169932. i++;
  169933. }
  169934. }
  169935. }
  169936. break;
  169937. #endif
  169938. default:
  169939. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169940. break;
  169941. }
  169942. }
  169943. }
  169944. /*
  169945. * Initialize IDCT manager.
  169946. */
  169947. GLOBAL(void)
  169948. jinit_inverse_dct (j_decompress_ptr cinfo)
  169949. {
  169950. my_idct_ptr idct;
  169951. int ci;
  169952. jpeg_component_info *compptr;
  169953. idct = (my_idct_ptr)
  169954. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169955. SIZEOF(my_idct_controller));
  169956. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169957. idct->pub.start_pass = start_pass;
  169958. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169959. ci++, compptr++) {
  169960. /* Allocate and pre-zero a multiplier table for each component */
  169961. compptr->dct_table =
  169962. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169963. SIZEOF(multiplier_table));
  169964. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169965. /* Mark multiplier table not yet set up for any method */
  169966. idct->cur_method[ci] = -1;
  169967. }
  169968. }
  169969. /*** End of inlined file: jddctmgr.c ***/
  169970. #undef CONST_BITS
  169971. #undef ASSIGN_STATE
  169972. /*** Start of inlined file: jdhuff.c ***/
  169973. #define JPEG_INTERNALS
  169974. /*** Start of inlined file: jdhuff.h ***/
  169975. /* Short forms of external names for systems with brain-damaged linkers. */
  169976. #ifndef __jdhuff_h__
  169977. #define __jdhuff_h__
  169978. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169979. #define jpeg_make_d_derived_tbl jMkDDerived
  169980. #define jpeg_fill_bit_buffer jFilBitBuf
  169981. #define jpeg_huff_decode jHufDecode
  169982. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169983. /* Derived data constructed for each Huffman table */
  169984. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169985. typedef struct {
  169986. /* Basic tables: (element [0] of each array is unused) */
  169987. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169988. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169989. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169990. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169991. * the smallest code of length k; so given a code of length k, the
  169992. * corresponding symbol is huffval[code + valoffset[k]]
  169993. */
  169994. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169995. JHUFF_TBL *pub;
  169996. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169997. * the input data stream. If the next Huffman code is no more
  169998. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169999. * the corresponding symbol directly from these tables.
  170000. */
  170001. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  170002. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  170003. } d_derived_tbl;
  170004. /* Expand a Huffman table definition into the derived format */
  170005. EXTERN(void) jpeg_make_d_derived_tbl
  170006. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  170007. d_derived_tbl ** pdtbl));
  170008. /*
  170009. * Fetching the next N bits from the input stream is a time-critical operation
  170010. * for the Huffman decoders. We implement it with a combination of inline
  170011. * macros and out-of-line subroutines. Note that N (the number of bits
  170012. * demanded at one time) never exceeds 15 for JPEG use.
  170013. *
  170014. * We read source bytes into get_buffer and dole out bits as needed.
  170015. * If get_buffer already contains enough bits, they are fetched in-line
  170016. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  170017. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  170018. * as full as possible (not just to the number of bits needed; this
  170019. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  170020. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  170021. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  170022. * at least the requested number of bits --- dummy zeroes are inserted if
  170023. * necessary.
  170024. */
  170025. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  170026. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  170027. /* If long is > 32 bits on your machine, and shifting/masking longs is
  170028. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  170029. * appropriately should be a win. Unfortunately we can't define the size
  170030. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  170031. * because not all machines measure sizeof in 8-bit bytes.
  170032. */
  170033. typedef struct { /* Bitreading state saved across MCUs */
  170034. bit_buf_type get_buffer; /* current bit-extraction buffer */
  170035. int bits_left; /* # of unused bits in it */
  170036. } bitread_perm_state;
  170037. typedef struct { /* Bitreading working state within an MCU */
  170038. /* Current data source location */
  170039. /* We need a copy, rather than munging the original, in case of suspension */
  170040. const JOCTET * next_input_byte; /* => next byte to read from source */
  170041. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  170042. /* Bit input buffer --- note these values are kept in register variables,
  170043. * not in this struct, inside the inner loops.
  170044. */
  170045. bit_buf_type get_buffer; /* current bit-extraction buffer */
  170046. int bits_left; /* # of unused bits in it */
  170047. /* Pointer needed by jpeg_fill_bit_buffer. */
  170048. j_decompress_ptr cinfo; /* back link to decompress master record */
  170049. } bitread_working_state;
  170050. /* Macros to declare and load/save bitread local variables. */
  170051. #define BITREAD_STATE_VARS \
  170052. register bit_buf_type get_buffer; \
  170053. register int bits_left; \
  170054. bitread_working_state br_state
  170055. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  170056. br_state.cinfo = cinfop; \
  170057. br_state.next_input_byte = cinfop->src->next_input_byte; \
  170058. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  170059. get_buffer = permstate.get_buffer; \
  170060. bits_left = permstate.bits_left;
  170061. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  170062. cinfop->src->next_input_byte = br_state.next_input_byte; \
  170063. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  170064. permstate.get_buffer = get_buffer; \
  170065. permstate.bits_left = bits_left
  170066. /*
  170067. * These macros provide the in-line portion of bit fetching.
  170068. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  170069. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  170070. * The variables get_buffer and bits_left are assumed to be locals,
  170071. * but the state struct might not be (jpeg_huff_decode needs this).
  170072. * CHECK_BIT_BUFFER(state,n,action);
  170073. * Ensure there are N bits in get_buffer; if suspend, take action.
  170074. * val = GET_BITS(n);
  170075. * Fetch next N bits.
  170076. * val = PEEK_BITS(n);
  170077. * Fetch next N bits without removing them from the buffer.
  170078. * DROP_BITS(n);
  170079. * Discard next N bits.
  170080. * The value N should be a simple variable, not an expression, because it
  170081. * is evaluated multiple times.
  170082. */
  170083. #define CHECK_BIT_BUFFER(state,nbits,action) \
  170084. { if (bits_left < (nbits)) { \
  170085. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  170086. { action; } \
  170087. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  170088. #define GET_BITS(nbits) \
  170089. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  170090. #define PEEK_BITS(nbits) \
  170091. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  170092. #define DROP_BITS(nbits) \
  170093. (bits_left -= (nbits))
  170094. /* Load up the bit buffer to a depth of at least nbits */
  170095. EXTERN(boolean) jpeg_fill_bit_buffer
  170096. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170097. register int bits_left, int nbits));
  170098. /*
  170099. * Code for extracting next Huffman-coded symbol from input bit stream.
  170100. * Again, this is time-critical and we make the main paths be macros.
  170101. *
  170102. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  170103. * without looping. Usually, more than 95% of the Huffman codes will be 8
  170104. * or fewer bits long. The few overlength codes are handled with a loop,
  170105. * which need not be inline code.
  170106. *
  170107. * Notes about the HUFF_DECODE macro:
  170108. * 1. Near the end of the data segment, we may fail to get enough bits
  170109. * for a lookahead. In that case, we do it the hard way.
  170110. * 2. If the lookahead table contains no entry, the next code must be
  170111. * more than HUFF_LOOKAHEAD bits long.
  170112. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  170113. */
  170114. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  170115. { register int nb, look; \
  170116. if (bits_left < HUFF_LOOKAHEAD) { \
  170117. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  170118. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170119. if (bits_left < HUFF_LOOKAHEAD) { \
  170120. nb = 1; goto slowlabel; \
  170121. } \
  170122. } \
  170123. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170124. if ((nb = htbl->look_nbits[look]) != 0) { \
  170125. DROP_BITS(nb); \
  170126. result = htbl->look_sym[look]; \
  170127. } else { \
  170128. nb = HUFF_LOOKAHEAD+1; \
  170129. slowlabel: \
  170130. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170131. { failaction; } \
  170132. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170133. } \
  170134. }
  170135. /* Out-of-line case for Huffman code fetching */
  170136. EXTERN(int) jpeg_huff_decode
  170137. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170138. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170139. #endif
  170140. /*** End of inlined file: jdhuff.h ***/
  170141. /* Declarations shared with jdphuff.c */
  170142. /*
  170143. * Expanded entropy decoder object for Huffman decoding.
  170144. *
  170145. * The savable_state subrecord contains fields that change within an MCU,
  170146. * but must not be updated permanently until we complete the MCU.
  170147. */
  170148. typedef struct {
  170149. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170150. } savable_state2;
  170151. /* This macro is to work around compilers with missing or broken
  170152. * structure assignment. You'll need to fix this code if you have
  170153. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170154. */
  170155. #ifndef NO_STRUCT_ASSIGN
  170156. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170157. #else
  170158. #if MAX_COMPS_IN_SCAN == 4
  170159. #define ASSIGN_STATE(dest,src) \
  170160. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170161. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170162. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170163. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170164. #endif
  170165. #endif
  170166. typedef struct {
  170167. struct jpeg_entropy_decoder pub; /* public fields */
  170168. /* These fields are loaded into local variables at start of each MCU.
  170169. * In case of suspension, we exit WITHOUT updating them.
  170170. */
  170171. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170172. savable_state2 saved; /* Other state at start of MCU */
  170173. /* These fields are NOT loaded into local working state. */
  170174. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170175. /* Pointers to derived tables (these workspaces have image lifespan) */
  170176. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170177. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170178. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170179. /* Pointers to derived tables to be used for each block within an MCU */
  170180. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170181. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170182. /* Whether we care about the DC and AC coefficient values for each block */
  170183. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170184. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170185. } huff_entropy_decoder2;
  170186. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170187. /*
  170188. * Initialize for a Huffman-compressed scan.
  170189. */
  170190. METHODDEF(void)
  170191. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170192. {
  170193. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170194. int ci, blkn, dctbl, actbl;
  170195. jpeg_component_info * compptr;
  170196. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170197. * This ought to be an error condition, but we make it a warning because
  170198. * there are some baseline files out there with all zeroes in these bytes.
  170199. */
  170200. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170201. cinfo->Ah != 0 || cinfo->Al != 0)
  170202. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170203. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170204. compptr = cinfo->cur_comp_info[ci];
  170205. dctbl = compptr->dc_tbl_no;
  170206. actbl = compptr->ac_tbl_no;
  170207. /* Compute derived values for Huffman tables */
  170208. /* We may do this more than once for a table, but it's not expensive */
  170209. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170210. & entropy->dc_derived_tbls[dctbl]);
  170211. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170212. & entropy->ac_derived_tbls[actbl]);
  170213. /* Initialize DC predictions to 0 */
  170214. entropy->saved.last_dc_val[ci] = 0;
  170215. }
  170216. /* Precalculate decoding info for each block in an MCU of this scan */
  170217. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170218. ci = cinfo->MCU_membership[blkn];
  170219. compptr = cinfo->cur_comp_info[ci];
  170220. /* Precalculate which table to use for each block */
  170221. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170222. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170223. /* Decide whether we really care about the coefficient values */
  170224. if (compptr->component_needed) {
  170225. entropy->dc_needed[blkn] = TRUE;
  170226. /* we don't need the ACs if producing a 1/8th-size image */
  170227. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170228. } else {
  170229. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170230. }
  170231. }
  170232. /* Initialize bitread state variables */
  170233. entropy->bitstate.bits_left = 0;
  170234. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170235. entropy->pub.insufficient_data = FALSE;
  170236. /* Initialize restart counter */
  170237. entropy->restarts_to_go = cinfo->restart_interval;
  170238. }
  170239. /*
  170240. * Compute the derived values for a Huffman table.
  170241. * This routine also performs some validation checks on the table.
  170242. *
  170243. * Note this is also used by jdphuff.c.
  170244. */
  170245. GLOBAL(void)
  170246. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170247. d_derived_tbl ** pdtbl)
  170248. {
  170249. JHUFF_TBL *htbl;
  170250. d_derived_tbl *dtbl;
  170251. int p, i, l, si, numsymbols;
  170252. int lookbits, ctr;
  170253. char huffsize[257];
  170254. unsigned int huffcode[257];
  170255. unsigned int code;
  170256. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170257. * paralleling the order of the symbols themselves in htbl->huffval[].
  170258. */
  170259. /* Find the input Huffman table */
  170260. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170261. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170262. htbl =
  170263. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170264. if (htbl == NULL)
  170265. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170266. /* Allocate a workspace if we haven't already done so. */
  170267. if (*pdtbl == NULL)
  170268. *pdtbl = (d_derived_tbl *)
  170269. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170270. SIZEOF(d_derived_tbl));
  170271. dtbl = *pdtbl;
  170272. dtbl->pub = htbl; /* fill in back link */
  170273. /* Figure C.1: make table of Huffman code length for each symbol */
  170274. p = 0;
  170275. for (l = 1; l <= 16; l++) {
  170276. i = (int) htbl->bits[l];
  170277. if (i < 0 || p + i > 256) /* protect against table overrun */
  170278. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170279. while (i--)
  170280. huffsize[p++] = (char) l;
  170281. }
  170282. huffsize[p] = 0;
  170283. numsymbols = p;
  170284. /* Figure C.2: generate the codes themselves */
  170285. /* We also validate that the counts represent a legal Huffman code tree. */
  170286. code = 0;
  170287. si = huffsize[0];
  170288. p = 0;
  170289. while (huffsize[p]) {
  170290. while (((int) huffsize[p]) == si) {
  170291. huffcode[p++] = code;
  170292. code++;
  170293. }
  170294. /* code is now 1 more than the last code used for codelength si; but
  170295. * it must still fit in si bits, since no code is allowed to be all ones.
  170296. */
  170297. if (((INT32) code) >= (((INT32) 1) << si))
  170298. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170299. code <<= 1;
  170300. si++;
  170301. }
  170302. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170303. p = 0;
  170304. for (l = 1; l <= 16; l++) {
  170305. if (htbl->bits[l]) {
  170306. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170307. * minus the minimum code of length l
  170308. */
  170309. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170310. p += htbl->bits[l];
  170311. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170312. } else {
  170313. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170314. }
  170315. }
  170316. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170317. /* Compute lookahead tables to speed up decoding.
  170318. * First we set all the table entries to 0, indicating "too long";
  170319. * then we iterate through the Huffman codes that are short enough and
  170320. * fill in all the entries that correspond to bit sequences starting
  170321. * with that code.
  170322. */
  170323. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170324. p = 0;
  170325. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170326. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170327. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170328. /* Generate left-justified code followed by all possible bit sequences */
  170329. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170330. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170331. dtbl->look_nbits[lookbits] = l;
  170332. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170333. lookbits++;
  170334. }
  170335. }
  170336. }
  170337. /* Validate symbols as being reasonable.
  170338. * For AC tables, we make no check, but accept all byte values 0..255.
  170339. * For DC tables, we require the symbols to be in range 0..15.
  170340. * (Tighter bounds could be applied depending on the data depth and mode,
  170341. * but this is sufficient to ensure safe decoding.)
  170342. */
  170343. if (isDC) {
  170344. for (i = 0; i < numsymbols; i++) {
  170345. int sym = htbl->huffval[i];
  170346. if (sym < 0 || sym > 15)
  170347. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170348. }
  170349. }
  170350. }
  170351. /*
  170352. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170353. * See jdhuff.h for info about usage.
  170354. * Note: current values of get_buffer and bits_left are passed as parameters,
  170355. * but are returned in the corresponding fields of the state struct.
  170356. *
  170357. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170358. * of get_buffer to be used. (On machines with wider words, an even larger
  170359. * buffer could be used.) However, on some machines 32-bit shifts are
  170360. * quite slow and take time proportional to the number of places shifted.
  170361. * (This is true with most PC compilers, for instance.) In this case it may
  170362. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170363. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170364. */
  170365. #ifdef SLOW_SHIFT_32
  170366. #define MIN_GET_BITS 15 /* minimum allowable value */
  170367. #else
  170368. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170369. #endif
  170370. GLOBAL(boolean)
  170371. jpeg_fill_bit_buffer (bitread_working_state * state,
  170372. register bit_buf_type get_buffer, register int bits_left,
  170373. int nbits)
  170374. /* Load up the bit buffer to a depth of at least nbits */
  170375. {
  170376. /* Copy heavily used state fields into locals (hopefully registers) */
  170377. register const JOCTET * next_input_byte = state->next_input_byte;
  170378. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170379. j_decompress_ptr cinfo = state->cinfo;
  170380. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170381. /* (It is assumed that no request will be for more than that many bits.) */
  170382. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170383. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170384. while (bits_left < MIN_GET_BITS) {
  170385. register int c;
  170386. /* Attempt to read a byte */
  170387. if (bytes_in_buffer == 0) {
  170388. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170389. return FALSE;
  170390. next_input_byte = cinfo->src->next_input_byte;
  170391. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170392. }
  170393. bytes_in_buffer--;
  170394. c = GETJOCTET(*next_input_byte++);
  170395. /* If it's 0xFF, check and discard stuffed zero byte */
  170396. if (c == 0xFF) {
  170397. /* Loop here to discard any padding FF's on terminating marker,
  170398. * so that we can save a valid unread_marker value. NOTE: we will
  170399. * accept multiple FF's followed by a 0 as meaning a single FF data
  170400. * byte. This data pattern is not valid according to the standard.
  170401. */
  170402. do {
  170403. if (bytes_in_buffer == 0) {
  170404. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170405. return FALSE;
  170406. next_input_byte = cinfo->src->next_input_byte;
  170407. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170408. }
  170409. bytes_in_buffer--;
  170410. c = GETJOCTET(*next_input_byte++);
  170411. } while (c == 0xFF);
  170412. if (c == 0) {
  170413. /* Found FF/00, which represents an FF data byte */
  170414. c = 0xFF;
  170415. } else {
  170416. /* Oops, it's actually a marker indicating end of compressed data.
  170417. * Save the marker code for later use.
  170418. * Fine point: it might appear that we should save the marker into
  170419. * bitread working state, not straight into permanent state. But
  170420. * once we have hit a marker, we cannot need to suspend within the
  170421. * current MCU, because we will read no more bytes from the data
  170422. * source. So it is OK to update permanent state right away.
  170423. */
  170424. cinfo->unread_marker = c;
  170425. /* See if we need to insert some fake zero bits. */
  170426. goto no_more_bytes;
  170427. }
  170428. }
  170429. /* OK, load c into get_buffer */
  170430. get_buffer = (get_buffer << 8) | c;
  170431. bits_left += 8;
  170432. } /* end while */
  170433. } else {
  170434. no_more_bytes:
  170435. /* We get here if we've read the marker that terminates the compressed
  170436. * data segment. There should be enough bits in the buffer register
  170437. * to satisfy the request; if so, no problem.
  170438. */
  170439. if (nbits > bits_left) {
  170440. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170441. * the data stream, so that we can produce some kind of image.
  170442. * We use a nonvolatile flag to ensure that only one warning message
  170443. * appears per data segment.
  170444. */
  170445. if (! cinfo->entropy->insufficient_data) {
  170446. WARNMS(cinfo, JWRN_HIT_MARKER);
  170447. cinfo->entropy->insufficient_data = TRUE;
  170448. }
  170449. /* Fill the buffer with zero bits */
  170450. get_buffer <<= MIN_GET_BITS - bits_left;
  170451. bits_left = MIN_GET_BITS;
  170452. }
  170453. }
  170454. /* Unload the local registers */
  170455. state->next_input_byte = next_input_byte;
  170456. state->bytes_in_buffer = bytes_in_buffer;
  170457. state->get_buffer = get_buffer;
  170458. state->bits_left = bits_left;
  170459. return TRUE;
  170460. }
  170461. /*
  170462. * Out-of-line code for Huffman code decoding.
  170463. * See jdhuff.h for info about usage.
  170464. */
  170465. GLOBAL(int)
  170466. jpeg_huff_decode (bitread_working_state * state,
  170467. register bit_buf_type get_buffer, register int bits_left,
  170468. d_derived_tbl * htbl, int min_bits)
  170469. {
  170470. register int l = min_bits;
  170471. register INT32 code;
  170472. /* HUFF_DECODE has determined that the code is at least min_bits */
  170473. /* bits long, so fetch that many bits in one swoop. */
  170474. CHECK_BIT_BUFFER(*state, l, return -1);
  170475. code = GET_BITS(l);
  170476. /* Collect the rest of the Huffman code one bit at a time. */
  170477. /* This is per Figure F.16 in the JPEG spec. */
  170478. while (code > htbl->maxcode[l]) {
  170479. code <<= 1;
  170480. CHECK_BIT_BUFFER(*state, 1, return -1);
  170481. code |= GET_BITS(1);
  170482. l++;
  170483. }
  170484. /* Unload the local registers */
  170485. state->get_buffer = get_buffer;
  170486. state->bits_left = bits_left;
  170487. /* With garbage input we may reach the sentinel value l = 17. */
  170488. if (l > 16) {
  170489. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170490. return 0; /* fake a zero as the safest result */
  170491. }
  170492. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170493. }
  170494. /*
  170495. * Check for a restart marker & resynchronize decoder.
  170496. * Returns FALSE if must suspend.
  170497. */
  170498. LOCAL(boolean)
  170499. process_restart (j_decompress_ptr cinfo)
  170500. {
  170501. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170502. int ci;
  170503. /* Throw away any unused bits remaining in bit buffer; */
  170504. /* include any full bytes in next_marker's count of discarded bytes */
  170505. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170506. entropy->bitstate.bits_left = 0;
  170507. /* Advance past the RSTn marker */
  170508. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170509. return FALSE;
  170510. /* Re-initialize DC predictions to 0 */
  170511. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170512. entropy->saved.last_dc_val[ci] = 0;
  170513. /* Reset restart counter */
  170514. entropy->restarts_to_go = cinfo->restart_interval;
  170515. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170516. * against a marker. In that case we will end up treating the next data
  170517. * segment as empty, and we can avoid producing bogus output pixels by
  170518. * leaving the flag set.
  170519. */
  170520. if (cinfo->unread_marker == 0)
  170521. entropy->pub.insufficient_data = FALSE;
  170522. return TRUE;
  170523. }
  170524. /*
  170525. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170526. * The coefficients are reordered from zigzag order into natural array order,
  170527. * but are not dequantized.
  170528. *
  170529. * The i'th block of the MCU is stored into the block pointed to by
  170530. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170531. * (Wholesale zeroing is usually a little faster than retail...)
  170532. *
  170533. * Returns FALSE if data source requested suspension. In that case no
  170534. * changes have been made to permanent state. (Exception: some output
  170535. * coefficients may already have been assigned. This is harmless for
  170536. * this module, since we'll just re-assign them on the next call.)
  170537. */
  170538. METHODDEF(boolean)
  170539. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170540. {
  170541. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170542. int blkn;
  170543. BITREAD_STATE_VARS;
  170544. savable_state2 state;
  170545. /* Process restart marker if needed; may have to suspend */
  170546. if (cinfo->restart_interval) {
  170547. if (entropy->restarts_to_go == 0)
  170548. if (! process_restart(cinfo))
  170549. return FALSE;
  170550. }
  170551. /* If we've run out of data, just leave the MCU set to zeroes.
  170552. * This way, we return uniform gray for the remainder of the segment.
  170553. */
  170554. if (! entropy->pub.insufficient_data) {
  170555. /* Load up working state */
  170556. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170557. ASSIGN_STATE(state, entropy->saved);
  170558. /* Outer loop handles each block in the MCU */
  170559. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170560. JBLOCKROW block = MCU_data[blkn];
  170561. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170562. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170563. register int s, k, r;
  170564. /* Decode a single block's worth of coefficients */
  170565. /* Section F.2.2.1: decode the DC coefficient difference */
  170566. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170567. if (s) {
  170568. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170569. r = GET_BITS(s);
  170570. s = HUFF_EXTEND(r, s);
  170571. }
  170572. if (entropy->dc_needed[blkn]) {
  170573. /* Convert DC difference to actual value, update last_dc_val */
  170574. int ci = cinfo->MCU_membership[blkn];
  170575. s += state.last_dc_val[ci];
  170576. state.last_dc_val[ci] = s;
  170577. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170578. (*block)[0] = (JCOEF) s;
  170579. }
  170580. if (entropy->ac_needed[blkn]) {
  170581. /* Section F.2.2.2: decode the AC coefficients */
  170582. /* Since zeroes are skipped, output area must be cleared beforehand */
  170583. for (k = 1; k < DCTSIZE2; k++) {
  170584. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170585. r = s >> 4;
  170586. s &= 15;
  170587. if (s) {
  170588. k += r;
  170589. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170590. r = GET_BITS(s);
  170591. s = HUFF_EXTEND(r, s);
  170592. /* Output coefficient in natural (dezigzagged) order.
  170593. * Note: the extra entries in jpeg_natural_order[] will save us
  170594. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170595. */
  170596. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170597. } else {
  170598. if (r != 15)
  170599. break;
  170600. k += 15;
  170601. }
  170602. }
  170603. } else {
  170604. /* Section F.2.2.2: decode the AC coefficients */
  170605. /* In this path we just discard the values */
  170606. for (k = 1; k < DCTSIZE2; k++) {
  170607. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170608. r = s >> 4;
  170609. s &= 15;
  170610. if (s) {
  170611. k += r;
  170612. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170613. DROP_BITS(s);
  170614. } else {
  170615. if (r != 15)
  170616. break;
  170617. k += 15;
  170618. }
  170619. }
  170620. }
  170621. }
  170622. /* Completed MCU, so update state */
  170623. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170624. ASSIGN_STATE(entropy->saved, state);
  170625. }
  170626. /* Account for restart interval (no-op if not using restarts) */
  170627. entropy->restarts_to_go--;
  170628. return TRUE;
  170629. }
  170630. /*
  170631. * Module initialization routine for Huffman entropy decoding.
  170632. */
  170633. GLOBAL(void)
  170634. jinit_huff_decoder (j_decompress_ptr cinfo)
  170635. {
  170636. huff_entropy_ptr2 entropy;
  170637. int i;
  170638. entropy = (huff_entropy_ptr2)
  170639. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170640. SIZEOF(huff_entropy_decoder2));
  170641. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170642. entropy->pub.start_pass = start_pass_huff_decoder;
  170643. entropy->pub.decode_mcu = decode_mcu;
  170644. /* Mark tables unallocated */
  170645. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170646. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170647. }
  170648. }
  170649. /*** End of inlined file: jdhuff.c ***/
  170650. /*** Start of inlined file: jdinput.c ***/
  170651. #define JPEG_INTERNALS
  170652. /* Private state */
  170653. typedef struct {
  170654. struct jpeg_input_controller pub; /* public fields */
  170655. boolean inheaders; /* TRUE until first SOS is reached */
  170656. } my_input_controller;
  170657. typedef my_input_controller * my_inputctl_ptr;
  170658. /* Forward declarations */
  170659. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170660. /*
  170661. * Routines to calculate various quantities related to the size of the image.
  170662. */
  170663. LOCAL(void)
  170664. initial_setup2 (j_decompress_ptr cinfo)
  170665. /* Called once, when first SOS marker is reached */
  170666. {
  170667. int ci;
  170668. jpeg_component_info *compptr;
  170669. /* Make sure image isn't bigger than I can handle */
  170670. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170671. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170672. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170673. /* For now, precision must match compiled-in value... */
  170674. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170675. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170676. /* Check that number of components won't exceed internal array sizes */
  170677. if (cinfo->num_components > MAX_COMPONENTS)
  170678. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170679. MAX_COMPONENTS);
  170680. /* Compute maximum sampling factors; check factor validity */
  170681. cinfo->max_h_samp_factor = 1;
  170682. cinfo->max_v_samp_factor = 1;
  170683. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170684. ci++, compptr++) {
  170685. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170686. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170687. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170688. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170689. compptr->h_samp_factor);
  170690. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170691. compptr->v_samp_factor);
  170692. }
  170693. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170694. * In the full decompressor, this will be overridden by jdmaster.c;
  170695. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170696. */
  170697. cinfo->min_DCT_scaled_size = DCTSIZE;
  170698. /* Compute dimensions of components */
  170699. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170700. ci++, compptr++) {
  170701. compptr->DCT_scaled_size = DCTSIZE;
  170702. /* Size in DCT blocks */
  170703. compptr->width_in_blocks = (JDIMENSION)
  170704. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170705. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170706. compptr->height_in_blocks = (JDIMENSION)
  170707. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170708. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170709. /* downsampled_width and downsampled_height will also be overridden by
  170710. * jdmaster.c if we are doing full decompression. The transcoder library
  170711. * doesn't use these values, but the calling application might.
  170712. */
  170713. /* Size in samples */
  170714. compptr->downsampled_width = (JDIMENSION)
  170715. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170716. (long) cinfo->max_h_samp_factor);
  170717. compptr->downsampled_height = (JDIMENSION)
  170718. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170719. (long) cinfo->max_v_samp_factor);
  170720. /* Mark component needed, until color conversion says otherwise */
  170721. compptr->component_needed = TRUE;
  170722. /* Mark no quantization table yet saved for component */
  170723. compptr->quant_table = NULL;
  170724. }
  170725. /* Compute number of fully interleaved MCU rows. */
  170726. cinfo->total_iMCU_rows = (JDIMENSION)
  170727. jdiv_round_up((long) cinfo->image_height,
  170728. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170729. /* Decide whether file contains multiple scans */
  170730. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170731. cinfo->inputctl->has_multiple_scans = TRUE;
  170732. else
  170733. cinfo->inputctl->has_multiple_scans = FALSE;
  170734. }
  170735. LOCAL(void)
  170736. per_scan_setup2 (j_decompress_ptr cinfo)
  170737. /* Do computations that are needed before processing a JPEG scan */
  170738. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170739. {
  170740. int ci, mcublks, tmp;
  170741. jpeg_component_info *compptr;
  170742. if (cinfo->comps_in_scan == 1) {
  170743. /* Noninterleaved (single-component) scan */
  170744. compptr = cinfo->cur_comp_info[0];
  170745. /* Overall image size in MCUs */
  170746. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170747. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170748. /* For noninterleaved scan, always one block per MCU */
  170749. compptr->MCU_width = 1;
  170750. compptr->MCU_height = 1;
  170751. compptr->MCU_blocks = 1;
  170752. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170753. compptr->last_col_width = 1;
  170754. /* For noninterleaved scans, it is convenient to define last_row_height
  170755. * as the number of block rows present in the last iMCU row.
  170756. */
  170757. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170758. if (tmp == 0) tmp = compptr->v_samp_factor;
  170759. compptr->last_row_height = tmp;
  170760. /* Prepare array describing MCU composition */
  170761. cinfo->blocks_in_MCU = 1;
  170762. cinfo->MCU_membership[0] = 0;
  170763. } else {
  170764. /* Interleaved (multi-component) scan */
  170765. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170766. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170767. MAX_COMPS_IN_SCAN);
  170768. /* Overall image size in MCUs */
  170769. cinfo->MCUs_per_row = (JDIMENSION)
  170770. jdiv_round_up((long) cinfo->image_width,
  170771. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170772. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170773. jdiv_round_up((long) cinfo->image_height,
  170774. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170775. cinfo->blocks_in_MCU = 0;
  170776. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170777. compptr = cinfo->cur_comp_info[ci];
  170778. /* Sampling factors give # of blocks of component in each MCU */
  170779. compptr->MCU_width = compptr->h_samp_factor;
  170780. compptr->MCU_height = compptr->v_samp_factor;
  170781. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170782. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170783. /* Figure number of non-dummy blocks in last MCU column & row */
  170784. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170785. if (tmp == 0) tmp = compptr->MCU_width;
  170786. compptr->last_col_width = tmp;
  170787. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170788. if (tmp == 0) tmp = compptr->MCU_height;
  170789. compptr->last_row_height = tmp;
  170790. /* Prepare array describing MCU composition */
  170791. mcublks = compptr->MCU_blocks;
  170792. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170793. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170794. while (mcublks-- > 0) {
  170795. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170796. }
  170797. }
  170798. }
  170799. }
  170800. /*
  170801. * Save away a copy of the Q-table referenced by each component present
  170802. * in the current scan, unless already saved during a prior scan.
  170803. *
  170804. * In a multiple-scan JPEG file, the encoder could assign different components
  170805. * the same Q-table slot number, but change table definitions between scans
  170806. * so that each component uses a different Q-table. (The IJG encoder is not
  170807. * currently capable of doing this, but other encoders might.) Since we want
  170808. * to be able to dequantize all the components at the end of the file, this
  170809. * means that we have to save away the table actually used for each component.
  170810. * We do this by copying the table at the start of the first scan containing
  170811. * the component.
  170812. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170813. * slot between scans of a component using that slot. If the encoder does so
  170814. * anyway, this decoder will simply use the Q-table values that were current
  170815. * at the start of the first scan for the component.
  170816. *
  170817. * The decompressor output side looks only at the saved quant tables,
  170818. * not at the current Q-table slots.
  170819. */
  170820. LOCAL(void)
  170821. latch_quant_tables (j_decompress_ptr cinfo)
  170822. {
  170823. int ci, qtblno;
  170824. jpeg_component_info *compptr;
  170825. JQUANT_TBL * qtbl;
  170826. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170827. compptr = cinfo->cur_comp_info[ci];
  170828. /* No work if we already saved Q-table for this component */
  170829. if (compptr->quant_table != NULL)
  170830. continue;
  170831. /* Make sure specified quantization table is present */
  170832. qtblno = compptr->quant_tbl_no;
  170833. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170834. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170835. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170836. /* OK, save away the quantization table */
  170837. qtbl = (JQUANT_TBL *)
  170838. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170839. SIZEOF(JQUANT_TBL));
  170840. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170841. compptr->quant_table = qtbl;
  170842. }
  170843. }
  170844. /*
  170845. * Initialize the input modules to read a scan of compressed data.
  170846. * The first call to this is done by jdmaster.c after initializing
  170847. * the entire decompressor (during jpeg_start_decompress).
  170848. * Subsequent calls come from consume_markers, below.
  170849. */
  170850. METHODDEF(void)
  170851. start_input_pass2 (j_decompress_ptr cinfo)
  170852. {
  170853. per_scan_setup2(cinfo);
  170854. latch_quant_tables(cinfo);
  170855. (*cinfo->entropy->start_pass) (cinfo);
  170856. (*cinfo->coef->start_input_pass) (cinfo);
  170857. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170858. }
  170859. /*
  170860. * Finish up after inputting a compressed-data scan.
  170861. * This is called by the coefficient controller after it's read all
  170862. * the expected data of the scan.
  170863. */
  170864. METHODDEF(void)
  170865. finish_input_pass (j_decompress_ptr cinfo)
  170866. {
  170867. cinfo->inputctl->consume_input = consume_markers;
  170868. }
  170869. /*
  170870. * Read JPEG markers before, between, or after compressed-data scans.
  170871. * Change state as necessary when a new scan is reached.
  170872. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170873. *
  170874. * The consume_input method pointer points either here or to the
  170875. * coefficient controller's consume_data routine, depending on whether
  170876. * we are reading a compressed data segment or inter-segment markers.
  170877. */
  170878. METHODDEF(int)
  170879. consume_markers (j_decompress_ptr cinfo)
  170880. {
  170881. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170882. int val;
  170883. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170884. return JPEG_REACHED_EOI;
  170885. val = (*cinfo->marker->read_markers) (cinfo);
  170886. switch (val) {
  170887. case JPEG_REACHED_SOS: /* Found SOS */
  170888. if (inputctl->inheaders) { /* 1st SOS */
  170889. initial_setup2(cinfo);
  170890. inputctl->inheaders = FALSE;
  170891. /* Note: start_input_pass must be called by jdmaster.c
  170892. * before any more input can be consumed. jdapimin.c is
  170893. * responsible for enforcing this sequencing.
  170894. */
  170895. } else { /* 2nd or later SOS marker */
  170896. if (! inputctl->pub.has_multiple_scans)
  170897. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170898. start_input_pass2(cinfo);
  170899. }
  170900. break;
  170901. case JPEG_REACHED_EOI: /* Found EOI */
  170902. inputctl->pub.eoi_reached = TRUE;
  170903. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170904. if (cinfo->marker->saw_SOF)
  170905. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170906. } else {
  170907. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170908. * if user set output_scan_number larger than number of scans.
  170909. */
  170910. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170911. cinfo->output_scan_number = cinfo->input_scan_number;
  170912. }
  170913. break;
  170914. case JPEG_SUSPENDED:
  170915. break;
  170916. }
  170917. return val;
  170918. }
  170919. /*
  170920. * Reset state to begin a fresh datastream.
  170921. */
  170922. METHODDEF(void)
  170923. reset_input_controller (j_decompress_ptr cinfo)
  170924. {
  170925. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170926. inputctl->pub.consume_input = consume_markers;
  170927. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170928. inputctl->pub.eoi_reached = FALSE;
  170929. inputctl->inheaders = TRUE;
  170930. /* Reset other modules */
  170931. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170932. (*cinfo->marker->reset_marker_reader) (cinfo);
  170933. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170934. cinfo->coef_bits = NULL;
  170935. }
  170936. /*
  170937. * Initialize the input controller module.
  170938. * This is called only once, when the decompression object is created.
  170939. */
  170940. GLOBAL(void)
  170941. jinit_input_controller (j_decompress_ptr cinfo)
  170942. {
  170943. my_inputctl_ptr inputctl;
  170944. /* Create subobject in permanent pool */
  170945. inputctl = (my_inputctl_ptr)
  170946. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170947. SIZEOF(my_input_controller));
  170948. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170949. /* Initialize method pointers */
  170950. inputctl->pub.consume_input = consume_markers;
  170951. inputctl->pub.reset_input_controller = reset_input_controller;
  170952. inputctl->pub.start_input_pass = start_input_pass2;
  170953. inputctl->pub.finish_input_pass = finish_input_pass;
  170954. /* Initialize state: can't use reset_input_controller since we don't
  170955. * want to try to reset other modules yet.
  170956. */
  170957. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170958. inputctl->pub.eoi_reached = FALSE;
  170959. inputctl->inheaders = TRUE;
  170960. }
  170961. /*** End of inlined file: jdinput.c ***/
  170962. /*** Start of inlined file: jdmainct.c ***/
  170963. #define JPEG_INTERNALS
  170964. /*
  170965. * In the current system design, the main buffer need never be a full-image
  170966. * buffer; any full-height buffers will be found inside the coefficient or
  170967. * postprocessing controllers. Nonetheless, the main controller is not
  170968. * trivial. Its responsibility is to provide context rows for upsampling/
  170969. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170970. *
  170971. * Postprocessor input data is counted in "row groups". A row group
  170972. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170973. * sample rows of each component. (We require DCT_scaled_size values to be
  170974. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170975. * values will likely be powers of two, so we actually have the stronger
  170976. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170977. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170978. * row group (times any additional scale factor that the upsampler is
  170979. * applying).
  170980. *
  170981. * The coefficient controller will deliver data to us one iMCU row at a time;
  170982. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170983. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170984. * to one row of MCUs when the image is fully interleaved.) Note that the
  170985. * number of sample rows varies across components, but the number of row
  170986. * groups does not. Some garbage sample rows may be included in the last iMCU
  170987. * row at the bottom of the image.
  170988. *
  170989. * Depending on the vertical scaling algorithm used, the upsampler may need
  170990. * access to the sample row(s) above and below its current input row group.
  170991. * The upsampler is required to set need_context_rows TRUE at global selection
  170992. * time if so. When need_context_rows is FALSE, this controller can simply
  170993. * obtain one iMCU row at a time from the coefficient controller and dole it
  170994. * out as row groups to the postprocessor.
  170995. *
  170996. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170997. * passed to postprocessing contains at least one row group's worth of samples
  170998. * above and below the row group(s) being processed. Note that the context
  170999. * rows "above" the first passed row group appear at negative row offsets in
  171000. * the passed buffer. At the top and bottom of the image, the required
  171001. * context rows are manufactured by duplicating the first or last real sample
  171002. * row; this avoids having special cases in the upsampling inner loops.
  171003. *
  171004. * The amount of context is fixed at one row group just because that's a
  171005. * convenient number for this controller to work with. The existing
  171006. * upsamplers really only need one sample row of context. An upsampler
  171007. * supporting arbitrary output rescaling might wish for more than one row
  171008. * group of context when shrinking the image; tough, we don't handle that.
  171009. * (This is justified by the assumption that downsizing will be handled mostly
  171010. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  171011. * the upsample step needn't be much less than one.)
  171012. *
  171013. * To provide the desired context, we have to retain the last two row groups
  171014. * of one iMCU row while reading in the next iMCU row. (The last row group
  171015. * can't be processed until we have another row group for its below-context,
  171016. * and so we have to save the next-to-last group too for its above-context.)
  171017. * We could do this most simply by copying data around in our buffer, but
  171018. * that'd be very slow. We can avoid copying any data by creating a rather
  171019. * strange pointer structure. Here's how it works. We allocate a workspace
  171020. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  171021. * of row groups per iMCU row). We create two sets of redundant pointers to
  171022. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  171023. * pointer lists look like this:
  171024. * M+1 M-1
  171025. * master pointer --> 0 master pointer --> 0
  171026. * 1 1
  171027. * ... ...
  171028. * M-3 M-3
  171029. * M-2 M
  171030. * M-1 M+1
  171031. * M M-2
  171032. * M+1 M-1
  171033. * 0 0
  171034. * We read alternate iMCU rows using each master pointer; thus the last two
  171035. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  171036. * The pointer lists are set up so that the required context rows appear to
  171037. * be adjacent to the proper places when we pass the pointer lists to the
  171038. * upsampler.
  171039. *
  171040. * The above pictures describe the normal state of the pointer lists.
  171041. * At top and bottom of the image, we diddle the pointer lists to duplicate
  171042. * the first or last sample row as necessary (this is cheaper than copying
  171043. * sample rows around).
  171044. *
  171045. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  171046. * situation each iMCU row provides only one row group so the buffering logic
  171047. * must be different (eg, we must read two iMCU rows before we can emit the
  171048. * first row group). For now, we simply do not support providing context
  171049. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  171050. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  171051. * want it quick and dirty, so a context-free upsampler is sufficient.
  171052. */
  171053. /* Private buffer controller object */
  171054. typedef struct {
  171055. struct jpeg_d_main_controller pub; /* public fields */
  171056. /* Pointer to allocated workspace (M or M+2 row groups). */
  171057. JSAMPARRAY buffer[MAX_COMPONENTS];
  171058. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  171059. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  171060. /* Remaining fields are only used in the context case. */
  171061. /* These are the master pointers to the funny-order pointer lists. */
  171062. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  171063. int whichptr; /* indicates which pointer set is now in use */
  171064. int context_state; /* process_data state machine status */
  171065. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  171066. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  171067. } my_main_controller4;
  171068. typedef my_main_controller4 * my_main_ptr4;
  171069. /* context_state values: */
  171070. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  171071. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  171072. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  171073. /* Forward declarations */
  171074. METHODDEF(void) process_data_simple_main2
  171075. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171076. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171077. METHODDEF(void) process_data_context_main
  171078. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171079. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171080. #ifdef QUANT_2PASS_SUPPORTED
  171081. METHODDEF(void) process_data_crank_post
  171082. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171083. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171084. #endif
  171085. LOCAL(void)
  171086. alloc_funny_pointers (j_decompress_ptr cinfo)
  171087. /* Allocate space for the funny pointer lists.
  171088. * This is done only once, not once per pass.
  171089. */
  171090. {
  171091. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171092. int ci, rgroup;
  171093. int M = cinfo->min_DCT_scaled_size;
  171094. jpeg_component_info *compptr;
  171095. JSAMPARRAY xbuf;
  171096. /* Get top-level space for component array pointers.
  171097. * We alloc both arrays with one call to save a few cycles.
  171098. */
  171099. main_->xbuffer[0] = (JSAMPIMAGE)
  171100. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171101. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  171102. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  171103. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171104. ci++, compptr++) {
  171105. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171106. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171107. /* Get space for pointer lists --- M+4 row groups in each list.
  171108. * We alloc both pointer lists with one call to save a few cycles.
  171109. */
  171110. xbuf = (JSAMPARRAY)
  171111. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171112. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  171113. xbuf += rgroup; /* want one row group at negative offsets */
  171114. main_->xbuffer[0][ci] = xbuf;
  171115. xbuf += rgroup * (M + 4);
  171116. main_->xbuffer[1][ci] = xbuf;
  171117. }
  171118. }
  171119. LOCAL(void)
  171120. make_funny_pointers (j_decompress_ptr cinfo)
  171121. /* Create the funny pointer lists discussed in the comments above.
  171122. * The actual workspace is already allocated (in main->buffer),
  171123. * and the space for the pointer lists is allocated too.
  171124. * This routine just fills in the curiously ordered lists.
  171125. * This will be repeated at the beginning of each pass.
  171126. */
  171127. {
  171128. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171129. int ci, i, rgroup;
  171130. int M = cinfo->min_DCT_scaled_size;
  171131. jpeg_component_info *compptr;
  171132. JSAMPARRAY buf, xbuf0, xbuf1;
  171133. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171134. ci++, compptr++) {
  171135. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171136. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171137. xbuf0 = main_->xbuffer[0][ci];
  171138. xbuf1 = main_->xbuffer[1][ci];
  171139. /* First copy the workspace pointers as-is */
  171140. buf = main_->buffer[ci];
  171141. for (i = 0; i < rgroup * (M + 2); i++) {
  171142. xbuf0[i] = xbuf1[i] = buf[i];
  171143. }
  171144. /* In the second list, put the last four row groups in swapped order */
  171145. for (i = 0; i < rgroup * 2; i++) {
  171146. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171147. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171148. }
  171149. /* The wraparound pointers at top and bottom will be filled later
  171150. * (see set_wraparound_pointers, below). Initially we want the "above"
  171151. * pointers to duplicate the first actual data line. This only needs
  171152. * to happen in xbuffer[0].
  171153. */
  171154. for (i = 0; i < rgroup; i++) {
  171155. xbuf0[i - rgroup] = xbuf0[0];
  171156. }
  171157. }
  171158. }
  171159. LOCAL(void)
  171160. set_wraparound_pointers (j_decompress_ptr cinfo)
  171161. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171162. * This changes the pointer list state from top-of-image to the normal state.
  171163. */
  171164. {
  171165. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171166. int ci, i, rgroup;
  171167. int M = cinfo->min_DCT_scaled_size;
  171168. jpeg_component_info *compptr;
  171169. JSAMPARRAY xbuf0, xbuf1;
  171170. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171171. ci++, compptr++) {
  171172. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171173. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171174. xbuf0 = main_->xbuffer[0][ci];
  171175. xbuf1 = main_->xbuffer[1][ci];
  171176. for (i = 0; i < rgroup; i++) {
  171177. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171178. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171179. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171180. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171181. }
  171182. }
  171183. }
  171184. LOCAL(void)
  171185. set_bottom_pointers (j_decompress_ptr cinfo)
  171186. /* Change the pointer lists to duplicate the last sample row at the bottom
  171187. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171188. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171189. */
  171190. {
  171191. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171192. int ci, i, rgroup, iMCUheight, rows_left;
  171193. jpeg_component_info *compptr;
  171194. JSAMPARRAY xbuf;
  171195. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171196. ci++, compptr++) {
  171197. /* Count sample rows in one iMCU row and in one row group */
  171198. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171199. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171200. /* Count nondummy sample rows remaining for this component */
  171201. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171202. if (rows_left == 0) rows_left = iMCUheight;
  171203. /* Count nondummy row groups. Should get same answer for each component,
  171204. * so we need only do it once.
  171205. */
  171206. if (ci == 0) {
  171207. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171208. }
  171209. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171210. * last partial rowgroup and ensures at least one full rowgroup of context.
  171211. */
  171212. xbuf = main_->xbuffer[main_->whichptr][ci];
  171213. for (i = 0; i < rgroup * 2; i++) {
  171214. xbuf[rows_left + i] = xbuf[rows_left-1];
  171215. }
  171216. }
  171217. }
  171218. /*
  171219. * Initialize for a processing pass.
  171220. */
  171221. METHODDEF(void)
  171222. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171223. {
  171224. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171225. switch (pass_mode) {
  171226. case JBUF_PASS_THRU:
  171227. if (cinfo->upsample->need_context_rows) {
  171228. main_->pub.process_data = process_data_context_main;
  171229. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171230. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171231. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171232. main_->iMCU_row_ctr = 0;
  171233. } else {
  171234. /* Simple case with no context needed */
  171235. main_->pub.process_data = process_data_simple_main2;
  171236. }
  171237. main_->buffer_full = FALSE; /* Mark buffer empty */
  171238. main_->rowgroup_ctr = 0;
  171239. break;
  171240. #ifdef QUANT_2PASS_SUPPORTED
  171241. case JBUF_CRANK_DEST:
  171242. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171243. main_->pub.process_data = process_data_crank_post;
  171244. break;
  171245. #endif
  171246. default:
  171247. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171248. break;
  171249. }
  171250. }
  171251. /*
  171252. * Process some data.
  171253. * This handles the simple case where no context is required.
  171254. */
  171255. METHODDEF(void)
  171256. process_data_simple_main2 (j_decompress_ptr cinfo,
  171257. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171258. JDIMENSION out_rows_avail)
  171259. {
  171260. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171261. JDIMENSION rowgroups_avail;
  171262. /* Read input data if we haven't filled the main buffer yet */
  171263. if (! main_->buffer_full) {
  171264. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171265. return; /* suspension forced, can do nothing more */
  171266. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171267. }
  171268. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171269. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171270. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171271. * to the postprocessor. The postprocessor has to check for bottom
  171272. * of image anyway (at row resolution), so no point in us doing it too.
  171273. */
  171274. /* Feed the postprocessor */
  171275. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171276. &main_->rowgroup_ctr, rowgroups_avail,
  171277. output_buf, out_row_ctr, out_rows_avail);
  171278. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171279. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171280. main_->buffer_full = FALSE;
  171281. main_->rowgroup_ctr = 0;
  171282. }
  171283. }
  171284. /*
  171285. * Process some data.
  171286. * This handles the case where context rows must be provided.
  171287. */
  171288. METHODDEF(void)
  171289. process_data_context_main (j_decompress_ptr cinfo,
  171290. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171291. JDIMENSION out_rows_avail)
  171292. {
  171293. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171294. /* Read input data if we haven't filled the main buffer yet */
  171295. if (! main_->buffer_full) {
  171296. if (! (*cinfo->coef->decompress_data) (cinfo,
  171297. main_->xbuffer[main_->whichptr]))
  171298. return; /* suspension forced, can do nothing more */
  171299. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171300. main_->iMCU_row_ctr++; /* count rows received */
  171301. }
  171302. /* Postprocessor typically will not swallow all the input data it is handed
  171303. * in one call (due to filling the output buffer first). Must be prepared
  171304. * to exit and restart. This switch lets us keep track of how far we got.
  171305. * Note that each case falls through to the next on successful completion.
  171306. */
  171307. switch (main_->context_state) {
  171308. case CTX_POSTPONED_ROW:
  171309. /* Call postprocessor using previously set pointers for postponed row */
  171310. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171311. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171312. output_buf, out_row_ctr, out_rows_avail);
  171313. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171314. return; /* Need to suspend */
  171315. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171316. if (*out_row_ctr >= out_rows_avail)
  171317. return; /* Postprocessor exactly filled output buf */
  171318. /*FALLTHROUGH*/
  171319. case CTX_PREPARE_FOR_IMCU:
  171320. /* Prepare to process first M-1 row groups of this iMCU row */
  171321. main_->rowgroup_ctr = 0;
  171322. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171323. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171324. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171325. */
  171326. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171327. set_bottom_pointers(cinfo);
  171328. main_->context_state = CTX_PROCESS_IMCU;
  171329. /*FALLTHROUGH*/
  171330. case CTX_PROCESS_IMCU:
  171331. /* Call postprocessor using previously set pointers */
  171332. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171333. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171334. output_buf, out_row_ctr, out_rows_avail);
  171335. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171336. return; /* Need to suspend */
  171337. /* After the first iMCU, change wraparound pointers to normal state */
  171338. if (main_->iMCU_row_ctr == 1)
  171339. set_wraparound_pointers(cinfo);
  171340. /* Prepare to load new iMCU row using other xbuffer list */
  171341. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171342. main_->buffer_full = FALSE;
  171343. /* Still need to process last row group of this iMCU row, */
  171344. /* which is saved at index M+1 of the other xbuffer */
  171345. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171346. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171347. main_->context_state = CTX_POSTPONED_ROW;
  171348. }
  171349. }
  171350. /*
  171351. * Process some data.
  171352. * Final pass of two-pass quantization: just call the postprocessor.
  171353. * Source data will be the postprocessor controller's internal buffer.
  171354. */
  171355. #ifdef QUANT_2PASS_SUPPORTED
  171356. METHODDEF(void)
  171357. process_data_crank_post (j_decompress_ptr cinfo,
  171358. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171359. JDIMENSION out_rows_avail)
  171360. {
  171361. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171362. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171363. output_buf, out_row_ctr, out_rows_avail);
  171364. }
  171365. #endif /* QUANT_2PASS_SUPPORTED */
  171366. /*
  171367. * Initialize main buffer controller.
  171368. */
  171369. GLOBAL(void)
  171370. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171371. {
  171372. my_main_ptr4 main_;
  171373. int ci, rgroup, ngroups;
  171374. jpeg_component_info *compptr;
  171375. main_ = (my_main_ptr4)
  171376. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171377. SIZEOF(my_main_controller4));
  171378. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171379. main_->pub.start_pass = start_pass_main2;
  171380. if (need_full_buffer) /* shouldn't happen */
  171381. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171382. /* Allocate the workspace.
  171383. * ngroups is the number of row groups we need.
  171384. */
  171385. if (cinfo->upsample->need_context_rows) {
  171386. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171387. ERREXIT(cinfo, JERR_NOTIMPL);
  171388. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171389. ngroups = cinfo->min_DCT_scaled_size + 2;
  171390. } else {
  171391. ngroups = cinfo->min_DCT_scaled_size;
  171392. }
  171393. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171394. ci++, compptr++) {
  171395. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171396. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171397. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171398. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171399. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171400. (JDIMENSION) (rgroup * ngroups));
  171401. }
  171402. }
  171403. /*** End of inlined file: jdmainct.c ***/
  171404. /*** Start of inlined file: jdmarker.c ***/
  171405. #define JPEG_INTERNALS
  171406. /* Private state */
  171407. typedef struct {
  171408. struct jpeg_marker_reader pub; /* public fields */
  171409. /* Application-overridable marker processing methods */
  171410. jpeg_marker_parser_method process_COM;
  171411. jpeg_marker_parser_method process_APPn[16];
  171412. /* Limit on marker data length to save for each marker type */
  171413. unsigned int length_limit_COM;
  171414. unsigned int length_limit_APPn[16];
  171415. /* Status of COM/APPn marker saving */
  171416. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171417. unsigned int bytes_read; /* data bytes read so far in marker */
  171418. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171419. } my_marker_reader;
  171420. typedef my_marker_reader * my_marker_ptr2;
  171421. /*
  171422. * Macros for fetching data from the data source module.
  171423. *
  171424. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171425. * the current restart point; we update them only when we have reached a
  171426. * suitable place to restart if a suspension occurs.
  171427. */
  171428. /* Declare and initialize local copies of input pointer/count */
  171429. #define INPUT_VARS(cinfo) \
  171430. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171431. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171432. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171433. /* Unload the local copies --- do this only at a restart boundary */
  171434. #define INPUT_SYNC(cinfo) \
  171435. ( datasrc->next_input_byte = next_input_byte, \
  171436. datasrc->bytes_in_buffer = bytes_in_buffer )
  171437. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171438. #define INPUT_RELOAD(cinfo) \
  171439. ( next_input_byte = datasrc->next_input_byte, \
  171440. bytes_in_buffer = datasrc->bytes_in_buffer )
  171441. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171442. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171443. * but we must reload the local copies after a successful fill.
  171444. */
  171445. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171446. if (bytes_in_buffer == 0) { \
  171447. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171448. { action; } \
  171449. INPUT_RELOAD(cinfo); \
  171450. }
  171451. /* Read a byte into variable V.
  171452. * If must suspend, take the specified action (typically "return FALSE").
  171453. */
  171454. #define INPUT_BYTE(cinfo,V,action) \
  171455. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171456. bytes_in_buffer--; \
  171457. V = GETJOCTET(*next_input_byte++); )
  171458. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171459. * V should be declared unsigned int or perhaps INT32.
  171460. */
  171461. #define INPUT_2BYTES(cinfo,V,action) \
  171462. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171463. bytes_in_buffer--; \
  171464. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171465. MAKE_BYTE_AVAIL(cinfo,action); \
  171466. bytes_in_buffer--; \
  171467. V += GETJOCTET(*next_input_byte++); )
  171468. /*
  171469. * Routines to process JPEG markers.
  171470. *
  171471. * Entry condition: JPEG marker itself has been read and its code saved
  171472. * in cinfo->unread_marker; input restart point is just after the marker.
  171473. *
  171474. * Exit: if return TRUE, have read and processed any parameters, and have
  171475. * updated the restart point to point after the parameters.
  171476. * If return FALSE, was forced to suspend before reaching end of
  171477. * marker parameters; restart point has not been moved. Same routine
  171478. * will be called again after application supplies more input data.
  171479. *
  171480. * This approach to suspension assumes that all of a marker's parameters
  171481. * can fit into a single input bufferload. This should hold for "normal"
  171482. * markers. Some COM/APPn markers might have large parameter segments
  171483. * that might not fit. If we are simply dropping such a marker, we use
  171484. * skip_input_data to get past it, and thereby put the problem on the
  171485. * source manager's shoulders. If we are saving the marker's contents
  171486. * into memory, we use a slightly different convention: when forced to
  171487. * suspend, the marker processor updates the restart point to the end of
  171488. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171489. * On resumption, cinfo->unread_marker still contains the marker code,
  171490. * but the data source will point to the next chunk of marker data.
  171491. * The marker processor must retain internal state to deal with this.
  171492. *
  171493. * Note that we don't bother to avoid duplicate trace messages if a
  171494. * suspension occurs within marker parameters. Other side effects
  171495. * require more care.
  171496. */
  171497. LOCAL(boolean)
  171498. get_soi (j_decompress_ptr cinfo)
  171499. /* Process an SOI marker */
  171500. {
  171501. int i;
  171502. TRACEMS(cinfo, 1, JTRC_SOI);
  171503. if (cinfo->marker->saw_SOI)
  171504. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171505. /* Reset all parameters that are defined to be reset by SOI */
  171506. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171507. cinfo->arith_dc_L[i] = 0;
  171508. cinfo->arith_dc_U[i] = 1;
  171509. cinfo->arith_ac_K[i] = 5;
  171510. }
  171511. cinfo->restart_interval = 0;
  171512. /* Set initial assumptions for colorspace etc */
  171513. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171514. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171515. cinfo->saw_JFIF_marker = FALSE;
  171516. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171517. cinfo->JFIF_minor_version = 1;
  171518. cinfo->density_unit = 0;
  171519. cinfo->X_density = 1;
  171520. cinfo->Y_density = 1;
  171521. cinfo->saw_Adobe_marker = FALSE;
  171522. cinfo->Adobe_transform = 0;
  171523. cinfo->marker->saw_SOI = TRUE;
  171524. return TRUE;
  171525. }
  171526. LOCAL(boolean)
  171527. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171528. /* Process a SOFn marker */
  171529. {
  171530. INT32 length;
  171531. int c, ci;
  171532. jpeg_component_info * compptr;
  171533. INPUT_VARS(cinfo);
  171534. cinfo->progressive_mode = is_prog;
  171535. cinfo->arith_code = is_arith;
  171536. INPUT_2BYTES(cinfo, length, return FALSE);
  171537. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171538. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171539. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171540. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171541. length -= 8;
  171542. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171543. (int) cinfo->image_width, (int) cinfo->image_height,
  171544. cinfo->num_components);
  171545. if (cinfo->marker->saw_SOF)
  171546. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171547. /* We don't support files in which the image height is initially specified */
  171548. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171549. /* might as well have a general sanity check. */
  171550. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171551. || cinfo->num_components <= 0)
  171552. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171553. if (length != (cinfo->num_components * 3))
  171554. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171555. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171556. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171557. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171558. cinfo->num_components * SIZEOF(jpeg_component_info));
  171559. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171560. ci++, compptr++) {
  171561. compptr->component_index = ci;
  171562. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171563. INPUT_BYTE(cinfo, c, return FALSE);
  171564. compptr->h_samp_factor = (c >> 4) & 15;
  171565. compptr->v_samp_factor = (c ) & 15;
  171566. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171567. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171568. compptr->component_id, compptr->h_samp_factor,
  171569. compptr->v_samp_factor, compptr->quant_tbl_no);
  171570. }
  171571. cinfo->marker->saw_SOF = TRUE;
  171572. INPUT_SYNC(cinfo);
  171573. return TRUE;
  171574. }
  171575. LOCAL(boolean)
  171576. get_sos (j_decompress_ptr cinfo)
  171577. /* Process a SOS marker */
  171578. {
  171579. INT32 length;
  171580. int i, ci, n, c, cc;
  171581. jpeg_component_info * compptr;
  171582. INPUT_VARS(cinfo);
  171583. if (! cinfo->marker->saw_SOF)
  171584. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171585. INPUT_2BYTES(cinfo, length, return FALSE);
  171586. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171587. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171588. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171589. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171590. cinfo->comps_in_scan = n;
  171591. /* Collect the component-spec parameters */
  171592. for (i = 0; i < n; i++) {
  171593. INPUT_BYTE(cinfo, cc, return FALSE);
  171594. INPUT_BYTE(cinfo, c, return FALSE);
  171595. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171596. ci++, compptr++) {
  171597. if (cc == compptr->component_id)
  171598. goto id_found;
  171599. }
  171600. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171601. id_found:
  171602. cinfo->cur_comp_info[i] = compptr;
  171603. compptr->dc_tbl_no = (c >> 4) & 15;
  171604. compptr->ac_tbl_no = (c ) & 15;
  171605. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171606. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171607. }
  171608. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171609. INPUT_BYTE(cinfo, c, return FALSE);
  171610. cinfo->Ss = c;
  171611. INPUT_BYTE(cinfo, c, return FALSE);
  171612. cinfo->Se = c;
  171613. INPUT_BYTE(cinfo, c, return FALSE);
  171614. cinfo->Ah = (c >> 4) & 15;
  171615. cinfo->Al = (c ) & 15;
  171616. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171617. cinfo->Ah, cinfo->Al);
  171618. /* Prepare to scan data & restart markers */
  171619. cinfo->marker->next_restart_num = 0;
  171620. /* Count another SOS marker */
  171621. cinfo->input_scan_number++;
  171622. INPUT_SYNC(cinfo);
  171623. return TRUE;
  171624. }
  171625. #ifdef D_ARITH_CODING_SUPPORTED
  171626. LOCAL(boolean)
  171627. get_dac (j_decompress_ptr cinfo)
  171628. /* Process a DAC marker */
  171629. {
  171630. INT32 length;
  171631. int index, val;
  171632. INPUT_VARS(cinfo);
  171633. INPUT_2BYTES(cinfo, length, return FALSE);
  171634. length -= 2;
  171635. while (length > 0) {
  171636. INPUT_BYTE(cinfo, index, return FALSE);
  171637. INPUT_BYTE(cinfo, val, return FALSE);
  171638. length -= 2;
  171639. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171640. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171641. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171642. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171643. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171644. } else { /* define DC table */
  171645. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171646. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171647. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171648. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171649. }
  171650. }
  171651. if (length != 0)
  171652. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171653. INPUT_SYNC(cinfo);
  171654. return TRUE;
  171655. }
  171656. #else /* ! D_ARITH_CODING_SUPPORTED */
  171657. #define get_dac(cinfo) skip_variable(cinfo)
  171658. #endif /* D_ARITH_CODING_SUPPORTED */
  171659. LOCAL(boolean)
  171660. get_dht (j_decompress_ptr cinfo)
  171661. /* Process a DHT marker */
  171662. {
  171663. INT32 length;
  171664. UINT8 bits[17];
  171665. UINT8 huffval[256];
  171666. int i, index, count;
  171667. JHUFF_TBL **htblptr;
  171668. INPUT_VARS(cinfo);
  171669. INPUT_2BYTES(cinfo, length, return FALSE);
  171670. length -= 2;
  171671. while (length > 16) {
  171672. INPUT_BYTE(cinfo, index, return FALSE);
  171673. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171674. bits[0] = 0;
  171675. count = 0;
  171676. for (i = 1; i <= 16; i++) {
  171677. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171678. count += bits[i];
  171679. }
  171680. length -= 1 + 16;
  171681. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171682. bits[1], bits[2], bits[3], bits[4],
  171683. bits[5], bits[6], bits[7], bits[8]);
  171684. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171685. bits[9], bits[10], bits[11], bits[12],
  171686. bits[13], bits[14], bits[15], bits[16]);
  171687. /* Here we just do minimal validation of the counts to avoid walking
  171688. * off the end of our table space. jdhuff.c will check more carefully.
  171689. */
  171690. if (count > 256 || ((INT32) count) > length)
  171691. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171692. for (i = 0; i < count; i++)
  171693. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171694. length -= count;
  171695. if (index & 0x10) { /* AC table definition */
  171696. index -= 0x10;
  171697. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171698. } else { /* DC table definition */
  171699. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171700. }
  171701. if (index < 0 || index >= NUM_HUFF_TBLS)
  171702. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171703. if (*htblptr == NULL)
  171704. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171705. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171706. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171707. }
  171708. if (length != 0)
  171709. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171710. INPUT_SYNC(cinfo);
  171711. return TRUE;
  171712. }
  171713. LOCAL(boolean)
  171714. get_dqt (j_decompress_ptr cinfo)
  171715. /* Process a DQT marker */
  171716. {
  171717. INT32 length;
  171718. int n, i, prec;
  171719. unsigned int tmp;
  171720. JQUANT_TBL *quant_ptr;
  171721. INPUT_VARS(cinfo);
  171722. INPUT_2BYTES(cinfo, length, return FALSE);
  171723. length -= 2;
  171724. while (length > 0) {
  171725. INPUT_BYTE(cinfo, n, return FALSE);
  171726. prec = n >> 4;
  171727. n &= 0x0F;
  171728. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171729. if (n >= NUM_QUANT_TBLS)
  171730. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171731. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171732. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171733. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171734. for (i = 0; i < DCTSIZE2; i++) {
  171735. if (prec)
  171736. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171737. else
  171738. INPUT_BYTE(cinfo, tmp, return FALSE);
  171739. /* We convert the zigzag-order table to natural array order. */
  171740. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171741. }
  171742. if (cinfo->err->trace_level >= 2) {
  171743. for (i = 0; i < DCTSIZE2; i += 8) {
  171744. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171745. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171746. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171747. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171748. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171749. }
  171750. }
  171751. length -= DCTSIZE2+1;
  171752. if (prec) length -= DCTSIZE2;
  171753. }
  171754. if (length != 0)
  171755. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171756. INPUT_SYNC(cinfo);
  171757. return TRUE;
  171758. }
  171759. LOCAL(boolean)
  171760. get_dri (j_decompress_ptr cinfo)
  171761. /* Process a DRI marker */
  171762. {
  171763. INT32 length;
  171764. unsigned int tmp;
  171765. INPUT_VARS(cinfo);
  171766. INPUT_2BYTES(cinfo, length, return FALSE);
  171767. if (length != 4)
  171768. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171769. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171770. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171771. cinfo->restart_interval = tmp;
  171772. INPUT_SYNC(cinfo);
  171773. return TRUE;
  171774. }
  171775. /*
  171776. * Routines for processing APPn and COM markers.
  171777. * These are either saved in memory or discarded, per application request.
  171778. * APP0 and APP14 are specially checked to see if they are
  171779. * JFIF and Adobe markers, respectively.
  171780. */
  171781. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171782. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171783. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171784. LOCAL(void)
  171785. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171786. unsigned int datalen, INT32 remaining)
  171787. /* Examine first few bytes from an APP0.
  171788. * Take appropriate action if it is a JFIF marker.
  171789. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171790. */
  171791. {
  171792. INT32 totallen = (INT32) datalen + remaining;
  171793. if (datalen >= APP0_DATA_LEN &&
  171794. GETJOCTET(data[0]) == 0x4A &&
  171795. GETJOCTET(data[1]) == 0x46 &&
  171796. GETJOCTET(data[2]) == 0x49 &&
  171797. GETJOCTET(data[3]) == 0x46 &&
  171798. GETJOCTET(data[4]) == 0) {
  171799. /* Found JFIF APP0 marker: save info */
  171800. cinfo->saw_JFIF_marker = TRUE;
  171801. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171802. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171803. cinfo->density_unit = GETJOCTET(data[7]);
  171804. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171805. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171806. /* Check version.
  171807. * Major version must be 1, anything else signals an incompatible change.
  171808. * (We used to treat this as an error, but now it's a nonfatal warning,
  171809. * because some bozo at Hijaak couldn't read the spec.)
  171810. * Minor version should be 0..2, but process anyway if newer.
  171811. */
  171812. if (cinfo->JFIF_major_version != 1)
  171813. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171814. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171815. /* Generate trace messages */
  171816. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171817. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171818. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171819. /* Validate thumbnail dimensions and issue appropriate messages */
  171820. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171821. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171822. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171823. totallen -= APP0_DATA_LEN;
  171824. if (totallen !=
  171825. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171826. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171827. } else if (datalen >= 6 &&
  171828. GETJOCTET(data[0]) == 0x4A &&
  171829. GETJOCTET(data[1]) == 0x46 &&
  171830. GETJOCTET(data[2]) == 0x58 &&
  171831. GETJOCTET(data[3]) == 0x58 &&
  171832. GETJOCTET(data[4]) == 0) {
  171833. /* Found JFIF "JFXX" extension APP0 marker */
  171834. /* The library doesn't actually do anything with these,
  171835. * but we try to produce a helpful trace message.
  171836. */
  171837. switch (GETJOCTET(data[5])) {
  171838. case 0x10:
  171839. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171840. break;
  171841. case 0x11:
  171842. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171843. break;
  171844. case 0x13:
  171845. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171846. break;
  171847. default:
  171848. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171849. GETJOCTET(data[5]), (int) totallen);
  171850. break;
  171851. }
  171852. } else {
  171853. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171854. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171855. }
  171856. }
  171857. LOCAL(void)
  171858. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171859. unsigned int datalen, INT32 remaining)
  171860. /* Examine first few bytes from an APP14.
  171861. * Take appropriate action if it is an Adobe marker.
  171862. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171863. */
  171864. {
  171865. unsigned int version, flags0, flags1, transform;
  171866. if (datalen >= APP14_DATA_LEN &&
  171867. GETJOCTET(data[0]) == 0x41 &&
  171868. GETJOCTET(data[1]) == 0x64 &&
  171869. GETJOCTET(data[2]) == 0x6F &&
  171870. GETJOCTET(data[3]) == 0x62 &&
  171871. GETJOCTET(data[4]) == 0x65) {
  171872. /* Found Adobe APP14 marker */
  171873. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171874. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171875. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171876. transform = GETJOCTET(data[11]);
  171877. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171878. cinfo->saw_Adobe_marker = TRUE;
  171879. cinfo->Adobe_transform = (UINT8) transform;
  171880. } else {
  171881. /* Start of APP14 does not match "Adobe", or too short */
  171882. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171883. }
  171884. }
  171885. METHODDEF(boolean)
  171886. get_interesting_appn (j_decompress_ptr cinfo)
  171887. /* Process an APP0 or APP14 marker without saving it */
  171888. {
  171889. INT32 length;
  171890. JOCTET b[APPN_DATA_LEN];
  171891. unsigned int i, numtoread;
  171892. INPUT_VARS(cinfo);
  171893. INPUT_2BYTES(cinfo, length, return FALSE);
  171894. length -= 2;
  171895. /* get the interesting part of the marker data */
  171896. if (length >= APPN_DATA_LEN)
  171897. numtoread = APPN_DATA_LEN;
  171898. else if (length > 0)
  171899. numtoread = (unsigned int) length;
  171900. else
  171901. numtoread = 0;
  171902. for (i = 0; i < numtoread; i++)
  171903. INPUT_BYTE(cinfo, b[i], return FALSE);
  171904. length -= numtoread;
  171905. /* process it */
  171906. switch (cinfo->unread_marker) {
  171907. case M_APP0:
  171908. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171909. break;
  171910. case M_APP14:
  171911. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171912. break;
  171913. default:
  171914. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171915. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171916. break;
  171917. }
  171918. /* skip any remaining data -- could be lots */
  171919. INPUT_SYNC(cinfo);
  171920. if (length > 0)
  171921. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171922. return TRUE;
  171923. }
  171924. #ifdef SAVE_MARKERS_SUPPORTED
  171925. METHODDEF(boolean)
  171926. save_marker (j_decompress_ptr cinfo)
  171927. /* Save an APPn or COM marker into the marker list */
  171928. {
  171929. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171930. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171931. unsigned int bytes_read, data_length;
  171932. JOCTET FAR * data;
  171933. INT32 length = 0;
  171934. INPUT_VARS(cinfo);
  171935. if (cur_marker == NULL) {
  171936. /* begin reading a marker */
  171937. INPUT_2BYTES(cinfo, length, return FALSE);
  171938. length -= 2;
  171939. if (length >= 0) { /* watch out for bogus length word */
  171940. /* figure out how much we want to save */
  171941. unsigned int limit;
  171942. if (cinfo->unread_marker == (int) M_COM)
  171943. limit = marker->length_limit_COM;
  171944. else
  171945. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171946. if ((unsigned int) length < limit)
  171947. limit = (unsigned int) length;
  171948. /* allocate and initialize the marker item */
  171949. cur_marker = (jpeg_saved_marker_ptr)
  171950. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171951. SIZEOF(struct jpeg_marker_struct) + limit);
  171952. cur_marker->next = NULL;
  171953. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171954. cur_marker->original_length = (unsigned int) length;
  171955. cur_marker->data_length = limit;
  171956. /* data area is just beyond the jpeg_marker_struct */
  171957. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171958. marker->cur_marker = cur_marker;
  171959. marker->bytes_read = 0;
  171960. bytes_read = 0;
  171961. data_length = limit;
  171962. } else {
  171963. /* deal with bogus length word */
  171964. bytes_read = data_length = 0;
  171965. data = NULL;
  171966. }
  171967. } else {
  171968. /* resume reading a marker */
  171969. bytes_read = marker->bytes_read;
  171970. data_length = cur_marker->data_length;
  171971. data = cur_marker->data + bytes_read;
  171972. }
  171973. while (bytes_read < data_length) {
  171974. INPUT_SYNC(cinfo); /* move the restart point to here */
  171975. marker->bytes_read = bytes_read;
  171976. /* If there's not at least one byte in buffer, suspend */
  171977. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171978. /* Copy bytes with reasonable rapidity */
  171979. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171980. *data++ = *next_input_byte++;
  171981. bytes_in_buffer--;
  171982. bytes_read++;
  171983. }
  171984. }
  171985. /* Done reading what we want to read */
  171986. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171987. /* Add new marker to end of list */
  171988. if (cinfo->marker_list == NULL) {
  171989. cinfo->marker_list = cur_marker;
  171990. } else {
  171991. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171992. while (prev->next != NULL)
  171993. prev = prev->next;
  171994. prev->next = cur_marker;
  171995. }
  171996. /* Reset pointer & calc remaining data length */
  171997. data = cur_marker->data;
  171998. length = cur_marker->original_length - data_length;
  171999. }
  172000. /* Reset to initial state for next marker */
  172001. marker->cur_marker = NULL;
  172002. /* Process the marker if interesting; else just make a generic trace msg */
  172003. switch (cinfo->unread_marker) {
  172004. case M_APP0:
  172005. examine_app0(cinfo, data, data_length, length);
  172006. break;
  172007. case M_APP14:
  172008. examine_app14(cinfo, data, data_length, length);
  172009. break;
  172010. default:
  172011. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  172012. (int) (data_length + length));
  172013. break;
  172014. }
  172015. /* skip any remaining data -- could be lots */
  172016. INPUT_SYNC(cinfo); /* do before skip_input_data */
  172017. if (length > 0)
  172018. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  172019. return TRUE;
  172020. }
  172021. #endif /* SAVE_MARKERS_SUPPORTED */
  172022. METHODDEF(boolean)
  172023. skip_variable (j_decompress_ptr cinfo)
  172024. /* Skip over an unknown or uninteresting variable-length marker */
  172025. {
  172026. INT32 length;
  172027. INPUT_VARS(cinfo);
  172028. INPUT_2BYTES(cinfo, length, return FALSE);
  172029. length -= 2;
  172030. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  172031. INPUT_SYNC(cinfo); /* do before skip_input_data */
  172032. if (length > 0)
  172033. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  172034. return TRUE;
  172035. }
  172036. /*
  172037. * Find the next JPEG marker, save it in cinfo->unread_marker.
  172038. * Returns FALSE if had to suspend before reaching a marker;
  172039. * in that case cinfo->unread_marker is unchanged.
  172040. *
  172041. * Note that the result might not be a valid marker code,
  172042. * but it will never be 0 or FF.
  172043. */
  172044. LOCAL(boolean)
  172045. next_marker (j_decompress_ptr cinfo)
  172046. {
  172047. int c;
  172048. INPUT_VARS(cinfo);
  172049. for (;;) {
  172050. INPUT_BYTE(cinfo, c, return FALSE);
  172051. /* Skip any non-FF bytes.
  172052. * This may look a bit inefficient, but it will not occur in a valid file.
  172053. * We sync after each discarded byte so that a suspending data source
  172054. * can discard the byte from its buffer.
  172055. */
  172056. while (c != 0xFF) {
  172057. cinfo->marker->discarded_bytes++;
  172058. INPUT_SYNC(cinfo);
  172059. INPUT_BYTE(cinfo, c, return FALSE);
  172060. }
  172061. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  172062. * pad bytes, so don't count them in discarded_bytes. We assume there
  172063. * will not be so many consecutive FF bytes as to overflow a suspending
  172064. * data source's input buffer.
  172065. */
  172066. do {
  172067. INPUT_BYTE(cinfo, c, return FALSE);
  172068. } while (c == 0xFF);
  172069. if (c != 0)
  172070. break; /* found a valid marker, exit loop */
  172071. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  172072. * Discard it and loop back to try again.
  172073. */
  172074. cinfo->marker->discarded_bytes += 2;
  172075. INPUT_SYNC(cinfo);
  172076. }
  172077. if (cinfo->marker->discarded_bytes != 0) {
  172078. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  172079. cinfo->marker->discarded_bytes = 0;
  172080. }
  172081. cinfo->unread_marker = c;
  172082. INPUT_SYNC(cinfo);
  172083. return TRUE;
  172084. }
  172085. LOCAL(boolean)
  172086. first_marker (j_decompress_ptr cinfo)
  172087. /* Like next_marker, but used to obtain the initial SOI marker. */
  172088. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  172089. * we might well scan an entire input file before realizing it ain't JPEG.
  172090. * If an application wants to process non-JFIF files, it must seek to the
  172091. * SOI before calling the JPEG library.
  172092. */
  172093. {
  172094. int c, c2;
  172095. INPUT_VARS(cinfo);
  172096. INPUT_BYTE(cinfo, c, return FALSE);
  172097. INPUT_BYTE(cinfo, c2, return FALSE);
  172098. if (c != 0xFF || c2 != (int) M_SOI)
  172099. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  172100. cinfo->unread_marker = c2;
  172101. INPUT_SYNC(cinfo);
  172102. return TRUE;
  172103. }
  172104. /*
  172105. * Read markers until SOS or EOI.
  172106. *
  172107. * Returns same codes as are defined for jpeg_consume_input:
  172108. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  172109. */
  172110. METHODDEF(int)
  172111. read_markers (j_decompress_ptr cinfo)
  172112. {
  172113. /* Outer loop repeats once for each marker. */
  172114. for (;;) {
  172115. /* Collect the marker proper, unless we already did. */
  172116. /* NB: first_marker() enforces the requirement that SOI appear first. */
  172117. if (cinfo->unread_marker == 0) {
  172118. if (! cinfo->marker->saw_SOI) {
  172119. if (! first_marker(cinfo))
  172120. return JPEG_SUSPENDED;
  172121. } else {
  172122. if (! next_marker(cinfo))
  172123. return JPEG_SUSPENDED;
  172124. }
  172125. }
  172126. /* At this point cinfo->unread_marker contains the marker code and the
  172127. * input point is just past the marker proper, but before any parameters.
  172128. * A suspension will cause us to return with this state still true.
  172129. */
  172130. switch (cinfo->unread_marker) {
  172131. case M_SOI:
  172132. if (! get_soi(cinfo))
  172133. return JPEG_SUSPENDED;
  172134. break;
  172135. case M_SOF0: /* Baseline */
  172136. case M_SOF1: /* Extended sequential, Huffman */
  172137. if (! get_sof(cinfo, FALSE, FALSE))
  172138. return JPEG_SUSPENDED;
  172139. break;
  172140. case M_SOF2: /* Progressive, Huffman */
  172141. if (! get_sof(cinfo, TRUE, FALSE))
  172142. return JPEG_SUSPENDED;
  172143. break;
  172144. case M_SOF9: /* Extended sequential, arithmetic */
  172145. if (! get_sof(cinfo, FALSE, TRUE))
  172146. return JPEG_SUSPENDED;
  172147. break;
  172148. case M_SOF10: /* Progressive, arithmetic */
  172149. if (! get_sof(cinfo, TRUE, TRUE))
  172150. return JPEG_SUSPENDED;
  172151. break;
  172152. /* Currently unsupported SOFn types */
  172153. case M_SOF3: /* Lossless, Huffman */
  172154. case M_SOF5: /* Differential sequential, Huffman */
  172155. case M_SOF6: /* Differential progressive, Huffman */
  172156. case M_SOF7: /* Differential lossless, Huffman */
  172157. case M_JPG: /* Reserved for JPEG extensions */
  172158. case M_SOF11: /* Lossless, arithmetic */
  172159. case M_SOF13: /* Differential sequential, arithmetic */
  172160. case M_SOF14: /* Differential progressive, arithmetic */
  172161. case M_SOF15: /* Differential lossless, arithmetic */
  172162. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172163. break;
  172164. case M_SOS:
  172165. if (! get_sos(cinfo))
  172166. return JPEG_SUSPENDED;
  172167. cinfo->unread_marker = 0; /* processed the marker */
  172168. return JPEG_REACHED_SOS;
  172169. case M_EOI:
  172170. TRACEMS(cinfo, 1, JTRC_EOI);
  172171. cinfo->unread_marker = 0; /* processed the marker */
  172172. return JPEG_REACHED_EOI;
  172173. case M_DAC:
  172174. if (! get_dac(cinfo))
  172175. return JPEG_SUSPENDED;
  172176. break;
  172177. case M_DHT:
  172178. if (! get_dht(cinfo))
  172179. return JPEG_SUSPENDED;
  172180. break;
  172181. case M_DQT:
  172182. if (! get_dqt(cinfo))
  172183. return JPEG_SUSPENDED;
  172184. break;
  172185. case M_DRI:
  172186. if (! get_dri(cinfo))
  172187. return JPEG_SUSPENDED;
  172188. break;
  172189. case M_APP0:
  172190. case M_APP1:
  172191. case M_APP2:
  172192. case M_APP3:
  172193. case M_APP4:
  172194. case M_APP5:
  172195. case M_APP6:
  172196. case M_APP7:
  172197. case M_APP8:
  172198. case M_APP9:
  172199. case M_APP10:
  172200. case M_APP11:
  172201. case M_APP12:
  172202. case M_APP13:
  172203. case M_APP14:
  172204. case M_APP15:
  172205. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172206. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172207. return JPEG_SUSPENDED;
  172208. break;
  172209. case M_COM:
  172210. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172211. return JPEG_SUSPENDED;
  172212. break;
  172213. case M_RST0: /* these are all parameterless */
  172214. case M_RST1:
  172215. case M_RST2:
  172216. case M_RST3:
  172217. case M_RST4:
  172218. case M_RST5:
  172219. case M_RST6:
  172220. case M_RST7:
  172221. case M_TEM:
  172222. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172223. break;
  172224. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172225. if (! skip_variable(cinfo))
  172226. return JPEG_SUSPENDED;
  172227. break;
  172228. default: /* must be DHP, EXP, JPGn, or RESn */
  172229. /* For now, we treat the reserved markers as fatal errors since they are
  172230. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172231. * Once the JPEG 3 version-number marker is well defined, this code
  172232. * ought to change!
  172233. */
  172234. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172235. break;
  172236. }
  172237. /* Successfully processed marker, so reset state variable */
  172238. cinfo->unread_marker = 0;
  172239. } /* end loop */
  172240. }
  172241. /*
  172242. * Read a restart marker, which is expected to appear next in the datastream;
  172243. * if the marker is not there, take appropriate recovery action.
  172244. * Returns FALSE if suspension is required.
  172245. *
  172246. * This is called by the entropy decoder after it has read an appropriate
  172247. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172248. * has already read a marker from the data source. Under normal conditions
  172249. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172250. * it holds a marker which the decoder will be unable to read past.
  172251. */
  172252. METHODDEF(boolean)
  172253. read_restart_marker (j_decompress_ptr cinfo)
  172254. {
  172255. /* Obtain a marker unless we already did. */
  172256. /* Note that next_marker will complain if it skips any data. */
  172257. if (cinfo->unread_marker == 0) {
  172258. if (! next_marker(cinfo))
  172259. return FALSE;
  172260. }
  172261. if (cinfo->unread_marker ==
  172262. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172263. /* Normal case --- swallow the marker and let entropy decoder continue */
  172264. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172265. cinfo->unread_marker = 0;
  172266. } else {
  172267. /* Uh-oh, the restart markers have been messed up. */
  172268. /* Let the data source manager determine how to resync. */
  172269. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172270. cinfo->marker->next_restart_num))
  172271. return FALSE;
  172272. }
  172273. /* Update next-restart state */
  172274. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172275. return TRUE;
  172276. }
  172277. /*
  172278. * This is the default resync_to_restart method for data source managers
  172279. * to use if they don't have any better approach. Some data source managers
  172280. * may be able to back up, or may have additional knowledge about the data
  172281. * which permits a more intelligent recovery strategy; such managers would
  172282. * presumably supply their own resync method.
  172283. *
  172284. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172285. * the restart marker it was expecting. (This code is *not* used unless
  172286. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172287. * the marker code actually found (might be anything, except 0 or FF).
  172288. * The desired restart marker number (0..7) is passed as a parameter.
  172289. * This routine is supposed to apply whatever error recovery strategy seems
  172290. * appropriate in order to position the input stream to the next data segment.
  172291. * Note that cinfo->unread_marker is treated as a marker appearing before
  172292. * the current data-source input point; usually it should be reset to zero
  172293. * before returning.
  172294. * Returns FALSE if suspension is required.
  172295. *
  172296. * This implementation is substantially constrained by wanting to treat the
  172297. * input as a data stream; this means we can't back up. Therefore, we have
  172298. * only the following actions to work with:
  172299. * 1. Simply discard the marker and let the entropy decoder resume at next
  172300. * byte of file.
  172301. * 2. Read forward until we find another marker, discarding intervening
  172302. * data. (In theory we could look ahead within the current bufferload,
  172303. * without having to discard data if we don't find the desired marker.
  172304. * This idea is not implemented here, in part because it makes behavior
  172305. * dependent on buffer size and chance buffer-boundary positions.)
  172306. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172307. * This will cause the entropy decoder to process an empty data segment,
  172308. * inserting dummy zeroes, and then we will reprocess the marker.
  172309. *
  172310. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172311. * appropriate if the found marker is a future restart marker (indicating
  172312. * that we have missed the desired restart marker, probably because it got
  172313. * corrupted).
  172314. * We apply #2 or #3 if the found marker is a restart marker no more than
  172315. * two counts behind or ahead of the expected one. We also apply #2 if the
  172316. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172317. * If the found marker is a restart marker more than 2 counts away, we do #1
  172318. * (too much risk that the marker is erroneous; with luck we will be able to
  172319. * resync at some future point).
  172320. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172321. * overrunning the end of a scan. An implementation limited to single-scan
  172322. * files might find it better to apply #2 for markers other than EOI, since
  172323. * any other marker would have to be bogus data in that case.
  172324. */
  172325. GLOBAL(boolean)
  172326. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172327. {
  172328. int marker = cinfo->unread_marker;
  172329. int action = 1;
  172330. /* Always put up a warning. */
  172331. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172332. /* Outer loop handles repeated decision after scanning forward. */
  172333. for (;;) {
  172334. if (marker < (int) M_SOF0)
  172335. action = 2; /* invalid marker */
  172336. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172337. action = 3; /* valid non-restart marker */
  172338. else {
  172339. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172340. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172341. action = 3; /* one of the next two expected restarts */
  172342. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172343. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172344. action = 2; /* a prior restart, so advance */
  172345. else
  172346. action = 1; /* desired restart or too far away */
  172347. }
  172348. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172349. switch (action) {
  172350. case 1:
  172351. /* Discard marker and let entropy decoder resume processing. */
  172352. cinfo->unread_marker = 0;
  172353. return TRUE;
  172354. case 2:
  172355. /* Scan to the next marker, and repeat the decision loop. */
  172356. if (! next_marker(cinfo))
  172357. return FALSE;
  172358. marker = cinfo->unread_marker;
  172359. break;
  172360. case 3:
  172361. /* Return without advancing past this marker. */
  172362. /* Entropy decoder will be forced to process an empty segment. */
  172363. return TRUE;
  172364. }
  172365. } /* end loop */
  172366. }
  172367. /*
  172368. * Reset marker processing state to begin a fresh datastream.
  172369. */
  172370. METHODDEF(void)
  172371. reset_marker_reader (j_decompress_ptr cinfo)
  172372. {
  172373. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172374. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172375. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172376. cinfo->unread_marker = 0; /* no pending marker */
  172377. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172378. marker->pub.saw_SOF = FALSE;
  172379. marker->pub.discarded_bytes = 0;
  172380. marker->cur_marker = NULL;
  172381. }
  172382. /*
  172383. * Initialize the marker reader module.
  172384. * This is called only once, when the decompression object is created.
  172385. */
  172386. GLOBAL(void)
  172387. jinit_marker_reader (j_decompress_ptr cinfo)
  172388. {
  172389. my_marker_ptr2 marker;
  172390. int i;
  172391. /* Create subobject in permanent pool */
  172392. marker = (my_marker_ptr2)
  172393. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172394. SIZEOF(my_marker_reader));
  172395. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172396. /* Initialize public method pointers */
  172397. marker->pub.reset_marker_reader = reset_marker_reader;
  172398. marker->pub.read_markers = read_markers;
  172399. marker->pub.read_restart_marker = read_restart_marker;
  172400. /* Initialize COM/APPn processing.
  172401. * By default, we examine and then discard APP0 and APP14,
  172402. * but simply discard COM and all other APPn.
  172403. */
  172404. marker->process_COM = skip_variable;
  172405. marker->length_limit_COM = 0;
  172406. for (i = 0; i < 16; i++) {
  172407. marker->process_APPn[i] = skip_variable;
  172408. marker->length_limit_APPn[i] = 0;
  172409. }
  172410. marker->process_APPn[0] = get_interesting_appn;
  172411. marker->process_APPn[14] = get_interesting_appn;
  172412. /* Reset marker processing state */
  172413. reset_marker_reader(cinfo);
  172414. }
  172415. /*
  172416. * Control saving of COM and APPn markers into marker_list.
  172417. */
  172418. #ifdef SAVE_MARKERS_SUPPORTED
  172419. GLOBAL(void)
  172420. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172421. unsigned int length_limit)
  172422. {
  172423. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172424. long maxlength;
  172425. jpeg_marker_parser_method processor;
  172426. /* Length limit mustn't be larger than what we can allocate
  172427. * (should only be a concern in a 16-bit environment).
  172428. */
  172429. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172430. if (((long) length_limit) > maxlength)
  172431. length_limit = (unsigned int) maxlength;
  172432. /* Choose processor routine to use.
  172433. * APP0/APP14 have special requirements.
  172434. */
  172435. if (length_limit) {
  172436. processor = save_marker;
  172437. /* If saving APP0/APP14, save at least enough for our internal use. */
  172438. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172439. length_limit = APP0_DATA_LEN;
  172440. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172441. length_limit = APP14_DATA_LEN;
  172442. } else {
  172443. processor = skip_variable;
  172444. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172445. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172446. processor = get_interesting_appn;
  172447. }
  172448. if (marker_code == (int) M_COM) {
  172449. marker->process_COM = processor;
  172450. marker->length_limit_COM = length_limit;
  172451. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172452. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172453. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172454. } else
  172455. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172456. }
  172457. #endif /* SAVE_MARKERS_SUPPORTED */
  172458. /*
  172459. * Install a special processing method for COM or APPn markers.
  172460. */
  172461. GLOBAL(void)
  172462. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172463. jpeg_marker_parser_method routine)
  172464. {
  172465. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172466. if (marker_code == (int) M_COM)
  172467. marker->process_COM = routine;
  172468. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172469. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172470. else
  172471. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172472. }
  172473. /*** End of inlined file: jdmarker.c ***/
  172474. /*** Start of inlined file: jdmaster.c ***/
  172475. #define JPEG_INTERNALS
  172476. /* Private state */
  172477. typedef struct {
  172478. struct jpeg_decomp_master pub; /* public fields */
  172479. int pass_number; /* # of passes completed */
  172480. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172481. /* Saved references to initialized quantizer modules,
  172482. * in case we need to switch modes.
  172483. */
  172484. struct jpeg_color_quantizer * quantizer_1pass;
  172485. struct jpeg_color_quantizer * quantizer_2pass;
  172486. } my_decomp_master;
  172487. typedef my_decomp_master * my_master_ptr6;
  172488. /*
  172489. * Determine whether merged upsample/color conversion should be used.
  172490. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172491. */
  172492. LOCAL(boolean)
  172493. use_merged_upsample (j_decompress_ptr cinfo)
  172494. {
  172495. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172496. /* Merging is the equivalent of plain box-filter upsampling */
  172497. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172498. return FALSE;
  172499. /* jdmerge.c only supports YCC=>RGB color conversion */
  172500. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172501. cinfo->out_color_space != JCS_RGB ||
  172502. cinfo->out_color_components != RGB_PIXELSIZE)
  172503. return FALSE;
  172504. /* and it only handles 2h1v or 2h2v sampling ratios */
  172505. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172506. cinfo->comp_info[1].h_samp_factor != 1 ||
  172507. cinfo->comp_info[2].h_samp_factor != 1 ||
  172508. cinfo->comp_info[0].v_samp_factor > 2 ||
  172509. cinfo->comp_info[1].v_samp_factor != 1 ||
  172510. cinfo->comp_info[2].v_samp_factor != 1)
  172511. return FALSE;
  172512. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172513. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172514. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172515. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172516. return FALSE;
  172517. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172518. return TRUE; /* by golly, it'll work... */
  172519. #else
  172520. return FALSE;
  172521. #endif
  172522. }
  172523. /*
  172524. * Compute output image dimensions and related values.
  172525. * NOTE: this is exported for possible use by application.
  172526. * Hence it mustn't do anything that can't be done twice.
  172527. * Also note that it may be called before the master module is initialized!
  172528. */
  172529. GLOBAL(void)
  172530. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172531. /* Do computations that are needed before master selection phase */
  172532. {
  172533. #ifdef IDCT_SCALING_SUPPORTED
  172534. int ci;
  172535. jpeg_component_info *compptr;
  172536. #endif
  172537. /* Prevent application from calling me at wrong times */
  172538. if (cinfo->global_state != DSTATE_READY)
  172539. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172540. #ifdef IDCT_SCALING_SUPPORTED
  172541. /* Compute actual output image dimensions and DCT scaling choices. */
  172542. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172543. /* Provide 1/8 scaling */
  172544. cinfo->output_width = (JDIMENSION)
  172545. jdiv_round_up((long) cinfo->image_width, 8L);
  172546. cinfo->output_height = (JDIMENSION)
  172547. jdiv_round_up((long) cinfo->image_height, 8L);
  172548. cinfo->min_DCT_scaled_size = 1;
  172549. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172550. /* Provide 1/4 scaling */
  172551. cinfo->output_width = (JDIMENSION)
  172552. jdiv_round_up((long) cinfo->image_width, 4L);
  172553. cinfo->output_height = (JDIMENSION)
  172554. jdiv_round_up((long) cinfo->image_height, 4L);
  172555. cinfo->min_DCT_scaled_size = 2;
  172556. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172557. /* Provide 1/2 scaling */
  172558. cinfo->output_width = (JDIMENSION)
  172559. jdiv_round_up((long) cinfo->image_width, 2L);
  172560. cinfo->output_height = (JDIMENSION)
  172561. jdiv_round_up((long) cinfo->image_height, 2L);
  172562. cinfo->min_DCT_scaled_size = 4;
  172563. } else {
  172564. /* Provide 1/1 scaling */
  172565. cinfo->output_width = cinfo->image_width;
  172566. cinfo->output_height = cinfo->image_height;
  172567. cinfo->min_DCT_scaled_size = DCTSIZE;
  172568. }
  172569. /* In selecting the actual DCT scaling for each component, we try to
  172570. * scale up the chroma components via IDCT scaling rather than upsampling.
  172571. * This saves time if the upsampler gets to use 1:1 scaling.
  172572. * Note this code assumes that the supported DCT scalings are powers of 2.
  172573. */
  172574. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172575. ci++, compptr++) {
  172576. int ssize = cinfo->min_DCT_scaled_size;
  172577. while (ssize < DCTSIZE &&
  172578. (compptr->h_samp_factor * ssize * 2 <=
  172579. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172580. (compptr->v_samp_factor * ssize * 2 <=
  172581. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172582. ssize = ssize * 2;
  172583. }
  172584. compptr->DCT_scaled_size = ssize;
  172585. }
  172586. /* Recompute downsampled dimensions of components;
  172587. * application needs to know these if using raw downsampled data.
  172588. */
  172589. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172590. ci++, compptr++) {
  172591. /* Size in samples, after IDCT scaling */
  172592. compptr->downsampled_width = (JDIMENSION)
  172593. jdiv_round_up((long) cinfo->image_width *
  172594. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172595. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172596. compptr->downsampled_height = (JDIMENSION)
  172597. jdiv_round_up((long) cinfo->image_height *
  172598. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172599. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172600. }
  172601. #else /* !IDCT_SCALING_SUPPORTED */
  172602. /* Hardwire it to "no scaling" */
  172603. cinfo->output_width = cinfo->image_width;
  172604. cinfo->output_height = cinfo->image_height;
  172605. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172606. * and has computed unscaled downsampled_width and downsampled_height.
  172607. */
  172608. #endif /* IDCT_SCALING_SUPPORTED */
  172609. /* Report number of components in selected colorspace. */
  172610. /* Probably this should be in the color conversion module... */
  172611. switch (cinfo->out_color_space) {
  172612. case JCS_GRAYSCALE:
  172613. cinfo->out_color_components = 1;
  172614. break;
  172615. case JCS_RGB:
  172616. #if RGB_PIXELSIZE != 3
  172617. cinfo->out_color_components = RGB_PIXELSIZE;
  172618. break;
  172619. #endif /* else share code with YCbCr */
  172620. case JCS_YCbCr:
  172621. cinfo->out_color_components = 3;
  172622. break;
  172623. case JCS_CMYK:
  172624. case JCS_YCCK:
  172625. cinfo->out_color_components = 4;
  172626. break;
  172627. default: /* else must be same colorspace as in file */
  172628. cinfo->out_color_components = cinfo->num_components;
  172629. break;
  172630. }
  172631. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172632. cinfo->out_color_components);
  172633. /* See if upsampler will want to emit more than one row at a time */
  172634. if (use_merged_upsample(cinfo))
  172635. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172636. else
  172637. cinfo->rec_outbuf_height = 1;
  172638. }
  172639. /*
  172640. * Several decompression processes need to range-limit values to the range
  172641. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172642. * due to noise introduced by quantization, roundoff error, etc. These
  172643. * processes are inner loops and need to be as fast as possible. On most
  172644. * machines, particularly CPUs with pipelines or instruction prefetch,
  172645. * a (subscript-check-less) C table lookup
  172646. * x = sample_range_limit[x];
  172647. * is faster than explicit tests
  172648. * if (x < 0) x = 0;
  172649. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172650. * These processes all use a common table prepared by the routine below.
  172651. *
  172652. * For most steps we can mathematically guarantee that the initial value
  172653. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172654. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172655. * limiting step (just after the IDCT), a wildly out-of-range value is
  172656. * possible if the input data is corrupt. To avoid any chance of indexing
  172657. * off the end of memory and getting a bad-pointer trap, we perform the
  172658. * post-IDCT limiting thus:
  172659. * x = range_limit[x & MASK];
  172660. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172661. * samples. Under normal circumstances this is more than enough range and
  172662. * a correct output will be generated; with bogus input data the mask will
  172663. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172664. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172665. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172666. * So the post-IDCT limiting table ends up looking like this:
  172667. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172668. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172669. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172670. * 0,1,...,CENTERJSAMPLE-1
  172671. * Negative inputs select values from the upper half of the table after
  172672. * masking.
  172673. *
  172674. * We can save some space by overlapping the start of the post-IDCT table
  172675. * with the simpler range limiting table. The post-IDCT table begins at
  172676. * sample_range_limit + CENTERJSAMPLE.
  172677. *
  172678. * Note that the table is allocated in near data space on PCs; it's small
  172679. * enough and used often enough to justify this.
  172680. */
  172681. LOCAL(void)
  172682. prepare_range_limit_table (j_decompress_ptr cinfo)
  172683. /* Allocate and fill in the sample_range_limit table */
  172684. {
  172685. JSAMPLE * table;
  172686. int i;
  172687. table = (JSAMPLE *)
  172688. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172689. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172690. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172691. cinfo->sample_range_limit = table;
  172692. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172693. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172694. /* Main part of "simple" table: limit[x] = x */
  172695. for (i = 0; i <= MAXJSAMPLE; i++)
  172696. table[i] = (JSAMPLE) i;
  172697. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172698. /* End of simple table, rest of first half of post-IDCT table */
  172699. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172700. table[i] = MAXJSAMPLE;
  172701. /* Second half of post-IDCT table */
  172702. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172703. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172704. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172705. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172706. }
  172707. /*
  172708. * Master selection of decompression modules.
  172709. * This is done once at jpeg_start_decompress time. We determine
  172710. * which modules will be used and give them appropriate initialization calls.
  172711. * We also initialize the decompressor input side to begin consuming data.
  172712. *
  172713. * Since jpeg_read_header has finished, we know what is in the SOF
  172714. * and (first) SOS markers. We also have all the application parameter
  172715. * settings.
  172716. */
  172717. LOCAL(void)
  172718. master_selection (j_decompress_ptr cinfo)
  172719. {
  172720. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172721. boolean use_c_buffer;
  172722. long samplesperrow;
  172723. JDIMENSION jd_samplesperrow;
  172724. /* Initialize dimensions and other stuff */
  172725. jpeg_calc_output_dimensions(cinfo);
  172726. prepare_range_limit_table(cinfo);
  172727. /* Width of an output scanline must be representable as JDIMENSION. */
  172728. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172729. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172730. if ((long) jd_samplesperrow != samplesperrow)
  172731. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172732. /* Initialize my private state */
  172733. master->pass_number = 0;
  172734. master->using_merged_upsample = use_merged_upsample(cinfo);
  172735. /* Color quantizer selection */
  172736. master->quantizer_1pass = NULL;
  172737. master->quantizer_2pass = NULL;
  172738. /* No mode changes if not using buffered-image mode. */
  172739. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172740. cinfo->enable_1pass_quant = FALSE;
  172741. cinfo->enable_external_quant = FALSE;
  172742. cinfo->enable_2pass_quant = FALSE;
  172743. }
  172744. if (cinfo->quantize_colors) {
  172745. if (cinfo->raw_data_out)
  172746. ERREXIT(cinfo, JERR_NOTIMPL);
  172747. /* 2-pass quantizer only works in 3-component color space. */
  172748. if (cinfo->out_color_components != 3) {
  172749. cinfo->enable_1pass_quant = TRUE;
  172750. cinfo->enable_external_quant = FALSE;
  172751. cinfo->enable_2pass_quant = FALSE;
  172752. cinfo->colormap = NULL;
  172753. } else if (cinfo->colormap != NULL) {
  172754. cinfo->enable_external_quant = TRUE;
  172755. } else if (cinfo->two_pass_quantize) {
  172756. cinfo->enable_2pass_quant = TRUE;
  172757. } else {
  172758. cinfo->enable_1pass_quant = TRUE;
  172759. }
  172760. if (cinfo->enable_1pass_quant) {
  172761. #ifdef QUANT_1PASS_SUPPORTED
  172762. jinit_1pass_quantizer(cinfo);
  172763. master->quantizer_1pass = cinfo->cquantize;
  172764. #else
  172765. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172766. #endif
  172767. }
  172768. /* We use the 2-pass code to map to external colormaps. */
  172769. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172770. #ifdef QUANT_2PASS_SUPPORTED
  172771. jinit_2pass_quantizer(cinfo);
  172772. master->quantizer_2pass = cinfo->cquantize;
  172773. #else
  172774. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172775. #endif
  172776. }
  172777. /* If both quantizers are initialized, the 2-pass one is left active;
  172778. * this is necessary for starting with quantization to an external map.
  172779. */
  172780. }
  172781. /* Post-processing: in particular, color conversion first */
  172782. if (! cinfo->raw_data_out) {
  172783. if (master->using_merged_upsample) {
  172784. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172785. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172786. #else
  172787. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172788. #endif
  172789. } else {
  172790. jinit_color_deconverter(cinfo);
  172791. jinit_upsampler(cinfo);
  172792. }
  172793. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172794. }
  172795. /* Inverse DCT */
  172796. jinit_inverse_dct(cinfo);
  172797. /* Entropy decoding: either Huffman or arithmetic coding. */
  172798. if (cinfo->arith_code) {
  172799. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172800. } else {
  172801. if (cinfo->progressive_mode) {
  172802. #ifdef D_PROGRESSIVE_SUPPORTED
  172803. jinit_phuff_decoder(cinfo);
  172804. #else
  172805. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172806. #endif
  172807. } else
  172808. jinit_huff_decoder(cinfo);
  172809. }
  172810. /* Initialize principal buffer controllers. */
  172811. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172812. jinit_d_coef_controller(cinfo, use_c_buffer);
  172813. if (! cinfo->raw_data_out)
  172814. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172815. /* We can now tell the memory manager to allocate virtual arrays. */
  172816. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172817. /* Initialize input side of decompressor to consume first scan. */
  172818. (*cinfo->inputctl->start_input_pass) (cinfo);
  172819. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172820. /* If jpeg_start_decompress will read the whole file, initialize
  172821. * progress monitoring appropriately. The input step is counted
  172822. * as one pass.
  172823. */
  172824. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172825. cinfo->inputctl->has_multiple_scans) {
  172826. int nscans;
  172827. /* Estimate number of scans to set pass_limit. */
  172828. if (cinfo->progressive_mode) {
  172829. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172830. nscans = 2 + 3 * cinfo->num_components;
  172831. } else {
  172832. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172833. nscans = cinfo->num_components;
  172834. }
  172835. cinfo->progress->pass_counter = 0L;
  172836. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172837. cinfo->progress->completed_passes = 0;
  172838. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172839. /* Count the input pass as done */
  172840. master->pass_number++;
  172841. }
  172842. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172843. }
  172844. /*
  172845. * Per-pass setup.
  172846. * This is called at the beginning of each output pass. We determine which
  172847. * modules will be active during this pass and give them appropriate
  172848. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172849. * is a "real" output pass or a dummy pass for color quantization.
  172850. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172851. */
  172852. METHODDEF(void)
  172853. prepare_for_output_pass (j_decompress_ptr cinfo)
  172854. {
  172855. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172856. if (master->pub.is_dummy_pass) {
  172857. #ifdef QUANT_2PASS_SUPPORTED
  172858. /* Final pass of 2-pass quantization */
  172859. master->pub.is_dummy_pass = FALSE;
  172860. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172861. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172862. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172863. #else
  172864. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172865. #endif /* QUANT_2PASS_SUPPORTED */
  172866. } else {
  172867. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172868. /* Select new quantization method */
  172869. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172870. cinfo->cquantize = master->quantizer_2pass;
  172871. master->pub.is_dummy_pass = TRUE;
  172872. } else if (cinfo->enable_1pass_quant) {
  172873. cinfo->cquantize = master->quantizer_1pass;
  172874. } else {
  172875. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172876. }
  172877. }
  172878. (*cinfo->idct->start_pass) (cinfo);
  172879. (*cinfo->coef->start_output_pass) (cinfo);
  172880. if (! cinfo->raw_data_out) {
  172881. if (! master->using_merged_upsample)
  172882. (*cinfo->cconvert->start_pass) (cinfo);
  172883. (*cinfo->upsample->start_pass) (cinfo);
  172884. if (cinfo->quantize_colors)
  172885. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172886. (*cinfo->post->start_pass) (cinfo,
  172887. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172888. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172889. }
  172890. }
  172891. /* Set up progress monitor's pass info if present */
  172892. if (cinfo->progress != NULL) {
  172893. cinfo->progress->completed_passes = master->pass_number;
  172894. cinfo->progress->total_passes = master->pass_number +
  172895. (master->pub.is_dummy_pass ? 2 : 1);
  172896. /* In buffered-image mode, we assume one more output pass if EOI not
  172897. * yet reached, but no more passes if EOI has been reached.
  172898. */
  172899. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172900. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172901. }
  172902. }
  172903. }
  172904. /*
  172905. * Finish up at end of an output pass.
  172906. */
  172907. METHODDEF(void)
  172908. finish_output_pass (j_decompress_ptr cinfo)
  172909. {
  172910. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172911. if (cinfo->quantize_colors)
  172912. (*cinfo->cquantize->finish_pass) (cinfo);
  172913. master->pass_number++;
  172914. }
  172915. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172916. /*
  172917. * Switch to a new external colormap between output passes.
  172918. */
  172919. GLOBAL(void)
  172920. jpeg_new_colormap (j_decompress_ptr cinfo)
  172921. {
  172922. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172923. /* Prevent application from calling me at wrong times */
  172924. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172925. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172926. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172927. cinfo->colormap != NULL) {
  172928. /* Select 2-pass quantizer for external colormap use */
  172929. cinfo->cquantize = master->quantizer_2pass;
  172930. /* Notify quantizer of colormap change */
  172931. (*cinfo->cquantize->new_color_map) (cinfo);
  172932. master->pub.is_dummy_pass = FALSE; /* just in case */
  172933. } else
  172934. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172935. }
  172936. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172937. /*
  172938. * Initialize master decompression control and select active modules.
  172939. * This is performed at the start of jpeg_start_decompress.
  172940. */
  172941. GLOBAL(void)
  172942. jinit_master_decompress (j_decompress_ptr cinfo)
  172943. {
  172944. my_master_ptr6 master;
  172945. master = (my_master_ptr6)
  172946. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172947. SIZEOF(my_decomp_master));
  172948. cinfo->master = (struct jpeg_decomp_master *) master;
  172949. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172950. master->pub.finish_output_pass = finish_output_pass;
  172951. master->pub.is_dummy_pass = FALSE;
  172952. master_selection(cinfo);
  172953. }
  172954. /*** End of inlined file: jdmaster.c ***/
  172955. #undef FIX
  172956. /*** Start of inlined file: jdmerge.c ***/
  172957. #define JPEG_INTERNALS
  172958. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172959. /* Private subobject */
  172960. typedef struct {
  172961. struct jpeg_upsampler pub; /* public fields */
  172962. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172963. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172964. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172965. JSAMPARRAY output_buf));
  172966. /* Private state for YCC->RGB conversion */
  172967. int * Cr_r_tab; /* => table for Cr to R conversion */
  172968. int * Cb_b_tab; /* => table for Cb to B conversion */
  172969. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172970. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172971. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172972. * We need a "spare" row buffer to hold the second output row if the
  172973. * application provides just a one-row buffer; we also use the spare
  172974. * to discard the dummy last row if the image height is odd.
  172975. */
  172976. JSAMPROW spare_row;
  172977. boolean spare_full; /* T if spare buffer is occupied */
  172978. JDIMENSION out_row_width; /* samples per output row */
  172979. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172980. } my_upsampler;
  172981. typedef my_upsampler * my_upsample_ptr;
  172982. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172983. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172984. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172985. /*
  172986. * Initialize tables for YCC->RGB colorspace conversion.
  172987. * This is taken directly from jdcolor.c; see that file for more info.
  172988. */
  172989. LOCAL(void)
  172990. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172991. {
  172992. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172993. int i;
  172994. INT32 x;
  172995. SHIFT_TEMPS
  172996. upsample->Cr_r_tab = (int *)
  172997. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172998. (MAXJSAMPLE+1) * SIZEOF(int));
  172999. upsample->Cb_b_tab = (int *)
  173000. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173001. (MAXJSAMPLE+1) * SIZEOF(int));
  173002. upsample->Cr_g_tab = (INT32 *)
  173003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173004. (MAXJSAMPLE+1) * SIZEOF(INT32));
  173005. upsample->Cb_g_tab = (INT32 *)
  173006. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173007. (MAXJSAMPLE+1) * SIZEOF(INT32));
  173008. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  173009. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  173010. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  173011. /* Cr=>R value is nearest int to 1.40200 * x */
  173012. upsample->Cr_r_tab[i] = (int)
  173013. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  173014. /* Cb=>B value is nearest int to 1.77200 * x */
  173015. upsample->Cb_b_tab[i] = (int)
  173016. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  173017. /* Cr=>G value is scaled-up -0.71414 * x */
  173018. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  173019. /* Cb=>G value is scaled-up -0.34414 * x */
  173020. /* We also add in ONE_HALF so that need not do it in inner loop */
  173021. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  173022. }
  173023. }
  173024. /*
  173025. * Initialize for an upsampling pass.
  173026. */
  173027. METHODDEF(void)
  173028. start_pass_merged_upsample (j_decompress_ptr cinfo)
  173029. {
  173030. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173031. /* Mark the spare buffer empty */
  173032. upsample->spare_full = FALSE;
  173033. /* Initialize total-height counter for detecting bottom of image */
  173034. upsample->rows_to_go = cinfo->output_height;
  173035. }
  173036. /*
  173037. * Control routine to do upsampling (and color conversion).
  173038. *
  173039. * The control routine just handles the row buffering considerations.
  173040. */
  173041. METHODDEF(void)
  173042. merged_2v_upsample (j_decompress_ptr cinfo,
  173043. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173044. JDIMENSION,
  173045. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173046. JDIMENSION out_rows_avail)
  173047. /* 2:1 vertical sampling case: may need a spare row. */
  173048. {
  173049. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173050. JSAMPROW work_ptrs[2];
  173051. JDIMENSION num_rows; /* number of rows returned to caller */
  173052. if (upsample->spare_full) {
  173053. /* If we have a spare row saved from a previous cycle, just return it. */
  173054. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  173055. 1, upsample->out_row_width);
  173056. num_rows = 1;
  173057. upsample->spare_full = FALSE;
  173058. } else {
  173059. /* Figure number of rows to return to caller. */
  173060. num_rows = 2;
  173061. /* Not more than the distance to the end of the image. */
  173062. if (num_rows > upsample->rows_to_go)
  173063. num_rows = upsample->rows_to_go;
  173064. /* And not more than what the client can accept: */
  173065. out_rows_avail -= *out_row_ctr;
  173066. if (num_rows > out_rows_avail)
  173067. num_rows = out_rows_avail;
  173068. /* Create output pointer array for upsampler. */
  173069. work_ptrs[0] = output_buf[*out_row_ctr];
  173070. if (num_rows > 1) {
  173071. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  173072. } else {
  173073. work_ptrs[1] = upsample->spare_row;
  173074. upsample->spare_full = TRUE;
  173075. }
  173076. /* Now do the upsampling. */
  173077. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  173078. }
  173079. /* Adjust counts */
  173080. *out_row_ctr += num_rows;
  173081. upsample->rows_to_go -= num_rows;
  173082. /* When the buffer is emptied, declare this input row group consumed */
  173083. if (! upsample->spare_full)
  173084. (*in_row_group_ctr)++;
  173085. }
  173086. METHODDEF(void)
  173087. merged_1v_upsample (j_decompress_ptr cinfo,
  173088. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173089. JDIMENSION,
  173090. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173091. JDIMENSION)
  173092. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  173093. {
  173094. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173095. /* Just do the upsampling. */
  173096. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  173097. output_buf + *out_row_ctr);
  173098. /* Adjust counts */
  173099. (*out_row_ctr)++;
  173100. (*in_row_group_ctr)++;
  173101. }
  173102. /*
  173103. * These are the routines invoked by the control routines to do
  173104. * the actual upsampling/conversion. One row group is processed per call.
  173105. *
  173106. * Note: since we may be writing directly into application-supplied buffers,
  173107. * we have to be honest about the output width; we can't assume the buffer
  173108. * has been rounded up to an even width.
  173109. */
  173110. /*
  173111. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  173112. */
  173113. METHODDEF(void)
  173114. h2v1_merged_upsample (j_decompress_ptr cinfo,
  173115. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173116. JSAMPARRAY output_buf)
  173117. {
  173118. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173119. register int y, cred, cgreen, cblue;
  173120. int cb, cr;
  173121. register JSAMPROW outptr;
  173122. JSAMPROW inptr0, inptr1, inptr2;
  173123. JDIMENSION col;
  173124. /* copy these pointers into registers if possible */
  173125. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173126. int * Crrtab = upsample->Cr_r_tab;
  173127. int * Cbbtab = upsample->Cb_b_tab;
  173128. INT32 * Crgtab = upsample->Cr_g_tab;
  173129. INT32 * Cbgtab = upsample->Cb_g_tab;
  173130. SHIFT_TEMPS
  173131. inptr0 = input_buf[0][in_row_group_ctr];
  173132. inptr1 = input_buf[1][in_row_group_ctr];
  173133. inptr2 = input_buf[2][in_row_group_ctr];
  173134. outptr = output_buf[0];
  173135. /* Loop for each pair of output pixels */
  173136. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173137. /* Do the chroma part of the calculation */
  173138. cb = GETJSAMPLE(*inptr1++);
  173139. cr = GETJSAMPLE(*inptr2++);
  173140. cred = Crrtab[cr];
  173141. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173142. cblue = Cbbtab[cb];
  173143. /* Fetch 2 Y values and emit 2 pixels */
  173144. y = GETJSAMPLE(*inptr0++);
  173145. outptr[RGB_RED] = range_limit[y + cred];
  173146. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173147. outptr[RGB_BLUE] = range_limit[y + cblue];
  173148. outptr += RGB_PIXELSIZE;
  173149. y = GETJSAMPLE(*inptr0++);
  173150. outptr[RGB_RED] = range_limit[y + cred];
  173151. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173152. outptr[RGB_BLUE] = range_limit[y + cblue];
  173153. outptr += RGB_PIXELSIZE;
  173154. }
  173155. /* If image width is odd, do the last output column separately */
  173156. if (cinfo->output_width & 1) {
  173157. cb = GETJSAMPLE(*inptr1);
  173158. cr = GETJSAMPLE(*inptr2);
  173159. cred = Crrtab[cr];
  173160. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173161. cblue = Cbbtab[cb];
  173162. y = GETJSAMPLE(*inptr0);
  173163. outptr[RGB_RED] = range_limit[y + cred];
  173164. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173165. outptr[RGB_BLUE] = range_limit[y + cblue];
  173166. }
  173167. }
  173168. /*
  173169. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173170. */
  173171. METHODDEF(void)
  173172. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173173. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173174. JSAMPARRAY output_buf)
  173175. {
  173176. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173177. register int y, cred, cgreen, cblue;
  173178. int cb, cr;
  173179. register JSAMPROW outptr0, outptr1;
  173180. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173181. JDIMENSION col;
  173182. /* copy these pointers into registers if possible */
  173183. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173184. int * Crrtab = upsample->Cr_r_tab;
  173185. int * Cbbtab = upsample->Cb_b_tab;
  173186. INT32 * Crgtab = upsample->Cr_g_tab;
  173187. INT32 * Cbgtab = upsample->Cb_g_tab;
  173188. SHIFT_TEMPS
  173189. inptr00 = input_buf[0][in_row_group_ctr*2];
  173190. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173191. inptr1 = input_buf[1][in_row_group_ctr];
  173192. inptr2 = input_buf[2][in_row_group_ctr];
  173193. outptr0 = output_buf[0];
  173194. outptr1 = output_buf[1];
  173195. /* Loop for each group of output pixels */
  173196. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173197. /* Do the chroma part of the calculation */
  173198. cb = GETJSAMPLE(*inptr1++);
  173199. cr = GETJSAMPLE(*inptr2++);
  173200. cred = Crrtab[cr];
  173201. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173202. cblue = Cbbtab[cb];
  173203. /* Fetch 4 Y values and emit 4 pixels */
  173204. y = GETJSAMPLE(*inptr00++);
  173205. outptr0[RGB_RED] = range_limit[y + cred];
  173206. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173207. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173208. outptr0 += RGB_PIXELSIZE;
  173209. y = GETJSAMPLE(*inptr00++);
  173210. outptr0[RGB_RED] = range_limit[y + cred];
  173211. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173212. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173213. outptr0 += RGB_PIXELSIZE;
  173214. y = GETJSAMPLE(*inptr01++);
  173215. outptr1[RGB_RED] = range_limit[y + cred];
  173216. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173217. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173218. outptr1 += RGB_PIXELSIZE;
  173219. y = GETJSAMPLE(*inptr01++);
  173220. outptr1[RGB_RED] = range_limit[y + cred];
  173221. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173222. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173223. outptr1 += RGB_PIXELSIZE;
  173224. }
  173225. /* If image width is odd, do the last output column separately */
  173226. if (cinfo->output_width & 1) {
  173227. cb = GETJSAMPLE(*inptr1);
  173228. cr = GETJSAMPLE(*inptr2);
  173229. cred = Crrtab[cr];
  173230. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173231. cblue = Cbbtab[cb];
  173232. y = GETJSAMPLE(*inptr00);
  173233. outptr0[RGB_RED] = range_limit[y + cred];
  173234. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173235. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173236. y = GETJSAMPLE(*inptr01);
  173237. outptr1[RGB_RED] = range_limit[y + cred];
  173238. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173239. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173240. }
  173241. }
  173242. /*
  173243. * Module initialization routine for merged upsampling/color conversion.
  173244. *
  173245. * NB: this is called under the conditions determined by use_merged_upsample()
  173246. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173247. * of this module; no safety checks are made here.
  173248. */
  173249. GLOBAL(void)
  173250. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173251. {
  173252. my_upsample_ptr upsample;
  173253. upsample = (my_upsample_ptr)
  173254. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173255. SIZEOF(my_upsampler));
  173256. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173257. upsample->pub.start_pass = start_pass_merged_upsample;
  173258. upsample->pub.need_context_rows = FALSE;
  173259. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173260. if (cinfo->max_v_samp_factor == 2) {
  173261. upsample->pub.upsample = merged_2v_upsample;
  173262. upsample->upmethod = h2v2_merged_upsample;
  173263. /* Allocate a spare row buffer */
  173264. upsample->spare_row = (JSAMPROW)
  173265. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173266. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173267. } else {
  173268. upsample->pub.upsample = merged_1v_upsample;
  173269. upsample->upmethod = h2v1_merged_upsample;
  173270. /* No spare row needed */
  173271. upsample->spare_row = NULL;
  173272. }
  173273. build_ycc_rgb_table2(cinfo);
  173274. }
  173275. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173276. /*** End of inlined file: jdmerge.c ***/
  173277. #undef ASSIGN_STATE
  173278. /*** Start of inlined file: jdphuff.c ***/
  173279. #define JPEG_INTERNALS
  173280. #ifdef D_PROGRESSIVE_SUPPORTED
  173281. /*
  173282. * Expanded entropy decoder object for progressive Huffman decoding.
  173283. *
  173284. * The savable_state subrecord contains fields that change within an MCU,
  173285. * but must not be updated permanently until we complete the MCU.
  173286. */
  173287. typedef struct {
  173288. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173289. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173290. } savable_state3;
  173291. /* This macro is to work around compilers with missing or broken
  173292. * structure assignment. You'll need to fix this code if you have
  173293. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173294. */
  173295. #ifndef NO_STRUCT_ASSIGN
  173296. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173297. #else
  173298. #if MAX_COMPS_IN_SCAN == 4
  173299. #define ASSIGN_STATE(dest,src) \
  173300. ((dest).EOBRUN = (src).EOBRUN, \
  173301. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173302. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173303. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173304. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173305. #endif
  173306. #endif
  173307. typedef struct {
  173308. struct jpeg_entropy_decoder pub; /* public fields */
  173309. /* These fields are loaded into local variables at start of each MCU.
  173310. * In case of suspension, we exit WITHOUT updating them.
  173311. */
  173312. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173313. savable_state3 saved; /* Other state at start of MCU */
  173314. /* These fields are NOT loaded into local working state. */
  173315. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173316. /* Pointers to derived tables (these workspaces have image lifespan) */
  173317. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173318. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173319. } phuff_entropy_decoder;
  173320. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173321. /* Forward declarations */
  173322. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173323. JBLOCKROW *MCU_data));
  173324. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173325. JBLOCKROW *MCU_data));
  173326. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173327. JBLOCKROW *MCU_data));
  173328. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173329. JBLOCKROW *MCU_data));
  173330. /*
  173331. * Initialize for a Huffman-compressed scan.
  173332. */
  173333. METHODDEF(void)
  173334. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173335. {
  173336. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173337. boolean is_DC_band, bad;
  173338. int ci, coefi, tbl;
  173339. int *coef_bit_ptr;
  173340. jpeg_component_info * compptr;
  173341. is_DC_band = (cinfo->Ss == 0);
  173342. /* Validate scan parameters */
  173343. bad = FALSE;
  173344. if (is_DC_band) {
  173345. if (cinfo->Se != 0)
  173346. bad = TRUE;
  173347. } else {
  173348. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173349. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173350. bad = TRUE;
  173351. /* AC scans may have only one component */
  173352. if (cinfo->comps_in_scan != 1)
  173353. bad = TRUE;
  173354. }
  173355. if (cinfo->Ah != 0) {
  173356. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173357. if (cinfo->Al != cinfo->Ah-1)
  173358. bad = TRUE;
  173359. }
  173360. if (cinfo->Al > 13) /* need not check for < 0 */
  173361. bad = TRUE;
  173362. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173363. * but the spec doesn't say so, and we try to be liberal about what we
  173364. * accept. Note: large Al values could result in out-of-range DC
  173365. * coefficients during early scans, leading to bizarre displays due to
  173366. * overflows in the IDCT math. But we won't crash.
  173367. */
  173368. if (bad)
  173369. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173370. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173371. /* Update progression status, and verify that scan order is legal.
  173372. * Note that inter-scan inconsistencies are treated as warnings
  173373. * not fatal errors ... not clear if this is right way to behave.
  173374. */
  173375. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173376. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173377. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173378. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173379. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173380. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173381. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173382. if (cinfo->Ah != expected)
  173383. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173384. coef_bit_ptr[coefi] = cinfo->Al;
  173385. }
  173386. }
  173387. /* Select MCU decoding routine */
  173388. if (cinfo->Ah == 0) {
  173389. if (is_DC_band)
  173390. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173391. else
  173392. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173393. } else {
  173394. if (is_DC_band)
  173395. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173396. else
  173397. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173398. }
  173399. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173400. compptr = cinfo->cur_comp_info[ci];
  173401. /* Make sure requested tables are present, and compute derived tables.
  173402. * We may build same derived table more than once, but it's not expensive.
  173403. */
  173404. if (is_DC_band) {
  173405. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173406. tbl = compptr->dc_tbl_no;
  173407. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173408. & entropy->derived_tbls[tbl]);
  173409. }
  173410. } else {
  173411. tbl = compptr->ac_tbl_no;
  173412. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173413. & entropy->derived_tbls[tbl]);
  173414. /* remember the single active table */
  173415. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173416. }
  173417. /* Initialize DC predictions to 0 */
  173418. entropy->saved.last_dc_val[ci] = 0;
  173419. }
  173420. /* Initialize bitread state variables */
  173421. entropy->bitstate.bits_left = 0;
  173422. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173423. entropy->pub.insufficient_data = FALSE;
  173424. /* Initialize private state variables */
  173425. entropy->saved.EOBRUN = 0;
  173426. /* Initialize restart counter */
  173427. entropy->restarts_to_go = cinfo->restart_interval;
  173428. }
  173429. /*
  173430. * Check for a restart marker & resynchronize decoder.
  173431. * Returns FALSE if must suspend.
  173432. */
  173433. LOCAL(boolean)
  173434. process_restartp (j_decompress_ptr cinfo)
  173435. {
  173436. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173437. int ci;
  173438. /* Throw away any unused bits remaining in bit buffer; */
  173439. /* include any full bytes in next_marker's count of discarded bytes */
  173440. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173441. entropy->bitstate.bits_left = 0;
  173442. /* Advance past the RSTn marker */
  173443. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173444. return FALSE;
  173445. /* Re-initialize DC predictions to 0 */
  173446. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173447. entropy->saved.last_dc_val[ci] = 0;
  173448. /* Re-init EOB run count, too */
  173449. entropy->saved.EOBRUN = 0;
  173450. /* Reset restart counter */
  173451. entropy->restarts_to_go = cinfo->restart_interval;
  173452. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173453. * against a marker. In that case we will end up treating the next data
  173454. * segment as empty, and we can avoid producing bogus output pixels by
  173455. * leaving the flag set.
  173456. */
  173457. if (cinfo->unread_marker == 0)
  173458. entropy->pub.insufficient_data = FALSE;
  173459. return TRUE;
  173460. }
  173461. /*
  173462. * Huffman MCU decoding.
  173463. * Each of these routines decodes and returns one MCU's worth of
  173464. * Huffman-compressed coefficients.
  173465. * The coefficients are reordered from zigzag order into natural array order,
  173466. * but are not dequantized.
  173467. *
  173468. * The i'th block of the MCU is stored into the block pointed to by
  173469. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173470. *
  173471. * We return FALSE if data source requested suspension. In that case no
  173472. * changes have been made to permanent state. (Exception: some output
  173473. * coefficients may already have been assigned. This is harmless for
  173474. * spectral selection, since we'll just re-assign them on the next call.
  173475. * Successive approximation AC refinement has to be more careful, however.)
  173476. */
  173477. /*
  173478. * MCU decoding for DC initial scan (either spectral selection,
  173479. * or first pass of successive approximation).
  173480. */
  173481. METHODDEF(boolean)
  173482. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173483. {
  173484. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173485. int Al = cinfo->Al;
  173486. register int s, r;
  173487. int blkn, ci;
  173488. JBLOCKROW block;
  173489. BITREAD_STATE_VARS;
  173490. savable_state3 state;
  173491. d_derived_tbl * tbl;
  173492. jpeg_component_info * compptr;
  173493. /* Process restart marker if needed; may have to suspend */
  173494. if (cinfo->restart_interval) {
  173495. if (entropy->restarts_to_go == 0)
  173496. if (! process_restartp(cinfo))
  173497. return FALSE;
  173498. }
  173499. /* If we've run out of data, just leave the MCU set to zeroes.
  173500. * This way, we return uniform gray for the remainder of the segment.
  173501. */
  173502. if (! entropy->pub.insufficient_data) {
  173503. /* Load up working state */
  173504. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173505. ASSIGN_STATE(state, entropy->saved);
  173506. /* Outer loop handles each block in the MCU */
  173507. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173508. block = MCU_data[blkn];
  173509. ci = cinfo->MCU_membership[blkn];
  173510. compptr = cinfo->cur_comp_info[ci];
  173511. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173512. /* Decode a single block's worth of coefficients */
  173513. /* Section F.2.2.1: decode the DC coefficient difference */
  173514. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173515. if (s) {
  173516. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173517. r = GET_BITS(s);
  173518. s = HUFF_EXTEND(r, s);
  173519. }
  173520. /* Convert DC difference to actual value, update last_dc_val */
  173521. s += state.last_dc_val[ci];
  173522. state.last_dc_val[ci] = s;
  173523. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173524. (*block)[0] = (JCOEF) (s << Al);
  173525. }
  173526. /* Completed MCU, so update state */
  173527. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173528. ASSIGN_STATE(entropy->saved, state);
  173529. }
  173530. /* Account for restart interval (no-op if not using restarts) */
  173531. entropy->restarts_to_go--;
  173532. return TRUE;
  173533. }
  173534. /*
  173535. * MCU decoding for AC initial scan (either spectral selection,
  173536. * or first pass of successive approximation).
  173537. */
  173538. METHODDEF(boolean)
  173539. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173540. {
  173541. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173542. int Se = cinfo->Se;
  173543. int Al = cinfo->Al;
  173544. register int s, k, r;
  173545. unsigned int EOBRUN;
  173546. JBLOCKROW block;
  173547. BITREAD_STATE_VARS;
  173548. d_derived_tbl * tbl;
  173549. /* Process restart marker if needed; may have to suspend */
  173550. if (cinfo->restart_interval) {
  173551. if (entropy->restarts_to_go == 0)
  173552. if (! process_restartp(cinfo))
  173553. return FALSE;
  173554. }
  173555. /* If we've run out of data, just leave the MCU set to zeroes.
  173556. * This way, we return uniform gray for the remainder of the segment.
  173557. */
  173558. if (! entropy->pub.insufficient_data) {
  173559. /* Load up working state.
  173560. * We can avoid loading/saving bitread state if in an EOB run.
  173561. */
  173562. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173563. /* There is always only one block per MCU */
  173564. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173565. EOBRUN--; /* ...process it now (we do nothing) */
  173566. else {
  173567. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173568. block = MCU_data[0];
  173569. tbl = entropy->ac_derived_tbl;
  173570. for (k = cinfo->Ss; k <= Se; k++) {
  173571. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173572. r = s >> 4;
  173573. s &= 15;
  173574. if (s) {
  173575. k += r;
  173576. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173577. r = GET_BITS(s);
  173578. s = HUFF_EXTEND(r, s);
  173579. /* Scale and output coefficient in natural (dezigzagged) order */
  173580. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173581. } else {
  173582. if (r == 15) { /* ZRL */
  173583. k += 15; /* skip 15 zeroes in band */
  173584. } else { /* EOBr, run length is 2^r + appended bits */
  173585. EOBRUN = 1 << r;
  173586. if (r) { /* EOBr, r > 0 */
  173587. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173588. r = GET_BITS(r);
  173589. EOBRUN += r;
  173590. }
  173591. EOBRUN--; /* this band is processed at this moment */
  173592. break; /* force end-of-band */
  173593. }
  173594. }
  173595. }
  173596. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173597. }
  173598. /* Completed MCU, so update state */
  173599. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173600. }
  173601. /* Account for restart interval (no-op if not using restarts) */
  173602. entropy->restarts_to_go--;
  173603. return TRUE;
  173604. }
  173605. /*
  173606. * MCU decoding for DC successive approximation refinement scan.
  173607. * Note: we assume such scans can be multi-component, although the spec
  173608. * is not very clear on the point.
  173609. */
  173610. METHODDEF(boolean)
  173611. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173612. {
  173613. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173614. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173615. int blkn;
  173616. JBLOCKROW block;
  173617. BITREAD_STATE_VARS;
  173618. /* Process restart marker if needed; may have to suspend */
  173619. if (cinfo->restart_interval) {
  173620. if (entropy->restarts_to_go == 0)
  173621. if (! process_restartp(cinfo))
  173622. return FALSE;
  173623. }
  173624. /* Not worth the cycles to check insufficient_data here,
  173625. * since we will not change the data anyway if we read zeroes.
  173626. */
  173627. /* Load up working state */
  173628. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173629. /* Outer loop handles each block in the MCU */
  173630. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173631. block = MCU_data[blkn];
  173632. /* Encoded data is simply the next bit of the two's-complement DC value */
  173633. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173634. if (GET_BITS(1))
  173635. (*block)[0] |= p1;
  173636. /* Note: since we use |=, repeating the assignment later is safe */
  173637. }
  173638. /* Completed MCU, so update state */
  173639. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173640. /* Account for restart interval (no-op if not using restarts) */
  173641. entropy->restarts_to_go--;
  173642. return TRUE;
  173643. }
  173644. /*
  173645. * MCU decoding for AC successive approximation refinement scan.
  173646. */
  173647. METHODDEF(boolean)
  173648. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173649. {
  173650. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173651. int Se = cinfo->Se;
  173652. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173653. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173654. register int s, k, r;
  173655. unsigned int EOBRUN;
  173656. JBLOCKROW block;
  173657. JCOEFPTR thiscoef;
  173658. BITREAD_STATE_VARS;
  173659. d_derived_tbl * tbl;
  173660. int num_newnz;
  173661. int newnz_pos[DCTSIZE2];
  173662. /* Process restart marker if needed; may have to suspend */
  173663. if (cinfo->restart_interval) {
  173664. if (entropy->restarts_to_go == 0)
  173665. if (! process_restartp(cinfo))
  173666. return FALSE;
  173667. }
  173668. /* If we've run out of data, don't modify the MCU.
  173669. */
  173670. if (! entropy->pub.insufficient_data) {
  173671. /* Load up working state */
  173672. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173673. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173674. /* There is always only one block per MCU */
  173675. block = MCU_data[0];
  173676. tbl = entropy->ac_derived_tbl;
  173677. /* If we are forced to suspend, we must undo the assignments to any newly
  173678. * nonzero coefficients in the block, because otherwise we'd get confused
  173679. * next time about which coefficients were already nonzero.
  173680. * But we need not undo addition of bits to already-nonzero coefficients;
  173681. * instead, we can test the current bit to see if we already did it.
  173682. */
  173683. num_newnz = 0;
  173684. /* initialize coefficient loop counter to start of band */
  173685. k = cinfo->Ss;
  173686. if (EOBRUN == 0) {
  173687. for (; k <= Se; k++) {
  173688. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173689. r = s >> 4;
  173690. s &= 15;
  173691. if (s) {
  173692. if (s != 1) /* size of new coef should always be 1 */
  173693. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173694. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173695. if (GET_BITS(1))
  173696. s = p1; /* newly nonzero coef is positive */
  173697. else
  173698. s = m1; /* newly nonzero coef is negative */
  173699. } else {
  173700. if (r != 15) {
  173701. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173702. if (r) {
  173703. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173704. r = GET_BITS(r);
  173705. EOBRUN += r;
  173706. }
  173707. break; /* rest of block is handled by EOB logic */
  173708. }
  173709. /* note s = 0 for processing ZRL */
  173710. }
  173711. /* Advance over already-nonzero coefs and r still-zero coefs,
  173712. * appending correction bits to the nonzeroes. A correction bit is 1
  173713. * if the absolute value of the coefficient must be increased.
  173714. */
  173715. do {
  173716. thiscoef = *block + jpeg_natural_order[k];
  173717. if (*thiscoef != 0) {
  173718. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173719. if (GET_BITS(1)) {
  173720. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173721. if (*thiscoef >= 0)
  173722. *thiscoef += p1;
  173723. else
  173724. *thiscoef += m1;
  173725. }
  173726. }
  173727. } else {
  173728. if (--r < 0)
  173729. break; /* reached target zero coefficient */
  173730. }
  173731. k++;
  173732. } while (k <= Se);
  173733. if (s) {
  173734. int pos = jpeg_natural_order[k];
  173735. /* Output newly nonzero coefficient */
  173736. (*block)[pos] = (JCOEF) s;
  173737. /* Remember its position in case we have to suspend */
  173738. newnz_pos[num_newnz++] = pos;
  173739. }
  173740. }
  173741. }
  173742. if (EOBRUN > 0) {
  173743. /* Scan any remaining coefficient positions after the end-of-band
  173744. * (the last newly nonzero coefficient, if any). Append a correction
  173745. * bit to each already-nonzero coefficient. A correction bit is 1
  173746. * if the absolute value of the coefficient must be increased.
  173747. */
  173748. for (; k <= Se; k++) {
  173749. thiscoef = *block + jpeg_natural_order[k];
  173750. if (*thiscoef != 0) {
  173751. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173752. if (GET_BITS(1)) {
  173753. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173754. if (*thiscoef >= 0)
  173755. *thiscoef += p1;
  173756. else
  173757. *thiscoef += m1;
  173758. }
  173759. }
  173760. }
  173761. }
  173762. /* Count one block completed in EOB run */
  173763. EOBRUN--;
  173764. }
  173765. /* Completed MCU, so update state */
  173766. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173767. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173768. }
  173769. /* Account for restart interval (no-op if not using restarts) */
  173770. entropy->restarts_to_go--;
  173771. return TRUE;
  173772. undoit:
  173773. /* Re-zero any output coefficients that we made newly nonzero */
  173774. while (num_newnz > 0)
  173775. (*block)[newnz_pos[--num_newnz]] = 0;
  173776. return FALSE;
  173777. }
  173778. /*
  173779. * Module initialization routine for progressive Huffman entropy decoding.
  173780. */
  173781. GLOBAL(void)
  173782. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173783. {
  173784. phuff_entropy_ptr2 entropy;
  173785. int *coef_bit_ptr;
  173786. int ci, i;
  173787. entropy = (phuff_entropy_ptr2)
  173788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173789. SIZEOF(phuff_entropy_decoder));
  173790. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173791. entropy->pub.start_pass = start_pass_phuff_decoder;
  173792. /* Mark derived tables unallocated */
  173793. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173794. entropy->derived_tbls[i] = NULL;
  173795. }
  173796. /* Create progression status table */
  173797. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173798. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173799. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173800. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173801. for (ci = 0; ci < cinfo->num_components; ci++)
  173802. for (i = 0; i < DCTSIZE2; i++)
  173803. *coef_bit_ptr++ = -1;
  173804. }
  173805. #endif /* D_PROGRESSIVE_SUPPORTED */
  173806. /*** End of inlined file: jdphuff.c ***/
  173807. /*** Start of inlined file: jdpostct.c ***/
  173808. #define JPEG_INTERNALS
  173809. /* Private buffer controller object */
  173810. typedef struct {
  173811. struct jpeg_d_post_controller pub; /* public fields */
  173812. /* Color quantization source buffer: this holds output data from
  173813. * the upsample/color conversion step to be passed to the quantizer.
  173814. * For two-pass color quantization, we need a full-image buffer;
  173815. * for one-pass operation, a strip buffer is sufficient.
  173816. */
  173817. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173818. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173819. JDIMENSION strip_height; /* buffer size in rows */
  173820. /* for two-pass mode only: */
  173821. JDIMENSION starting_row; /* row # of first row in current strip */
  173822. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173823. } my_post_controller;
  173824. typedef my_post_controller * my_post_ptr;
  173825. /* Forward declarations */
  173826. METHODDEF(void) post_process_1pass
  173827. JPP((j_decompress_ptr cinfo,
  173828. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173829. JDIMENSION in_row_groups_avail,
  173830. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173831. JDIMENSION out_rows_avail));
  173832. #ifdef QUANT_2PASS_SUPPORTED
  173833. METHODDEF(void) post_process_prepass
  173834. JPP((j_decompress_ptr cinfo,
  173835. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173836. JDIMENSION in_row_groups_avail,
  173837. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173838. JDIMENSION out_rows_avail));
  173839. METHODDEF(void) post_process_2pass
  173840. JPP((j_decompress_ptr cinfo,
  173841. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173842. JDIMENSION in_row_groups_avail,
  173843. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173844. JDIMENSION out_rows_avail));
  173845. #endif
  173846. /*
  173847. * Initialize for a processing pass.
  173848. */
  173849. METHODDEF(void)
  173850. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173851. {
  173852. my_post_ptr post = (my_post_ptr) cinfo->post;
  173853. switch (pass_mode) {
  173854. case JBUF_PASS_THRU:
  173855. if (cinfo->quantize_colors) {
  173856. /* Single-pass processing with color quantization. */
  173857. post->pub.post_process_data = post_process_1pass;
  173858. /* We could be doing buffered-image output before starting a 2-pass
  173859. * color quantization; in that case, jinit_d_post_controller did not
  173860. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173861. */
  173862. if (post->buffer == NULL) {
  173863. post->buffer = (*cinfo->mem->access_virt_sarray)
  173864. ((j_common_ptr) cinfo, post->whole_image,
  173865. (JDIMENSION) 0, post->strip_height, TRUE);
  173866. }
  173867. } else {
  173868. /* For single-pass processing without color quantization,
  173869. * I have no work to do; just call the upsampler directly.
  173870. */
  173871. post->pub.post_process_data = cinfo->upsample->upsample;
  173872. }
  173873. break;
  173874. #ifdef QUANT_2PASS_SUPPORTED
  173875. case JBUF_SAVE_AND_PASS:
  173876. /* First pass of 2-pass quantization */
  173877. if (post->whole_image == NULL)
  173878. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173879. post->pub.post_process_data = post_process_prepass;
  173880. break;
  173881. case JBUF_CRANK_DEST:
  173882. /* Second pass of 2-pass quantization */
  173883. if (post->whole_image == NULL)
  173884. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173885. post->pub.post_process_data = post_process_2pass;
  173886. break;
  173887. #endif /* QUANT_2PASS_SUPPORTED */
  173888. default:
  173889. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173890. break;
  173891. }
  173892. post->starting_row = post->next_row = 0;
  173893. }
  173894. /*
  173895. * Process some data in the one-pass (strip buffer) case.
  173896. * This is used for color precision reduction as well as one-pass quantization.
  173897. */
  173898. METHODDEF(void)
  173899. post_process_1pass (j_decompress_ptr cinfo,
  173900. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173901. JDIMENSION in_row_groups_avail,
  173902. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173903. JDIMENSION out_rows_avail)
  173904. {
  173905. my_post_ptr post = (my_post_ptr) cinfo->post;
  173906. JDIMENSION num_rows, max_rows;
  173907. /* Fill the buffer, but not more than what we can dump out in one go. */
  173908. /* Note we rely on the upsampler to detect bottom of image. */
  173909. max_rows = out_rows_avail - *out_row_ctr;
  173910. if (max_rows > post->strip_height)
  173911. max_rows = post->strip_height;
  173912. num_rows = 0;
  173913. (*cinfo->upsample->upsample) (cinfo,
  173914. input_buf, in_row_group_ctr, in_row_groups_avail,
  173915. post->buffer, &num_rows, max_rows);
  173916. /* Quantize and emit data. */
  173917. (*cinfo->cquantize->color_quantize) (cinfo,
  173918. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173919. *out_row_ctr += num_rows;
  173920. }
  173921. #ifdef QUANT_2PASS_SUPPORTED
  173922. /*
  173923. * Process some data in the first pass of 2-pass quantization.
  173924. */
  173925. METHODDEF(void)
  173926. post_process_prepass (j_decompress_ptr cinfo,
  173927. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173928. JDIMENSION in_row_groups_avail,
  173929. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173930. JDIMENSION)
  173931. {
  173932. my_post_ptr post = (my_post_ptr) cinfo->post;
  173933. JDIMENSION old_next_row, num_rows;
  173934. /* Reposition virtual buffer if at start of strip. */
  173935. if (post->next_row == 0) {
  173936. post->buffer = (*cinfo->mem->access_virt_sarray)
  173937. ((j_common_ptr) cinfo, post->whole_image,
  173938. post->starting_row, post->strip_height, TRUE);
  173939. }
  173940. /* Upsample some data (up to a strip height's worth). */
  173941. old_next_row = post->next_row;
  173942. (*cinfo->upsample->upsample) (cinfo,
  173943. input_buf, in_row_group_ctr, in_row_groups_avail,
  173944. post->buffer, &post->next_row, post->strip_height);
  173945. /* Allow quantizer to scan new data. No data is emitted, */
  173946. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173947. if (post->next_row > old_next_row) {
  173948. num_rows = post->next_row - old_next_row;
  173949. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173950. (JSAMPARRAY) NULL, (int) num_rows);
  173951. *out_row_ctr += num_rows;
  173952. }
  173953. /* Advance if we filled the strip. */
  173954. if (post->next_row >= post->strip_height) {
  173955. post->starting_row += post->strip_height;
  173956. post->next_row = 0;
  173957. }
  173958. }
  173959. /*
  173960. * Process some data in the second pass of 2-pass quantization.
  173961. */
  173962. METHODDEF(void)
  173963. post_process_2pass (j_decompress_ptr cinfo,
  173964. JSAMPIMAGE, JDIMENSION *,
  173965. JDIMENSION,
  173966. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173967. JDIMENSION out_rows_avail)
  173968. {
  173969. my_post_ptr post = (my_post_ptr) cinfo->post;
  173970. JDIMENSION num_rows, max_rows;
  173971. /* Reposition virtual buffer if at start of strip. */
  173972. if (post->next_row == 0) {
  173973. post->buffer = (*cinfo->mem->access_virt_sarray)
  173974. ((j_common_ptr) cinfo, post->whole_image,
  173975. post->starting_row, post->strip_height, FALSE);
  173976. }
  173977. /* Determine number of rows to emit. */
  173978. num_rows = post->strip_height - post->next_row; /* available in strip */
  173979. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173980. if (num_rows > max_rows)
  173981. num_rows = max_rows;
  173982. /* We have to check bottom of image here, can't depend on upsampler. */
  173983. max_rows = cinfo->output_height - post->starting_row;
  173984. if (num_rows > max_rows)
  173985. num_rows = max_rows;
  173986. /* Quantize and emit data. */
  173987. (*cinfo->cquantize->color_quantize) (cinfo,
  173988. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173989. (int) num_rows);
  173990. *out_row_ctr += num_rows;
  173991. /* Advance if we filled the strip. */
  173992. post->next_row += num_rows;
  173993. if (post->next_row >= post->strip_height) {
  173994. post->starting_row += post->strip_height;
  173995. post->next_row = 0;
  173996. }
  173997. }
  173998. #endif /* QUANT_2PASS_SUPPORTED */
  173999. /*
  174000. * Initialize postprocessing controller.
  174001. */
  174002. GLOBAL(void)
  174003. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  174004. {
  174005. my_post_ptr post;
  174006. post = (my_post_ptr)
  174007. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174008. SIZEOF(my_post_controller));
  174009. cinfo->post = (struct jpeg_d_post_controller *) post;
  174010. post->pub.start_pass = start_pass_dpost;
  174011. post->whole_image = NULL; /* flag for no virtual arrays */
  174012. post->buffer = NULL; /* flag for no strip buffer */
  174013. /* Create the quantization buffer, if needed */
  174014. if (cinfo->quantize_colors) {
  174015. /* The buffer strip height is max_v_samp_factor, which is typically
  174016. * an efficient number of rows for upsampling to return.
  174017. * (In the presence of output rescaling, we might want to be smarter?)
  174018. */
  174019. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  174020. if (need_full_buffer) {
  174021. /* Two-pass color quantization: need full-image storage. */
  174022. /* We round up the number of rows to a multiple of the strip height. */
  174023. #ifdef QUANT_2PASS_SUPPORTED
  174024. post->whole_image = (*cinfo->mem->request_virt_sarray)
  174025. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  174026. cinfo->output_width * cinfo->out_color_components,
  174027. (JDIMENSION) jround_up((long) cinfo->output_height,
  174028. (long) post->strip_height),
  174029. post->strip_height);
  174030. #else
  174031. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  174032. #endif /* QUANT_2PASS_SUPPORTED */
  174033. } else {
  174034. /* One-pass color quantization: just make a strip buffer. */
  174035. post->buffer = (*cinfo->mem->alloc_sarray)
  174036. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174037. cinfo->output_width * cinfo->out_color_components,
  174038. post->strip_height);
  174039. }
  174040. }
  174041. }
  174042. /*** End of inlined file: jdpostct.c ***/
  174043. #undef FIX
  174044. /*** Start of inlined file: jdsample.c ***/
  174045. #define JPEG_INTERNALS
  174046. /* Pointer to routine to upsample a single component */
  174047. typedef JMETHOD(void, upsample1_ptr,
  174048. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174049. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  174050. /* Private subobject */
  174051. typedef struct {
  174052. struct jpeg_upsampler pub; /* public fields */
  174053. /* Color conversion buffer. When using separate upsampling and color
  174054. * conversion steps, this buffer holds one upsampled row group until it
  174055. * has been color converted and output.
  174056. * Note: we do not allocate any storage for component(s) which are full-size,
  174057. * ie do not need rescaling. The corresponding entry of color_buf[] is
  174058. * simply set to point to the input data array, thereby avoiding copying.
  174059. */
  174060. JSAMPARRAY color_buf[MAX_COMPONENTS];
  174061. /* Per-component upsampling method pointers */
  174062. upsample1_ptr methods[MAX_COMPONENTS];
  174063. int next_row_out; /* counts rows emitted from color_buf */
  174064. JDIMENSION rows_to_go; /* counts rows remaining in image */
  174065. /* Height of an input row group for each component. */
  174066. int rowgroup_height[MAX_COMPONENTS];
  174067. /* These arrays save pixel expansion factors so that int_expand need not
  174068. * recompute them each time. They are unused for other upsampling methods.
  174069. */
  174070. UINT8 h_expand[MAX_COMPONENTS];
  174071. UINT8 v_expand[MAX_COMPONENTS];
  174072. } my_upsampler2;
  174073. typedef my_upsampler2 * my_upsample_ptr2;
  174074. /*
  174075. * Initialize for an upsampling pass.
  174076. */
  174077. METHODDEF(void)
  174078. start_pass_upsample (j_decompress_ptr cinfo)
  174079. {
  174080. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174081. /* Mark the conversion buffer empty */
  174082. upsample->next_row_out = cinfo->max_v_samp_factor;
  174083. /* Initialize total-height counter for detecting bottom of image */
  174084. upsample->rows_to_go = cinfo->output_height;
  174085. }
  174086. /*
  174087. * Control routine to do upsampling (and color conversion).
  174088. *
  174089. * In this version we upsample each component independently.
  174090. * We upsample one row group into the conversion buffer, then apply
  174091. * color conversion a row at a time.
  174092. */
  174093. METHODDEF(void)
  174094. sep_upsample (j_decompress_ptr cinfo,
  174095. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174096. JDIMENSION,
  174097. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174098. JDIMENSION out_rows_avail)
  174099. {
  174100. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174101. int ci;
  174102. jpeg_component_info * compptr;
  174103. JDIMENSION num_rows;
  174104. /* Fill the conversion buffer, if it's empty */
  174105. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  174106. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174107. ci++, compptr++) {
  174108. /* Invoke per-component upsample method. Notice we pass a POINTER
  174109. * to color_buf[ci], so that fullsize_upsample can change it.
  174110. */
  174111. (*upsample->methods[ci]) (cinfo, compptr,
  174112. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  174113. upsample->color_buf + ci);
  174114. }
  174115. upsample->next_row_out = 0;
  174116. }
  174117. /* Color-convert and emit rows */
  174118. /* How many we have in the buffer: */
  174119. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  174120. /* Not more than the distance to the end of the image. Need this test
  174121. * in case the image height is not a multiple of max_v_samp_factor:
  174122. */
  174123. if (num_rows > upsample->rows_to_go)
  174124. num_rows = upsample->rows_to_go;
  174125. /* And not more than what the client can accept: */
  174126. out_rows_avail -= *out_row_ctr;
  174127. if (num_rows > out_rows_avail)
  174128. num_rows = out_rows_avail;
  174129. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174130. (JDIMENSION) upsample->next_row_out,
  174131. output_buf + *out_row_ctr,
  174132. (int) num_rows);
  174133. /* Adjust counts */
  174134. *out_row_ctr += num_rows;
  174135. upsample->rows_to_go -= num_rows;
  174136. upsample->next_row_out += num_rows;
  174137. /* When the buffer is emptied, declare this input row group consumed */
  174138. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174139. (*in_row_group_ctr)++;
  174140. }
  174141. /*
  174142. * These are the routines invoked by sep_upsample to upsample pixel values
  174143. * of a single component. One row group is processed per call.
  174144. */
  174145. /*
  174146. * For full-size components, we just make color_buf[ci] point at the
  174147. * input buffer, and thus avoid copying any data. Note that this is
  174148. * safe only because sep_upsample doesn't declare the input row group
  174149. * "consumed" until we are done color converting and emitting it.
  174150. */
  174151. METHODDEF(void)
  174152. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  174153. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174154. {
  174155. *output_data_ptr = input_data;
  174156. }
  174157. /*
  174158. * This is a no-op version used for "uninteresting" components.
  174159. * These components will not be referenced by color conversion.
  174160. */
  174161. METHODDEF(void)
  174162. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  174163. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  174164. {
  174165. *output_data_ptr = NULL; /* safety check */
  174166. }
  174167. /*
  174168. * This version handles any integral sampling ratios.
  174169. * This is not used for typical JPEG files, so it need not be fast.
  174170. * Nor, for that matter, is it particularly accurate: the algorithm is
  174171. * simple replication of the input pixel onto the corresponding output
  174172. * pixels. The hi-falutin sampling literature refers to this as a
  174173. * "box filter". A box filter tends to introduce visible artifacts,
  174174. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174175. * you would be well advised to improve this code.
  174176. */
  174177. METHODDEF(void)
  174178. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174179. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174180. {
  174181. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174182. JSAMPARRAY output_data = *output_data_ptr;
  174183. register JSAMPROW inptr, outptr;
  174184. register JSAMPLE invalue;
  174185. register int h;
  174186. JSAMPROW outend;
  174187. int h_expand, v_expand;
  174188. int inrow, outrow;
  174189. h_expand = upsample->h_expand[compptr->component_index];
  174190. v_expand = upsample->v_expand[compptr->component_index];
  174191. inrow = outrow = 0;
  174192. while (outrow < cinfo->max_v_samp_factor) {
  174193. /* Generate one output row with proper horizontal expansion */
  174194. inptr = input_data[inrow];
  174195. outptr = output_data[outrow];
  174196. outend = outptr + cinfo->output_width;
  174197. while (outptr < outend) {
  174198. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174199. for (h = h_expand; h > 0; h--) {
  174200. *outptr++ = invalue;
  174201. }
  174202. }
  174203. /* Generate any additional output rows by duplicating the first one */
  174204. if (v_expand > 1) {
  174205. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174206. v_expand-1, cinfo->output_width);
  174207. }
  174208. inrow++;
  174209. outrow += v_expand;
  174210. }
  174211. }
  174212. /*
  174213. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174214. * It's still a box filter.
  174215. */
  174216. METHODDEF(void)
  174217. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174218. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174219. {
  174220. JSAMPARRAY output_data = *output_data_ptr;
  174221. register JSAMPROW inptr, outptr;
  174222. register JSAMPLE invalue;
  174223. JSAMPROW outend;
  174224. int inrow;
  174225. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174226. inptr = input_data[inrow];
  174227. outptr = output_data[inrow];
  174228. outend = outptr + cinfo->output_width;
  174229. while (outptr < outend) {
  174230. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174231. *outptr++ = invalue;
  174232. *outptr++ = invalue;
  174233. }
  174234. }
  174235. }
  174236. /*
  174237. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174238. * It's still a box filter.
  174239. */
  174240. METHODDEF(void)
  174241. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174242. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174243. {
  174244. JSAMPARRAY output_data = *output_data_ptr;
  174245. register JSAMPROW inptr, outptr;
  174246. register JSAMPLE invalue;
  174247. JSAMPROW outend;
  174248. int inrow, outrow;
  174249. inrow = outrow = 0;
  174250. while (outrow < cinfo->max_v_samp_factor) {
  174251. inptr = input_data[inrow];
  174252. outptr = output_data[outrow];
  174253. outend = outptr + cinfo->output_width;
  174254. while (outptr < outend) {
  174255. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174256. *outptr++ = invalue;
  174257. *outptr++ = invalue;
  174258. }
  174259. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174260. 1, cinfo->output_width);
  174261. inrow++;
  174262. outrow += 2;
  174263. }
  174264. }
  174265. /*
  174266. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174267. *
  174268. * The upsampling algorithm is linear interpolation between pixel centers,
  174269. * also known as a "triangle filter". This is a good compromise between
  174270. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174271. * of the way between input pixel centers.
  174272. *
  174273. * A note about the "bias" calculations: when rounding fractional values to
  174274. * integer, we do not want to always round 0.5 up to the next integer.
  174275. * If we did that, we'd introduce a noticeable bias towards larger values.
  174276. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174277. * alternate pixel locations (a simple ordered dither pattern).
  174278. */
  174279. METHODDEF(void)
  174280. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174281. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174282. {
  174283. JSAMPARRAY output_data = *output_data_ptr;
  174284. register JSAMPROW inptr, outptr;
  174285. register int invalue;
  174286. register JDIMENSION colctr;
  174287. int inrow;
  174288. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174289. inptr = input_data[inrow];
  174290. outptr = output_data[inrow];
  174291. /* Special case for first column */
  174292. invalue = GETJSAMPLE(*inptr++);
  174293. *outptr++ = (JSAMPLE) invalue;
  174294. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174295. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174296. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174297. invalue = GETJSAMPLE(*inptr++) * 3;
  174298. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174299. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174300. }
  174301. /* Special case for last column */
  174302. invalue = GETJSAMPLE(*inptr);
  174303. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174304. *outptr++ = (JSAMPLE) invalue;
  174305. }
  174306. }
  174307. /*
  174308. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174309. * Again a triangle filter; see comments for h2v1 case, above.
  174310. *
  174311. * It is OK for us to reference the adjacent input rows because we demanded
  174312. * context from the main buffer controller (see initialization code).
  174313. */
  174314. METHODDEF(void)
  174315. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174316. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174317. {
  174318. JSAMPARRAY output_data = *output_data_ptr;
  174319. register JSAMPROW inptr0, inptr1, outptr;
  174320. #if BITS_IN_JSAMPLE == 8
  174321. register int thiscolsum, lastcolsum, nextcolsum;
  174322. #else
  174323. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174324. #endif
  174325. register JDIMENSION colctr;
  174326. int inrow, outrow, v;
  174327. inrow = outrow = 0;
  174328. while (outrow < cinfo->max_v_samp_factor) {
  174329. for (v = 0; v < 2; v++) {
  174330. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174331. inptr0 = input_data[inrow];
  174332. if (v == 0) /* next nearest is row above */
  174333. inptr1 = input_data[inrow-1];
  174334. else /* next nearest is row below */
  174335. inptr1 = input_data[inrow+1];
  174336. outptr = output_data[outrow++];
  174337. /* Special case for first column */
  174338. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174339. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174340. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174341. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174342. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174343. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174344. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174345. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174346. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174347. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174348. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174349. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174350. }
  174351. /* Special case for last column */
  174352. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174353. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174354. }
  174355. inrow++;
  174356. }
  174357. }
  174358. /*
  174359. * Module initialization routine for upsampling.
  174360. */
  174361. GLOBAL(void)
  174362. jinit_upsampler (j_decompress_ptr cinfo)
  174363. {
  174364. my_upsample_ptr2 upsample;
  174365. int ci;
  174366. jpeg_component_info * compptr;
  174367. boolean need_buffer, do_fancy;
  174368. int h_in_group, v_in_group, h_out_group, v_out_group;
  174369. upsample = (my_upsample_ptr2)
  174370. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174371. SIZEOF(my_upsampler2));
  174372. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174373. upsample->pub.start_pass = start_pass_upsample;
  174374. upsample->pub.upsample = sep_upsample;
  174375. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174376. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174377. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174378. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174379. * so don't ask for it.
  174380. */
  174381. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174382. /* Verify we can handle the sampling factors, select per-component methods,
  174383. * and create storage as needed.
  174384. */
  174385. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174386. ci++, compptr++) {
  174387. /* Compute size of an "input group" after IDCT scaling. This many samples
  174388. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174389. */
  174390. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174391. cinfo->min_DCT_scaled_size;
  174392. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174393. cinfo->min_DCT_scaled_size;
  174394. h_out_group = cinfo->max_h_samp_factor;
  174395. v_out_group = cinfo->max_v_samp_factor;
  174396. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174397. need_buffer = TRUE;
  174398. if (! compptr->component_needed) {
  174399. /* Don't bother to upsample an uninteresting component. */
  174400. upsample->methods[ci] = noop_upsample;
  174401. need_buffer = FALSE;
  174402. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174403. /* Fullsize components can be processed without any work. */
  174404. upsample->methods[ci] = fullsize_upsample;
  174405. need_buffer = FALSE;
  174406. } else if (h_in_group * 2 == h_out_group &&
  174407. v_in_group == v_out_group) {
  174408. /* Special cases for 2h1v upsampling */
  174409. if (do_fancy && compptr->downsampled_width > 2)
  174410. upsample->methods[ci] = h2v1_fancy_upsample;
  174411. else
  174412. upsample->methods[ci] = h2v1_upsample;
  174413. } else if (h_in_group * 2 == h_out_group &&
  174414. v_in_group * 2 == v_out_group) {
  174415. /* Special cases for 2h2v upsampling */
  174416. if (do_fancy && compptr->downsampled_width > 2) {
  174417. upsample->methods[ci] = h2v2_fancy_upsample;
  174418. upsample->pub.need_context_rows = TRUE;
  174419. } else
  174420. upsample->methods[ci] = h2v2_upsample;
  174421. } else if ((h_out_group % h_in_group) == 0 &&
  174422. (v_out_group % v_in_group) == 0) {
  174423. /* Generic integral-factors upsampling method */
  174424. upsample->methods[ci] = int_upsample;
  174425. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174426. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174427. } else
  174428. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174429. if (need_buffer) {
  174430. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174431. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174432. (JDIMENSION) jround_up((long) cinfo->output_width,
  174433. (long) cinfo->max_h_samp_factor),
  174434. (JDIMENSION) cinfo->max_v_samp_factor);
  174435. }
  174436. }
  174437. }
  174438. /*** End of inlined file: jdsample.c ***/
  174439. /*** Start of inlined file: jdtrans.c ***/
  174440. #define JPEG_INTERNALS
  174441. /* Forward declarations */
  174442. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174443. /*
  174444. * Read the coefficient arrays from a JPEG file.
  174445. * jpeg_read_header must be completed before calling this.
  174446. *
  174447. * The entire image is read into a set of virtual coefficient-block arrays,
  174448. * one per component. The return value is a pointer to the array of
  174449. * virtual-array descriptors. These can be manipulated directly via the
  174450. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174451. * To release the memory occupied by the virtual arrays, call
  174452. * jpeg_finish_decompress() when done with the data.
  174453. *
  174454. * An alternative usage is to simply obtain access to the coefficient arrays
  174455. * during a buffered-image-mode decompression operation. This is allowed
  174456. * after any jpeg_finish_output() call. The arrays can be accessed until
  174457. * jpeg_finish_decompress() is called. (Note that any call to the library
  174458. * may reposition the arrays, so don't rely on access_virt_barray() results
  174459. * to stay valid across library calls.)
  174460. *
  174461. * Returns NULL if suspended. This case need be checked only if
  174462. * a suspending data source is used.
  174463. */
  174464. GLOBAL(jvirt_barray_ptr *)
  174465. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174466. {
  174467. if (cinfo->global_state == DSTATE_READY) {
  174468. /* First call: initialize active modules */
  174469. transdecode_master_selection(cinfo);
  174470. cinfo->global_state = DSTATE_RDCOEFS;
  174471. }
  174472. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174473. /* Absorb whole file into the coef buffer */
  174474. for (;;) {
  174475. int retcode;
  174476. /* Call progress monitor hook if present */
  174477. if (cinfo->progress != NULL)
  174478. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174479. /* Absorb some more input */
  174480. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174481. if (retcode == JPEG_SUSPENDED)
  174482. return NULL;
  174483. if (retcode == JPEG_REACHED_EOI)
  174484. break;
  174485. /* Advance progress counter if appropriate */
  174486. if (cinfo->progress != NULL &&
  174487. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174488. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174489. /* startup underestimated number of scans; ratchet up one scan */
  174490. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174491. }
  174492. }
  174493. }
  174494. /* Set state so that jpeg_finish_decompress does the right thing */
  174495. cinfo->global_state = DSTATE_STOPPING;
  174496. }
  174497. /* At this point we should be in state DSTATE_STOPPING if being used
  174498. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174499. * to the coefficients during a full buffered-image-mode decompression.
  174500. */
  174501. if ((cinfo->global_state == DSTATE_STOPPING ||
  174502. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174503. return cinfo->coef->coef_arrays;
  174504. }
  174505. /* Oops, improper usage */
  174506. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174507. return NULL; /* keep compiler happy */
  174508. }
  174509. /*
  174510. * Master selection of decompression modules for transcoding.
  174511. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174512. */
  174513. LOCAL(void)
  174514. transdecode_master_selection (j_decompress_ptr cinfo)
  174515. {
  174516. /* This is effectively a buffered-image operation. */
  174517. cinfo->buffered_image = TRUE;
  174518. /* Entropy decoding: either Huffman or arithmetic coding. */
  174519. if (cinfo->arith_code) {
  174520. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174521. } else {
  174522. if (cinfo->progressive_mode) {
  174523. #ifdef D_PROGRESSIVE_SUPPORTED
  174524. jinit_phuff_decoder(cinfo);
  174525. #else
  174526. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174527. #endif
  174528. } else
  174529. jinit_huff_decoder(cinfo);
  174530. }
  174531. /* Always get a full-image coefficient buffer. */
  174532. jinit_d_coef_controller(cinfo, TRUE);
  174533. /* We can now tell the memory manager to allocate virtual arrays. */
  174534. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174535. /* Initialize input side of decompressor to consume first scan. */
  174536. (*cinfo->inputctl->start_input_pass) (cinfo);
  174537. /* Initialize progress monitoring. */
  174538. if (cinfo->progress != NULL) {
  174539. int nscans;
  174540. /* Estimate number of scans to set pass_limit. */
  174541. if (cinfo->progressive_mode) {
  174542. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174543. nscans = 2 + 3 * cinfo->num_components;
  174544. } else if (cinfo->inputctl->has_multiple_scans) {
  174545. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174546. nscans = cinfo->num_components;
  174547. } else {
  174548. nscans = 1;
  174549. }
  174550. cinfo->progress->pass_counter = 0L;
  174551. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174552. cinfo->progress->completed_passes = 0;
  174553. cinfo->progress->total_passes = 1;
  174554. }
  174555. }
  174556. /*** End of inlined file: jdtrans.c ***/
  174557. /*** Start of inlined file: jfdctflt.c ***/
  174558. #define JPEG_INTERNALS
  174559. #ifdef DCT_FLOAT_SUPPORTED
  174560. /*
  174561. * This module is specialized to the case DCTSIZE = 8.
  174562. */
  174563. #if DCTSIZE != 8
  174564. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174565. #endif
  174566. /*
  174567. * Perform the forward DCT on one block of samples.
  174568. */
  174569. GLOBAL(void)
  174570. jpeg_fdct_float (FAST_FLOAT * data)
  174571. {
  174572. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174573. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174574. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174575. FAST_FLOAT *dataptr;
  174576. int ctr;
  174577. /* Pass 1: process rows. */
  174578. dataptr = data;
  174579. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174580. tmp0 = dataptr[0] + dataptr[7];
  174581. tmp7 = dataptr[0] - dataptr[7];
  174582. tmp1 = dataptr[1] + dataptr[6];
  174583. tmp6 = dataptr[1] - dataptr[6];
  174584. tmp2 = dataptr[2] + dataptr[5];
  174585. tmp5 = dataptr[2] - dataptr[5];
  174586. tmp3 = dataptr[3] + dataptr[4];
  174587. tmp4 = dataptr[3] - dataptr[4];
  174588. /* Even part */
  174589. tmp10 = tmp0 + tmp3; /* phase 2 */
  174590. tmp13 = tmp0 - tmp3;
  174591. tmp11 = tmp1 + tmp2;
  174592. tmp12 = tmp1 - tmp2;
  174593. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174594. dataptr[4] = tmp10 - tmp11;
  174595. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174596. dataptr[2] = tmp13 + z1; /* phase 5 */
  174597. dataptr[6] = tmp13 - z1;
  174598. /* Odd part */
  174599. tmp10 = tmp4 + tmp5; /* phase 2 */
  174600. tmp11 = tmp5 + tmp6;
  174601. tmp12 = tmp6 + tmp7;
  174602. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174603. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174604. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174605. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174606. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174607. z11 = tmp7 + z3; /* phase 5 */
  174608. z13 = tmp7 - z3;
  174609. dataptr[5] = z13 + z2; /* phase 6 */
  174610. dataptr[3] = z13 - z2;
  174611. dataptr[1] = z11 + z4;
  174612. dataptr[7] = z11 - z4;
  174613. dataptr += DCTSIZE; /* advance pointer to next row */
  174614. }
  174615. /* Pass 2: process columns. */
  174616. dataptr = data;
  174617. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174618. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174619. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174620. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174621. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174622. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174623. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174624. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174625. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174626. /* Even part */
  174627. tmp10 = tmp0 + tmp3; /* phase 2 */
  174628. tmp13 = tmp0 - tmp3;
  174629. tmp11 = tmp1 + tmp2;
  174630. tmp12 = tmp1 - tmp2;
  174631. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174632. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174633. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174634. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174635. dataptr[DCTSIZE*6] = tmp13 - z1;
  174636. /* Odd part */
  174637. tmp10 = tmp4 + tmp5; /* phase 2 */
  174638. tmp11 = tmp5 + tmp6;
  174639. tmp12 = tmp6 + tmp7;
  174640. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174641. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174642. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174643. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174644. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174645. z11 = tmp7 + z3; /* phase 5 */
  174646. z13 = tmp7 - z3;
  174647. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174648. dataptr[DCTSIZE*3] = z13 - z2;
  174649. dataptr[DCTSIZE*1] = z11 + z4;
  174650. dataptr[DCTSIZE*7] = z11 - z4;
  174651. dataptr++; /* advance pointer to next column */
  174652. }
  174653. }
  174654. #endif /* DCT_FLOAT_SUPPORTED */
  174655. /*** End of inlined file: jfdctflt.c ***/
  174656. /*** Start of inlined file: jfdctint.c ***/
  174657. #define JPEG_INTERNALS
  174658. #ifdef DCT_ISLOW_SUPPORTED
  174659. /*
  174660. * This module is specialized to the case DCTSIZE = 8.
  174661. */
  174662. #if DCTSIZE != 8
  174663. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174664. #endif
  174665. /*
  174666. * The poop on this scaling stuff is as follows:
  174667. *
  174668. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174669. * larger than the true DCT outputs. The final outputs are therefore
  174670. * a factor of N larger than desired; since N=8 this can be cured by
  174671. * a simple right shift at the end of the algorithm. The advantage of
  174672. * this arrangement is that we save two multiplications per 1-D DCT,
  174673. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174674. * In the IJG code, this factor of 8 is removed by the quantization step
  174675. * (in jcdctmgr.c), NOT in this module.
  174676. *
  174677. * We have to do addition and subtraction of the integer inputs, which
  174678. * is no problem, and multiplication by fractional constants, which is
  174679. * a problem to do in integer arithmetic. We multiply all the constants
  174680. * by CONST_SCALE and convert them to integer constants (thus retaining
  174681. * CONST_BITS bits of precision in the constants). After doing a
  174682. * multiplication we have to divide the product by CONST_SCALE, with proper
  174683. * rounding, to produce the correct output. This division can be done
  174684. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174685. * as long as possible so that partial sums can be added together with
  174686. * full fractional precision.
  174687. *
  174688. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174689. * they are represented to better-than-integral precision. These outputs
  174690. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174691. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174692. * array is INT32 anyway.)
  174693. *
  174694. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174695. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174696. * shows that the values given below are the most effective.
  174697. */
  174698. #if BITS_IN_JSAMPLE == 8
  174699. #define CONST_BITS 13
  174700. #define PASS1_BITS 2
  174701. #else
  174702. #define CONST_BITS 13
  174703. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174704. #endif
  174705. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174706. * causing a lot of useless floating-point operations at run time.
  174707. * To get around this we use the following pre-calculated constants.
  174708. * If you change CONST_BITS you may want to add appropriate values.
  174709. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174710. */
  174711. #if CONST_BITS == 13
  174712. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174713. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174714. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174715. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174716. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174717. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174718. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174719. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174720. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174721. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174722. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174723. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174724. #else
  174725. #define FIX_0_298631336 FIX(0.298631336)
  174726. #define FIX_0_390180644 FIX(0.390180644)
  174727. #define FIX_0_541196100 FIX(0.541196100)
  174728. #define FIX_0_765366865 FIX(0.765366865)
  174729. #define FIX_0_899976223 FIX(0.899976223)
  174730. #define FIX_1_175875602 FIX(1.175875602)
  174731. #define FIX_1_501321110 FIX(1.501321110)
  174732. #define FIX_1_847759065 FIX(1.847759065)
  174733. #define FIX_1_961570560 FIX(1.961570560)
  174734. #define FIX_2_053119869 FIX(2.053119869)
  174735. #define FIX_2_562915447 FIX(2.562915447)
  174736. #define FIX_3_072711026 FIX(3.072711026)
  174737. #endif
  174738. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174739. * For 8-bit samples with the recommended scaling, all the variable
  174740. * and constant values involved are no more than 16 bits wide, so a
  174741. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174742. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174743. */
  174744. #if BITS_IN_JSAMPLE == 8
  174745. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174746. #else
  174747. #define MULTIPLY(var,const) ((var) * (const))
  174748. #endif
  174749. /*
  174750. * Perform the forward DCT on one block of samples.
  174751. */
  174752. GLOBAL(void)
  174753. jpeg_fdct_islow (DCTELEM * data)
  174754. {
  174755. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174756. INT32 tmp10, tmp11, tmp12, tmp13;
  174757. INT32 z1, z2, z3, z4, z5;
  174758. DCTELEM *dataptr;
  174759. int ctr;
  174760. SHIFT_TEMPS
  174761. /* Pass 1: process rows. */
  174762. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174763. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174764. dataptr = data;
  174765. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174766. tmp0 = dataptr[0] + dataptr[7];
  174767. tmp7 = dataptr[0] - dataptr[7];
  174768. tmp1 = dataptr[1] + dataptr[6];
  174769. tmp6 = dataptr[1] - dataptr[6];
  174770. tmp2 = dataptr[2] + dataptr[5];
  174771. tmp5 = dataptr[2] - dataptr[5];
  174772. tmp3 = dataptr[3] + dataptr[4];
  174773. tmp4 = dataptr[3] - dataptr[4];
  174774. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174775. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174776. */
  174777. tmp10 = tmp0 + tmp3;
  174778. tmp13 = tmp0 - tmp3;
  174779. tmp11 = tmp1 + tmp2;
  174780. tmp12 = tmp1 - tmp2;
  174781. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174782. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174783. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174784. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174785. CONST_BITS-PASS1_BITS);
  174786. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174787. CONST_BITS-PASS1_BITS);
  174788. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174789. * cK represents cos(K*pi/16).
  174790. * i0..i3 in the paper are tmp4..tmp7 here.
  174791. */
  174792. z1 = tmp4 + tmp7;
  174793. z2 = tmp5 + tmp6;
  174794. z3 = tmp4 + tmp6;
  174795. z4 = tmp5 + tmp7;
  174796. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174797. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174798. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174799. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174800. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174801. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174802. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174803. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174804. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174805. z3 += z5;
  174806. z4 += z5;
  174807. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174808. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174809. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174810. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174811. dataptr += DCTSIZE; /* advance pointer to next row */
  174812. }
  174813. /* Pass 2: process columns.
  174814. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174815. * by an overall factor of 8.
  174816. */
  174817. dataptr = data;
  174818. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174819. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174820. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174821. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174822. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174823. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174824. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174825. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174826. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174827. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174828. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174829. */
  174830. tmp10 = tmp0 + tmp3;
  174831. tmp13 = tmp0 - tmp3;
  174832. tmp11 = tmp1 + tmp2;
  174833. tmp12 = tmp1 - tmp2;
  174834. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174835. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174836. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174837. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174838. CONST_BITS+PASS1_BITS);
  174839. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174840. CONST_BITS+PASS1_BITS);
  174841. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174842. * cK represents cos(K*pi/16).
  174843. * i0..i3 in the paper are tmp4..tmp7 here.
  174844. */
  174845. z1 = tmp4 + tmp7;
  174846. z2 = tmp5 + tmp6;
  174847. z3 = tmp4 + tmp6;
  174848. z4 = tmp5 + tmp7;
  174849. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174850. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174851. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174852. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174853. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174854. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174855. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174856. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174857. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174858. z3 += z5;
  174859. z4 += z5;
  174860. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174861. CONST_BITS+PASS1_BITS);
  174862. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174863. CONST_BITS+PASS1_BITS);
  174864. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174865. CONST_BITS+PASS1_BITS);
  174866. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174867. CONST_BITS+PASS1_BITS);
  174868. dataptr++; /* advance pointer to next column */
  174869. }
  174870. }
  174871. #endif /* DCT_ISLOW_SUPPORTED */
  174872. /*** End of inlined file: jfdctint.c ***/
  174873. #undef CONST_BITS
  174874. #undef MULTIPLY
  174875. #undef FIX_0_541196100
  174876. /*** Start of inlined file: jfdctfst.c ***/
  174877. #define JPEG_INTERNALS
  174878. #ifdef DCT_IFAST_SUPPORTED
  174879. /*
  174880. * This module is specialized to the case DCTSIZE = 8.
  174881. */
  174882. #if DCTSIZE != 8
  174883. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174884. #endif
  174885. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174886. * see jfdctint.c for more details. However, we choose to descale
  174887. * (right shift) multiplication products as soon as they are formed,
  174888. * rather than carrying additional fractional bits into subsequent additions.
  174889. * This compromises accuracy slightly, but it lets us save a few shifts.
  174890. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174891. * everywhere except in the multiplications proper; this saves a good deal
  174892. * of work on 16-bit-int machines.
  174893. *
  174894. * Again to save a few shifts, the intermediate results between pass 1 and
  174895. * pass 2 are not upscaled, but are represented only to integral precision.
  174896. *
  174897. * A final compromise is to represent the multiplicative constants to only
  174898. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174899. * machines, and may also reduce the cost of multiplication (since there
  174900. * are fewer one-bits in the constants).
  174901. */
  174902. #define CONST_BITS 8
  174903. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174904. * causing a lot of useless floating-point operations at run time.
  174905. * To get around this we use the following pre-calculated constants.
  174906. * If you change CONST_BITS you may want to add appropriate values.
  174907. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174908. */
  174909. #if CONST_BITS == 8
  174910. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174911. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174912. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174913. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174914. #else
  174915. #define FIX_0_382683433 FIX(0.382683433)
  174916. #define FIX_0_541196100 FIX(0.541196100)
  174917. #define FIX_0_707106781 FIX(0.707106781)
  174918. #define FIX_1_306562965 FIX(1.306562965)
  174919. #endif
  174920. /* We can gain a little more speed, with a further compromise in accuracy,
  174921. * by omitting the addition in a descaling shift. This yields an incorrectly
  174922. * rounded result half the time...
  174923. */
  174924. #ifndef USE_ACCURATE_ROUNDING
  174925. #undef DESCALE
  174926. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174927. #endif
  174928. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174929. * descale to yield a DCTELEM result.
  174930. */
  174931. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174932. /*
  174933. * Perform the forward DCT on one block of samples.
  174934. */
  174935. GLOBAL(void)
  174936. jpeg_fdct_ifast (DCTELEM * data)
  174937. {
  174938. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174939. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174940. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174941. DCTELEM *dataptr;
  174942. int ctr;
  174943. SHIFT_TEMPS
  174944. /* Pass 1: process rows. */
  174945. dataptr = data;
  174946. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174947. tmp0 = dataptr[0] + dataptr[7];
  174948. tmp7 = dataptr[0] - dataptr[7];
  174949. tmp1 = dataptr[1] + dataptr[6];
  174950. tmp6 = dataptr[1] - dataptr[6];
  174951. tmp2 = dataptr[2] + dataptr[5];
  174952. tmp5 = dataptr[2] - dataptr[5];
  174953. tmp3 = dataptr[3] + dataptr[4];
  174954. tmp4 = dataptr[3] - dataptr[4];
  174955. /* Even part */
  174956. tmp10 = tmp0 + tmp3; /* phase 2 */
  174957. tmp13 = tmp0 - tmp3;
  174958. tmp11 = tmp1 + tmp2;
  174959. tmp12 = tmp1 - tmp2;
  174960. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174961. dataptr[4] = tmp10 - tmp11;
  174962. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174963. dataptr[2] = tmp13 + z1; /* phase 5 */
  174964. dataptr[6] = tmp13 - z1;
  174965. /* Odd part */
  174966. tmp10 = tmp4 + tmp5; /* phase 2 */
  174967. tmp11 = tmp5 + tmp6;
  174968. tmp12 = tmp6 + tmp7;
  174969. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174970. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174971. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174972. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174973. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174974. z11 = tmp7 + z3; /* phase 5 */
  174975. z13 = tmp7 - z3;
  174976. dataptr[5] = z13 + z2; /* phase 6 */
  174977. dataptr[3] = z13 - z2;
  174978. dataptr[1] = z11 + z4;
  174979. dataptr[7] = z11 - z4;
  174980. dataptr += DCTSIZE; /* advance pointer to next row */
  174981. }
  174982. /* Pass 2: process columns. */
  174983. dataptr = data;
  174984. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174985. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174986. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174987. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174988. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174989. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174990. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174991. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174992. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174993. /* Even part */
  174994. tmp10 = tmp0 + tmp3; /* phase 2 */
  174995. tmp13 = tmp0 - tmp3;
  174996. tmp11 = tmp1 + tmp2;
  174997. tmp12 = tmp1 - tmp2;
  174998. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174999. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  175000. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  175001. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  175002. dataptr[DCTSIZE*6] = tmp13 - z1;
  175003. /* Odd part */
  175004. tmp10 = tmp4 + tmp5; /* phase 2 */
  175005. tmp11 = tmp5 + tmp6;
  175006. tmp12 = tmp6 + tmp7;
  175007. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  175008. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  175009. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  175010. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  175011. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  175012. z11 = tmp7 + z3; /* phase 5 */
  175013. z13 = tmp7 - z3;
  175014. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  175015. dataptr[DCTSIZE*3] = z13 - z2;
  175016. dataptr[DCTSIZE*1] = z11 + z4;
  175017. dataptr[DCTSIZE*7] = z11 - z4;
  175018. dataptr++; /* advance pointer to next column */
  175019. }
  175020. }
  175021. #endif /* DCT_IFAST_SUPPORTED */
  175022. /*** End of inlined file: jfdctfst.c ***/
  175023. #undef FIX_0_541196100
  175024. /*** Start of inlined file: jidctflt.c ***/
  175025. #define JPEG_INTERNALS
  175026. #ifdef DCT_FLOAT_SUPPORTED
  175027. /*
  175028. * This module is specialized to the case DCTSIZE = 8.
  175029. */
  175030. #if DCTSIZE != 8
  175031. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175032. #endif
  175033. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175034. * entry; produce a float result.
  175035. */
  175036. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  175037. /*
  175038. * Perform dequantization and inverse DCT on one block of coefficients.
  175039. */
  175040. GLOBAL(void)
  175041. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175042. JCOEFPTR coef_block,
  175043. JSAMPARRAY output_buf, JDIMENSION output_col)
  175044. {
  175045. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175046. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  175047. FAST_FLOAT z5, z10, z11, z12, z13;
  175048. JCOEFPTR inptr;
  175049. FLOAT_MULT_TYPE * quantptr;
  175050. FAST_FLOAT * wsptr;
  175051. JSAMPROW outptr;
  175052. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175053. int ctr;
  175054. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  175055. SHIFT_TEMPS
  175056. /* Pass 1: process columns from input, store into work array. */
  175057. inptr = coef_block;
  175058. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  175059. wsptr = workspace;
  175060. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175061. /* Due to quantization, we will usually find that many of the input
  175062. * coefficients are zero, especially the AC terms. We can exploit this
  175063. * by short-circuiting the IDCT calculation for any column in which all
  175064. * the AC terms are zero. In that case each output is equal to the
  175065. * DC coefficient (with scale factor as needed).
  175066. * With typical images and quantization tables, half or more of the
  175067. * column DCT calculations can be simplified this way.
  175068. */
  175069. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175070. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175071. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175072. inptr[DCTSIZE*7] == 0) {
  175073. /* AC terms all zero */
  175074. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175075. wsptr[DCTSIZE*0] = dcval;
  175076. wsptr[DCTSIZE*1] = dcval;
  175077. wsptr[DCTSIZE*2] = dcval;
  175078. wsptr[DCTSIZE*3] = dcval;
  175079. wsptr[DCTSIZE*4] = dcval;
  175080. wsptr[DCTSIZE*5] = dcval;
  175081. wsptr[DCTSIZE*6] = dcval;
  175082. wsptr[DCTSIZE*7] = dcval;
  175083. inptr++; /* advance pointers to next column */
  175084. quantptr++;
  175085. wsptr++;
  175086. continue;
  175087. }
  175088. /* Even part */
  175089. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175090. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175091. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175092. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175093. tmp10 = tmp0 + tmp2; /* phase 3 */
  175094. tmp11 = tmp0 - tmp2;
  175095. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175096. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  175097. tmp0 = tmp10 + tmp13; /* phase 2 */
  175098. tmp3 = tmp10 - tmp13;
  175099. tmp1 = tmp11 + tmp12;
  175100. tmp2 = tmp11 - tmp12;
  175101. /* Odd part */
  175102. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175103. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175104. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175105. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175106. z13 = tmp6 + tmp5; /* phase 6 */
  175107. z10 = tmp6 - tmp5;
  175108. z11 = tmp4 + tmp7;
  175109. z12 = tmp4 - tmp7;
  175110. tmp7 = z11 + z13; /* phase 5 */
  175111. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  175112. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175113. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175114. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175115. tmp6 = tmp12 - tmp7; /* phase 2 */
  175116. tmp5 = tmp11 - tmp6;
  175117. tmp4 = tmp10 + tmp5;
  175118. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  175119. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  175120. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  175121. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  175122. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175123. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175124. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175125. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175126. inptr++; /* advance pointers to next column */
  175127. quantptr++;
  175128. wsptr++;
  175129. }
  175130. /* Pass 2: process rows from work array, store into output array. */
  175131. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175132. wsptr = workspace;
  175133. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175134. outptr = output_buf[ctr] + output_col;
  175135. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175136. * However, the column calculation has created many nonzero AC terms, so
  175137. * the simplification applies less often (typically 5% to 10% of the time).
  175138. * And testing floats for zero is relatively expensive, so we don't bother.
  175139. */
  175140. /* Even part */
  175141. tmp10 = wsptr[0] + wsptr[4];
  175142. tmp11 = wsptr[0] - wsptr[4];
  175143. tmp13 = wsptr[2] + wsptr[6];
  175144. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175145. tmp0 = tmp10 + tmp13;
  175146. tmp3 = tmp10 - tmp13;
  175147. tmp1 = tmp11 + tmp12;
  175148. tmp2 = tmp11 - tmp12;
  175149. /* Odd part */
  175150. z13 = wsptr[5] + wsptr[3];
  175151. z10 = wsptr[5] - wsptr[3];
  175152. z11 = wsptr[1] + wsptr[7];
  175153. z12 = wsptr[1] - wsptr[7];
  175154. tmp7 = z11 + z13;
  175155. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175156. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175157. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175158. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175159. tmp6 = tmp12 - tmp7;
  175160. tmp5 = tmp11 - tmp6;
  175161. tmp4 = tmp10 + tmp5;
  175162. /* Final output stage: scale down by a factor of 8 and range-limit */
  175163. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175164. & RANGE_MASK];
  175165. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175166. & RANGE_MASK];
  175167. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175168. & RANGE_MASK];
  175169. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175170. & RANGE_MASK];
  175171. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175172. & RANGE_MASK];
  175173. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175174. & RANGE_MASK];
  175175. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175176. & RANGE_MASK];
  175177. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175178. & RANGE_MASK];
  175179. wsptr += DCTSIZE; /* advance pointer to next row */
  175180. }
  175181. }
  175182. #endif /* DCT_FLOAT_SUPPORTED */
  175183. /*** End of inlined file: jidctflt.c ***/
  175184. #undef CONST_BITS
  175185. #undef FIX_1_847759065
  175186. #undef MULTIPLY
  175187. #undef DEQUANTIZE
  175188. #undef DESCALE
  175189. /*** Start of inlined file: jidctfst.c ***/
  175190. #define JPEG_INTERNALS
  175191. #ifdef DCT_IFAST_SUPPORTED
  175192. /*
  175193. * This module is specialized to the case DCTSIZE = 8.
  175194. */
  175195. #if DCTSIZE != 8
  175196. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175197. #endif
  175198. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175199. * see jidctint.c for more details. However, we choose to descale
  175200. * (right shift) multiplication products as soon as they are formed,
  175201. * rather than carrying additional fractional bits into subsequent additions.
  175202. * This compromises accuracy slightly, but it lets us save a few shifts.
  175203. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175204. * everywhere except in the multiplications proper; this saves a good deal
  175205. * of work on 16-bit-int machines.
  175206. *
  175207. * The dequantized coefficients are not integers because the AA&N scaling
  175208. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175209. * so that the first and second IDCT rounds have the same input scaling.
  175210. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175211. * avoid a descaling shift; this compromises accuracy rather drastically
  175212. * for small quantization table entries, but it saves a lot of shifts.
  175213. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175214. * so we use a much larger scaling factor to preserve accuracy.
  175215. *
  175216. * A final compromise is to represent the multiplicative constants to only
  175217. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175218. * machines, and may also reduce the cost of multiplication (since there
  175219. * are fewer one-bits in the constants).
  175220. */
  175221. #if BITS_IN_JSAMPLE == 8
  175222. #define CONST_BITS 8
  175223. #define PASS1_BITS 2
  175224. #else
  175225. #define CONST_BITS 8
  175226. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175227. #endif
  175228. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175229. * causing a lot of useless floating-point operations at run time.
  175230. * To get around this we use the following pre-calculated constants.
  175231. * If you change CONST_BITS you may want to add appropriate values.
  175232. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175233. */
  175234. #if CONST_BITS == 8
  175235. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175236. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175237. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175238. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175239. #else
  175240. #define FIX_1_082392200 FIX(1.082392200)
  175241. #define FIX_1_414213562 FIX(1.414213562)
  175242. #define FIX_1_847759065 FIX(1.847759065)
  175243. #define FIX_2_613125930 FIX(2.613125930)
  175244. #endif
  175245. /* We can gain a little more speed, with a further compromise in accuracy,
  175246. * by omitting the addition in a descaling shift. This yields an incorrectly
  175247. * rounded result half the time...
  175248. */
  175249. #ifndef USE_ACCURATE_ROUNDING
  175250. #undef DESCALE
  175251. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175252. #endif
  175253. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175254. * descale to yield a DCTELEM result.
  175255. */
  175256. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175257. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175258. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175259. * multiplication will do. For 12-bit data, the multiplier table is
  175260. * declared INT32, so a 32-bit multiply will be used.
  175261. */
  175262. #if BITS_IN_JSAMPLE == 8
  175263. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175264. #else
  175265. #define DEQUANTIZE(coef,quantval) \
  175266. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175267. #endif
  175268. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175269. * We assume that int right shift is unsigned if INT32 right shift is.
  175270. */
  175271. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175272. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175273. #if BITS_IN_JSAMPLE == 8
  175274. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175275. #else
  175276. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175277. #endif
  175278. #define IRIGHT_SHIFT(x,shft) \
  175279. ((ishift_temp = (x)) < 0 ? \
  175280. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175281. (ishift_temp >> (shft)))
  175282. #else
  175283. #define ISHIFT_TEMPS
  175284. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175285. #endif
  175286. #ifdef USE_ACCURATE_ROUNDING
  175287. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175288. #else
  175289. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175290. #endif
  175291. /*
  175292. * Perform dequantization and inverse DCT on one block of coefficients.
  175293. */
  175294. GLOBAL(void)
  175295. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175296. JCOEFPTR coef_block,
  175297. JSAMPARRAY output_buf, JDIMENSION output_col)
  175298. {
  175299. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175300. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175301. DCTELEM z5, z10, z11, z12, z13;
  175302. JCOEFPTR inptr;
  175303. IFAST_MULT_TYPE * quantptr;
  175304. int * wsptr;
  175305. JSAMPROW outptr;
  175306. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175307. int ctr;
  175308. int workspace[DCTSIZE2]; /* buffers data between passes */
  175309. SHIFT_TEMPS /* for DESCALE */
  175310. ISHIFT_TEMPS /* for IDESCALE */
  175311. /* Pass 1: process columns from input, store into work array. */
  175312. inptr = coef_block;
  175313. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175314. wsptr = workspace;
  175315. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175316. /* Due to quantization, we will usually find that many of the input
  175317. * coefficients are zero, especially the AC terms. We can exploit this
  175318. * by short-circuiting the IDCT calculation for any column in which all
  175319. * the AC terms are zero. In that case each output is equal to the
  175320. * DC coefficient (with scale factor as needed).
  175321. * With typical images and quantization tables, half or more of the
  175322. * column DCT calculations can be simplified this way.
  175323. */
  175324. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175325. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175326. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175327. inptr[DCTSIZE*7] == 0) {
  175328. /* AC terms all zero */
  175329. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175330. wsptr[DCTSIZE*0] = dcval;
  175331. wsptr[DCTSIZE*1] = dcval;
  175332. wsptr[DCTSIZE*2] = dcval;
  175333. wsptr[DCTSIZE*3] = dcval;
  175334. wsptr[DCTSIZE*4] = dcval;
  175335. wsptr[DCTSIZE*5] = dcval;
  175336. wsptr[DCTSIZE*6] = dcval;
  175337. wsptr[DCTSIZE*7] = dcval;
  175338. inptr++; /* advance pointers to next column */
  175339. quantptr++;
  175340. wsptr++;
  175341. continue;
  175342. }
  175343. /* Even part */
  175344. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175345. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175346. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175347. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175348. tmp10 = tmp0 + tmp2; /* phase 3 */
  175349. tmp11 = tmp0 - tmp2;
  175350. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175351. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175352. tmp0 = tmp10 + tmp13; /* phase 2 */
  175353. tmp3 = tmp10 - tmp13;
  175354. tmp1 = tmp11 + tmp12;
  175355. tmp2 = tmp11 - tmp12;
  175356. /* Odd part */
  175357. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175358. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175359. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175360. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175361. z13 = tmp6 + tmp5; /* phase 6 */
  175362. z10 = tmp6 - tmp5;
  175363. z11 = tmp4 + tmp7;
  175364. z12 = tmp4 - tmp7;
  175365. tmp7 = z11 + z13; /* phase 5 */
  175366. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175367. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175368. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175369. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175370. tmp6 = tmp12 - tmp7; /* phase 2 */
  175371. tmp5 = tmp11 - tmp6;
  175372. tmp4 = tmp10 + tmp5;
  175373. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175374. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175375. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175376. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175377. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175378. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175379. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175380. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175381. inptr++; /* advance pointers to next column */
  175382. quantptr++;
  175383. wsptr++;
  175384. }
  175385. /* Pass 2: process rows from work array, store into output array. */
  175386. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175387. /* and also undo the PASS1_BITS scaling. */
  175388. wsptr = workspace;
  175389. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175390. outptr = output_buf[ctr] + output_col;
  175391. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175392. * However, the column calculation has created many nonzero AC terms, so
  175393. * the simplification applies less often (typically 5% to 10% of the time).
  175394. * On machines with very fast multiplication, it's possible that the
  175395. * test takes more time than it's worth. In that case this section
  175396. * may be commented out.
  175397. */
  175398. #ifndef NO_ZERO_ROW_TEST
  175399. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175400. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175401. /* AC terms all zero */
  175402. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175403. & RANGE_MASK];
  175404. outptr[0] = dcval;
  175405. outptr[1] = dcval;
  175406. outptr[2] = dcval;
  175407. outptr[3] = dcval;
  175408. outptr[4] = dcval;
  175409. outptr[5] = dcval;
  175410. outptr[6] = dcval;
  175411. outptr[7] = dcval;
  175412. wsptr += DCTSIZE; /* advance pointer to next row */
  175413. continue;
  175414. }
  175415. #endif
  175416. /* Even part */
  175417. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175418. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175419. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175420. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175421. - tmp13;
  175422. tmp0 = tmp10 + tmp13;
  175423. tmp3 = tmp10 - tmp13;
  175424. tmp1 = tmp11 + tmp12;
  175425. tmp2 = tmp11 - tmp12;
  175426. /* Odd part */
  175427. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175428. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175429. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175430. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175431. tmp7 = z11 + z13; /* phase 5 */
  175432. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175433. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175434. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175435. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175436. tmp6 = tmp12 - tmp7; /* phase 2 */
  175437. tmp5 = tmp11 - tmp6;
  175438. tmp4 = tmp10 + tmp5;
  175439. /* Final output stage: scale down by a factor of 8 and range-limit */
  175440. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175441. & RANGE_MASK];
  175442. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175443. & RANGE_MASK];
  175444. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175445. & RANGE_MASK];
  175446. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175447. & RANGE_MASK];
  175448. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175449. & RANGE_MASK];
  175450. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175451. & RANGE_MASK];
  175452. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175453. & RANGE_MASK];
  175454. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175455. & RANGE_MASK];
  175456. wsptr += DCTSIZE; /* advance pointer to next row */
  175457. }
  175458. }
  175459. #endif /* DCT_IFAST_SUPPORTED */
  175460. /*** End of inlined file: jidctfst.c ***/
  175461. #undef CONST_BITS
  175462. #undef FIX_1_847759065
  175463. #undef MULTIPLY
  175464. #undef DEQUANTIZE
  175465. /*** Start of inlined file: jidctint.c ***/
  175466. #define JPEG_INTERNALS
  175467. #ifdef DCT_ISLOW_SUPPORTED
  175468. /*
  175469. * This module is specialized to the case DCTSIZE = 8.
  175470. */
  175471. #if DCTSIZE != 8
  175472. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175473. #endif
  175474. /*
  175475. * The poop on this scaling stuff is as follows:
  175476. *
  175477. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175478. * larger than the true IDCT outputs. The final outputs are therefore
  175479. * a factor of N larger than desired; since N=8 this can be cured by
  175480. * a simple right shift at the end of the algorithm. The advantage of
  175481. * this arrangement is that we save two multiplications per 1-D IDCT,
  175482. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175483. *
  175484. * We have to do addition and subtraction of the integer inputs, which
  175485. * is no problem, and multiplication by fractional constants, which is
  175486. * a problem to do in integer arithmetic. We multiply all the constants
  175487. * by CONST_SCALE and convert them to integer constants (thus retaining
  175488. * CONST_BITS bits of precision in the constants). After doing a
  175489. * multiplication we have to divide the product by CONST_SCALE, with proper
  175490. * rounding, to produce the correct output. This division can be done
  175491. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175492. * as long as possible so that partial sums can be added together with
  175493. * full fractional precision.
  175494. *
  175495. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175496. * they are represented to better-than-integral precision. These outputs
  175497. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175498. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175499. * intermediate INT32 array would be needed.)
  175500. *
  175501. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175502. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175503. * shows that the values given below are the most effective.
  175504. */
  175505. #if BITS_IN_JSAMPLE == 8
  175506. #define CONST_BITS 13
  175507. #define PASS1_BITS 2
  175508. #else
  175509. #define CONST_BITS 13
  175510. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175511. #endif
  175512. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175513. * causing a lot of useless floating-point operations at run time.
  175514. * To get around this we use the following pre-calculated constants.
  175515. * If you change CONST_BITS you may want to add appropriate values.
  175516. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175517. */
  175518. #if CONST_BITS == 13
  175519. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175520. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175521. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175522. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175523. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175524. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175525. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175526. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175527. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175528. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175529. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175530. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175531. #else
  175532. #define FIX_0_298631336 FIX(0.298631336)
  175533. #define FIX_0_390180644 FIX(0.390180644)
  175534. #define FIX_0_541196100 FIX(0.541196100)
  175535. #define FIX_0_765366865 FIX(0.765366865)
  175536. #define FIX_0_899976223 FIX(0.899976223)
  175537. #define FIX_1_175875602 FIX(1.175875602)
  175538. #define FIX_1_501321110 FIX(1.501321110)
  175539. #define FIX_1_847759065 FIX(1.847759065)
  175540. #define FIX_1_961570560 FIX(1.961570560)
  175541. #define FIX_2_053119869 FIX(2.053119869)
  175542. #define FIX_2_562915447 FIX(2.562915447)
  175543. #define FIX_3_072711026 FIX(3.072711026)
  175544. #endif
  175545. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175546. * For 8-bit samples with the recommended scaling, all the variable
  175547. * and constant values involved are no more than 16 bits wide, so a
  175548. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175549. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175550. */
  175551. #if BITS_IN_JSAMPLE == 8
  175552. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175553. #else
  175554. #define MULTIPLY(var,const) ((var) * (const))
  175555. #endif
  175556. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175557. * entry; produce an int result. In this module, both inputs and result
  175558. * are 16 bits or less, so either int or short multiply will work.
  175559. */
  175560. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175561. /*
  175562. * Perform dequantization and inverse DCT on one block of coefficients.
  175563. */
  175564. GLOBAL(void)
  175565. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175566. JCOEFPTR coef_block,
  175567. JSAMPARRAY output_buf, JDIMENSION output_col)
  175568. {
  175569. INT32 tmp0, tmp1, tmp2, tmp3;
  175570. INT32 tmp10, tmp11, tmp12, tmp13;
  175571. INT32 z1, z2, z3, z4, z5;
  175572. JCOEFPTR inptr;
  175573. ISLOW_MULT_TYPE * quantptr;
  175574. int * wsptr;
  175575. JSAMPROW outptr;
  175576. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175577. int ctr;
  175578. int workspace[DCTSIZE2]; /* buffers data between passes */
  175579. SHIFT_TEMPS
  175580. /* Pass 1: process columns from input, store into work array. */
  175581. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175582. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175583. inptr = coef_block;
  175584. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175585. wsptr = workspace;
  175586. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175587. /* Due to quantization, we will usually find that many of the input
  175588. * coefficients are zero, especially the AC terms. We can exploit this
  175589. * by short-circuiting the IDCT calculation for any column in which all
  175590. * the AC terms are zero. In that case each output is equal to the
  175591. * DC coefficient (with scale factor as needed).
  175592. * With typical images and quantization tables, half or more of the
  175593. * column DCT calculations can be simplified this way.
  175594. */
  175595. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175596. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175597. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175598. inptr[DCTSIZE*7] == 0) {
  175599. /* AC terms all zero */
  175600. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175601. wsptr[DCTSIZE*0] = dcval;
  175602. wsptr[DCTSIZE*1] = dcval;
  175603. wsptr[DCTSIZE*2] = dcval;
  175604. wsptr[DCTSIZE*3] = dcval;
  175605. wsptr[DCTSIZE*4] = dcval;
  175606. wsptr[DCTSIZE*5] = dcval;
  175607. wsptr[DCTSIZE*6] = dcval;
  175608. wsptr[DCTSIZE*7] = dcval;
  175609. inptr++; /* advance pointers to next column */
  175610. quantptr++;
  175611. wsptr++;
  175612. continue;
  175613. }
  175614. /* Even part: reverse the even part of the forward DCT. */
  175615. /* The rotator is sqrt(2)*c(-6). */
  175616. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175617. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175618. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175619. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175620. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175621. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175622. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175623. tmp0 = (z2 + z3) << CONST_BITS;
  175624. tmp1 = (z2 - z3) << CONST_BITS;
  175625. tmp10 = tmp0 + tmp3;
  175626. tmp13 = tmp0 - tmp3;
  175627. tmp11 = tmp1 + tmp2;
  175628. tmp12 = tmp1 - tmp2;
  175629. /* Odd part per figure 8; the matrix is unitary and hence its
  175630. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175631. */
  175632. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175633. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175634. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175635. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175636. z1 = tmp0 + tmp3;
  175637. z2 = tmp1 + tmp2;
  175638. z3 = tmp0 + tmp2;
  175639. z4 = tmp1 + tmp3;
  175640. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175641. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175642. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175643. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175644. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175645. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175646. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175647. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175648. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175649. z3 += z5;
  175650. z4 += z5;
  175651. tmp0 += z1 + z3;
  175652. tmp1 += z2 + z4;
  175653. tmp2 += z2 + z3;
  175654. tmp3 += z1 + z4;
  175655. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175656. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175657. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175658. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175659. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175660. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175661. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175662. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175663. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175664. inptr++; /* advance pointers to next column */
  175665. quantptr++;
  175666. wsptr++;
  175667. }
  175668. /* Pass 2: process rows from work array, store into output array. */
  175669. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175670. /* and also undo the PASS1_BITS scaling. */
  175671. wsptr = workspace;
  175672. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175673. outptr = output_buf[ctr] + output_col;
  175674. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175675. * However, the column calculation has created many nonzero AC terms, so
  175676. * the simplification applies less often (typically 5% to 10% of the time).
  175677. * On machines with very fast multiplication, it's possible that the
  175678. * test takes more time than it's worth. In that case this section
  175679. * may be commented out.
  175680. */
  175681. #ifndef NO_ZERO_ROW_TEST
  175682. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175683. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175684. /* AC terms all zero */
  175685. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175686. & RANGE_MASK];
  175687. outptr[0] = dcval;
  175688. outptr[1] = dcval;
  175689. outptr[2] = dcval;
  175690. outptr[3] = dcval;
  175691. outptr[4] = dcval;
  175692. outptr[5] = dcval;
  175693. outptr[6] = dcval;
  175694. outptr[7] = dcval;
  175695. wsptr += DCTSIZE; /* advance pointer to next row */
  175696. continue;
  175697. }
  175698. #endif
  175699. /* Even part: reverse the even part of the forward DCT. */
  175700. /* The rotator is sqrt(2)*c(-6). */
  175701. z2 = (INT32) wsptr[2];
  175702. z3 = (INT32) wsptr[6];
  175703. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175704. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175705. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175706. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175707. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175708. tmp10 = tmp0 + tmp3;
  175709. tmp13 = tmp0 - tmp3;
  175710. tmp11 = tmp1 + tmp2;
  175711. tmp12 = tmp1 - tmp2;
  175712. /* Odd part per figure 8; the matrix is unitary and hence its
  175713. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175714. */
  175715. tmp0 = (INT32) wsptr[7];
  175716. tmp1 = (INT32) wsptr[5];
  175717. tmp2 = (INT32) wsptr[3];
  175718. tmp3 = (INT32) wsptr[1];
  175719. z1 = tmp0 + tmp3;
  175720. z2 = tmp1 + tmp2;
  175721. z3 = tmp0 + tmp2;
  175722. z4 = tmp1 + tmp3;
  175723. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175724. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175725. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175726. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175727. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175728. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175729. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175730. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175731. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175732. z3 += z5;
  175733. z4 += z5;
  175734. tmp0 += z1 + z3;
  175735. tmp1 += z2 + z4;
  175736. tmp2 += z2 + z3;
  175737. tmp3 += z1 + z4;
  175738. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175739. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175740. CONST_BITS+PASS1_BITS+3)
  175741. & RANGE_MASK];
  175742. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175743. CONST_BITS+PASS1_BITS+3)
  175744. & RANGE_MASK];
  175745. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175746. CONST_BITS+PASS1_BITS+3)
  175747. & RANGE_MASK];
  175748. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175749. CONST_BITS+PASS1_BITS+3)
  175750. & RANGE_MASK];
  175751. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175752. CONST_BITS+PASS1_BITS+3)
  175753. & RANGE_MASK];
  175754. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175755. CONST_BITS+PASS1_BITS+3)
  175756. & RANGE_MASK];
  175757. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175758. CONST_BITS+PASS1_BITS+3)
  175759. & RANGE_MASK];
  175760. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175761. CONST_BITS+PASS1_BITS+3)
  175762. & RANGE_MASK];
  175763. wsptr += DCTSIZE; /* advance pointer to next row */
  175764. }
  175765. }
  175766. #endif /* DCT_ISLOW_SUPPORTED */
  175767. /*** End of inlined file: jidctint.c ***/
  175768. /*** Start of inlined file: jidctred.c ***/
  175769. #define JPEG_INTERNALS
  175770. #ifdef IDCT_SCALING_SUPPORTED
  175771. /*
  175772. * This module is specialized to the case DCTSIZE = 8.
  175773. */
  175774. #if DCTSIZE != 8
  175775. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175776. #endif
  175777. /* Scaling is the same as in jidctint.c. */
  175778. #if BITS_IN_JSAMPLE == 8
  175779. #define CONST_BITS 13
  175780. #define PASS1_BITS 2
  175781. #else
  175782. #define CONST_BITS 13
  175783. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175784. #endif
  175785. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175786. * causing a lot of useless floating-point operations at run time.
  175787. * To get around this we use the following pre-calculated constants.
  175788. * If you change CONST_BITS you may want to add appropriate values.
  175789. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175790. */
  175791. #if CONST_BITS == 13
  175792. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175793. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175794. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175795. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175796. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175797. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175798. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175799. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175800. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175801. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175802. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175803. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175804. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175805. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175806. #else
  175807. #define FIX_0_211164243 FIX(0.211164243)
  175808. #define FIX_0_509795579 FIX(0.509795579)
  175809. #define FIX_0_601344887 FIX(0.601344887)
  175810. #define FIX_0_720959822 FIX(0.720959822)
  175811. #define FIX_0_765366865 FIX(0.765366865)
  175812. #define FIX_0_850430095 FIX(0.850430095)
  175813. #define FIX_0_899976223 FIX(0.899976223)
  175814. #define FIX_1_061594337 FIX(1.061594337)
  175815. #define FIX_1_272758580 FIX(1.272758580)
  175816. #define FIX_1_451774981 FIX(1.451774981)
  175817. #define FIX_1_847759065 FIX(1.847759065)
  175818. #define FIX_2_172734803 FIX(2.172734803)
  175819. #define FIX_2_562915447 FIX(2.562915447)
  175820. #define FIX_3_624509785 FIX(3.624509785)
  175821. #endif
  175822. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175823. * For 8-bit samples with the recommended scaling, all the variable
  175824. * and constant values involved are no more than 16 bits wide, so a
  175825. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175826. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175827. */
  175828. #if BITS_IN_JSAMPLE == 8
  175829. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175830. #else
  175831. #define MULTIPLY(var,const) ((var) * (const))
  175832. #endif
  175833. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175834. * entry; produce an int result. In this module, both inputs and result
  175835. * are 16 bits or less, so either int or short multiply will work.
  175836. */
  175837. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175838. /*
  175839. * Perform dequantization and inverse DCT on one block of coefficients,
  175840. * producing a reduced-size 4x4 output block.
  175841. */
  175842. GLOBAL(void)
  175843. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175844. JCOEFPTR coef_block,
  175845. JSAMPARRAY output_buf, JDIMENSION output_col)
  175846. {
  175847. INT32 tmp0, tmp2, tmp10, tmp12;
  175848. INT32 z1, z2, z3, z4;
  175849. JCOEFPTR inptr;
  175850. ISLOW_MULT_TYPE * quantptr;
  175851. int * wsptr;
  175852. JSAMPROW outptr;
  175853. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175854. int ctr;
  175855. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175856. SHIFT_TEMPS
  175857. /* Pass 1: process columns from input, store into work array. */
  175858. inptr = coef_block;
  175859. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175860. wsptr = workspace;
  175861. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175862. /* Don't bother to process column 4, because second pass won't use it */
  175863. if (ctr == DCTSIZE-4)
  175864. continue;
  175865. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175866. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175867. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175868. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175869. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175870. wsptr[DCTSIZE*0] = dcval;
  175871. wsptr[DCTSIZE*1] = dcval;
  175872. wsptr[DCTSIZE*2] = dcval;
  175873. wsptr[DCTSIZE*3] = dcval;
  175874. continue;
  175875. }
  175876. /* Even part */
  175877. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175878. tmp0 <<= (CONST_BITS+1);
  175879. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175880. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175881. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175882. tmp10 = tmp0 + tmp2;
  175883. tmp12 = tmp0 - tmp2;
  175884. /* Odd part */
  175885. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175886. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175887. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175888. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175889. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175890. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175891. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175892. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175893. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175894. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175895. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175896. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175897. /* Final output stage */
  175898. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175899. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175900. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175901. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175902. }
  175903. /* Pass 2: process 4 rows from work array, store into output array. */
  175904. wsptr = workspace;
  175905. for (ctr = 0; ctr < 4; ctr++) {
  175906. outptr = output_buf[ctr] + output_col;
  175907. /* It's not clear whether a zero row test is worthwhile here ... */
  175908. #ifndef NO_ZERO_ROW_TEST
  175909. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175910. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175911. /* AC terms all zero */
  175912. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175913. & RANGE_MASK];
  175914. outptr[0] = dcval;
  175915. outptr[1] = dcval;
  175916. outptr[2] = dcval;
  175917. outptr[3] = dcval;
  175918. wsptr += DCTSIZE; /* advance pointer to next row */
  175919. continue;
  175920. }
  175921. #endif
  175922. /* Even part */
  175923. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175924. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175925. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175926. tmp10 = tmp0 + tmp2;
  175927. tmp12 = tmp0 - tmp2;
  175928. /* Odd part */
  175929. z1 = (INT32) wsptr[7];
  175930. z2 = (INT32) wsptr[5];
  175931. z3 = (INT32) wsptr[3];
  175932. z4 = (INT32) wsptr[1];
  175933. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175934. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175935. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175936. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175937. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175938. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175939. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175940. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175941. /* Final output stage */
  175942. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175943. CONST_BITS+PASS1_BITS+3+1)
  175944. & RANGE_MASK];
  175945. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175946. CONST_BITS+PASS1_BITS+3+1)
  175947. & RANGE_MASK];
  175948. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175949. CONST_BITS+PASS1_BITS+3+1)
  175950. & RANGE_MASK];
  175951. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175952. CONST_BITS+PASS1_BITS+3+1)
  175953. & RANGE_MASK];
  175954. wsptr += DCTSIZE; /* advance pointer to next row */
  175955. }
  175956. }
  175957. /*
  175958. * Perform dequantization and inverse DCT on one block of coefficients,
  175959. * producing a reduced-size 2x2 output block.
  175960. */
  175961. GLOBAL(void)
  175962. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175963. JCOEFPTR coef_block,
  175964. JSAMPARRAY output_buf, JDIMENSION output_col)
  175965. {
  175966. INT32 tmp0, tmp10, z1;
  175967. JCOEFPTR inptr;
  175968. ISLOW_MULT_TYPE * quantptr;
  175969. int * wsptr;
  175970. JSAMPROW outptr;
  175971. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175972. int ctr;
  175973. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175974. SHIFT_TEMPS
  175975. /* Pass 1: process columns from input, store into work array. */
  175976. inptr = coef_block;
  175977. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175978. wsptr = workspace;
  175979. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175980. /* Don't bother to process columns 2,4,6 */
  175981. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175982. continue;
  175983. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175984. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175985. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175986. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175987. wsptr[DCTSIZE*0] = dcval;
  175988. wsptr[DCTSIZE*1] = dcval;
  175989. continue;
  175990. }
  175991. /* Even part */
  175992. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175993. tmp10 = z1 << (CONST_BITS+2);
  175994. /* Odd part */
  175995. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175996. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175997. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175998. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175999. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  176000. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  176001. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  176002. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  176003. /* Final output stage */
  176004. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  176005. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  176006. }
  176007. /* Pass 2: process 2 rows from work array, store into output array. */
  176008. wsptr = workspace;
  176009. for (ctr = 0; ctr < 2; ctr++) {
  176010. outptr = output_buf[ctr] + output_col;
  176011. /* It's not clear whether a zero row test is worthwhile here ... */
  176012. #ifndef NO_ZERO_ROW_TEST
  176013. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  176014. /* AC terms all zero */
  176015. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  176016. & RANGE_MASK];
  176017. outptr[0] = dcval;
  176018. outptr[1] = dcval;
  176019. wsptr += DCTSIZE; /* advance pointer to next row */
  176020. continue;
  176021. }
  176022. #endif
  176023. /* Even part */
  176024. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  176025. /* Odd part */
  176026. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  176027. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  176028. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  176029. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  176030. /* Final output stage */
  176031. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  176032. CONST_BITS+PASS1_BITS+3+2)
  176033. & RANGE_MASK];
  176034. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  176035. CONST_BITS+PASS1_BITS+3+2)
  176036. & RANGE_MASK];
  176037. wsptr += DCTSIZE; /* advance pointer to next row */
  176038. }
  176039. }
  176040. /*
  176041. * Perform dequantization and inverse DCT on one block of coefficients,
  176042. * producing a reduced-size 1x1 output block.
  176043. */
  176044. GLOBAL(void)
  176045. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  176046. JCOEFPTR coef_block,
  176047. JSAMPARRAY output_buf, JDIMENSION output_col)
  176048. {
  176049. int dcval;
  176050. ISLOW_MULT_TYPE * quantptr;
  176051. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  176052. SHIFT_TEMPS
  176053. /* We hardly need an inverse DCT routine for this: just take the
  176054. * average pixel value, which is one-eighth of the DC coefficient.
  176055. */
  176056. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  176057. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  176058. dcval = (int) DESCALE((INT32) dcval, 3);
  176059. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  176060. }
  176061. #endif /* IDCT_SCALING_SUPPORTED */
  176062. /*** End of inlined file: jidctred.c ***/
  176063. /*** Start of inlined file: jmemmgr.c ***/
  176064. #define JPEG_INTERNALS
  176065. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  176066. /*** Start of inlined file: jmemsys.h ***/
  176067. #ifndef __jmemsys_h__
  176068. #define __jmemsys_h__
  176069. /* Short forms of external names for systems with brain-damaged linkers. */
  176070. #ifdef NEED_SHORT_EXTERNAL_NAMES
  176071. #define jpeg_get_small jGetSmall
  176072. #define jpeg_free_small jFreeSmall
  176073. #define jpeg_get_large jGetLarge
  176074. #define jpeg_free_large jFreeLarge
  176075. #define jpeg_mem_available jMemAvail
  176076. #define jpeg_open_backing_store jOpenBackStore
  176077. #define jpeg_mem_init jMemInit
  176078. #define jpeg_mem_term jMemTerm
  176079. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  176080. /*
  176081. * These two functions are used to allocate and release small chunks of
  176082. * memory. (Typically the total amount requested through jpeg_get_small is
  176083. * no more than 20K or so; this will be requested in chunks of a few K each.)
  176084. * Behavior should be the same as for the standard library functions malloc
  176085. * and free; in particular, jpeg_get_small must return NULL on failure.
  176086. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  176087. * size of the object being freed, just in case it's needed.
  176088. * On an 80x86 machine using small-data memory model, these manage near heap.
  176089. */
  176090. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  176091. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  176092. size_t sizeofobject));
  176093. /*
  176094. * These two functions are used to allocate and release large chunks of
  176095. * memory (up to the total free space designated by jpeg_mem_available).
  176096. * The interface is the same as above, except that on an 80x86 machine,
  176097. * far pointers are used. On most other machines these are identical to
  176098. * the jpeg_get/free_small routines; but we keep them separate anyway,
  176099. * in case a different allocation strategy is desirable for large chunks.
  176100. */
  176101. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  176102. size_t sizeofobject));
  176103. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  176104. size_t sizeofobject));
  176105. /*
  176106. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  176107. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  176108. * matter, but that case should never come into play). This macro is needed
  176109. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  176110. * On those machines, we expect that jconfig.h will provide a proper value.
  176111. * On machines with 32-bit flat address spaces, any large constant may be used.
  176112. *
  176113. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  176114. * size_t and will be a multiple of sizeof(align_type).
  176115. */
  176116. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  176117. #define MAX_ALLOC_CHUNK 1000000000L
  176118. #endif
  176119. /*
  176120. * This routine computes the total space still available for allocation by
  176121. * jpeg_get_large. If more space than this is needed, backing store will be
  176122. * used. NOTE: any memory already allocated must not be counted.
  176123. *
  176124. * There is a minimum space requirement, corresponding to the minimum
  176125. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176126. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176127. * all working storage in memory, is also passed in case it is useful.
  176128. * Finally, the total space already allocated is passed. If no better
  176129. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176130. * is often a suitable calculation.
  176131. *
  176132. * It is OK for jpeg_mem_available to underestimate the space available
  176133. * (that'll just lead to more backing-store access than is really necessary).
  176134. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176135. * a slop factor from the true available space. 5% should be enough.
  176136. *
  176137. * On machines with lots of virtual memory, any large constant may be returned.
  176138. * Conversely, zero may be returned to always use the minimum amount of memory.
  176139. */
  176140. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176141. long min_bytes_needed,
  176142. long max_bytes_needed,
  176143. long already_allocated));
  176144. /*
  176145. * This structure holds whatever state is needed to access a single
  176146. * backing-store object. The read/write/close method pointers are called
  176147. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176148. * are private to the system-dependent backing store routines.
  176149. */
  176150. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176151. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176152. typedef unsigned short XMSH; /* type of extended-memory handles */
  176153. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176154. typedef union {
  176155. short file_handle; /* DOS file handle if it's a temp file */
  176156. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176157. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176158. } handle_union;
  176159. #endif /* USE_MSDOS_MEMMGR */
  176160. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176161. #include <Files.h>
  176162. #endif /* USE_MAC_MEMMGR */
  176163. //typedef struct backing_store_struct * backing_store_ptr;
  176164. typedef struct backing_store_struct {
  176165. /* Methods for reading/writing/closing this backing-store object */
  176166. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176167. struct backing_store_struct *info,
  176168. void FAR * buffer_address,
  176169. long file_offset, long byte_count));
  176170. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176171. struct backing_store_struct *info,
  176172. void FAR * buffer_address,
  176173. long file_offset, long byte_count));
  176174. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176175. struct backing_store_struct *info));
  176176. /* Private fields for system-dependent backing-store management */
  176177. #ifdef USE_MSDOS_MEMMGR
  176178. /* For the MS-DOS manager (jmemdos.c), we need: */
  176179. handle_union handle; /* reference to backing-store storage object */
  176180. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176181. #else
  176182. #ifdef USE_MAC_MEMMGR
  176183. /* For the Mac manager (jmemmac.c), we need: */
  176184. short temp_file; /* file reference number to temp file */
  176185. FSSpec tempSpec; /* the FSSpec for the temp file */
  176186. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176187. #else
  176188. /* For a typical implementation with temp files, we need: */
  176189. FILE * temp_file; /* stdio reference to temp file */
  176190. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176191. #endif
  176192. #endif
  176193. } backing_store_info;
  176194. /*
  176195. * Initial opening of a backing-store object. This must fill in the
  176196. * read/write/close pointers in the object. The read/write routines
  176197. * may take an error exit if the specified maximum file size is exceeded.
  176198. * (If jpeg_mem_available always returns a large value, this routine can
  176199. * just take an error exit.)
  176200. */
  176201. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176202. struct backing_store_struct *info,
  176203. long total_bytes_needed));
  176204. /*
  176205. * These routines take care of any system-dependent initialization and
  176206. * cleanup required. jpeg_mem_init will be called before anything is
  176207. * allocated (and, therefore, nothing in cinfo is of use except the error
  176208. * manager pointer). It should return a suitable default value for
  176209. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176210. * application. (Note that max_memory_to_use is only important if
  176211. * jpeg_mem_available chooses to consult it ... no one else will.)
  176212. * jpeg_mem_term may assume that all requested memory has been freed and that
  176213. * all opened backing-store objects have been closed.
  176214. */
  176215. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176216. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176217. #endif
  176218. /*** End of inlined file: jmemsys.h ***/
  176219. /* import the system-dependent declarations */
  176220. #ifndef NO_GETENV
  176221. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176222. extern char * getenv JPP((const char * name));
  176223. #endif
  176224. #endif
  176225. /*
  176226. * Some important notes:
  176227. * The allocation routines provided here must never return NULL.
  176228. * They should exit to error_exit if unsuccessful.
  176229. *
  176230. * It's not a good idea to try to merge the sarray and barray routines,
  176231. * even though they are textually almost the same, because samples are
  176232. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176233. * in machines where byte pointers have a different representation from
  176234. * word pointers, the resulting machine code could not be the same.
  176235. */
  176236. /*
  176237. * Many machines require storage alignment: longs must start on 4-byte
  176238. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176239. * always returns pointers that are multiples of the worst-case alignment
  176240. * requirement, and we had better do so too.
  176241. * There isn't any really portable way to determine the worst-case alignment
  176242. * requirement. This module assumes that the alignment requirement is
  176243. * multiples of sizeof(ALIGN_TYPE).
  176244. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176245. * workstations (where doubles really do need 8-byte alignment) and will work
  176246. * fine on nearly everything. If your machine has lesser alignment needs,
  176247. * you can save a few bytes by making ALIGN_TYPE smaller.
  176248. * The only place I know of where this will NOT work is certain Macintosh
  176249. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176250. * Doing 10-byte alignment is counterproductive because longwords won't be
  176251. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176252. * such a compiler.
  176253. */
  176254. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176255. #define ALIGN_TYPE double
  176256. #endif
  176257. /*
  176258. * We allocate objects from "pools", where each pool is gotten with a single
  176259. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176260. * overhead within a pool, except for alignment padding. Each pool has a
  176261. * header with a link to the next pool of the same class.
  176262. * Small and large pool headers are identical except that the latter's
  176263. * link pointer must be FAR on 80x86 machines.
  176264. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176265. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176266. * of the alignment requirement of ALIGN_TYPE.
  176267. */
  176268. typedef union small_pool_struct * small_pool_ptr;
  176269. typedef union small_pool_struct {
  176270. struct {
  176271. small_pool_ptr next; /* next in list of pools */
  176272. size_t bytes_used; /* how many bytes already used within pool */
  176273. size_t bytes_left; /* bytes still available in this pool */
  176274. } hdr;
  176275. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176276. } small_pool_hdr;
  176277. typedef union large_pool_struct FAR * large_pool_ptr;
  176278. typedef union large_pool_struct {
  176279. struct {
  176280. large_pool_ptr next; /* next in list of pools */
  176281. size_t bytes_used; /* how many bytes already used within pool */
  176282. size_t bytes_left; /* bytes still available in this pool */
  176283. } hdr;
  176284. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176285. } large_pool_hdr;
  176286. /*
  176287. * Here is the full definition of a memory manager object.
  176288. */
  176289. typedef struct {
  176290. struct jpeg_memory_mgr pub; /* public fields */
  176291. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176292. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176293. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176294. /* Since we only have one lifetime class of virtual arrays, only one
  176295. * linked list is necessary (for each datatype). Note that the virtual
  176296. * array control blocks being linked together are actually stored somewhere
  176297. * in the small-pool list.
  176298. */
  176299. jvirt_sarray_ptr virt_sarray_list;
  176300. jvirt_barray_ptr virt_barray_list;
  176301. /* This counts total space obtained from jpeg_get_small/large */
  176302. long total_space_allocated;
  176303. /* alloc_sarray and alloc_barray set this value for use by virtual
  176304. * array routines.
  176305. */
  176306. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176307. } my_memory_mgr;
  176308. typedef my_memory_mgr * my_mem_ptr;
  176309. /*
  176310. * The control blocks for virtual arrays.
  176311. * Note that these blocks are allocated in the "small" pool area.
  176312. * System-dependent info for the associated backing store (if any) is hidden
  176313. * inside the backing_store_info struct.
  176314. */
  176315. struct jvirt_sarray_control {
  176316. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176317. JDIMENSION rows_in_array; /* total virtual array height */
  176318. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176319. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176320. JDIMENSION rows_in_mem; /* height of memory buffer */
  176321. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176322. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176323. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176324. boolean pre_zero; /* pre-zero mode requested? */
  176325. boolean dirty; /* do current buffer contents need written? */
  176326. boolean b_s_open; /* is backing-store data valid? */
  176327. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176328. backing_store_info b_s_info; /* System-dependent control info */
  176329. };
  176330. struct jvirt_barray_control {
  176331. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176332. JDIMENSION rows_in_array; /* total virtual array height */
  176333. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176334. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176335. JDIMENSION rows_in_mem; /* height of memory buffer */
  176336. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176337. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176338. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176339. boolean pre_zero; /* pre-zero mode requested? */
  176340. boolean dirty; /* do current buffer contents need written? */
  176341. boolean b_s_open; /* is backing-store data valid? */
  176342. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176343. backing_store_info b_s_info; /* System-dependent control info */
  176344. };
  176345. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176346. LOCAL(void)
  176347. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176348. {
  176349. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176350. small_pool_ptr shdr_ptr;
  176351. large_pool_ptr lhdr_ptr;
  176352. /* Since this is only a debugging stub, we can cheat a little by using
  176353. * fprintf directly rather than going through the trace message code.
  176354. * This is helpful because message parm array can't handle longs.
  176355. */
  176356. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176357. pool_id, mem->total_space_allocated);
  176358. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176359. lhdr_ptr = lhdr_ptr->hdr.next) {
  176360. fprintf(stderr, " Large chunk used %ld\n",
  176361. (long) lhdr_ptr->hdr.bytes_used);
  176362. }
  176363. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176364. shdr_ptr = shdr_ptr->hdr.next) {
  176365. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176366. (long) shdr_ptr->hdr.bytes_used,
  176367. (long) shdr_ptr->hdr.bytes_left);
  176368. }
  176369. }
  176370. #endif /* MEM_STATS */
  176371. LOCAL(void)
  176372. out_of_memory (j_common_ptr cinfo, int which)
  176373. /* Report an out-of-memory error and stop execution */
  176374. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176375. {
  176376. #ifdef MEM_STATS
  176377. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176378. #endif
  176379. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176380. }
  176381. /*
  176382. * Allocation of "small" objects.
  176383. *
  176384. * For these, we use pooled storage. When a new pool must be created,
  176385. * we try to get enough space for the current request plus a "slop" factor,
  176386. * where the slop will be the amount of leftover space in the new pool.
  176387. * The speed vs. space tradeoff is largely determined by the slop values.
  176388. * A different slop value is provided for each pool class (lifetime),
  176389. * and we also distinguish the first pool of a class from later ones.
  176390. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176391. * machines, but may be too small if longs are 64 bits or more.
  176392. */
  176393. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176394. {
  176395. 1600, /* first PERMANENT pool */
  176396. 16000 /* first IMAGE pool */
  176397. };
  176398. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176399. {
  176400. 0, /* additional PERMANENT pools */
  176401. 5000 /* additional IMAGE pools */
  176402. };
  176403. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176404. METHODDEF(void *)
  176405. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176406. /* Allocate a "small" object */
  176407. {
  176408. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176409. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176410. char * data_ptr;
  176411. size_t odd_bytes, min_request, slop;
  176412. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176413. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176414. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176415. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176416. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176417. if (odd_bytes > 0)
  176418. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176419. /* See if space is available in any existing pool */
  176420. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176421. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176422. prev_hdr_ptr = NULL;
  176423. hdr_ptr = mem->small_list[pool_id];
  176424. while (hdr_ptr != NULL) {
  176425. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176426. break; /* found pool with enough space */
  176427. prev_hdr_ptr = hdr_ptr;
  176428. hdr_ptr = hdr_ptr->hdr.next;
  176429. }
  176430. /* Time to make a new pool? */
  176431. if (hdr_ptr == NULL) {
  176432. /* min_request is what we need now, slop is what will be leftover */
  176433. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176434. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176435. slop = first_pool_slop[pool_id];
  176436. else
  176437. slop = extra_pool_slop[pool_id];
  176438. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176439. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176440. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176441. /* Try to get space, if fail reduce slop and try again */
  176442. for (;;) {
  176443. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176444. if (hdr_ptr != NULL)
  176445. break;
  176446. slop /= 2;
  176447. if (slop < MIN_SLOP) /* give up when it gets real small */
  176448. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176449. }
  176450. mem->total_space_allocated += min_request + slop;
  176451. /* Success, initialize the new pool header and add to end of list */
  176452. hdr_ptr->hdr.next = NULL;
  176453. hdr_ptr->hdr.bytes_used = 0;
  176454. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176455. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176456. mem->small_list[pool_id] = hdr_ptr;
  176457. else
  176458. prev_hdr_ptr->hdr.next = hdr_ptr;
  176459. }
  176460. /* OK, allocate the object from the current pool */
  176461. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176462. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176463. hdr_ptr->hdr.bytes_used += sizeofobject;
  176464. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176465. return (void *) data_ptr;
  176466. }
  176467. /*
  176468. * Allocation of "large" objects.
  176469. *
  176470. * The external semantics of these are the same as "small" objects,
  176471. * except that FAR pointers are used on 80x86. However the pool
  176472. * management heuristics are quite different. We assume that each
  176473. * request is large enough that it may as well be passed directly to
  176474. * jpeg_get_large; the pool management just links everything together
  176475. * so that we can free it all on demand.
  176476. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176477. * structures. The routines that create these structures (see below)
  176478. * deliberately bunch rows together to ensure a large request size.
  176479. */
  176480. METHODDEF(void FAR *)
  176481. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176482. /* Allocate a "large" object */
  176483. {
  176484. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176485. large_pool_ptr hdr_ptr;
  176486. size_t odd_bytes;
  176487. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176488. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176489. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176490. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176491. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176492. if (odd_bytes > 0)
  176493. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176494. /* Always make a new pool */
  176495. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176496. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176497. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176498. SIZEOF(large_pool_hdr));
  176499. if (hdr_ptr == NULL)
  176500. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176501. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176502. /* Success, initialize the new pool header and add to list */
  176503. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176504. /* We maintain space counts in each pool header for statistical purposes,
  176505. * even though they are not needed for allocation.
  176506. */
  176507. hdr_ptr->hdr.bytes_used = sizeofobject;
  176508. hdr_ptr->hdr.bytes_left = 0;
  176509. mem->large_list[pool_id] = hdr_ptr;
  176510. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176511. }
  176512. /*
  176513. * Creation of 2-D sample arrays.
  176514. * The pointers are in near heap, the samples themselves in FAR heap.
  176515. *
  176516. * To minimize allocation overhead and to allow I/O of large contiguous
  176517. * blocks, we allocate the sample rows in groups of as many rows as possible
  176518. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176519. * NB: the virtual array control routines, later in this file, know about
  176520. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176521. * object so that it can be saved away if this sarray is the workspace for
  176522. * a virtual array.
  176523. */
  176524. METHODDEF(JSAMPARRAY)
  176525. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176526. JDIMENSION samplesperrow, JDIMENSION numrows)
  176527. /* Allocate a 2-D sample array */
  176528. {
  176529. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176530. JSAMPARRAY result;
  176531. JSAMPROW workspace;
  176532. JDIMENSION rowsperchunk, currow, i;
  176533. long ltemp;
  176534. /* Calculate max # of rows allowed in one allocation chunk */
  176535. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176536. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176537. if (ltemp <= 0)
  176538. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176539. if (ltemp < (long) numrows)
  176540. rowsperchunk = (JDIMENSION) ltemp;
  176541. else
  176542. rowsperchunk = numrows;
  176543. mem->last_rowsperchunk = rowsperchunk;
  176544. /* Get space for row pointers (small object) */
  176545. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176546. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176547. /* Get the rows themselves (large objects) */
  176548. currow = 0;
  176549. while (currow < numrows) {
  176550. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176551. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176552. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176553. * SIZEOF(JSAMPLE)));
  176554. for (i = rowsperchunk; i > 0; i--) {
  176555. result[currow++] = workspace;
  176556. workspace += samplesperrow;
  176557. }
  176558. }
  176559. return result;
  176560. }
  176561. /*
  176562. * Creation of 2-D coefficient-block arrays.
  176563. * This is essentially the same as the code for sample arrays, above.
  176564. */
  176565. METHODDEF(JBLOCKARRAY)
  176566. alloc_barray (j_common_ptr cinfo, int pool_id,
  176567. JDIMENSION blocksperrow, JDIMENSION numrows)
  176568. /* Allocate a 2-D coefficient-block array */
  176569. {
  176570. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176571. JBLOCKARRAY result;
  176572. JBLOCKROW workspace;
  176573. JDIMENSION rowsperchunk, currow, i;
  176574. long ltemp;
  176575. /* Calculate max # of rows allowed in one allocation chunk */
  176576. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176577. ((long) blocksperrow * SIZEOF(JBLOCK));
  176578. if (ltemp <= 0)
  176579. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176580. if (ltemp < (long) numrows)
  176581. rowsperchunk = (JDIMENSION) ltemp;
  176582. else
  176583. rowsperchunk = numrows;
  176584. mem->last_rowsperchunk = rowsperchunk;
  176585. /* Get space for row pointers (small object) */
  176586. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176587. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176588. /* Get the rows themselves (large objects) */
  176589. currow = 0;
  176590. while (currow < numrows) {
  176591. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176592. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176593. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176594. * SIZEOF(JBLOCK)));
  176595. for (i = rowsperchunk; i > 0; i--) {
  176596. result[currow++] = workspace;
  176597. workspace += blocksperrow;
  176598. }
  176599. }
  176600. return result;
  176601. }
  176602. /*
  176603. * About virtual array management:
  176604. *
  176605. * The above "normal" array routines are only used to allocate strip buffers
  176606. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176607. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176608. * time, but the memory manager must save the whole array for repeated
  176609. * accesses. The intended implementation is that there is a strip buffer in
  176610. * memory (as high as is possible given the desired memory limit), plus a
  176611. * backing file that holds the rest of the array.
  176612. *
  176613. * The request_virt_array routines are told the total size of the image and
  176614. * the maximum number of rows that will be accessed at once. The in-memory
  176615. * buffer must be at least as large as the maxaccess value.
  176616. *
  176617. * The request routines create control blocks but not the in-memory buffers.
  176618. * That is postponed until realize_virt_arrays is called. At that time the
  176619. * total amount of space needed is known (approximately, anyway), so free
  176620. * memory can be divided up fairly.
  176621. *
  176622. * The access_virt_array routines are responsible for making a specific strip
  176623. * area accessible (after reading or writing the backing file, if necessary).
  176624. * Note that the access routines are told whether the caller intends to modify
  176625. * the accessed strip; during a read-only pass this saves having to rewrite
  176626. * data to disk. The access routines are also responsible for pre-zeroing
  176627. * any newly accessed rows, if pre-zeroing was requested.
  176628. *
  176629. * In current usage, the access requests are usually for nonoverlapping
  176630. * strips; that is, successive access start_row numbers differ by exactly
  176631. * num_rows = maxaccess. This means we can get good performance with simple
  176632. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176633. * of the access height; then there will never be accesses across bufferload
  176634. * boundaries. The code will still work with overlapping access requests,
  176635. * but it doesn't handle bufferload overlaps very efficiently.
  176636. */
  176637. METHODDEF(jvirt_sarray_ptr)
  176638. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176639. JDIMENSION samplesperrow, JDIMENSION numrows,
  176640. JDIMENSION maxaccess)
  176641. /* Request a virtual 2-D sample array */
  176642. {
  176643. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176644. jvirt_sarray_ptr result;
  176645. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176646. if (pool_id != JPOOL_IMAGE)
  176647. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176648. /* get control block */
  176649. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176650. SIZEOF(struct jvirt_sarray_control));
  176651. result->mem_buffer = NULL; /* marks array not yet realized */
  176652. result->rows_in_array = numrows;
  176653. result->samplesperrow = samplesperrow;
  176654. result->maxaccess = maxaccess;
  176655. result->pre_zero = pre_zero;
  176656. result->b_s_open = FALSE; /* no associated backing-store object */
  176657. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176658. mem->virt_sarray_list = result;
  176659. return result;
  176660. }
  176661. METHODDEF(jvirt_barray_ptr)
  176662. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176663. JDIMENSION blocksperrow, JDIMENSION numrows,
  176664. JDIMENSION maxaccess)
  176665. /* Request a virtual 2-D coefficient-block array */
  176666. {
  176667. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176668. jvirt_barray_ptr result;
  176669. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176670. if (pool_id != JPOOL_IMAGE)
  176671. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176672. /* get control block */
  176673. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176674. SIZEOF(struct jvirt_barray_control));
  176675. result->mem_buffer = NULL; /* marks array not yet realized */
  176676. result->rows_in_array = numrows;
  176677. result->blocksperrow = blocksperrow;
  176678. result->maxaccess = maxaccess;
  176679. result->pre_zero = pre_zero;
  176680. result->b_s_open = FALSE; /* no associated backing-store object */
  176681. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176682. mem->virt_barray_list = result;
  176683. return result;
  176684. }
  176685. METHODDEF(void)
  176686. realize_virt_arrays (j_common_ptr cinfo)
  176687. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176688. {
  176689. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176690. long space_per_minheight, maximum_space, avail_mem;
  176691. long minheights, max_minheights;
  176692. jvirt_sarray_ptr sptr;
  176693. jvirt_barray_ptr bptr;
  176694. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176695. * and the maximum space needed (full image height in each buffer).
  176696. * These may be of use to the system-dependent jpeg_mem_available routine.
  176697. */
  176698. space_per_minheight = 0;
  176699. maximum_space = 0;
  176700. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176701. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176702. space_per_minheight += (long) sptr->maxaccess *
  176703. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176704. maximum_space += (long) sptr->rows_in_array *
  176705. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176706. }
  176707. }
  176708. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176709. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176710. space_per_minheight += (long) bptr->maxaccess *
  176711. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176712. maximum_space += (long) bptr->rows_in_array *
  176713. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176714. }
  176715. }
  176716. if (space_per_minheight <= 0)
  176717. return; /* no unrealized arrays, no work */
  176718. /* Determine amount of memory to actually use; this is system-dependent. */
  176719. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176720. mem->total_space_allocated);
  176721. /* If the maximum space needed is available, make all the buffers full
  176722. * height; otherwise parcel it out with the same number of minheights
  176723. * in each buffer.
  176724. */
  176725. if (avail_mem >= maximum_space)
  176726. max_minheights = 1000000000L;
  176727. else {
  176728. max_minheights = avail_mem / space_per_minheight;
  176729. /* If there doesn't seem to be enough space, try to get the minimum
  176730. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176731. */
  176732. if (max_minheights <= 0)
  176733. max_minheights = 1;
  176734. }
  176735. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176736. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176737. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176738. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176739. if (minheights <= max_minheights) {
  176740. /* This buffer fits in memory */
  176741. sptr->rows_in_mem = sptr->rows_in_array;
  176742. } else {
  176743. /* It doesn't fit in memory, create backing store. */
  176744. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176745. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176746. (long) sptr->rows_in_array *
  176747. (long) sptr->samplesperrow *
  176748. (long) SIZEOF(JSAMPLE));
  176749. sptr->b_s_open = TRUE;
  176750. }
  176751. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176752. sptr->samplesperrow, sptr->rows_in_mem);
  176753. sptr->rowsperchunk = mem->last_rowsperchunk;
  176754. sptr->cur_start_row = 0;
  176755. sptr->first_undef_row = 0;
  176756. sptr->dirty = FALSE;
  176757. }
  176758. }
  176759. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176760. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176761. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176762. if (minheights <= max_minheights) {
  176763. /* This buffer fits in memory */
  176764. bptr->rows_in_mem = bptr->rows_in_array;
  176765. } else {
  176766. /* It doesn't fit in memory, create backing store. */
  176767. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176768. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176769. (long) bptr->rows_in_array *
  176770. (long) bptr->blocksperrow *
  176771. (long) SIZEOF(JBLOCK));
  176772. bptr->b_s_open = TRUE;
  176773. }
  176774. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176775. bptr->blocksperrow, bptr->rows_in_mem);
  176776. bptr->rowsperchunk = mem->last_rowsperchunk;
  176777. bptr->cur_start_row = 0;
  176778. bptr->first_undef_row = 0;
  176779. bptr->dirty = FALSE;
  176780. }
  176781. }
  176782. }
  176783. LOCAL(void)
  176784. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176785. /* Do backing store read or write of a virtual sample array */
  176786. {
  176787. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176788. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176789. file_offset = ptr->cur_start_row * bytesperrow;
  176790. /* Loop to read or write each allocation chunk in mem_buffer */
  176791. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176792. /* One chunk, but check for short chunk at end of buffer */
  176793. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176794. /* Transfer no more than is currently defined */
  176795. thisrow = (long) ptr->cur_start_row + i;
  176796. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176797. /* Transfer no more than fits in file */
  176798. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176799. if (rows <= 0) /* this chunk might be past end of file! */
  176800. break;
  176801. byte_count = rows * bytesperrow;
  176802. if (writing)
  176803. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176804. (void FAR *) ptr->mem_buffer[i],
  176805. file_offset, byte_count);
  176806. else
  176807. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176808. (void FAR *) ptr->mem_buffer[i],
  176809. file_offset, byte_count);
  176810. file_offset += byte_count;
  176811. }
  176812. }
  176813. LOCAL(void)
  176814. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176815. /* Do backing store read or write of a virtual coefficient-block array */
  176816. {
  176817. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176818. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176819. file_offset = ptr->cur_start_row * bytesperrow;
  176820. /* Loop to read or write each allocation chunk in mem_buffer */
  176821. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176822. /* One chunk, but check for short chunk at end of buffer */
  176823. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176824. /* Transfer no more than is currently defined */
  176825. thisrow = (long) ptr->cur_start_row + i;
  176826. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176827. /* Transfer no more than fits in file */
  176828. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176829. if (rows <= 0) /* this chunk might be past end of file! */
  176830. break;
  176831. byte_count = rows * bytesperrow;
  176832. if (writing)
  176833. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176834. (void FAR *) ptr->mem_buffer[i],
  176835. file_offset, byte_count);
  176836. else
  176837. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176838. (void FAR *) ptr->mem_buffer[i],
  176839. file_offset, byte_count);
  176840. file_offset += byte_count;
  176841. }
  176842. }
  176843. METHODDEF(JSAMPARRAY)
  176844. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176845. JDIMENSION start_row, JDIMENSION num_rows,
  176846. boolean writable)
  176847. /* Access the part of a virtual sample array starting at start_row */
  176848. /* and extending for num_rows rows. writable is true if */
  176849. /* caller intends to modify the accessed area. */
  176850. {
  176851. JDIMENSION end_row = start_row + num_rows;
  176852. JDIMENSION undef_row;
  176853. /* debugging check */
  176854. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176855. ptr->mem_buffer == NULL)
  176856. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176857. /* Make the desired part of the virtual array accessible */
  176858. if (start_row < ptr->cur_start_row ||
  176859. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176860. if (! ptr->b_s_open)
  176861. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176862. /* Flush old buffer contents if necessary */
  176863. if (ptr->dirty) {
  176864. do_sarray_io(cinfo, ptr, TRUE);
  176865. ptr->dirty = FALSE;
  176866. }
  176867. /* Decide what part of virtual array to access.
  176868. * Algorithm: if target address > current window, assume forward scan,
  176869. * load starting at target address. If target address < current window,
  176870. * assume backward scan, load so that target area is top of window.
  176871. * Note that when switching from forward write to forward read, will have
  176872. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176873. */
  176874. if (start_row > ptr->cur_start_row) {
  176875. ptr->cur_start_row = start_row;
  176876. } else {
  176877. /* use long arithmetic here to avoid overflow & unsigned problems */
  176878. long ltemp;
  176879. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176880. if (ltemp < 0)
  176881. ltemp = 0; /* don't fall off front end of file */
  176882. ptr->cur_start_row = (JDIMENSION) ltemp;
  176883. }
  176884. /* Read in the selected part of the array.
  176885. * During the initial write pass, we will do no actual read
  176886. * because the selected part is all undefined.
  176887. */
  176888. do_sarray_io(cinfo, ptr, FALSE);
  176889. }
  176890. /* Ensure the accessed part of the array is defined; prezero if needed.
  176891. * To improve locality of access, we only prezero the part of the array
  176892. * that the caller is about to access, not the entire in-memory array.
  176893. */
  176894. if (ptr->first_undef_row < end_row) {
  176895. if (ptr->first_undef_row < start_row) {
  176896. if (writable) /* writer skipped over a section of array */
  176897. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176898. undef_row = start_row; /* but reader is allowed to read ahead */
  176899. } else {
  176900. undef_row = ptr->first_undef_row;
  176901. }
  176902. if (writable)
  176903. ptr->first_undef_row = end_row;
  176904. if (ptr->pre_zero) {
  176905. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176906. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176907. end_row -= ptr->cur_start_row;
  176908. while (undef_row < end_row) {
  176909. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176910. undef_row++;
  176911. }
  176912. } else {
  176913. if (! writable) /* reader looking at undefined data */
  176914. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176915. }
  176916. }
  176917. /* Flag the buffer dirty if caller will write in it */
  176918. if (writable)
  176919. ptr->dirty = TRUE;
  176920. /* Return address of proper part of the buffer */
  176921. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176922. }
  176923. METHODDEF(JBLOCKARRAY)
  176924. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176925. JDIMENSION start_row, JDIMENSION num_rows,
  176926. boolean writable)
  176927. /* Access the part of a virtual block array starting at start_row */
  176928. /* and extending for num_rows rows. writable is true if */
  176929. /* caller intends to modify the accessed area. */
  176930. {
  176931. JDIMENSION end_row = start_row + num_rows;
  176932. JDIMENSION undef_row;
  176933. /* debugging check */
  176934. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176935. ptr->mem_buffer == NULL)
  176936. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176937. /* Make the desired part of the virtual array accessible */
  176938. if (start_row < ptr->cur_start_row ||
  176939. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176940. if (! ptr->b_s_open)
  176941. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176942. /* Flush old buffer contents if necessary */
  176943. if (ptr->dirty) {
  176944. do_barray_io(cinfo, ptr, TRUE);
  176945. ptr->dirty = FALSE;
  176946. }
  176947. /* Decide what part of virtual array to access.
  176948. * Algorithm: if target address > current window, assume forward scan,
  176949. * load starting at target address. If target address < current window,
  176950. * assume backward scan, load so that target area is top of window.
  176951. * Note that when switching from forward write to forward read, will have
  176952. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176953. */
  176954. if (start_row > ptr->cur_start_row) {
  176955. ptr->cur_start_row = start_row;
  176956. } else {
  176957. /* use long arithmetic here to avoid overflow & unsigned problems */
  176958. long ltemp;
  176959. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176960. if (ltemp < 0)
  176961. ltemp = 0; /* don't fall off front end of file */
  176962. ptr->cur_start_row = (JDIMENSION) ltemp;
  176963. }
  176964. /* Read in the selected part of the array.
  176965. * During the initial write pass, we will do no actual read
  176966. * because the selected part is all undefined.
  176967. */
  176968. do_barray_io(cinfo, ptr, FALSE);
  176969. }
  176970. /* Ensure the accessed part of the array is defined; prezero if needed.
  176971. * To improve locality of access, we only prezero the part of the array
  176972. * that the caller is about to access, not the entire in-memory array.
  176973. */
  176974. if (ptr->first_undef_row < end_row) {
  176975. if (ptr->first_undef_row < start_row) {
  176976. if (writable) /* writer skipped over a section of array */
  176977. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176978. undef_row = start_row; /* but reader is allowed to read ahead */
  176979. } else {
  176980. undef_row = ptr->first_undef_row;
  176981. }
  176982. if (writable)
  176983. ptr->first_undef_row = end_row;
  176984. if (ptr->pre_zero) {
  176985. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176986. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176987. end_row -= ptr->cur_start_row;
  176988. while (undef_row < end_row) {
  176989. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176990. undef_row++;
  176991. }
  176992. } else {
  176993. if (! writable) /* reader looking at undefined data */
  176994. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176995. }
  176996. }
  176997. /* Flag the buffer dirty if caller will write in it */
  176998. if (writable)
  176999. ptr->dirty = TRUE;
  177000. /* Return address of proper part of the buffer */
  177001. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  177002. }
  177003. /*
  177004. * Release all objects belonging to a specified pool.
  177005. */
  177006. METHODDEF(void)
  177007. free_pool (j_common_ptr cinfo, int pool_id)
  177008. {
  177009. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177010. small_pool_ptr shdr_ptr;
  177011. large_pool_ptr lhdr_ptr;
  177012. size_t space_freed;
  177013. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  177014. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  177015. #ifdef MEM_STATS
  177016. if (cinfo->err->trace_level > 1)
  177017. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  177018. #endif
  177019. /* If freeing IMAGE pool, close any virtual arrays first */
  177020. if (pool_id == JPOOL_IMAGE) {
  177021. jvirt_sarray_ptr sptr;
  177022. jvirt_barray_ptr bptr;
  177023. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  177024. if (sptr->b_s_open) { /* there may be no backing store */
  177025. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  177026. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  177027. }
  177028. }
  177029. mem->virt_sarray_list = NULL;
  177030. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  177031. if (bptr->b_s_open) { /* there may be no backing store */
  177032. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  177033. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  177034. }
  177035. }
  177036. mem->virt_barray_list = NULL;
  177037. }
  177038. /* Release large objects */
  177039. lhdr_ptr = mem->large_list[pool_id];
  177040. mem->large_list[pool_id] = NULL;
  177041. while (lhdr_ptr != NULL) {
  177042. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  177043. space_freed = lhdr_ptr->hdr.bytes_used +
  177044. lhdr_ptr->hdr.bytes_left +
  177045. SIZEOF(large_pool_hdr);
  177046. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  177047. mem->total_space_allocated -= space_freed;
  177048. lhdr_ptr = next_lhdr_ptr;
  177049. }
  177050. /* Release small objects */
  177051. shdr_ptr = mem->small_list[pool_id];
  177052. mem->small_list[pool_id] = NULL;
  177053. while (shdr_ptr != NULL) {
  177054. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  177055. space_freed = shdr_ptr->hdr.bytes_used +
  177056. shdr_ptr->hdr.bytes_left +
  177057. SIZEOF(small_pool_hdr);
  177058. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  177059. mem->total_space_allocated -= space_freed;
  177060. shdr_ptr = next_shdr_ptr;
  177061. }
  177062. }
  177063. /*
  177064. * Close up shop entirely.
  177065. * Note that this cannot be called unless cinfo->mem is non-NULL.
  177066. */
  177067. METHODDEF(void)
  177068. self_destruct (j_common_ptr cinfo)
  177069. {
  177070. int pool;
  177071. /* Close all backing store, release all memory.
  177072. * Releasing pools in reverse order might help avoid fragmentation
  177073. * with some (brain-damaged) malloc libraries.
  177074. */
  177075. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177076. free_pool(cinfo, pool);
  177077. }
  177078. /* Release the memory manager control block too. */
  177079. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  177080. cinfo->mem = NULL; /* ensures I will be called only once */
  177081. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177082. }
  177083. /*
  177084. * Memory manager initialization.
  177085. * When this is called, only the error manager pointer is valid in cinfo!
  177086. */
  177087. GLOBAL(void)
  177088. jinit_memory_mgr (j_common_ptr cinfo)
  177089. {
  177090. my_mem_ptr mem;
  177091. long max_to_use;
  177092. int pool;
  177093. size_t test_mac;
  177094. cinfo->mem = NULL; /* for safety if init fails */
  177095. /* Check for configuration errors.
  177096. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  177097. * doesn't reflect any real hardware alignment requirement.
  177098. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  177099. * in common if and only if X is a power of 2, ie has only one one-bit.
  177100. * Some compilers may give an "unreachable code" warning here; ignore it.
  177101. */
  177102. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  177103. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  177104. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  177105. * a multiple of SIZEOF(ALIGN_TYPE).
  177106. * Again, an "unreachable code" warning may be ignored here.
  177107. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  177108. */
  177109. test_mac = (size_t) MAX_ALLOC_CHUNK;
  177110. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  177111. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  177112. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  177113. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  177114. /* Attempt to allocate memory manager's control block */
  177115. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  177116. if (mem == NULL) {
  177117. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177118. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  177119. }
  177120. /* OK, fill in the method pointers */
  177121. mem->pub.alloc_small = alloc_small;
  177122. mem->pub.alloc_large = alloc_large;
  177123. mem->pub.alloc_sarray = alloc_sarray;
  177124. mem->pub.alloc_barray = alloc_barray;
  177125. mem->pub.request_virt_sarray = request_virt_sarray;
  177126. mem->pub.request_virt_barray = request_virt_barray;
  177127. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177128. mem->pub.access_virt_sarray = access_virt_sarray;
  177129. mem->pub.access_virt_barray = access_virt_barray;
  177130. mem->pub.free_pool = free_pool;
  177131. mem->pub.self_destruct = self_destruct;
  177132. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177133. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177134. /* Initialize working state */
  177135. mem->pub.max_memory_to_use = max_to_use;
  177136. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177137. mem->small_list[pool] = NULL;
  177138. mem->large_list[pool] = NULL;
  177139. }
  177140. mem->virt_sarray_list = NULL;
  177141. mem->virt_barray_list = NULL;
  177142. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177143. /* Declare ourselves open for business */
  177144. cinfo->mem = & mem->pub;
  177145. /* Check for an environment variable JPEGMEM; if found, override the
  177146. * default max_memory setting from jpeg_mem_init. Note that the
  177147. * surrounding application may again override this value.
  177148. * If your system doesn't support getenv(), define NO_GETENV to disable
  177149. * this feature.
  177150. */
  177151. #ifndef NO_GETENV
  177152. { char * memenv;
  177153. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177154. char ch = 'x';
  177155. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177156. if (ch == 'm' || ch == 'M')
  177157. max_to_use *= 1000L;
  177158. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177159. }
  177160. }
  177161. }
  177162. #endif
  177163. }
  177164. /*** End of inlined file: jmemmgr.c ***/
  177165. /*** Start of inlined file: jmemnobs.c ***/
  177166. #define JPEG_INTERNALS
  177167. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177168. extern void * malloc JPP((size_t size));
  177169. extern void free JPP((void *ptr));
  177170. #endif
  177171. /*
  177172. * Memory allocation and freeing are controlled by the regular library
  177173. * routines malloc() and free().
  177174. */
  177175. GLOBAL(void *)
  177176. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  177177. {
  177178. return (void *) malloc(sizeofobject);
  177179. }
  177180. GLOBAL(void)
  177181. jpeg_free_small (j_common_ptr , void * object, size_t)
  177182. {
  177183. free(object);
  177184. }
  177185. /*
  177186. * "Large" objects are treated the same as "small" ones.
  177187. * NB: although we include FAR keywords in the routine declarations,
  177188. * this file won't actually work in 80x86 small/medium model; at least,
  177189. * you probably won't be able to process useful-size images in only 64KB.
  177190. */
  177191. GLOBAL(void FAR *)
  177192. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  177193. {
  177194. return (void FAR *) malloc(sizeofobject);
  177195. }
  177196. GLOBAL(void)
  177197. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177198. {
  177199. free(object);
  177200. }
  177201. /*
  177202. * This routine computes the total memory space available for allocation.
  177203. * Here we always say, "we got all you want bud!"
  177204. */
  177205. GLOBAL(long)
  177206. jpeg_mem_available (j_common_ptr, long,
  177207. long max_bytes_needed, long)
  177208. {
  177209. return max_bytes_needed;
  177210. }
  177211. /*
  177212. * Backing store (temporary file) management.
  177213. * Since jpeg_mem_available always promised the moon,
  177214. * this should never be called and we can just error out.
  177215. */
  177216. GLOBAL(void)
  177217. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177218. long )
  177219. {
  177220. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177221. }
  177222. /*
  177223. * These routines take care of any system-dependent initialization and
  177224. * cleanup required. Here, there isn't any.
  177225. */
  177226. GLOBAL(long)
  177227. jpeg_mem_init (j_common_ptr)
  177228. {
  177229. return 0; /* just set max_memory_to_use to 0 */
  177230. }
  177231. GLOBAL(void)
  177232. jpeg_mem_term (j_common_ptr)
  177233. {
  177234. /* no work */
  177235. }
  177236. /*** End of inlined file: jmemnobs.c ***/
  177237. /*** Start of inlined file: jquant1.c ***/
  177238. #define JPEG_INTERNALS
  177239. #ifdef QUANT_1PASS_SUPPORTED
  177240. /*
  177241. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177242. * high quality, colormapped output capability. A 2-pass quantizer usually
  177243. * gives better visual quality; however, for quantized grayscale output this
  177244. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177245. * quantizer, though you can turn it off if you really want to.
  177246. *
  177247. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177248. * image. We use a map consisting of all combinations of Ncolors[i] color
  177249. * values for the i'th component. The Ncolors[] values are chosen so that
  177250. * their product, the total number of colors, is no more than that requested.
  177251. * (In most cases, the product will be somewhat less.)
  177252. *
  177253. * Since the colormap is orthogonal, the representative value for each color
  177254. * component can be determined without considering the other components;
  177255. * then these indexes can be combined into a colormap index by a standard
  177256. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177257. * can be precalculated and stored in the lookup table colorindex[].
  177258. * colorindex[i][j] maps pixel value j in component i to the nearest
  177259. * representative value (grid plane) for that component; this index is
  177260. * multiplied by the array stride for component i, so that the
  177261. * index of the colormap entry closest to a given pixel value is just
  177262. * sum( colorindex[component-number][pixel-component-value] )
  177263. * Aside from being fast, this scheme allows for variable spacing between
  177264. * representative values with no additional lookup cost.
  177265. *
  177266. * If gamma correction has been applied in color conversion, it might be wise
  177267. * to adjust the color grid spacing so that the representative colors are
  177268. * equidistant in linear space. At this writing, gamma correction is not
  177269. * implemented by jdcolor, so nothing is done here.
  177270. */
  177271. /* Declarations for ordered dithering.
  177272. *
  177273. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177274. * dithering is described in many references, for instance Dale Schumacher's
  177275. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177276. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177277. * "dither" value to the input pixel and then round the result to the nearest
  177278. * output value. The dither value is equivalent to (0.5 - threshold) times
  177279. * the distance between output values. For ordered dithering, we assume that
  177280. * the output colors are equally spaced; if not, results will probably be
  177281. * worse, since the dither may be too much or too little at a given point.
  177282. *
  177283. * The normal calculation would be to form pixel value + dither, range-limit
  177284. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177285. * We can skip the separate range-limiting step by extending the colorindex
  177286. * table in both directions.
  177287. */
  177288. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177289. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177290. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177291. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177292. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177293. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177294. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177295. /* Bayer's order-4 dither array. Generated by the code given in
  177296. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177297. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177298. */
  177299. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177300. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177301. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177302. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177303. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177304. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177305. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177306. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177307. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177308. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177309. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177310. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177311. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177312. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177313. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177314. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177315. };
  177316. /* Declarations for Floyd-Steinberg dithering.
  177317. *
  177318. * Errors are accumulated into the array fserrors[], at a resolution of
  177319. * 1/16th of a pixel count. The error at a given pixel is propagated
  177320. * to its not-yet-processed neighbors using the standard F-S fractions,
  177321. * ... (here) 7/16
  177322. * 3/16 5/16 1/16
  177323. * We work left-to-right on even rows, right-to-left on odd rows.
  177324. *
  177325. * We can get away with a single array (holding one row's worth of errors)
  177326. * by using it to store the current row's errors at pixel columns not yet
  177327. * processed, but the next row's errors at columns already processed. We
  177328. * need only a few extra variables to hold the errors immediately around the
  177329. * current column. (If we are lucky, those variables are in registers, but
  177330. * even if not, they're probably cheaper to access than array elements are.)
  177331. *
  177332. * The fserrors[] array is indexed [component#][position].
  177333. * We provide (#columns + 2) entries per component; the extra entry at each
  177334. * end saves us from special-casing the first and last pixels.
  177335. *
  177336. * Note: on a wide image, we might not have enough room in a PC's near data
  177337. * segment to hold the error array; so it is allocated with alloc_large.
  177338. */
  177339. #if BITS_IN_JSAMPLE == 8
  177340. typedef INT16 FSERROR; /* 16 bits should be enough */
  177341. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177342. #else
  177343. typedef INT32 FSERROR; /* may need more than 16 bits */
  177344. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177345. #endif
  177346. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177347. /* Private subobject */
  177348. #define MAX_Q_COMPS 4 /* max components I can handle */
  177349. typedef struct {
  177350. struct jpeg_color_quantizer pub; /* public fields */
  177351. /* Initially allocated colormap is saved here */
  177352. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177353. int sv_actual; /* number of entries in use */
  177354. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177355. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177356. * premultiplied as described above. Since colormap indexes must fit into
  177357. * JSAMPLEs, the entries of this array will too.
  177358. */
  177359. boolean is_padded; /* is the colorindex padded for odither? */
  177360. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177361. /* Variables for ordered dithering */
  177362. int row_index; /* cur row's vertical index in dither matrix */
  177363. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177364. /* Variables for Floyd-Steinberg dithering */
  177365. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177366. boolean on_odd_row; /* flag to remember which row we are on */
  177367. } my_cquantizer;
  177368. typedef my_cquantizer * my_cquantize_ptr;
  177369. /*
  177370. * Policy-making subroutines for create_colormap and create_colorindex.
  177371. * These routines determine the colormap to be used. The rest of the module
  177372. * only assumes that the colormap is orthogonal.
  177373. *
  177374. * * select_ncolors decides how to divvy up the available colors
  177375. * among the components.
  177376. * * output_value defines the set of representative values for a component.
  177377. * * largest_input_value defines the mapping from input values to
  177378. * representative values for a component.
  177379. * Note that the latter two routines may impose different policies for
  177380. * different components, though this is not currently done.
  177381. */
  177382. LOCAL(int)
  177383. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177384. /* Determine allocation of desired colors to components, */
  177385. /* and fill in Ncolors[] array to indicate choice. */
  177386. /* Return value is total number of colors (product of Ncolors[] values). */
  177387. {
  177388. int nc = cinfo->out_color_components; /* number of color components */
  177389. int max_colors = cinfo->desired_number_of_colors;
  177390. int total_colors, iroot, i, j;
  177391. boolean changed;
  177392. long temp;
  177393. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177394. /* We can allocate at least the nc'th root of max_colors per component. */
  177395. /* Compute floor(nc'th root of max_colors). */
  177396. iroot = 1;
  177397. do {
  177398. iroot++;
  177399. temp = iroot; /* set temp = iroot ** nc */
  177400. for (i = 1; i < nc; i++)
  177401. temp *= iroot;
  177402. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177403. iroot--; /* now iroot = floor(root) */
  177404. /* Must have at least 2 color values per component */
  177405. if (iroot < 2)
  177406. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177407. /* Initialize to iroot color values for each component */
  177408. total_colors = 1;
  177409. for (i = 0; i < nc; i++) {
  177410. Ncolors[i] = iroot;
  177411. total_colors *= iroot;
  177412. }
  177413. /* We may be able to increment the count for one or more components without
  177414. * exceeding max_colors, though we know not all can be incremented.
  177415. * Sometimes, the first component can be incremented more than once!
  177416. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177417. * In RGB colorspace, try to increment G first, then R, then B.
  177418. */
  177419. do {
  177420. changed = FALSE;
  177421. for (i = 0; i < nc; i++) {
  177422. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177423. /* calculate new total_colors if Ncolors[j] is incremented */
  177424. temp = total_colors / Ncolors[j];
  177425. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177426. if (temp > (long) max_colors)
  177427. break; /* won't fit, done with this pass */
  177428. Ncolors[j]++; /* OK, apply the increment */
  177429. total_colors = (int) temp;
  177430. changed = TRUE;
  177431. }
  177432. } while (changed);
  177433. return total_colors;
  177434. }
  177435. LOCAL(int)
  177436. output_value (j_decompress_ptr, int, int j, int maxj)
  177437. /* Return j'th output value, where j will range from 0 to maxj */
  177438. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177439. {
  177440. /* We always provide values 0 and MAXJSAMPLE for each component;
  177441. * any additional values are equally spaced between these limits.
  177442. * (Forcing the upper and lower values to the limits ensures that
  177443. * dithering can't produce a color outside the selected gamut.)
  177444. */
  177445. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177446. }
  177447. LOCAL(int)
  177448. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177449. /* Return largest input value that should map to j'th output value */
  177450. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177451. {
  177452. /* Breakpoints are halfway between values returned by output_value */
  177453. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177454. }
  177455. /*
  177456. * Create the colormap.
  177457. */
  177458. LOCAL(void)
  177459. create_colormap (j_decompress_ptr cinfo)
  177460. {
  177461. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177462. JSAMPARRAY colormap; /* Created colormap */
  177463. int total_colors; /* Number of distinct output colors */
  177464. int i,j,k, nci, blksize, blkdist, ptr, val;
  177465. /* Select number of colors for each component */
  177466. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177467. /* Report selected color counts */
  177468. if (cinfo->out_color_components == 3)
  177469. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177470. total_colors, cquantize->Ncolors[0],
  177471. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177472. else
  177473. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177474. /* Allocate and fill in the colormap. */
  177475. /* The colors are ordered in the map in standard row-major order, */
  177476. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177477. colormap = (*cinfo->mem->alloc_sarray)
  177478. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177479. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177480. /* blksize is number of adjacent repeated entries for a component */
  177481. /* blkdist is distance between groups of identical entries for a component */
  177482. blkdist = total_colors;
  177483. for (i = 0; i < cinfo->out_color_components; i++) {
  177484. /* fill in colormap entries for i'th color component */
  177485. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177486. blksize = blkdist / nci;
  177487. for (j = 0; j < nci; j++) {
  177488. /* Compute j'th output value (out of nci) for component */
  177489. val = output_value(cinfo, i, j, nci-1);
  177490. /* Fill in all colormap entries that have this value of this component */
  177491. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177492. /* fill in blksize entries beginning at ptr */
  177493. for (k = 0; k < blksize; k++)
  177494. colormap[i][ptr+k] = (JSAMPLE) val;
  177495. }
  177496. }
  177497. blkdist = blksize; /* blksize of this color is blkdist of next */
  177498. }
  177499. /* Save the colormap in private storage,
  177500. * where it will survive color quantization mode changes.
  177501. */
  177502. cquantize->sv_colormap = colormap;
  177503. cquantize->sv_actual = total_colors;
  177504. }
  177505. /*
  177506. * Create the color index table.
  177507. */
  177508. LOCAL(void)
  177509. create_colorindex (j_decompress_ptr cinfo)
  177510. {
  177511. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177512. JSAMPROW indexptr;
  177513. int i,j,k, nci, blksize, val, pad;
  177514. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177515. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177516. * This is not necessary in the other dithering modes. However, we
  177517. * flag whether it was done in case user changes dithering mode.
  177518. */
  177519. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177520. pad = MAXJSAMPLE*2;
  177521. cquantize->is_padded = TRUE;
  177522. } else {
  177523. pad = 0;
  177524. cquantize->is_padded = FALSE;
  177525. }
  177526. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177527. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177528. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177529. (JDIMENSION) cinfo->out_color_components);
  177530. /* blksize is number of adjacent repeated entries for a component */
  177531. blksize = cquantize->sv_actual;
  177532. for (i = 0; i < cinfo->out_color_components; i++) {
  177533. /* fill in colorindex entries for i'th color component */
  177534. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177535. blksize = blksize / nci;
  177536. /* adjust colorindex pointers to provide padding at negative indexes. */
  177537. if (pad)
  177538. cquantize->colorindex[i] += MAXJSAMPLE;
  177539. /* in loop, val = index of current output value, */
  177540. /* and k = largest j that maps to current val */
  177541. indexptr = cquantize->colorindex[i];
  177542. val = 0;
  177543. k = largest_input_value(cinfo, i, 0, nci-1);
  177544. for (j = 0; j <= MAXJSAMPLE; j++) {
  177545. while (j > k) /* advance val if past boundary */
  177546. k = largest_input_value(cinfo, i, ++val, nci-1);
  177547. /* premultiply so that no multiplication needed in main processing */
  177548. indexptr[j] = (JSAMPLE) (val * blksize);
  177549. }
  177550. /* Pad at both ends if necessary */
  177551. if (pad)
  177552. for (j = 1; j <= MAXJSAMPLE; j++) {
  177553. indexptr[-j] = indexptr[0];
  177554. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177555. }
  177556. }
  177557. }
  177558. /*
  177559. * Create an ordered-dither array for a component having ncolors
  177560. * distinct output values.
  177561. */
  177562. LOCAL(ODITHER_MATRIX_PTR)
  177563. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177564. {
  177565. ODITHER_MATRIX_PTR odither;
  177566. int j,k;
  177567. INT32 num,den;
  177568. odither = (ODITHER_MATRIX_PTR)
  177569. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177570. SIZEOF(ODITHER_MATRIX));
  177571. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177572. * Hence the dither value for the matrix cell with fill order f
  177573. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177574. * On 16-bit-int machine, be careful to avoid overflow.
  177575. */
  177576. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177577. for (j = 0; j < ODITHER_SIZE; j++) {
  177578. for (k = 0; k < ODITHER_SIZE; k++) {
  177579. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177580. * MAXJSAMPLE;
  177581. /* Ensure round towards zero despite C's lack of consistency
  177582. * about rounding negative values in integer division...
  177583. */
  177584. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177585. }
  177586. }
  177587. return odither;
  177588. }
  177589. /*
  177590. * Create the ordered-dither tables.
  177591. * Components having the same number of representative colors may
  177592. * share a dither table.
  177593. */
  177594. LOCAL(void)
  177595. create_odither_tables (j_decompress_ptr cinfo)
  177596. {
  177597. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177598. ODITHER_MATRIX_PTR odither;
  177599. int i, j, nci;
  177600. for (i = 0; i < cinfo->out_color_components; i++) {
  177601. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177602. odither = NULL; /* search for matching prior component */
  177603. for (j = 0; j < i; j++) {
  177604. if (nci == cquantize->Ncolors[j]) {
  177605. odither = cquantize->odither[j];
  177606. break;
  177607. }
  177608. }
  177609. if (odither == NULL) /* need a new table? */
  177610. odither = make_odither_array(cinfo, nci);
  177611. cquantize->odither[i] = odither;
  177612. }
  177613. }
  177614. /*
  177615. * Map some rows of pixels to the output colormapped representation.
  177616. */
  177617. METHODDEF(void)
  177618. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177619. JSAMPARRAY output_buf, int num_rows)
  177620. /* General case, no dithering */
  177621. {
  177622. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177623. JSAMPARRAY colorindex = cquantize->colorindex;
  177624. register int pixcode, ci;
  177625. register JSAMPROW ptrin, ptrout;
  177626. int row;
  177627. JDIMENSION col;
  177628. JDIMENSION width = cinfo->output_width;
  177629. register int nc = cinfo->out_color_components;
  177630. for (row = 0; row < num_rows; row++) {
  177631. ptrin = input_buf[row];
  177632. ptrout = output_buf[row];
  177633. for (col = width; col > 0; col--) {
  177634. pixcode = 0;
  177635. for (ci = 0; ci < nc; ci++) {
  177636. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177637. }
  177638. *ptrout++ = (JSAMPLE) pixcode;
  177639. }
  177640. }
  177641. }
  177642. METHODDEF(void)
  177643. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177644. JSAMPARRAY output_buf, int num_rows)
  177645. /* Fast path for out_color_components==3, no dithering */
  177646. {
  177647. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177648. register int pixcode;
  177649. register JSAMPROW ptrin, ptrout;
  177650. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177651. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177652. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177653. int row;
  177654. JDIMENSION col;
  177655. JDIMENSION width = cinfo->output_width;
  177656. for (row = 0; row < num_rows; row++) {
  177657. ptrin = input_buf[row];
  177658. ptrout = output_buf[row];
  177659. for (col = width; col > 0; col--) {
  177660. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177661. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177662. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177663. *ptrout++ = (JSAMPLE) pixcode;
  177664. }
  177665. }
  177666. }
  177667. METHODDEF(void)
  177668. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177669. JSAMPARRAY output_buf, int num_rows)
  177670. /* General case, with ordered dithering */
  177671. {
  177672. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177673. register JSAMPROW input_ptr;
  177674. register JSAMPROW output_ptr;
  177675. JSAMPROW colorindex_ci;
  177676. int * dither; /* points to active row of dither matrix */
  177677. int row_index, col_index; /* current indexes into dither matrix */
  177678. int nc = cinfo->out_color_components;
  177679. int ci;
  177680. int row;
  177681. JDIMENSION col;
  177682. JDIMENSION width = cinfo->output_width;
  177683. for (row = 0; row < num_rows; row++) {
  177684. /* Initialize output values to 0 so can process components separately */
  177685. jzero_far((void FAR *) output_buf[row],
  177686. (size_t) (width * SIZEOF(JSAMPLE)));
  177687. row_index = cquantize->row_index;
  177688. for (ci = 0; ci < nc; ci++) {
  177689. input_ptr = input_buf[row] + ci;
  177690. output_ptr = output_buf[row];
  177691. colorindex_ci = cquantize->colorindex[ci];
  177692. dither = cquantize->odither[ci][row_index];
  177693. col_index = 0;
  177694. for (col = width; col > 0; col--) {
  177695. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177696. * select output value, accumulate into output code for this pixel.
  177697. * Range-limiting need not be done explicitly, as we have extended
  177698. * the colorindex table to produce the right answers for out-of-range
  177699. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177700. * required amount of padding.
  177701. */
  177702. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177703. input_ptr += nc;
  177704. output_ptr++;
  177705. col_index = (col_index + 1) & ODITHER_MASK;
  177706. }
  177707. }
  177708. /* Advance row index for next row */
  177709. row_index = (row_index + 1) & ODITHER_MASK;
  177710. cquantize->row_index = row_index;
  177711. }
  177712. }
  177713. METHODDEF(void)
  177714. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177715. JSAMPARRAY output_buf, int num_rows)
  177716. /* Fast path for out_color_components==3, with ordered dithering */
  177717. {
  177718. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177719. register int pixcode;
  177720. register JSAMPROW input_ptr;
  177721. register JSAMPROW output_ptr;
  177722. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177723. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177724. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177725. int * dither0; /* points to active row of dither matrix */
  177726. int * dither1;
  177727. int * dither2;
  177728. int row_index, col_index; /* current indexes into dither matrix */
  177729. int row;
  177730. JDIMENSION col;
  177731. JDIMENSION width = cinfo->output_width;
  177732. for (row = 0; row < num_rows; row++) {
  177733. row_index = cquantize->row_index;
  177734. input_ptr = input_buf[row];
  177735. output_ptr = output_buf[row];
  177736. dither0 = cquantize->odither[0][row_index];
  177737. dither1 = cquantize->odither[1][row_index];
  177738. dither2 = cquantize->odither[2][row_index];
  177739. col_index = 0;
  177740. for (col = width; col > 0; col--) {
  177741. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177742. dither0[col_index]]);
  177743. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177744. dither1[col_index]]);
  177745. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177746. dither2[col_index]]);
  177747. *output_ptr++ = (JSAMPLE) pixcode;
  177748. col_index = (col_index + 1) & ODITHER_MASK;
  177749. }
  177750. row_index = (row_index + 1) & ODITHER_MASK;
  177751. cquantize->row_index = row_index;
  177752. }
  177753. }
  177754. METHODDEF(void)
  177755. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177756. JSAMPARRAY output_buf, int num_rows)
  177757. /* General case, with Floyd-Steinberg dithering */
  177758. {
  177759. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177760. register LOCFSERROR cur; /* current error or pixel value */
  177761. LOCFSERROR belowerr; /* error for pixel below cur */
  177762. LOCFSERROR bpreverr; /* error for below/prev col */
  177763. LOCFSERROR bnexterr; /* error for below/next col */
  177764. LOCFSERROR delta;
  177765. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177766. register JSAMPROW input_ptr;
  177767. register JSAMPROW output_ptr;
  177768. JSAMPROW colorindex_ci;
  177769. JSAMPROW colormap_ci;
  177770. int pixcode;
  177771. int nc = cinfo->out_color_components;
  177772. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177773. int dirnc; /* dir * nc */
  177774. int ci;
  177775. int row;
  177776. JDIMENSION col;
  177777. JDIMENSION width = cinfo->output_width;
  177778. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177779. SHIFT_TEMPS
  177780. for (row = 0; row < num_rows; row++) {
  177781. /* Initialize output values to 0 so can process components separately */
  177782. jzero_far((void FAR *) output_buf[row],
  177783. (size_t) (width * SIZEOF(JSAMPLE)));
  177784. for (ci = 0; ci < nc; ci++) {
  177785. input_ptr = input_buf[row] + ci;
  177786. output_ptr = output_buf[row];
  177787. if (cquantize->on_odd_row) {
  177788. /* work right to left in this row */
  177789. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177790. output_ptr += width-1;
  177791. dir = -1;
  177792. dirnc = -nc;
  177793. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177794. } else {
  177795. /* work left to right in this row */
  177796. dir = 1;
  177797. dirnc = nc;
  177798. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177799. }
  177800. colorindex_ci = cquantize->colorindex[ci];
  177801. colormap_ci = cquantize->sv_colormap[ci];
  177802. /* Preset error values: no error propagated to first pixel from left */
  177803. cur = 0;
  177804. /* and no error propagated to row below yet */
  177805. belowerr = bpreverr = 0;
  177806. for (col = width; col > 0; col--) {
  177807. /* cur holds the error propagated from the previous pixel on the
  177808. * current line. Add the error propagated from the previous line
  177809. * to form the complete error correction term for this pixel, and
  177810. * round the error term (which is expressed * 16) to an integer.
  177811. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177812. * for either sign of the error value.
  177813. * Note: errorptr points to *previous* column's array entry.
  177814. */
  177815. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177816. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177817. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177818. * of the range_limit array.
  177819. */
  177820. cur += GETJSAMPLE(*input_ptr);
  177821. cur = GETJSAMPLE(range_limit[cur]);
  177822. /* Select output value, accumulate into output code for this pixel */
  177823. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177824. *output_ptr += (JSAMPLE) pixcode;
  177825. /* Compute actual representation error at this pixel */
  177826. /* Note: we can do this even though we don't have the final */
  177827. /* pixel code, because the colormap is orthogonal. */
  177828. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177829. /* Compute error fractions to be propagated to adjacent pixels.
  177830. * Add these into the running sums, and simultaneously shift the
  177831. * next-line error sums left by 1 column.
  177832. */
  177833. bnexterr = cur;
  177834. delta = cur * 2;
  177835. cur += delta; /* form error * 3 */
  177836. errorptr[0] = (FSERROR) (bpreverr + cur);
  177837. cur += delta; /* form error * 5 */
  177838. bpreverr = belowerr + cur;
  177839. belowerr = bnexterr;
  177840. cur += delta; /* form error * 7 */
  177841. /* At this point cur contains the 7/16 error value to be propagated
  177842. * to the next pixel on the current line, and all the errors for the
  177843. * next line have been shifted over. We are therefore ready to move on.
  177844. */
  177845. input_ptr += dirnc; /* advance input ptr to next column */
  177846. output_ptr += dir; /* advance output ptr to next column */
  177847. errorptr += dir; /* advance errorptr to current column */
  177848. }
  177849. /* Post-loop cleanup: we must unload the final error value into the
  177850. * final fserrors[] entry. Note we need not unload belowerr because
  177851. * it is for the dummy column before or after the actual array.
  177852. */
  177853. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177854. }
  177855. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177856. }
  177857. }
  177858. /*
  177859. * Allocate workspace for Floyd-Steinberg errors.
  177860. */
  177861. LOCAL(void)
  177862. alloc_fs_workspace (j_decompress_ptr cinfo)
  177863. {
  177864. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177865. size_t arraysize;
  177866. int i;
  177867. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177868. for (i = 0; i < cinfo->out_color_components; i++) {
  177869. cquantize->fserrors[i] = (FSERRPTR)
  177870. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177871. }
  177872. }
  177873. /*
  177874. * Initialize for one-pass color quantization.
  177875. */
  177876. METHODDEF(void)
  177877. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177878. {
  177879. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177880. size_t arraysize;
  177881. int i;
  177882. /* Install my colormap. */
  177883. cinfo->colormap = cquantize->sv_colormap;
  177884. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177885. /* Initialize for desired dithering mode. */
  177886. switch (cinfo->dither_mode) {
  177887. case JDITHER_NONE:
  177888. if (cinfo->out_color_components == 3)
  177889. cquantize->pub.color_quantize = color_quantize3;
  177890. else
  177891. cquantize->pub.color_quantize = color_quantize;
  177892. break;
  177893. case JDITHER_ORDERED:
  177894. if (cinfo->out_color_components == 3)
  177895. cquantize->pub.color_quantize = quantize3_ord_dither;
  177896. else
  177897. cquantize->pub.color_quantize = quantize_ord_dither;
  177898. cquantize->row_index = 0; /* initialize state for ordered dither */
  177899. /* If user changed to ordered dither from another mode,
  177900. * we must recreate the color index table with padding.
  177901. * This will cost extra space, but probably isn't very likely.
  177902. */
  177903. if (! cquantize->is_padded)
  177904. create_colorindex(cinfo);
  177905. /* Create ordered-dither tables if we didn't already. */
  177906. if (cquantize->odither[0] == NULL)
  177907. create_odither_tables(cinfo);
  177908. break;
  177909. case JDITHER_FS:
  177910. cquantize->pub.color_quantize = quantize_fs_dither;
  177911. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177912. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177913. if (cquantize->fserrors[0] == NULL)
  177914. alloc_fs_workspace(cinfo);
  177915. /* Initialize the propagated errors to zero. */
  177916. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177917. for (i = 0; i < cinfo->out_color_components; i++)
  177918. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177919. break;
  177920. default:
  177921. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177922. break;
  177923. }
  177924. }
  177925. /*
  177926. * Finish up at the end of the pass.
  177927. */
  177928. METHODDEF(void)
  177929. finish_pass_1_quant (j_decompress_ptr)
  177930. {
  177931. /* no work in 1-pass case */
  177932. }
  177933. /*
  177934. * Switch to a new external colormap between output passes.
  177935. * Shouldn't get to this module!
  177936. */
  177937. METHODDEF(void)
  177938. new_color_map_1_quant (j_decompress_ptr cinfo)
  177939. {
  177940. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177941. }
  177942. /*
  177943. * Module initialization routine for 1-pass color quantization.
  177944. */
  177945. GLOBAL(void)
  177946. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177947. {
  177948. my_cquantize_ptr cquantize;
  177949. cquantize = (my_cquantize_ptr)
  177950. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177951. SIZEOF(my_cquantizer));
  177952. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177953. cquantize->pub.start_pass = start_pass_1_quant;
  177954. cquantize->pub.finish_pass = finish_pass_1_quant;
  177955. cquantize->pub.new_color_map = new_color_map_1_quant;
  177956. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177957. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177958. /* Make sure my internal arrays won't overflow */
  177959. if (cinfo->out_color_components > MAX_Q_COMPS)
  177960. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177961. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177962. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177963. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177964. /* Create the colormap and color index table. */
  177965. create_colormap(cinfo);
  177966. create_colorindex(cinfo);
  177967. /* Allocate Floyd-Steinberg workspace now if requested.
  177968. * We do this now since it is FAR storage and may affect the memory
  177969. * manager's space calculations. If the user changes to FS dither
  177970. * mode in a later pass, we will allocate the space then, and will
  177971. * possibly overrun the max_memory_to_use setting.
  177972. */
  177973. if (cinfo->dither_mode == JDITHER_FS)
  177974. alloc_fs_workspace(cinfo);
  177975. }
  177976. #endif /* QUANT_1PASS_SUPPORTED */
  177977. /*** End of inlined file: jquant1.c ***/
  177978. /*** Start of inlined file: jquant2.c ***/
  177979. #define JPEG_INTERNALS
  177980. #ifdef QUANT_2PASS_SUPPORTED
  177981. /*
  177982. * This module implements the well-known Heckbert paradigm for color
  177983. * quantization. Most of the ideas used here can be traced back to
  177984. * Heckbert's seminal paper
  177985. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177986. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177987. *
  177988. * In the first pass over the image, we accumulate a histogram showing the
  177989. * usage count of each possible color. To keep the histogram to a reasonable
  177990. * size, we reduce the precision of the input; typical practice is to retain
  177991. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177992. * in the same histogram cell.
  177993. *
  177994. * Next, the color-selection step begins with a box representing the whole
  177995. * color space, and repeatedly splits the "largest" remaining box until we
  177996. * have as many boxes as desired colors. Then the mean color in each
  177997. * remaining box becomes one of the possible output colors.
  177998. *
  177999. * The second pass over the image maps each input pixel to the closest output
  178000. * color (optionally after applying a Floyd-Steinberg dithering correction).
  178001. * This mapping is logically trivial, but making it go fast enough requires
  178002. * considerable care.
  178003. *
  178004. * Heckbert-style quantizers vary a good deal in their policies for choosing
  178005. * the "largest" box and deciding where to cut it. The particular policies
  178006. * used here have proved out well in experimental comparisons, but better ones
  178007. * may yet be found.
  178008. *
  178009. * In earlier versions of the IJG code, this module quantized in YCbCr color
  178010. * space, processing the raw upsampled data without a color conversion step.
  178011. * This allowed the color conversion math to be done only once per colormap
  178012. * entry, not once per pixel. However, that optimization precluded other
  178013. * useful optimizations (such as merging color conversion with upsampling)
  178014. * and it also interfered with desired capabilities such as quantizing to an
  178015. * externally-supplied colormap. We have therefore abandoned that approach.
  178016. * The present code works in the post-conversion color space, typically RGB.
  178017. *
  178018. * To improve the visual quality of the results, we actually work in scaled
  178019. * RGB space, giving G distances more weight than R, and R in turn more than
  178020. * B. To do everything in integer math, we must use integer scale factors.
  178021. * The 2/3/1 scale factors used here correspond loosely to the relative
  178022. * weights of the colors in the NTSC grayscale equation.
  178023. * If you want to use this code to quantize a non-RGB color space, you'll
  178024. * probably need to change these scale factors.
  178025. */
  178026. #define R_SCALE 2 /* scale R distances by this much */
  178027. #define G_SCALE 3 /* scale G distances by this much */
  178028. #define B_SCALE 1 /* and B by this much */
  178029. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  178030. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  178031. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  178032. * you'll get compile errors until you extend this logic. In that case
  178033. * you'll probably want to tweak the histogram sizes too.
  178034. */
  178035. #if RGB_RED == 0
  178036. #define C0_SCALE R_SCALE
  178037. #endif
  178038. #if RGB_BLUE == 0
  178039. #define C0_SCALE B_SCALE
  178040. #endif
  178041. #if RGB_GREEN == 1
  178042. #define C1_SCALE G_SCALE
  178043. #endif
  178044. #if RGB_RED == 2
  178045. #define C2_SCALE R_SCALE
  178046. #endif
  178047. #if RGB_BLUE == 2
  178048. #define C2_SCALE B_SCALE
  178049. #endif
  178050. /*
  178051. * First we have the histogram data structure and routines for creating it.
  178052. *
  178053. * The number of bits of precision can be adjusted by changing these symbols.
  178054. * We recommend keeping 6 bits for G and 5 each for R and B.
  178055. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  178056. * better results; if you are short of memory, 5 bits all around will save
  178057. * some space but degrade the results.
  178058. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  178059. * (preferably unsigned long) for each cell. In practice this is overkill;
  178060. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  178061. * and clamping those that do overflow to the maximum value will give close-
  178062. * enough results. This reduces the recommended histogram size from 256Kb
  178063. * to 128Kb, which is a useful savings on PC-class machines.
  178064. * (In the second pass the histogram space is re-used for pixel mapping data;
  178065. * in that capacity, each cell must be able to store zero to the number of
  178066. * desired colors. 16 bits/cell is plenty for that too.)
  178067. * Since the JPEG code is intended to run in small memory model on 80x86
  178068. * machines, we can't just allocate the histogram in one chunk. Instead
  178069. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  178070. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  178071. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  178072. * on 80x86 machines, the pointer row is in near memory but the actual
  178073. * arrays are in far memory (same arrangement as we use for image arrays).
  178074. */
  178075. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  178076. /* These will do the right thing for either R,G,B or B,G,R color order,
  178077. * but you may not like the results for other color orders.
  178078. */
  178079. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  178080. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  178081. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  178082. /* Number of elements along histogram axes. */
  178083. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  178084. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  178085. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  178086. /* These are the amounts to shift an input value to get a histogram index. */
  178087. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  178088. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  178089. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  178090. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  178091. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  178092. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  178093. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  178094. typedef hist2d * hist3d; /* type for top-level pointer */
  178095. /* Declarations for Floyd-Steinberg dithering.
  178096. *
  178097. * Errors are accumulated into the array fserrors[], at a resolution of
  178098. * 1/16th of a pixel count. The error at a given pixel is propagated
  178099. * to its not-yet-processed neighbors using the standard F-S fractions,
  178100. * ... (here) 7/16
  178101. * 3/16 5/16 1/16
  178102. * We work left-to-right on even rows, right-to-left on odd rows.
  178103. *
  178104. * We can get away with a single array (holding one row's worth of errors)
  178105. * by using it to store the current row's errors at pixel columns not yet
  178106. * processed, but the next row's errors at columns already processed. We
  178107. * need only a few extra variables to hold the errors immediately around the
  178108. * current column. (If we are lucky, those variables are in registers, but
  178109. * even if not, they're probably cheaper to access than array elements are.)
  178110. *
  178111. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  178112. * each end saves us from special-casing the first and last pixels.
  178113. * Each entry is three values long, one value for each color component.
  178114. *
  178115. * Note: on a wide image, we might not have enough room in a PC's near data
  178116. * segment to hold the error array; so it is allocated with alloc_large.
  178117. */
  178118. #if BITS_IN_JSAMPLE == 8
  178119. typedef INT16 FSERROR; /* 16 bits should be enough */
  178120. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178121. #else
  178122. typedef INT32 FSERROR; /* may need more than 16 bits */
  178123. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178124. #endif
  178125. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178126. /* Private subobject */
  178127. typedef struct {
  178128. struct jpeg_color_quantizer pub; /* public fields */
  178129. /* Space for the eventually created colormap is stashed here */
  178130. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178131. int desired; /* desired # of colors = size of colormap */
  178132. /* Variables for accumulating image statistics */
  178133. hist3d histogram; /* pointer to the histogram */
  178134. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178135. /* Variables for Floyd-Steinberg dithering */
  178136. FSERRPTR fserrors; /* accumulated errors */
  178137. boolean on_odd_row; /* flag to remember which row we are on */
  178138. int * error_limiter; /* table for clamping the applied error */
  178139. } my_cquantizer2;
  178140. typedef my_cquantizer2 * my_cquantize_ptr2;
  178141. /*
  178142. * Prescan some rows of pixels.
  178143. * In this module the prescan simply updates the histogram, which has been
  178144. * initialized to zeroes by start_pass.
  178145. * An output_buf parameter is required by the method signature, but no data
  178146. * is actually output (in fact the buffer controller is probably passing a
  178147. * NULL pointer).
  178148. */
  178149. METHODDEF(void)
  178150. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178151. JSAMPARRAY, int num_rows)
  178152. {
  178153. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178154. register JSAMPROW ptr;
  178155. register histptr histp;
  178156. register hist3d histogram = cquantize->histogram;
  178157. int row;
  178158. JDIMENSION col;
  178159. JDIMENSION width = cinfo->output_width;
  178160. for (row = 0; row < num_rows; row++) {
  178161. ptr = input_buf[row];
  178162. for (col = width; col > 0; col--) {
  178163. /* get pixel value and index into the histogram */
  178164. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178165. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178166. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178167. /* increment, check for overflow and undo increment if so. */
  178168. if (++(*histp) <= 0)
  178169. (*histp)--;
  178170. ptr += 3;
  178171. }
  178172. }
  178173. }
  178174. /*
  178175. * Next we have the really interesting routines: selection of a colormap
  178176. * given the completed histogram.
  178177. * These routines work with a list of "boxes", each representing a rectangular
  178178. * subset of the input color space (to histogram precision).
  178179. */
  178180. typedef struct {
  178181. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178182. int c0min, c0max;
  178183. int c1min, c1max;
  178184. int c2min, c2max;
  178185. /* The volume (actually 2-norm) of the box */
  178186. INT32 volume;
  178187. /* The number of nonzero histogram cells within this box */
  178188. long colorcount;
  178189. } box;
  178190. typedef box * boxptr;
  178191. LOCAL(boxptr)
  178192. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178193. /* Find the splittable box with the largest color population */
  178194. /* Returns NULL if no splittable boxes remain */
  178195. {
  178196. register boxptr boxp;
  178197. register int i;
  178198. register long maxc = 0;
  178199. boxptr which = NULL;
  178200. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178201. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178202. which = boxp;
  178203. maxc = boxp->colorcount;
  178204. }
  178205. }
  178206. return which;
  178207. }
  178208. LOCAL(boxptr)
  178209. find_biggest_volume (boxptr boxlist, int numboxes)
  178210. /* Find the splittable box with the largest (scaled) volume */
  178211. /* Returns NULL if no splittable boxes remain */
  178212. {
  178213. register boxptr boxp;
  178214. register int i;
  178215. register INT32 maxv = 0;
  178216. boxptr which = NULL;
  178217. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178218. if (boxp->volume > maxv) {
  178219. which = boxp;
  178220. maxv = boxp->volume;
  178221. }
  178222. }
  178223. return which;
  178224. }
  178225. LOCAL(void)
  178226. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178227. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178228. /* and recompute its volume and population */
  178229. {
  178230. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178231. hist3d histogram = cquantize->histogram;
  178232. histptr histp;
  178233. int c0,c1,c2;
  178234. int c0min,c0max,c1min,c1max,c2min,c2max;
  178235. INT32 dist0,dist1,dist2;
  178236. long ccount;
  178237. c0min = boxp->c0min; c0max = boxp->c0max;
  178238. c1min = boxp->c1min; c1max = boxp->c1max;
  178239. c2min = boxp->c2min; c2max = boxp->c2max;
  178240. if (c0max > c0min)
  178241. for (c0 = c0min; c0 <= c0max; c0++)
  178242. for (c1 = c1min; c1 <= c1max; c1++) {
  178243. histp = & histogram[c0][c1][c2min];
  178244. for (c2 = c2min; c2 <= c2max; c2++)
  178245. if (*histp++ != 0) {
  178246. boxp->c0min = c0min = c0;
  178247. goto have_c0min;
  178248. }
  178249. }
  178250. have_c0min:
  178251. if (c0max > c0min)
  178252. for (c0 = c0max; c0 >= c0min; c0--)
  178253. for (c1 = c1min; c1 <= c1max; c1++) {
  178254. histp = & histogram[c0][c1][c2min];
  178255. for (c2 = c2min; c2 <= c2max; c2++)
  178256. if (*histp++ != 0) {
  178257. boxp->c0max = c0max = c0;
  178258. goto have_c0max;
  178259. }
  178260. }
  178261. have_c0max:
  178262. if (c1max > c1min)
  178263. for (c1 = c1min; c1 <= c1max; c1++)
  178264. for (c0 = c0min; c0 <= c0max; c0++) {
  178265. histp = & histogram[c0][c1][c2min];
  178266. for (c2 = c2min; c2 <= c2max; c2++)
  178267. if (*histp++ != 0) {
  178268. boxp->c1min = c1min = c1;
  178269. goto have_c1min;
  178270. }
  178271. }
  178272. have_c1min:
  178273. if (c1max > c1min)
  178274. for (c1 = c1max; c1 >= c1min; c1--)
  178275. for (c0 = c0min; c0 <= c0max; c0++) {
  178276. histp = & histogram[c0][c1][c2min];
  178277. for (c2 = c2min; c2 <= c2max; c2++)
  178278. if (*histp++ != 0) {
  178279. boxp->c1max = c1max = c1;
  178280. goto have_c1max;
  178281. }
  178282. }
  178283. have_c1max:
  178284. if (c2max > c2min)
  178285. for (c2 = c2min; c2 <= c2max; c2++)
  178286. for (c0 = c0min; c0 <= c0max; c0++) {
  178287. histp = & histogram[c0][c1min][c2];
  178288. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178289. if (*histp != 0) {
  178290. boxp->c2min = c2min = c2;
  178291. goto have_c2min;
  178292. }
  178293. }
  178294. have_c2min:
  178295. if (c2max > c2min)
  178296. for (c2 = c2max; c2 >= c2min; c2--)
  178297. for (c0 = c0min; c0 <= c0max; c0++) {
  178298. histp = & histogram[c0][c1min][c2];
  178299. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178300. if (*histp != 0) {
  178301. boxp->c2max = c2max = c2;
  178302. goto have_c2max;
  178303. }
  178304. }
  178305. have_c2max:
  178306. /* Update box volume.
  178307. * We use 2-norm rather than real volume here; this biases the method
  178308. * against making long narrow boxes, and it has the side benefit that
  178309. * a box is splittable iff norm > 0.
  178310. * Since the differences are expressed in histogram-cell units,
  178311. * we have to shift back to JSAMPLE units to get consistent distances;
  178312. * after which, we scale according to the selected distance scale factors.
  178313. */
  178314. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178315. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178316. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178317. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178318. /* Now scan remaining volume of box and compute population */
  178319. ccount = 0;
  178320. for (c0 = c0min; c0 <= c0max; c0++)
  178321. for (c1 = c1min; c1 <= c1max; c1++) {
  178322. histp = & histogram[c0][c1][c2min];
  178323. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178324. if (*histp != 0) {
  178325. ccount++;
  178326. }
  178327. }
  178328. boxp->colorcount = ccount;
  178329. }
  178330. LOCAL(int)
  178331. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178332. int desired_colors)
  178333. /* Repeatedly select and split the largest box until we have enough boxes */
  178334. {
  178335. int n,lb;
  178336. int c0,c1,c2,cmax;
  178337. register boxptr b1,b2;
  178338. while (numboxes < desired_colors) {
  178339. /* Select box to split.
  178340. * Current algorithm: by population for first half, then by volume.
  178341. */
  178342. if (numboxes*2 <= desired_colors) {
  178343. b1 = find_biggest_color_pop(boxlist, numboxes);
  178344. } else {
  178345. b1 = find_biggest_volume(boxlist, numboxes);
  178346. }
  178347. if (b1 == NULL) /* no splittable boxes left! */
  178348. break;
  178349. b2 = &boxlist[numboxes]; /* where new box will go */
  178350. /* Copy the color bounds to the new box. */
  178351. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178352. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178353. /* Choose which axis to split the box on.
  178354. * Current algorithm: longest scaled axis.
  178355. * See notes in update_box about scaling distances.
  178356. */
  178357. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178358. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178359. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178360. /* We want to break any ties in favor of green, then red, blue last.
  178361. * This code does the right thing for R,G,B or B,G,R color orders only.
  178362. */
  178363. #if RGB_RED == 0
  178364. cmax = c1; n = 1;
  178365. if (c0 > cmax) { cmax = c0; n = 0; }
  178366. if (c2 > cmax) { n = 2; }
  178367. #else
  178368. cmax = c1; n = 1;
  178369. if (c2 > cmax) { cmax = c2; n = 2; }
  178370. if (c0 > cmax) { n = 0; }
  178371. #endif
  178372. /* Choose split point along selected axis, and update box bounds.
  178373. * Current algorithm: split at halfway point.
  178374. * (Since the box has been shrunk to minimum volume,
  178375. * any split will produce two nonempty subboxes.)
  178376. * Note that lb value is max for lower box, so must be < old max.
  178377. */
  178378. switch (n) {
  178379. case 0:
  178380. lb = (b1->c0max + b1->c0min) / 2;
  178381. b1->c0max = lb;
  178382. b2->c0min = lb+1;
  178383. break;
  178384. case 1:
  178385. lb = (b1->c1max + b1->c1min) / 2;
  178386. b1->c1max = lb;
  178387. b2->c1min = lb+1;
  178388. break;
  178389. case 2:
  178390. lb = (b1->c2max + b1->c2min) / 2;
  178391. b1->c2max = lb;
  178392. b2->c2min = lb+1;
  178393. break;
  178394. }
  178395. /* Update stats for boxes */
  178396. update_box(cinfo, b1);
  178397. update_box(cinfo, b2);
  178398. numboxes++;
  178399. }
  178400. return numboxes;
  178401. }
  178402. LOCAL(void)
  178403. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178404. /* Compute representative color for a box, put it in colormap[icolor] */
  178405. {
  178406. /* Current algorithm: mean weighted by pixels (not colors) */
  178407. /* Note it is important to get the rounding correct! */
  178408. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178409. hist3d histogram = cquantize->histogram;
  178410. histptr histp;
  178411. int c0,c1,c2;
  178412. int c0min,c0max,c1min,c1max,c2min,c2max;
  178413. long count;
  178414. long total = 0;
  178415. long c0total = 0;
  178416. long c1total = 0;
  178417. long c2total = 0;
  178418. c0min = boxp->c0min; c0max = boxp->c0max;
  178419. c1min = boxp->c1min; c1max = boxp->c1max;
  178420. c2min = boxp->c2min; c2max = boxp->c2max;
  178421. for (c0 = c0min; c0 <= c0max; c0++)
  178422. for (c1 = c1min; c1 <= c1max; c1++) {
  178423. histp = & histogram[c0][c1][c2min];
  178424. for (c2 = c2min; c2 <= c2max; c2++) {
  178425. if ((count = *histp++) != 0) {
  178426. total += count;
  178427. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178428. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178429. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178430. }
  178431. }
  178432. }
  178433. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178434. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178435. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178436. }
  178437. LOCAL(void)
  178438. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178439. /* Master routine for color selection */
  178440. {
  178441. boxptr boxlist;
  178442. int numboxes;
  178443. int i;
  178444. /* Allocate workspace for box list */
  178445. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178446. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178447. /* Initialize one box containing whole space */
  178448. numboxes = 1;
  178449. boxlist[0].c0min = 0;
  178450. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178451. boxlist[0].c1min = 0;
  178452. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178453. boxlist[0].c2min = 0;
  178454. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178455. /* Shrink it to actually-used volume and set its statistics */
  178456. update_box(cinfo, & boxlist[0]);
  178457. /* Perform median-cut to produce final box list */
  178458. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178459. /* Compute the representative color for each box, fill colormap */
  178460. for (i = 0; i < numboxes; i++)
  178461. compute_color(cinfo, & boxlist[i], i);
  178462. cinfo->actual_number_of_colors = numboxes;
  178463. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178464. }
  178465. /*
  178466. * These routines are concerned with the time-critical task of mapping input
  178467. * colors to the nearest color in the selected colormap.
  178468. *
  178469. * We re-use the histogram space as an "inverse color map", essentially a
  178470. * cache for the results of nearest-color searches. All colors within a
  178471. * histogram cell will be mapped to the same colormap entry, namely the one
  178472. * closest to the cell's center. This may not be quite the closest entry to
  178473. * the actual input color, but it's almost as good. A zero in the cache
  178474. * indicates we haven't found the nearest color for that cell yet; the array
  178475. * is cleared to zeroes before starting the mapping pass. When we find the
  178476. * nearest color for a cell, its colormap index plus one is recorded in the
  178477. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178478. * when they need to use an unfilled entry in the cache.
  178479. *
  178480. * Our method of efficiently finding nearest colors is based on the "locally
  178481. * sorted search" idea described by Heckbert and on the incremental distance
  178482. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178483. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178484. * the distances from a given colormap entry to each cell of the histogram can
  178485. * be computed quickly using an incremental method: the differences between
  178486. * distances to adjacent cells themselves differ by a constant. This allows a
  178487. * fairly fast implementation of the "brute force" approach of computing the
  178488. * distance from every colormap entry to every histogram cell. Unfortunately,
  178489. * it needs a work array to hold the best-distance-so-far for each histogram
  178490. * cell (because the inner loop has to be over cells, not colormap entries).
  178491. * The work array elements have to be INT32s, so the work array would need
  178492. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178493. *
  178494. * To get around these problems, we apply Thomas' method to compute the
  178495. * nearest colors for only the cells within a small subbox of the histogram.
  178496. * The work array need be only as big as the subbox, so the memory usage
  178497. * problem is solved. Furthermore, we need not fill subboxes that are never
  178498. * referenced in pass2; many images use only part of the color gamut, so a
  178499. * fair amount of work is saved. An additional advantage of this
  178500. * approach is that we can apply Heckbert's locality criterion to quickly
  178501. * eliminate colormap entries that are far away from the subbox; typically
  178502. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178503. * and we need not compute their distances to individual cells in the subbox.
  178504. * The speed of this approach is heavily influenced by the subbox size: too
  178505. * small means too much overhead, too big loses because Heckbert's criterion
  178506. * can't eliminate as many colormap entries. Empirically the best subbox
  178507. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178508. *
  178509. * Thomas' article also describes a refined method which is asymptotically
  178510. * faster than the brute-force method, but it is also far more complex and
  178511. * cannot efficiently be applied to small subboxes. It is therefore not
  178512. * useful for programs intended to be portable to DOS machines. On machines
  178513. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178514. * refined method might be faster than the present code --- but then again,
  178515. * it might not be any faster, and it's certainly more complicated.
  178516. */
  178517. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178518. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178519. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178520. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178521. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178522. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178523. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178524. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178525. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178526. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178527. /*
  178528. * The next three routines implement inverse colormap filling. They could
  178529. * all be folded into one big routine, but splitting them up this way saves
  178530. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178531. * and may allow some compilers to produce better code by registerizing more
  178532. * inner-loop variables.
  178533. */
  178534. LOCAL(int)
  178535. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178536. JSAMPLE colorlist[])
  178537. /* Locate the colormap entries close enough to an update box to be candidates
  178538. * for the nearest entry to some cell(s) in the update box. The update box
  178539. * is specified by the center coordinates of its first cell. The number of
  178540. * candidate colormap entries is returned, and their colormap indexes are
  178541. * placed in colorlist[].
  178542. * This routine uses Heckbert's "locally sorted search" criterion to select
  178543. * the colors that need further consideration.
  178544. */
  178545. {
  178546. int numcolors = cinfo->actual_number_of_colors;
  178547. int maxc0, maxc1, maxc2;
  178548. int centerc0, centerc1, centerc2;
  178549. int i, x, ncolors;
  178550. INT32 minmaxdist, min_dist, max_dist, tdist;
  178551. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178552. /* Compute true coordinates of update box's upper corner and center.
  178553. * Actually we compute the coordinates of the center of the upper-corner
  178554. * histogram cell, which are the upper bounds of the volume we care about.
  178555. * Note that since ">>" rounds down, the "center" values may be closer to
  178556. * min than to max; hence comparisons to them must be "<=", not "<".
  178557. */
  178558. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178559. centerc0 = (minc0 + maxc0) >> 1;
  178560. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178561. centerc1 = (minc1 + maxc1) >> 1;
  178562. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178563. centerc2 = (minc2 + maxc2) >> 1;
  178564. /* For each color in colormap, find:
  178565. * 1. its minimum squared-distance to any point in the update box
  178566. * (zero if color is within update box);
  178567. * 2. its maximum squared-distance to any point in the update box.
  178568. * Both of these can be found by considering only the corners of the box.
  178569. * We save the minimum distance for each color in mindist[];
  178570. * only the smallest maximum distance is of interest.
  178571. */
  178572. minmaxdist = 0x7FFFFFFFL;
  178573. for (i = 0; i < numcolors; i++) {
  178574. /* We compute the squared-c0-distance term, then add in the other two. */
  178575. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178576. if (x < minc0) {
  178577. tdist = (x - minc0) * C0_SCALE;
  178578. min_dist = tdist*tdist;
  178579. tdist = (x - maxc0) * C0_SCALE;
  178580. max_dist = tdist*tdist;
  178581. } else if (x > maxc0) {
  178582. tdist = (x - maxc0) * C0_SCALE;
  178583. min_dist = tdist*tdist;
  178584. tdist = (x - minc0) * C0_SCALE;
  178585. max_dist = tdist*tdist;
  178586. } else {
  178587. /* within cell range so no contribution to min_dist */
  178588. min_dist = 0;
  178589. if (x <= centerc0) {
  178590. tdist = (x - maxc0) * C0_SCALE;
  178591. max_dist = tdist*tdist;
  178592. } else {
  178593. tdist = (x - minc0) * C0_SCALE;
  178594. max_dist = tdist*tdist;
  178595. }
  178596. }
  178597. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178598. if (x < minc1) {
  178599. tdist = (x - minc1) * C1_SCALE;
  178600. min_dist += tdist*tdist;
  178601. tdist = (x - maxc1) * C1_SCALE;
  178602. max_dist += tdist*tdist;
  178603. } else if (x > maxc1) {
  178604. tdist = (x - maxc1) * C1_SCALE;
  178605. min_dist += tdist*tdist;
  178606. tdist = (x - minc1) * C1_SCALE;
  178607. max_dist += tdist*tdist;
  178608. } else {
  178609. /* within cell range so no contribution to min_dist */
  178610. if (x <= centerc1) {
  178611. tdist = (x - maxc1) * C1_SCALE;
  178612. max_dist += tdist*tdist;
  178613. } else {
  178614. tdist = (x - minc1) * C1_SCALE;
  178615. max_dist += tdist*tdist;
  178616. }
  178617. }
  178618. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178619. if (x < minc2) {
  178620. tdist = (x - minc2) * C2_SCALE;
  178621. min_dist += tdist*tdist;
  178622. tdist = (x - maxc2) * C2_SCALE;
  178623. max_dist += tdist*tdist;
  178624. } else if (x > maxc2) {
  178625. tdist = (x - maxc2) * C2_SCALE;
  178626. min_dist += tdist*tdist;
  178627. tdist = (x - minc2) * C2_SCALE;
  178628. max_dist += tdist*tdist;
  178629. } else {
  178630. /* within cell range so no contribution to min_dist */
  178631. if (x <= centerc2) {
  178632. tdist = (x - maxc2) * C2_SCALE;
  178633. max_dist += tdist*tdist;
  178634. } else {
  178635. tdist = (x - minc2) * C2_SCALE;
  178636. max_dist += tdist*tdist;
  178637. }
  178638. }
  178639. mindist[i] = min_dist; /* save away the results */
  178640. if (max_dist < minmaxdist)
  178641. minmaxdist = max_dist;
  178642. }
  178643. /* Now we know that no cell in the update box is more than minmaxdist
  178644. * away from some colormap entry. Therefore, only colors that are
  178645. * within minmaxdist of some part of the box need be considered.
  178646. */
  178647. ncolors = 0;
  178648. for (i = 0; i < numcolors; i++) {
  178649. if (mindist[i] <= minmaxdist)
  178650. colorlist[ncolors++] = (JSAMPLE) i;
  178651. }
  178652. return ncolors;
  178653. }
  178654. LOCAL(void)
  178655. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178656. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178657. /* Find the closest colormap entry for each cell in the update box,
  178658. * given the list of candidate colors prepared by find_nearby_colors.
  178659. * Return the indexes of the closest entries in the bestcolor[] array.
  178660. * This routine uses Thomas' incremental distance calculation method to
  178661. * find the distance from a colormap entry to successive cells in the box.
  178662. */
  178663. {
  178664. int ic0, ic1, ic2;
  178665. int i, icolor;
  178666. register INT32 * bptr; /* pointer into bestdist[] array */
  178667. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178668. INT32 dist0, dist1; /* initial distance values */
  178669. register INT32 dist2; /* current distance in inner loop */
  178670. INT32 xx0, xx1; /* distance increments */
  178671. register INT32 xx2;
  178672. INT32 inc0, inc1, inc2; /* initial values for increments */
  178673. /* This array holds the distance to the nearest-so-far color for each cell */
  178674. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178675. /* Initialize best-distance for each cell of the update box */
  178676. bptr = bestdist;
  178677. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178678. *bptr++ = 0x7FFFFFFFL;
  178679. /* For each color selected by find_nearby_colors,
  178680. * compute its distance to the center of each cell in the box.
  178681. * If that's less than best-so-far, update best distance and color number.
  178682. */
  178683. /* Nominal steps between cell centers ("x" in Thomas article) */
  178684. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178685. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178686. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178687. for (i = 0; i < numcolors; i++) {
  178688. icolor = GETJSAMPLE(colorlist[i]);
  178689. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178690. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178691. dist0 = inc0*inc0;
  178692. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178693. dist0 += inc1*inc1;
  178694. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178695. dist0 += inc2*inc2;
  178696. /* Form the initial difference increments */
  178697. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178698. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178699. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178700. /* Now loop over all cells in box, updating distance per Thomas method */
  178701. bptr = bestdist;
  178702. cptr = bestcolor;
  178703. xx0 = inc0;
  178704. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178705. dist1 = dist0;
  178706. xx1 = inc1;
  178707. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178708. dist2 = dist1;
  178709. xx2 = inc2;
  178710. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178711. if (dist2 < *bptr) {
  178712. *bptr = dist2;
  178713. *cptr = (JSAMPLE) icolor;
  178714. }
  178715. dist2 += xx2;
  178716. xx2 += 2 * STEP_C2 * STEP_C2;
  178717. bptr++;
  178718. cptr++;
  178719. }
  178720. dist1 += xx1;
  178721. xx1 += 2 * STEP_C1 * STEP_C1;
  178722. }
  178723. dist0 += xx0;
  178724. xx0 += 2 * STEP_C0 * STEP_C0;
  178725. }
  178726. }
  178727. }
  178728. LOCAL(void)
  178729. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178730. /* Fill the inverse-colormap entries in the update box that contains */
  178731. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178732. /* we can fill as many others as we wish.) */
  178733. {
  178734. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178735. hist3d histogram = cquantize->histogram;
  178736. int minc0, minc1, minc2; /* lower left corner of update box */
  178737. int ic0, ic1, ic2;
  178738. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178739. register histptr cachep; /* pointer into main cache array */
  178740. /* This array lists the candidate colormap indexes. */
  178741. JSAMPLE colorlist[MAXNUMCOLORS];
  178742. int numcolors; /* number of candidate colors */
  178743. /* This array holds the actually closest colormap index for each cell. */
  178744. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178745. /* Convert cell coordinates to update box ID */
  178746. c0 >>= BOX_C0_LOG;
  178747. c1 >>= BOX_C1_LOG;
  178748. c2 >>= BOX_C2_LOG;
  178749. /* Compute true coordinates of update box's origin corner.
  178750. * Actually we compute the coordinates of the center of the corner
  178751. * histogram cell, which are the lower bounds of the volume we care about.
  178752. */
  178753. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178754. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178755. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178756. /* Determine which colormap entries are close enough to be candidates
  178757. * for the nearest entry to some cell in the update box.
  178758. */
  178759. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178760. /* Determine the actually nearest colors. */
  178761. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178762. bestcolor);
  178763. /* Save the best color numbers (plus 1) in the main cache array */
  178764. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178765. c1 <<= BOX_C1_LOG;
  178766. c2 <<= BOX_C2_LOG;
  178767. cptr = bestcolor;
  178768. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178769. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178770. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178771. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178772. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178773. }
  178774. }
  178775. }
  178776. }
  178777. /*
  178778. * Map some rows of pixels to the output colormapped representation.
  178779. */
  178780. METHODDEF(void)
  178781. pass2_no_dither (j_decompress_ptr cinfo,
  178782. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178783. /* This version performs no dithering */
  178784. {
  178785. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178786. hist3d histogram = cquantize->histogram;
  178787. register JSAMPROW inptr, outptr;
  178788. register histptr cachep;
  178789. register int c0, c1, c2;
  178790. int row;
  178791. JDIMENSION col;
  178792. JDIMENSION width = cinfo->output_width;
  178793. for (row = 0; row < num_rows; row++) {
  178794. inptr = input_buf[row];
  178795. outptr = output_buf[row];
  178796. for (col = width; col > 0; col--) {
  178797. /* get pixel value and index into the cache */
  178798. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178799. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178800. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178801. cachep = & histogram[c0][c1][c2];
  178802. /* If we have not seen this color before, find nearest colormap entry */
  178803. /* and update the cache */
  178804. if (*cachep == 0)
  178805. fill_inverse_cmap(cinfo, c0,c1,c2);
  178806. /* Now emit the colormap index for this cell */
  178807. *outptr++ = (JSAMPLE) (*cachep - 1);
  178808. }
  178809. }
  178810. }
  178811. METHODDEF(void)
  178812. pass2_fs_dither (j_decompress_ptr cinfo,
  178813. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178814. /* This version performs Floyd-Steinberg dithering */
  178815. {
  178816. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178817. hist3d histogram = cquantize->histogram;
  178818. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178819. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178820. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178821. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178822. JSAMPROW inptr; /* => current input pixel */
  178823. JSAMPROW outptr; /* => current output pixel */
  178824. histptr cachep;
  178825. int dir; /* +1 or -1 depending on direction */
  178826. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178827. int row;
  178828. JDIMENSION col;
  178829. JDIMENSION width = cinfo->output_width;
  178830. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178831. int *error_limit = cquantize->error_limiter;
  178832. JSAMPROW colormap0 = cinfo->colormap[0];
  178833. JSAMPROW colormap1 = cinfo->colormap[1];
  178834. JSAMPROW colormap2 = cinfo->colormap[2];
  178835. SHIFT_TEMPS
  178836. for (row = 0; row < num_rows; row++) {
  178837. inptr = input_buf[row];
  178838. outptr = output_buf[row];
  178839. if (cquantize->on_odd_row) {
  178840. /* work right to left in this row */
  178841. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178842. outptr += width-1;
  178843. dir = -1;
  178844. dir3 = -3;
  178845. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178846. cquantize->on_odd_row = FALSE; /* flip for next time */
  178847. } else {
  178848. /* work left to right in this row */
  178849. dir = 1;
  178850. dir3 = 3;
  178851. errorptr = cquantize->fserrors; /* => entry before first real column */
  178852. cquantize->on_odd_row = TRUE; /* flip for next time */
  178853. }
  178854. /* Preset error values: no error propagated to first pixel from left */
  178855. cur0 = cur1 = cur2 = 0;
  178856. /* and no error propagated to row below yet */
  178857. belowerr0 = belowerr1 = belowerr2 = 0;
  178858. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178859. for (col = width; col > 0; col--) {
  178860. /* curN holds the error propagated from the previous pixel on the
  178861. * current line. Add the error propagated from the previous line
  178862. * to form the complete error correction term for this pixel, and
  178863. * round the error term (which is expressed * 16) to an integer.
  178864. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178865. * for either sign of the error value.
  178866. * Note: errorptr points to *previous* column's array entry.
  178867. */
  178868. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178869. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178870. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178871. /* Limit the error using transfer function set by init_error_limit.
  178872. * See comments with init_error_limit for rationale.
  178873. */
  178874. cur0 = error_limit[cur0];
  178875. cur1 = error_limit[cur1];
  178876. cur2 = error_limit[cur2];
  178877. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178878. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178879. * this sets the required size of the range_limit array.
  178880. */
  178881. cur0 += GETJSAMPLE(inptr[0]);
  178882. cur1 += GETJSAMPLE(inptr[1]);
  178883. cur2 += GETJSAMPLE(inptr[2]);
  178884. cur0 = GETJSAMPLE(range_limit[cur0]);
  178885. cur1 = GETJSAMPLE(range_limit[cur1]);
  178886. cur2 = GETJSAMPLE(range_limit[cur2]);
  178887. /* Index into the cache with adjusted pixel value */
  178888. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178889. /* If we have not seen this color before, find nearest colormap */
  178890. /* entry and update the cache */
  178891. if (*cachep == 0)
  178892. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178893. /* Now emit the colormap index for this cell */
  178894. { register int pixcode = *cachep - 1;
  178895. *outptr = (JSAMPLE) pixcode;
  178896. /* Compute representation error for this pixel */
  178897. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178898. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178899. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178900. }
  178901. /* Compute error fractions to be propagated to adjacent pixels.
  178902. * Add these into the running sums, and simultaneously shift the
  178903. * next-line error sums left by 1 column.
  178904. */
  178905. { register LOCFSERROR bnexterr, delta;
  178906. bnexterr = cur0; /* Process component 0 */
  178907. delta = cur0 * 2;
  178908. cur0 += delta; /* form error * 3 */
  178909. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178910. cur0 += delta; /* form error * 5 */
  178911. bpreverr0 = belowerr0 + cur0;
  178912. belowerr0 = bnexterr;
  178913. cur0 += delta; /* form error * 7 */
  178914. bnexterr = cur1; /* Process component 1 */
  178915. delta = cur1 * 2;
  178916. cur1 += delta; /* form error * 3 */
  178917. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178918. cur1 += delta; /* form error * 5 */
  178919. bpreverr1 = belowerr1 + cur1;
  178920. belowerr1 = bnexterr;
  178921. cur1 += delta; /* form error * 7 */
  178922. bnexterr = cur2; /* Process component 2 */
  178923. delta = cur2 * 2;
  178924. cur2 += delta; /* form error * 3 */
  178925. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178926. cur2 += delta; /* form error * 5 */
  178927. bpreverr2 = belowerr2 + cur2;
  178928. belowerr2 = bnexterr;
  178929. cur2 += delta; /* form error * 7 */
  178930. }
  178931. /* At this point curN contains the 7/16 error value to be propagated
  178932. * to the next pixel on the current line, and all the errors for the
  178933. * next line have been shifted over. We are therefore ready to move on.
  178934. */
  178935. inptr += dir3; /* Advance pixel pointers to next column */
  178936. outptr += dir;
  178937. errorptr += dir3; /* advance errorptr to current column */
  178938. }
  178939. /* Post-loop cleanup: we must unload the final error values into the
  178940. * final fserrors[] entry. Note we need not unload belowerrN because
  178941. * it is for the dummy column before or after the actual array.
  178942. */
  178943. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178944. errorptr[1] = (FSERROR) bpreverr1;
  178945. errorptr[2] = (FSERROR) bpreverr2;
  178946. }
  178947. }
  178948. /*
  178949. * Initialize the error-limiting transfer function (lookup table).
  178950. * The raw F-S error computation can potentially compute error values of up to
  178951. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178952. * much less, otherwise obviously wrong pixels will be created. (Typical
  178953. * effects include weird fringes at color-area boundaries, isolated bright
  178954. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178955. * is to ensure that the "corners" of the color cube are allocated as output
  178956. * colors; then repeated errors in the same direction cannot cause cascading
  178957. * error buildup. However, that only prevents the error from getting
  178958. * completely out of hand; Aaron Giles reports that error limiting improves
  178959. * the results even with corner colors allocated.
  178960. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178961. * well, but the smoother transfer function used below is even better. Thanks
  178962. * to Aaron Giles for this idea.
  178963. */
  178964. LOCAL(void)
  178965. init_error_limit (j_decompress_ptr cinfo)
  178966. /* Allocate and fill in the error_limiter table */
  178967. {
  178968. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178969. int * table;
  178970. int in, out;
  178971. table = (int *) (*cinfo->mem->alloc_small)
  178972. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178973. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178974. cquantize->error_limiter = table;
  178975. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178976. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178977. out = 0;
  178978. for (in = 0; in < STEPSIZE; in++, out++) {
  178979. table[in] = out; table[-in] = -out;
  178980. }
  178981. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178982. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178983. table[in] = out; table[-in] = -out;
  178984. }
  178985. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178986. for (; in <= MAXJSAMPLE; in++) {
  178987. table[in] = out; table[-in] = -out;
  178988. }
  178989. #undef STEPSIZE
  178990. }
  178991. /*
  178992. * Finish up at the end of each pass.
  178993. */
  178994. METHODDEF(void)
  178995. finish_pass1 (j_decompress_ptr cinfo)
  178996. {
  178997. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178998. /* Select the representative colors and fill in cinfo->colormap */
  178999. cinfo->colormap = cquantize->sv_colormap;
  179000. select_colors(cinfo, cquantize->desired);
  179001. /* Force next pass to zero the color index table */
  179002. cquantize->needs_zeroed = TRUE;
  179003. }
  179004. METHODDEF(void)
  179005. finish_pass2 (j_decompress_ptr)
  179006. {
  179007. /* no work */
  179008. }
  179009. /*
  179010. * Initialize for each processing pass.
  179011. */
  179012. METHODDEF(void)
  179013. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  179014. {
  179015. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179016. hist3d histogram = cquantize->histogram;
  179017. int i;
  179018. /* Only F-S dithering or no dithering is supported. */
  179019. /* If user asks for ordered dither, give him F-S. */
  179020. if (cinfo->dither_mode != JDITHER_NONE)
  179021. cinfo->dither_mode = JDITHER_FS;
  179022. if (is_pre_scan) {
  179023. /* Set up method pointers */
  179024. cquantize->pub.color_quantize = prescan_quantize;
  179025. cquantize->pub.finish_pass = finish_pass1;
  179026. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  179027. } else {
  179028. /* Set up method pointers */
  179029. if (cinfo->dither_mode == JDITHER_FS)
  179030. cquantize->pub.color_quantize = pass2_fs_dither;
  179031. else
  179032. cquantize->pub.color_quantize = pass2_no_dither;
  179033. cquantize->pub.finish_pass = finish_pass2;
  179034. /* Make sure color count is acceptable */
  179035. i = cinfo->actual_number_of_colors;
  179036. if (i < 1)
  179037. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  179038. if (i > MAXNUMCOLORS)
  179039. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179040. if (cinfo->dither_mode == JDITHER_FS) {
  179041. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  179042. (3 * SIZEOF(FSERROR)));
  179043. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  179044. if (cquantize->fserrors == NULL)
  179045. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179046. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  179047. /* Initialize the propagated errors to zero. */
  179048. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  179049. /* Make the error-limit table if we didn't already. */
  179050. if (cquantize->error_limiter == NULL)
  179051. init_error_limit(cinfo);
  179052. cquantize->on_odd_row = FALSE;
  179053. }
  179054. }
  179055. /* Zero the histogram or inverse color map, if necessary */
  179056. if (cquantize->needs_zeroed) {
  179057. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179058. jzero_far((void FAR *) histogram[i],
  179059. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179060. }
  179061. cquantize->needs_zeroed = FALSE;
  179062. }
  179063. }
  179064. /*
  179065. * Switch to a new external colormap between output passes.
  179066. */
  179067. METHODDEF(void)
  179068. new_color_map_2_quant (j_decompress_ptr cinfo)
  179069. {
  179070. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179071. /* Reset the inverse color map */
  179072. cquantize->needs_zeroed = TRUE;
  179073. }
  179074. /*
  179075. * Module initialization routine for 2-pass color quantization.
  179076. */
  179077. GLOBAL(void)
  179078. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  179079. {
  179080. my_cquantize_ptr2 cquantize;
  179081. int i;
  179082. cquantize = (my_cquantize_ptr2)
  179083. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179084. SIZEOF(my_cquantizer2));
  179085. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  179086. cquantize->pub.start_pass = start_pass_2_quant;
  179087. cquantize->pub.new_color_map = new_color_map_2_quant;
  179088. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  179089. cquantize->error_limiter = NULL;
  179090. /* Make sure jdmaster didn't give me a case I can't handle */
  179091. if (cinfo->out_color_components != 3)
  179092. ERREXIT(cinfo, JERR_NOTIMPL);
  179093. /* Allocate the histogram/inverse colormap storage */
  179094. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  179095. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  179096. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179097. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  179098. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179099. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179100. }
  179101. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  179102. /* Allocate storage for the completed colormap, if required.
  179103. * We do this now since it is FAR storage and may affect
  179104. * the memory manager's space calculations.
  179105. */
  179106. if (cinfo->enable_2pass_quant) {
  179107. /* Make sure color count is acceptable */
  179108. int desired = cinfo->desired_number_of_colors;
  179109. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  179110. if (desired < 8)
  179111. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  179112. /* Make sure colormap indexes can be represented by JSAMPLEs */
  179113. if (desired > MAXNUMCOLORS)
  179114. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179115. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  179116. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  179117. cquantize->desired = desired;
  179118. } else
  179119. cquantize->sv_colormap = NULL;
  179120. /* Only F-S dithering or no dithering is supported. */
  179121. /* If user asks for ordered dither, give him F-S. */
  179122. if (cinfo->dither_mode != JDITHER_NONE)
  179123. cinfo->dither_mode = JDITHER_FS;
  179124. /* Allocate Floyd-Steinberg workspace if necessary.
  179125. * This isn't really needed until pass 2, but again it is FAR storage.
  179126. * Although we will cope with a later change in dither_mode,
  179127. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179128. */
  179129. if (cinfo->dither_mode == JDITHER_FS) {
  179130. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179131. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179132. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179133. /* Might as well create the error-limiting table too. */
  179134. init_error_limit(cinfo);
  179135. }
  179136. }
  179137. #endif /* QUANT_2PASS_SUPPORTED */
  179138. /*** End of inlined file: jquant2.c ***/
  179139. /*** Start of inlined file: jutils.c ***/
  179140. #define JPEG_INTERNALS
  179141. /*
  179142. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179143. * of a DCT block read in natural order (left to right, top to bottom).
  179144. */
  179145. #if 0 /* This table is not actually needed in v6a */
  179146. const int jpeg_zigzag_order[DCTSIZE2] = {
  179147. 0, 1, 5, 6, 14, 15, 27, 28,
  179148. 2, 4, 7, 13, 16, 26, 29, 42,
  179149. 3, 8, 12, 17, 25, 30, 41, 43,
  179150. 9, 11, 18, 24, 31, 40, 44, 53,
  179151. 10, 19, 23, 32, 39, 45, 52, 54,
  179152. 20, 22, 33, 38, 46, 51, 55, 60,
  179153. 21, 34, 37, 47, 50, 56, 59, 61,
  179154. 35, 36, 48, 49, 57, 58, 62, 63
  179155. };
  179156. #endif
  179157. /*
  179158. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179159. * of zigzag order.
  179160. *
  179161. * When reading corrupted data, the Huffman decoders could attempt
  179162. * to reference an entry beyond the end of this array (if the decoded
  179163. * zero run length reaches past the end of the block). To prevent
  179164. * wild stores without adding an inner-loop test, we put some extra
  179165. * "63"s after the real entries. This will cause the extra coefficient
  179166. * to be stored in location 63 of the block, not somewhere random.
  179167. * The worst case would be a run-length of 15, which means we need 16
  179168. * fake entries.
  179169. */
  179170. const int jpeg_natural_order[DCTSIZE2+16] = {
  179171. 0, 1, 8, 16, 9, 2, 3, 10,
  179172. 17, 24, 32, 25, 18, 11, 4, 5,
  179173. 12, 19, 26, 33, 40, 48, 41, 34,
  179174. 27, 20, 13, 6, 7, 14, 21, 28,
  179175. 35, 42, 49, 56, 57, 50, 43, 36,
  179176. 29, 22, 15, 23, 30, 37, 44, 51,
  179177. 58, 59, 52, 45, 38, 31, 39, 46,
  179178. 53, 60, 61, 54, 47, 55, 62, 63,
  179179. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179180. 63, 63, 63, 63, 63, 63, 63, 63
  179181. };
  179182. /*
  179183. * Arithmetic utilities
  179184. */
  179185. GLOBAL(long)
  179186. jdiv_round_up (long a, long b)
  179187. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179188. /* Assumes a >= 0, b > 0 */
  179189. {
  179190. return (a + b - 1L) / b;
  179191. }
  179192. GLOBAL(long)
  179193. jround_up (long a, long b)
  179194. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179195. /* Assumes a >= 0, b > 0 */
  179196. {
  179197. a += b - 1L;
  179198. return a - (a % b);
  179199. }
  179200. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179201. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179202. * are FAR and we're assuming a small-pointer memory model. However, some
  179203. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179204. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179205. * Otherwise, the routines below do it the hard way. (The performance cost
  179206. * is not all that great, because these routines aren't very heavily used.)
  179207. */
  179208. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179209. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179210. #define FMEMZERO(target,size) MEMZERO(target,size)
  179211. #else /* 80x86 case, define if we can */
  179212. #ifdef USE_FMEM
  179213. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179214. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179215. #endif
  179216. #endif
  179217. GLOBAL(void)
  179218. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179219. JSAMPARRAY output_array, int dest_row,
  179220. int num_rows, JDIMENSION num_cols)
  179221. /* Copy some rows of samples from one place to another.
  179222. * num_rows rows are copied from input_array[source_row++]
  179223. * to output_array[dest_row++]; these areas may overlap for duplication.
  179224. * The source and destination arrays must be at least as wide as num_cols.
  179225. */
  179226. {
  179227. register JSAMPROW inptr, outptr;
  179228. #ifdef FMEMCOPY
  179229. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179230. #else
  179231. register JDIMENSION count;
  179232. #endif
  179233. register int row;
  179234. input_array += source_row;
  179235. output_array += dest_row;
  179236. for (row = num_rows; row > 0; row--) {
  179237. inptr = *input_array++;
  179238. outptr = *output_array++;
  179239. #ifdef FMEMCOPY
  179240. FMEMCOPY(outptr, inptr, count);
  179241. #else
  179242. for (count = num_cols; count > 0; count--)
  179243. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179244. #endif
  179245. }
  179246. }
  179247. GLOBAL(void)
  179248. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179249. JDIMENSION num_blocks)
  179250. /* Copy a row of coefficient blocks from one place to another. */
  179251. {
  179252. #ifdef FMEMCOPY
  179253. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179254. #else
  179255. register JCOEFPTR inptr, outptr;
  179256. register long count;
  179257. inptr = (JCOEFPTR) input_row;
  179258. outptr = (JCOEFPTR) output_row;
  179259. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179260. *outptr++ = *inptr++;
  179261. }
  179262. #endif
  179263. }
  179264. GLOBAL(void)
  179265. jzero_far (void FAR * target, size_t bytestozero)
  179266. /* Zero out a chunk of FAR memory. */
  179267. /* This might be sample-array data, block-array data, or alloc_large data. */
  179268. {
  179269. #ifdef FMEMZERO
  179270. FMEMZERO(target, bytestozero);
  179271. #else
  179272. register char FAR * ptr = (char FAR *) target;
  179273. register size_t count;
  179274. for (count = bytestozero; count > 0; count--) {
  179275. *ptr++ = 0;
  179276. }
  179277. #endif
  179278. }
  179279. /*** End of inlined file: jutils.c ***/
  179280. /*** Start of inlined file: transupp.c ***/
  179281. /* Although this file really shouldn't have access to the library internals,
  179282. * it's helpful to let it call jround_up() and jcopy_block_row().
  179283. */
  179284. #define JPEG_INTERNALS
  179285. /*** Start of inlined file: transupp.h ***/
  179286. /* If you happen not to want the image transform support, disable it here */
  179287. #ifndef TRANSFORMS_SUPPORTED
  179288. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179289. #endif
  179290. /* Short forms of external names for systems with brain-damaged linkers. */
  179291. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179292. #define jtransform_request_workspace jTrRequest
  179293. #define jtransform_adjust_parameters jTrAdjust
  179294. #define jtransform_execute_transformation jTrExec
  179295. #define jcopy_markers_setup jCMrkSetup
  179296. #define jcopy_markers_execute jCMrkExec
  179297. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179298. /*
  179299. * Codes for supported types of image transformations.
  179300. */
  179301. typedef enum {
  179302. JXFORM_NONE, /* no transformation */
  179303. JXFORM_FLIP_H, /* horizontal flip */
  179304. JXFORM_FLIP_V, /* vertical flip */
  179305. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179306. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179307. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179308. JXFORM_ROT_180, /* 180-degree rotation */
  179309. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179310. } JXFORM_CODE;
  179311. /*
  179312. * Although rotating and flipping data expressed as DCT coefficients is not
  179313. * hard, there is an asymmetry in the JPEG format specification for images
  179314. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179315. * image edges are padded out to the next iMCU boundary with junk data; but
  179316. * no padding is possible at the top and left edges. If we were to flip
  179317. * the whole image including the pad data, then pad garbage would become
  179318. * visible at the top and/or left, and real pixels would disappear into the
  179319. * pad margins --- perhaps permanently, since encoders & decoders may not
  179320. * bother to preserve DCT blocks that appear to be completely outside the
  179321. * nominal image area. So, we have to exclude any partial iMCUs from the
  179322. * basic transformation.
  179323. *
  179324. * Transpose is the only transformation that can handle partial iMCUs at the
  179325. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179326. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179327. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179328. * The other transforms are defined as combinations of these basic transforms
  179329. * and process edge blocks in a way that preserves the equivalence.
  179330. *
  179331. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179332. * this is not strictly lossless, but it usually gives the best-looking
  179333. * result for odd-size images. Note that when this option is active,
  179334. * the expected mathematical equivalences between the transforms may not hold.
  179335. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179336. * followed by -rot 180 -trim trims both edges.)
  179337. *
  179338. * We also offer a "force to grayscale" option, which simply discards the
  179339. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179340. * the luminance channel is preserved exactly. It's not the same kind of
  179341. * thing as the rotate/flip transformations, but it's convenient to handle it
  179342. * as part of this package, mainly because the transformation routines have to
  179343. * be aware of the option to know how many components to work on.
  179344. */
  179345. typedef struct {
  179346. /* Options: set by caller */
  179347. JXFORM_CODE transform; /* image transform operator */
  179348. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179349. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179350. /* Internal workspace: caller should not touch these */
  179351. int num_components; /* # of components in workspace */
  179352. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179353. } jpeg_transform_info;
  179354. #if TRANSFORMS_SUPPORTED
  179355. /* Request any required workspace */
  179356. EXTERN(void) jtransform_request_workspace
  179357. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179358. /* Adjust output image parameters */
  179359. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179360. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179361. jvirt_barray_ptr *src_coef_arrays,
  179362. jpeg_transform_info *info));
  179363. /* Execute the actual transformation, if any */
  179364. EXTERN(void) jtransform_execute_transformation
  179365. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179366. jvirt_barray_ptr *src_coef_arrays,
  179367. jpeg_transform_info *info));
  179368. #endif /* TRANSFORMS_SUPPORTED */
  179369. /*
  179370. * Support for copying optional markers from source to destination file.
  179371. */
  179372. typedef enum {
  179373. JCOPYOPT_NONE, /* copy no optional markers */
  179374. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179375. JCOPYOPT_ALL /* copy all optional markers */
  179376. } JCOPY_OPTION;
  179377. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179378. /* Setup decompression object to save desired markers in memory */
  179379. EXTERN(void) jcopy_markers_setup
  179380. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179381. /* Copy markers saved in the given source object to the destination object */
  179382. EXTERN(void) jcopy_markers_execute
  179383. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179384. JCOPY_OPTION option));
  179385. /*** End of inlined file: transupp.h ***/
  179386. /* My own external interface */
  179387. #if TRANSFORMS_SUPPORTED
  179388. /*
  179389. * Lossless image transformation routines. These routines work on DCT
  179390. * coefficient arrays and thus do not require any lossy decompression
  179391. * or recompression of the image.
  179392. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179393. *
  179394. * Horizontal flipping is done in-place, using a single top-to-bottom
  179395. * pass through the virtual source array. It will thus be much the
  179396. * fastest option for images larger than main memory.
  179397. *
  179398. * The other routines require a set of destination virtual arrays, so they
  179399. * need twice as much memory as jpegtran normally does. The destination
  179400. * arrays are always written in normal scan order (top to bottom) because
  179401. * the virtual array manager expects this. The source arrays will be scanned
  179402. * in the corresponding order, which means multiple passes through the source
  179403. * arrays for most of the transforms. That could result in much thrashing
  179404. * if the image is larger than main memory.
  179405. *
  179406. * Some notes about the operating environment of the individual transform
  179407. * routines:
  179408. * 1. Both the source and destination virtual arrays are allocated from the
  179409. * source JPEG object, and therefore should be manipulated by calling the
  179410. * source's memory manager.
  179411. * 2. The destination's component count should be used. It may be smaller
  179412. * than the source's when forcing to grayscale.
  179413. * 3. Likewise the destination's sampling factors should be used. When
  179414. * forcing to grayscale the destination's sampling factors will be all 1,
  179415. * and we may as well take that as the effective iMCU size.
  179416. * 4. When "trim" is in effect, the destination's dimensions will be the
  179417. * trimmed values but the source's will be untrimmed.
  179418. * 5. All the routines assume that the source and destination buffers are
  179419. * padded out to a full iMCU boundary. This is true, although for the
  179420. * source buffer it is an undocumented property of jdcoefct.c.
  179421. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179422. * dimensions and ignore the source's.
  179423. */
  179424. LOCAL(void)
  179425. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179426. jvirt_barray_ptr *src_coef_arrays)
  179427. /* Horizontal flip; done in-place, so no separate dest array is required */
  179428. {
  179429. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179430. int ci, k, offset_y;
  179431. JBLOCKARRAY buffer;
  179432. JCOEFPTR ptr1, ptr2;
  179433. JCOEF temp1, temp2;
  179434. jpeg_component_info *compptr;
  179435. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179436. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179437. * mirroring by changing the signs of odd-numbered columns.
  179438. * Partial iMCUs at the right edge are left untouched.
  179439. */
  179440. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179441. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179442. compptr = dstinfo->comp_info + ci;
  179443. comp_width = MCU_cols * compptr->h_samp_factor;
  179444. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179445. blk_y += compptr->v_samp_factor) {
  179446. buffer = (*srcinfo->mem->access_virt_barray)
  179447. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179448. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179449. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179450. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179451. ptr1 = buffer[offset_y][blk_x];
  179452. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179453. /* this unrolled loop doesn't need to know which row it's on... */
  179454. for (k = 0; k < DCTSIZE2; k += 2) {
  179455. temp1 = *ptr1; /* swap even column */
  179456. temp2 = *ptr2;
  179457. *ptr1++ = temp2;
  179458. *ptr2++ = temp1;
  179459. temp1 = *ptr1; /* swap odd column with sign change */
  179460. temp2 = *ptr2;
  179461. *ptr1++ = -temp2;
  179462. *ptr2++ = -temp1;
  179463. }
  179464. }
  179465. }
  179466. }
  179467. }
  179468. }
  179469. LOCAL(void)
  179470. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179471. jvirt_barray_ptr *src_coef_arrays,
  179472. jvirt_barray_ptr *dst_coef_arrays)
  179473. /* Vertical flip */
  179474. {
  179475. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179476. int ci, i, j, offset_y;
  179477. JBLOCKARRAY src_buffer, dst_buffer;
  179478. JBLOCKROW src_row_ptr, dst_row_ptr;
  179479. JCOEFPTR src_ptr, dst_ptr;
  179480. jpeg_component_info *compptr;
  179481. /* We output into a separate array because we can't touch different
  179482. * rows of the source virtual array simultaneously. Otherwise, this
  179483. * is a pretty straightforward analog of horizontal flip.
  179484. * Within a DCT block, vertical mirroring is done by changing the signs
  179485. * of odd-numbered rows.
  179486. * Partial iMCUs at the bottom edge are copied verbatim.
  179487. */
  179488. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179489. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179490. compptr = dstinfo->comp_info + ci;
  179491. comp_height = MCU_rows * compptr->v_samp_factor;
  179492. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179493. dst_blk_y += compptr->v_samp_factor) {
  179494. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179495. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179496. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179497. if (dst_blk_y < comp_height) {
  179498. /* Row is within the mirrorable area. */
  179499. src_buffer = (*srcinfo->mem->access_virt_barray)
  179500. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179501. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179502. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179503. } else {
  179504. /* Bottom-edge blocks will be copied verbatim. */
  179505. src_buffer = (*srcinfo->mem->access_virt_barray)
  179506. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179507. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179508. }
  179509. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179510. if (dst_blk_y < comp_height) {
  179511. /* Row is within the mirrorable area. */
  179512. dst_row_ptr = dst_buffer[offset_y];
  179513. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179514. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179515. dst_blk_x++) {
  179516. dst_ptr = dst_row_ptr[dst_blk_x];
  179517. src_ptr = src_row_ptr[dst_blk_x];
  179518. for (i = 0; i < DCTSIZE; i += 2) {
  179519. /* copy even row */
  179520. for (j = 0; j < DCTSIZE; j++)
  179521. *dst_ptr++ = *src_ptr++;
  179522. /* copy odd row with sign change */
  179523. for (j = 0; j < DCTSIZE; j++)
  179524. *dst_ptr++ = - *src_ptr++;
  179525. }
  179526. }
  179527. } else {
  179528. /* Just copy row verbatim. */
  179529. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179530. compptr->width_in_blocks);
  179531. }
  179532. }
  179533. }
  179534. }
  179535. }
  179536. LOCAL(void)
  179537. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179538. jvirt_barray_ptr *src_coef_arrays,
  179539. jvirt_barray_ptr *dst_coef_arrays)
  179540. /* Transpose source into destination */
  179541. {
  179542. JDIMENSION dst_blk_x, dst_blk_y;
  179543. int ci, i, j, offset_x, offset_y;
  179544. JBLOCKARRAY src_buffer, dst_buffer;
  179545. JCOEFPTR src_ptr, dst_ptr;
  179546. jpeg_component_info *compptr;
  179547. /* Transposing pixels within a block just requires transposing the
  179548. * DCT coefficients.
  179549. * Partial iMCUs at the edges require no special treatment; we simply
  179550. * process all the available DCT blocks for every component.
  179551. */
  179552. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179553. compptr = dstinfo->comp_info + ci;
  179554. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179555. dst_blk_y += compptr->v_samp_factor) {
  179556. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179557. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179558. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179559. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179560. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179561. dst_blk_x += compptr->h_samp_factor) {
  179562. src_buffer = (*srcinfo->mem->access_virt_barray)
  179563. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179564. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179565. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179566. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179567. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179568. for (i = 0; i < DCTSIZE; i++)
  179569. for (j = 0; j < DCTSIZE; j++)
  179570. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179571. }
  179572. }
  179573. }
  179574. }
  179575. }
  179576. }
  179577. LOCAL(void)
  179578. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179579. jvirt_barray_ptr *src_coef_arrays,
  179580. jvirt_barray_ptr *dst_coef_arrays)
  179581. /* 90 degree rotation is equivalent to
  179582. * 1. Transposing the image;
  179583. * 2. Horizontal mirroring.
  179584. * These two steps are merged into a single processing routine.
  179585. */
  179586. {
  179587. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179588. int ci, i, j, offset_x, offset_y;
  179589. JBLOCKARRAY src_buffer, dst_buffer;
  179590. JCOEFPTR src_ptr, dst_ptr;
  179591. jpeg_component_info *compptr;
  179592. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179593. * at the (output) right edge properly. They just get transposed and
  179594. * not mirrored.
  179595. */
  179596. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179597. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179598. compptr = dstinfo->comp_info + ci;
  179599. comp_width = MCU_cols * compptr->h_samp_factor;
  179600. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179601. dst_blk_y += compptr->v_samp_factor) {
  179602. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179603. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179604. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179605. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179606. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179607. dst_blk_x += compptr->h_samp_factor) {
  179608. src_buffer = (*srcinfo->mem->access_virt_barray)
  179609. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179610. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179611. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179612. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179613. if (dst_blk_x < comp_width) {
  179614. /* Block is within the mirrorable area. */
  179615. dst_ptr = dst_buffer[offset_y]
  179616. [comp_width - dst_blk_x - offset_x - 1];
  179617. for (i = 0; i < DCTSIZE; i++) {
  179618. for (j = 0; j < DCTSIZE; j++)
  179619. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179620. i++;
  179621. for (j = 0; j < DCTSIZE; j++)
  179622. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179623. }
  179624. } else {
  179625. /* Edge blocks are transposed but not mirrored. */
  179626. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179627. for (i = 0; i < DCTSIZE; i++)
  179628. for (j = 0; j < DCTSIZE; j++)
  179629. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179630. }
  179631. }
  179632. }
  179633. }
  179634. }
  179635. }
  179636. }
  179637. LOCAL(void)
  179638. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179639. jvirt_barray_ptr *src_coef_arrays,
  179640. jvirt_barray_ptr *dst_coef_arrays)
  179641. /* 270 degree rotation is equivalent to
  179642. * 1. Horizontal mirroring;
  179643. * 2. Transposing the image.
  179644. * These two steps are merged into a single processing routine.
  179645. */
  179646. {
  179647. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179648. int ci, i, j, offset_x, offset_y;
  179649. JBLOCKARRAY src_buffer, dst_buffer;
  179650. JCOEFPTR src_ptr, dst_ptr;
  179651. jpeg_component_info *compptr;
  179652. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179653. * at the (output) bottom edge properly. They just get transposed and
  179654. * not mirrored.
  179655. */
  179656. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179657. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179658. compptr = dstinfo->comp_info + ci;
  179659. comp_height = MCU_rows * compptr->v_samp_factor;
  179660. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179661. dst_blk_y += compptr->v_samp_factor) {
  179662. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179663. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179664. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179665. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179666. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179667. dst_blk_x += compptr->h_samp_factor) {
  179668. src_buffer = (*srcinfo->mem->access_virt_barray)
  179669. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179670. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179671. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179672. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179673. if (dst_blk_y < comp_height) {
  179674. /* Block is within the mirrorable area. */
  179675. src_ptr = src_buffer[offset_x]
  179676. [comp_height - dst_blk_y - offset_y - 1];
  179677. for (i = 0; i < DCTSIZE; i++) {
  179678. for (j = 0; j < DCTSIZE; j++) {
  179679. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179680. j++;
  179681. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179682. }
  179683. }
  179684. } else {
  179685. /* Edge blocks are transposed but not mirrored. */
  179686. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179687. for (i = 0; i < DCTSIZE; i++)
  179688. for (j = 0; j < DCTSIZE; j++)
  179689. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179690. }
  179691. }
  179692. }
  179693. }
  179694. }
  179695. }
  179696. }
  179697. LOCAL(void)
  179698. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179699. jvirt_barray_ptr *src_coef_arrays,
  179700. jvirt_barray_ptr *dst_coef_arrays)
  179701. /* 180 degree rotation is equivalent to
  179702. * 1. Vertical mirroring;
  179703. * 2. Horizontal mirroring.
  179704. * These two steps are merged into a single processing routine.
  179705. */
  179706. {
  179707. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179708. int ci, i, j, offset_y;
  179709. JBLOCKARRAY src_buffer, dst_buffer;
  179710. JBLOCKROW src_row_ptr, dst_row_ptr;
  179711. JCOEFPTR src_ptr, dst_ptr;
  179712. jpeg_component_info *compptr;
  179713. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179714. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179715. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179716. compptr = dstinfo->comp_info + ci;
  179717. comp_width = MCU_cols * compptr->h_samp_factor;
  179718. comp_height = MCU_rows * compptr->v_samp_factor;
  179719. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179720. dst_blk_y += compptr->v_samp_factor) {
  179721. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179722. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179723. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179724. if (dst_blk_y < comp_height) {
  179725. /* Row is within the vertically mirrorable area. */
  179726. src_buffer = (*srcinfo->mem->access_virt_barray)
  179727. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179728. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179729. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179730. } else {
  179731. /* Bottom-edge rows are only mirrored horizontally. */
  179732. src_buffer = (*srcinfo->mem->access_virt_barray)
  179733. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179734. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179735. }
  179736. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179737. if (dst_blk_y < comp_height) {
  179738. /* Row is within the mirrorable area. */
  179739. dst_row_ptr = dst_buffer[offset_y];
  179740. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179741. /* Process the blocks that can be mirrored both ways. */
  179742. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179743. dst_ptr = dst_row_ptr[dst_blk_x];
  179744. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179745. for (i = 0; i < DCTSIZE; i += 2) {
  179746. /* For even row, negate every odd column. */
  179747. for (j = 0; j < DCTSIZE; j += 2) {
  179748. *dst_ptr++ = *src_ptr++;
  179749. *dst_ptr++ = - *src_ptr++;
  179750. }
  179751. /* For odd row, negate every even column. */
  179752. for (j = 0; j < DCTSIZE; j += 2) {
  179753. *dst_ptr++ = - *src_ptr++;
  179754. *dst_ptr++ = *src_ptr++;
  179755. }
  179756. }
  179757. }
  179758. /* Any remaining right-edge blocks are only mirrored vertically. */
  179759. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179760. dst_ptr = dst_row_ptr[dst_blk_x];
  179761. src_ptr = src_row_ptr[dst_blk_x];
  179762. for (i = 0; i < DCTSIZE; i += 2) {
  179763. for (j = 0; j < DCTSIZE; j++)
  179764. *dst_ptr++ = *src_ptr++;
  179765. for (j = 0; j < DCTSIZE; j++)
  179766. *dst_ptr++ = - *src_ptr++;
  179767. }
  179768. }
  179769. } else {
  179770. /* Remaining rows are just mirrored horizontally. */
  179771. dst_row_ptr = dst_buffer[offset_y];
  179772. src_row_ptr = src_buffer[offset_y];
  179773. /* Process the blocks that can be mirrored. */
  179774. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179775. dst_ptr = dst_row_ptr[dst_blk_x];
  179776. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179777. for (i = 0; i < DCTSIZE2; i += 2) {
  179778. *dst_ptr++ = *src_ptr++;
  179779. *dst_ptr++ = - *src_ptr++;
  179780. }
  179781. }
  179782. /* Any remaining right-edge blocks are only copied. */
  179783. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179784. dst_ptr = dst_row_ptr[dst_blk_x];
  179785. src_ptr = src_row_ptr[dst_blk_x];
  179786. for (i = 0; i < DCTSIZE2; i++)
  179787. *dst_ptr++ = *src_ptr++;
  179788. }
  179789. }
  179790. }
  179791. }
  179792. }
  179793. }
  179794. LOCAL(void)
  179795. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179796. jvirt_barray_ptr *src_coef_arrays,
  179797. jvirt_barray_ptr *dst_coef_arrays)
  179798. /* Transverse transpose is equivalent to
  179799. * 1. 180 degree rotation;
  179800. * 2. Transposition;
  179801. * or
  179802. * 1. Horizontal mirroring;
  179803. * 2. Transposition;
  179804. * 3. Horizontal mirroring.
  179805. * These steps are merged into a single processing routine.
  179806. */
  179807. {
  179808. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179809. int ci, i, j, offset_x, offset_y;
  179810. JBLOCKARRAY src_buffer, dst_buffer;
  179811. JCOEFPTR src_ptr, dst_ptr;
  179812. jpeg_component_info *compptr;
  179813. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179814. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179815. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179816. compptr = dstinfo->comp_info + ci;
  179817. comp_width = MCU_cols * compptr->h_samp_factor;
  179818. comp_height = MCU_rows * compptr->v_samp_factor;
  179819. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179820. dst_blk_y += compptr->v_samp_factor) {
  179821. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179822. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179823. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179824. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179825. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179826. dst_blk_x += compptr->h_samp_factor) {
  179827. src_buffer = (*srcinfo->mem->access_virt_barray)
  179828. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179829. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179830. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179831. if (dst_blk_y < comp_height) {
  179832. src_ptr = src_buffer[offset_x]
  179833. [comp_height - dst_blk_y - offset_y - 1];
  179834. if (dst_blk_x < comp_width) {
  179835. /* Block is within the mirrorable area. */
  179836. dst_ptr = dst_buffer[offset_y]
  179837. [comp_width - dst_blk_x - offset_x - 1];
  179838. for (i = 0; i < DCTSIZE; i++) {
  179839. for (j = 0; j < DCTSIZE; j++) {
  179840. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179841. j++;
  179842. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179843. }
  179844. i++;
  179845. for (j = 0; j < DCTSIZE; j++) {
  179846. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179847. j++;
  179848. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179849. }
  179850. }
  179851. } else {
  179852. /* Right-edge blocks are mirrored in y only */
  179853. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179854. for (i = 0; i < DCTSIZE; i++) {
  179855. for (j = 0; j < DCTSIZE; j++) {
  179856. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179857. j++;
  179858. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179859. }
  179860. }
  179861. }
  179862. } else {
  179863. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179864. if (dst_blk_x < comp_width) {
  179865. /* Bottom-edge blocks are mirrored in x only */
  179866. dst_ptr = dst_buffer[offset_y]
  179867. [comp_width - dst_blk_x - offset_x - 1];
  179868. for (i = 0; i < DCTSIZE; i++) {
  179869. for (j = 0; j < DCTSIZE; j++)
  179870. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179871. i++;
  179872. for (j = 0; j < DCTSIZE; j++)
  179873. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179874. }
  179875. } else {
  179876. /* At lower right corner, just transpose, no mirroring */
  179877. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179878. for (i = 0; i < DCTSIZE; i++)
  179879. for (j = 0; j < DCTSIZE; j++)
  179880. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179881. }
  179882. }
  179883. }
  179884. }
  179885. }
  179886. }
  179887. }
  179888. }
  179889. /* Request any required workspace.
  179890. *
  179891. * We allocate the workspace virtual arrays from the source decompression
  179892. * object, so that all the arrays (both the original data and the workspace)
  179893. * will be taken into account while making memory management decisions.
  179894. * Hence, this routine must be called after jpeg_read_header (which reads
  179895. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179896. * the source's virtual arrays).
  179897. */
  179898. GLOBAL(void)
  179899. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179900. jpeg_transform_info *info)
  179901. {
  179902. jvirt_barray_ptr *coef_arrays = NULL;
  179903. jpeg_component_info *compptr;
  179904. int ci;
  179905. if (info->force_grayscale &&
  179906. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179907. srcinfo->num_components == 3) {
  179908. /* We'll only process the first component */
  179909. info->num_components = 1;
  179910. } else {
  179911. /* Process all the components */
  179912. info->num_components = srcinfo->num_components;
  179913. }
  179914. switch (info->transform) {
  179915. case JXFORM_NONE:
  179916. case JXFORM_FLIP_H:
  179917. /* Don't need a workspace array */
  179918. break;
  179919. case JXFORM_FLIP_V:
  179920. case JXFORM_ROT_180:
  179921. /* Need workspace arrays having same dimensions as source image.
  179922. * Note that we allocate arrays padded out to the next iMCU boundary,
  179923. * so that transform routines need not worry about missing edge blocks.
  179924. */
  179925. coef_arrays = (jvirt_barray_ptr *)
  179926. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179927. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179928. for (ci = 0; ci < info->num_components; ci++) {
  179929. compptr = srcinfo->comp_info + ci;
  179930. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179931. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179932. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179933. (long) compptr->h_samp_factor),
  179934. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179935. (long) compptr->v_samp_factor),
  179936. (JDIMENSION) compptr->v_samp_factor);
  179937. }
  179938. break;
  179939. case JXFORM_TRANSPOSE:
  179940. case JXFORM_TRANSVERSE:
  179941. case JXFORM_ROT_90:
  179942. case JXFORM_ROT_270:
  179943. /* Need workspace arrays having transposed dimensions.
  179944. * Note that we allocate arrays padded out to the next iMCU boundary,
  179945. * so that transform routines need not worry about missing edge blocks.
  179946. */
  179947. coef_arrays = (jvirt_barray_ptr *)
  179948. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179949. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179950. for (ci = 0; ci < info->num_components; ci++) {
  179951. compptr = srcinfo->comp_info + ci;
  179952. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179953. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179954. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179955. (long) compptr->v_samp_factor),
  179956. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179957. (long) compptr->h_samp_factor),
  179958. (JDIMENSION) compptr->h_samp_factor);
  179959. }
  179960. break;
  179961. }
  179962. info->workspace_coef_arrays = coef_arrays;
  179963. }
  179964. /* Transpose destination image parameters */
  179965. LOCAL(void)
  179966. transpose_critical_parameters (j_compress_ptr dstinfo)
  179967. {
  179968. int tblno, i, j, ci, itemp;
  179969. jpeg_component_info *compptr;
  179970. JQUANT_TBL *qtblptr;
  179971. JDIMENSION dtemp;
  179972. UINT16 qtemp;
  179973. /* Transpose basic image dimensions */
  179974. dtemp = dstinfo->image_width;
  179975. dstinfo->image_width = dstinfo->image_height;
  179976. dstinfo->image_height = dtemp;
  179977. /* Transpose sampling factors */
  179978. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179979. compptr = dstinfo->comp_info + ci;
  179980. itemp = compptr->h_samp_factor;
  179981. compptr->h_samp_factor = compptr->v_samp_factor;
  179982. compptr->v_samp_factor = itemp;
  179983. }
  179984. /* Transpose quantization tables */
  179985. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179986. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179987. if (qtblptr != NULL) {
  179988. for (i = 0; i < DCTSIZE; i++) {
  179989. for (j = 0; j < i; j++) {
  179990. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179991. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179992. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179993. }
  179994. }
  179995. }
  179996. }
  179997. }
  179998. /* Trim off any partial iMCUs on the indicated destination edge */
  179999. LOCAL(void)
  180000. trim_right_edge (j_compress_ptr dstinfo)
  180001. {
  180002. int ci, max_h_samp_factor;
  180003. JDIMENSION MCU_cols;
  180004. /* We have to compute max_h_samp_factor ourselves,
  180005. * because it hasn't been set yet in the destination
  180006. * (and we don't want to use the source's value).
  180007. */
  180008. max_h_samp_factor = 1;
  180009. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180010. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  180011. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  180012. }
  180013. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  180014. if (MCU_cols > 0) /* can't trim to 0 pixels */
  180015. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  180016. }
  180017. LOCAL(void)
  180018. trim_bottom_edge (j_compress_ptr dstinfo)
  180019. {
  180020. int ci, max_v_samp_factor;
  180021. JDIMENSION MCU_rows;
  180022. /* We have to compute max_v_samp_factor ourselves,
  180023. * because it hasn't been set yet in the destination
  180024. * (and we don't want to use the source's value).
  180025. */
  180026. max_v_samp_factor = 1;
  180027. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180028. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  180029. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  180030. }
  180031. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  180032. if (MCU_rows > 0) /* can't trim to 0 pixels */
  180033. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  180034. }
  180035. /* Adjust output image parameters as needed.
  180036. *
  180037. * This must be called after jpeg_copy_critical_parameters()
  180038. * and before jpeg_write_coefficients().
  180039. *
  180040. * The return value is the set of virtual coefficient arrays to be written
  180041. * (either the ones allocated by jtransform_request_workspace, or the
  180042. * original source data arrays). The caller will need to pass this value
  180043. * to jpeg_write_coefficients().
  180044. */
  180045. GLOBAL(jvirt_barray_ptr *)
  180046. jtransform_adjust_parameters (j_decompress_ptr,
  180047. j_compress_ptr dstinfo,
  180048. jvirt_barray_ptr *src_coef_arrays,
  180049. jpeg_transform_info *info)
  180050. {
  180051. /* If force-to-grayscale is requested, adjust destination parameters */
  180052. if (info->force_grayscale) {
  180053. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  180054. * properly. Among other things, the target h_samp_factor & v_samp_factor
  180055. * will get set to 1, which typically won't match the source.
  180056. * In fact we do this even if the source is already grayscale; that
  180057. * provides an easy way of coercing a grayscale JPEG with funny sampling
  180058. * factors to the customary 1,1. (Some decoders fail on other factors.)
  180059. */
  180060. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  180061. dstinfo->num_components == 3) ||
  180062. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  180063. dstinfo->num_components == 1)) {
  180064. /* We have to preserve the source's quantization table number. */
  180065. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  180066. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  180067. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  180068. } else {
  180069. /* Sorry, can't do it */
  180070. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  180071. }
  180072. }
  180073. /* Correct the destination's image dimensions etc if necessary */
  180074. switch (info->transform) {
  180075. case JXFORM_NONE:
  180076. /* Nothing to do */
  180077. break;
  180078. case JXFORM_FLIP_H:
  180079. if (info->trim)
  180080. trim_right_edge(dstinfo);
  180081. break;
  180082. case JXFORM_FLIP_V:
  180083. if (info->trim)
  180084. trim_bottom_edge(dstinfo);
  180085. break;
  180086. case JXFORM_TRANSPOSE:
  180087. transpose_critical_parameters(dstinfo);
  180088. /* transpose does NOT have to trim anything */
  180089. break;
  180090. case JXFORM_TRANSVERSE:
  180091. transpose_critical_parameters(dstinfo);
  180092. if (info->trim) {
  180093. trim_right_edge(dstinfo);
  180094. trim_bottom_edge(dstinfo);
  180095. }
  180096. break;
  180097. case JXFORM_ROT_90:
  180098. transpose_critical_parameters(dstinfo);
  180099. if (info->trim)
  180100. trim_right_edge(dstinfo);
  180101. break;
  180102. case JXFORM_ROT_180:
  180103. if (info->trim) {
  180104. trim_right_edge(dstinfo);
  180105. trim_bottom_edge(dstinfo);
  180106. }
  180107. break;
  180108. case JXFORM_ROT_270:
  180109. transpose_critical_parameters(dstinfo);
  180110. if (info->trim)
  180111. trim_bottom_edge(dstinfo);
  180112. break;
  180113. }
  180114. /* Return the appropriate output data set */
  180115. if (info->workspace_coef_arrays != NULL)
  180116. return info->workspace_coef_arrays;
  180117. return src_coef_arrays;
  180118. }
  180119. /* Execute the actual transformation, if any.
  180120. *
  180121. * This must be called *after* jpeg_write_coefficients, because it depends
  180122. * on jpeg_write_coefficients to have computed subsidiary values such as
  180123. * the per-component width and height fields in the destination object.
  180124. *
  180125. * Note that some transformations will modify the source data arrays!
  180126. */
  180127. GLOBAL(void)
  180128. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180129. j_compress_ptr dstinfo,
  180130. jvirt_barray_ptr *src_coef_arrays,
  180131. jpeg_transform_info *info)
  180132. {
  180133. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180134. switch (info->transform) {
  180135. case JXFORM_NONE:
  180136. break;
  180137. case JXFORM_FLIP_H:
  180138. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180139. break;
  180140. case JXFORM_FLIP_V:
  180141. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180142. break;
  180143. case JXFORM_TRANSPOSE:
  180144. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180145. break;
  180146. case JXFORM_TRANSVERSE:
  180147. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180148. break;
  180149. case JXFORM_ROT_90:
  180150. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180151. break;
  180152. case JXFORM_ROT_180:
  180153. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180154. break;
  180155. case JXFORM_ROT_270:
  180156. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180157. break;
  180158. }
  180159. }
  180160. #endif /* TRANSFORMS_SUPPORTED */
  180161. /* Setup decompression object to save desired markers in memory.
  180162. * This must be called before jpeg_read_header() to have the desired effect.
  180163. */
  180164. GLOBAL(void)
  180165. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180166. {
  180167. #ifdef SAVE_MARKERS_SUPPORTED
  180168. int m;
  180169. /* Save comments except under NONE option */
  180170. if (option != JCOPYOPT_NONE) {
  180171. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180172. }
  180173. /* Save all types of APPn markers iff ALL option */
  180174. if (option == JCOPYOPT_ALL) {
  180175. for (m = 0; m < 16; m++)
  180176. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180177. }
  180178. #endif /* SAVE_MARKERS_SUPPORTED */
  180179. }
  180180. /* Copy markers saved in the given source object to the destination object.
  180181. * This should be called just after jpeg_start_compress() or
  180182. * jpeg_write_coefficients().
  180183. * Note that those routines will have written the SOI, and also the
  180184. * JFIF APP0 or Adobe APP14 markers if selected.
  180185. */
  180186. GLOBAL(void)
  180187. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180188. JCOPY_OPTION)
  180189. {
  180190. jpeg_saved_marker_ptr marker;
  180191. /* In the current implementation, we don't actually need to examine the
  180192. * option flag here; we just copy everything that got saved.
  180193. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180194. * if the encoder library already wrote one.
  180195. */
  180196. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180197. if (dstinfo->write_JFIF_header &&
  180198. marker->marker == JPEG_APP0 &&
  180199. marker->data_length >= 5 &&
  180200. GETJOCTET(marker->data[0]) == 0x4A &&
  180201. GETJOCTET(marker->data[1]) == 0x46 &&
  180202. GETJOCTET(marker->data[2]) == 0x49 &&
  180203. GETJOCTET(marker->data[3]) == 0x46 &&
  180204. GETJOCTET(marker->data[4]) == 0)
  180205. continue; /* reject duplicate JFIF */
  180206. if (dstinfo->write_Adobe_marker &&
  180207. marker->marker == JPEG_APP0+14 &&
  180208. marker->data_length >= 5 &&
  180209. GETJOCTET(marker->data[0]) == 0x41 &&
  180210. GETJOCTET(marker->data[1]) == 0x64 &&
  180211. GETJOCTET(marker->data[2]) == 0x6F &&
  180212. GETJOCTET(marker->data[3]) == 0x62 &&
  180213. GETJOCTET(marker->data[4]) == 0x65)
  180214. continue; /* reject duplicate Adobe */
  180215. #ifdef NEED_FAR_POINTERS
  180216. /* We could use jpeg_write_marker if the data weren't FAR... */
  180217. {
  180218. unsigned int i;
  180219. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180220. for (i = 0; i < marker->data_length; i++)
  180221. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180222. }
  180223. #else
  180224. jpeg_write_marker(dstinfo, marker->marker,
  180225. marker->data, marker->data_length);
  180226. #endif
  180227. }
  180228. }
  180229. /*** End of inlined file: transupp.c ***/
  180230. #else
  180231. #define JPEG_INTERNALS
  180232. #undef FAR
  180233. #include <jpeglib.h>
  180234. #endif
  180235. }
  180236. #undef max
  180237. #undef min
  180238. #if JUCE_MSVC
  180239. #pragma warning (pop)
  180240. #endif
  180241. BEGIN_JUCE_NAMESPACE
  180242. namespace JPEGHelpers
  180243. {
  180244. using namespace jpeglibNamespace;
  180245. #if ! JUCE_MSVC
  180246. using jpeglibNamespace::boolean;
  180247. #endif
  180248. struct JPEGDecodingFailure {};
  180249. static void fatalErrorHandler (j_common_ptr)
  180250. {
  180251. throw JPEGDecodingFailure();
  180252. }
  180253. static void silentErrorCallback1 (j_common_ptr) {}
  180254. static void silentErrorCallback2 (j_common_ptr, int) {}
  180255. static void silentErrorCallback3 (j_common_ptr, char*) {}
  180256. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180257. {
  180258. zerostruct (err);
  180259. err.error_exit = fatalErrorHandler;
  180260. err.emit_message = silentErrorCallback2;
  180261. err.output_message = silentErrorCallback1;
  180262. err.format_message = silentErrorCallback3;
  180263. err.reset_error_mgr = silentErrorCallback1;
  180264. }
  180265. static void dummyCallback1 (j_decompress_ptr)
  180266. {
  180267. }
  180268. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  180269. {
  180270. decompStruct->src->next_input_byte += num;
  180271. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180272. decompStruct->src->bytes_in_buffer -= num;
  180273. }
  180274. static boolean jpegFill (j_decompress_ptr)
  180275. {
  180276. return 0;
  180277. }
  180278. static const int jpegBufferSize = 512;
  180279. struct JuceJpegDest : public jpeg_destination_mgr
  180280. {
  180281. OutputStream* output;
  180282. char* buffer;
  180283. };
  180284. static void jpegWriteInit (j_compress_ptr)
  180285. {
  180286. }
  180287. static void jpegWriteTerminate (j_compress_ptr cinfo)
  180288. {
  180289. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180290. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180291. dest->output->write (dest->buffer, (int) numToWrite);
  180292. }
  180293. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  180294. {
  180295. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180296. const int numToWrite = jpegBufferSize;
  180297. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180298. dest->free_in_buffer = jpegBufferSize;
  180299. return dest->output->write (dest->buffer, numToWrite);
  180300. }
  180301. }
  180302. JPEGImageFormat::JPEGImageFormat()
  180303. : quality (-1.0f)
  180304. {
  180305. }
  180306. JPEGImageFormat::~JPEGImageFormat() {}
  180307. void JPEGImageFormat::setQuality (const float newQuality)
  180308. {
  180309. quality = newQuality;
  180310. }
  180311. const String JPEGImageFormat::getFormatName()
  180312. {
  180313. return "JPEG";
  180314. }
  180315. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180316. {
  180317. const int bytesNeeded = 10;
  180318. uint8 header [bytesNeeded];
  180319. if (in.read (header, bytesNeeded) == bytesNeeded)
  180320. {
  180321. return header[0] == 0xff
  180322. && header[1] == 0xd8
  180323. && header[2] == 0xff
  180324. && (header[3] == 0xe0 || header[3] == 0xe1);
  180325. }
  180326. return false;
  180327. }
  180328. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180329. const Image juce_loadWithCoreImage (InputStream& input);
  180330. #endif
  180331. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180332. {
  180333. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180334. return juce_loadWithCoreImage (in);
  180335. #else
  180336. using namespace jpeglibNamespace;
  180337. using namespace JPEGHelpers;
  180338. MemoryOutputStream mb;
  180339. mb.writeFromInputStream (in, -1);
  180340. Image image;
  180341. if (mb.getDataSize() > 16)
  180342. {
  180343. struct jpeg_decompress_struct jpegDecompStruct;
  180344. struct jpeg_error_mgr jerr;
  180345. setupSilentErrorHandler (jerr);
  180346. jpegDecompStruct.err = &jerr;
  180347. jpeg_create_decompress (&jpegDecompStruct);
  180348. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180349. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180350. jpegDecompStruct.src->init_source = dummyCallback1;
  180351. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180352. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180353. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180354. jpegDecompStruct.src->term_source = dummyCallback1;
  180355. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180356. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180357. try
  180358. {
  180359. jpeg_read_header (&jpegDecompStruct, TRUE);
  180360. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180361. const int width = jpegDecompStruct.output_width;
  180362. const int height = jpegDecompStruct.output_height;
  180363. jpegDecompStruct.out_color_space = JCS_RGB;
  180364. JSAMPARRAY buffer
  180365. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180366. JPOOL_IMAGE,
  180367. width * 3, 1);
  180368. if (jpeg_start_decompress (&jpegDecompStruct))
  180369. {
  180370. image = Image (Image::RGB, width, height, false);
  180371. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180372. const Image::BitmapData destData (image, true);
  180373. for (int y = 0; y < height; ++y)
  180374. {
  180375. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180376. const uint8* src = *buffer;
  180377. uint8* dest = destData.getLinePointer (y);
  180378. if (hasAlphaChan)
  180379. {
  180380. for (int i = width; --i >= 0;)
  180381. {
  180382. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180383. ((PixelARGB*) dest)->premultiply();
  180384. dest += destData.pixelStride;
  180385. src += 3;
  180386. }
  180387. }
  180388. else
  180389. {
  180390. for (int i = width; --i >= 0;)
  180391. {
  180392. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180393. dest += destData.pixelStride;
  180394. src += 3;
  180395. }
  180396. }
  180397. }
  180398. jpeg_finish_decompress (&jpegDecompStruct);
  180399. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180400. }
  180401. jpeg_destroy_decompress (&jpegDecompStruct);
  180402. }
  180403. catch (...)
  180404. {}
  180405. }
  180406. return image;
  180407. #endif
  180408. }
  180409. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180410. {
  180411. using namespace jpeglibNamespace;
  180412. using namespace JPEGHelpers;
  180413. if (image.hasAlphaChannel())
  180414. {
  180415. // this method could fill the background in white and still save the image..
  180416. jassertfalse;
  180417. return true;
  180418. }
  180419. struct jpeg_compress_struct jpegCompStruct;
  180420. struct jpeg_error_mgr jerr;
  180421. setupSilentErrorHandler (jerr);
  180422. jpegCompStruct.err = &jerr;
  180423. jpeg_create_compress (&jpegCompStruct);
  180424. JuceJpegDest dest;
  180425. jpegCompStruct.dest = &dest;
  180426. dest.output = &out;
  180427. HeapBlock <char> tempBuffer (jpegBufferSize);
  180428. dest.buffer = tempBuffer;
  180429. dest.next_output_byte = (JOCTET*) dest.buffer;
  180430. dest.free_in_buffer = jpegBufferSize;
  180431. dest.init_destination = jpegWriteInit;
  180432. dest.empty_output_buffer = jpegWriteFlush;
  180433. dest.term_destination = jpegWriteTerminate;
  180434. jpegCompStruct.image_width = image.getWidth();
  180435. jpegCompStruct.image_height = image.getHeight();
  180436. jpegCompStruct.input_components = 3;
  180437. jpegCompStruct.in_color_space = JCS_RGB;
  180438. jpegCompStruct.write_JFIF_header = 1;
  180439. jpegCompStruct.X_density = 72;
  180440. jpegCompStruct.Y_density = 72;
  180441. jpeg_set_defaults (&jpegCompStruct);
  180442. jpegCompStruct.dct_method = JDCT_FLOAT;
  180443. jpegCompStruct.optimize_coding = 1;
  180444. //jpegCompStruct.smoothing_factor = 10;
  180445. if (quality < 0.0f)
  180446. quality = 0.85f;
  180447. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180448. jpeg_start_compress (&jpegCompStruct, TRUE);
  180449. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180450. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180451. JPOOL_IMAGE, strideBytes, 1);
  180452. const Image::BitmapData srcData (image, false);
  180453. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180454. {
  180455. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180456. uint8* dst = *buffer;
  180457. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180458. {
  180459. *dst++ = ((const PixelRGB*) src)->getRed();
  180460. *dst++ = ((const PixelRGB*) src)->getGreen();
  180461. *dst++ = ((const PixelRGB*) src)->getBlue();
  180462. src += srcData.pixelStride;
  180463. }
  180464. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180465. }
  180466. jpeg_finish_compress (&jpegCompStruct);
  180467. jpeg_destroy_compress (&jpegCompStruct);
  180468. out.flush();
  180469. return true;
  180470. }
  180471. END_JUCE_NAMESPACE
  180472. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180473. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180474. #if JUCE_MSVC
  180475. #pragma warning (push)
  180476. #pragma warning (disable: 4390 4611)
  180477. #endif
  180478. namespace zlibNamespace
  180479. {
  180480. #if JUCE_INCLUDE_ZLIB_CODE
  180481. #undef OS_CODE
  180482. #undef fdopen
  180483. #undef OS_CODE
  180484. #else
  180485. #include <zlib.h>
  180486. #endif
  180487. }
  180488. namespace pnglibNamespace
  180489. {
  180490. using namespace zlibNamespace;
  180491. #if JUCE_INCLUDE_PNGLIB_CODE
  180492. #if _MSC_VER != 1310
  180493. using ::calloc; // (causes conflict in VS.NET 2003)
  180494. using ::malloc;
  180495. using ::free;
  180496. #endif
  180497. using ::abs;
  180498. #define PNG_INTERNAL
  180499. #define NO_DUMMY_DECL
  180500. #define PNG_SETJMP_NOT_SUPPORTED
  180501. /*** Start of inlined file: png.h ***/
  180502. /* png.h - header file for PNG reference library
  180503. *
  180504. * libpng version 1.2.21 - October 4, 2007
  180505. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180506. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180507. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180508. *
  180509. * Authors and maintainers:
  180510. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180511. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180512. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180513. * See also "Contributing Authors", below.
  180514. *
  180515. * Note about libpng version numbers:
  180516. *
  180517. * Due to various miscommunications, unforeseen code incompatibilities
  180518. * and occasional factors outside the authors' control, version numbering
  180519. * on the library has not always been consistent and straightforward.
  180520. * The following table summarizes matters since version 0.89c, which was
  180521. * the first widely used release:
  180522. *
  180523. * source png.h png.h shared-lib
  180524. * version string int version
  180525. * ------- ------ ----- ----------
  180526. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180527. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180528. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180529. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180530. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180531. * 0.97c 0.97 97 2.0.97
  180532. * 0.98 0.98 98 2.0.98
  180533. * 0.99 0.99 98 2.0.99
  180534. * 0.99a-m 0.99 99 2.0.99
  180535. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180536. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180537. * 1.0.1 png.h string is 10001 2.1.0
  180538. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180539. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180540. * 1.0.2a-b 10003 version, except as noted.
  180541. * 1.0.3 10003
  180542. * 1.0.3a-d 10004
  180543. * 1.0.4 10004
  180544. * 1.0.4a-f 10005
  180545. * 1.0.5 (+ 2 patches) 10005
  180546. * 1.0.5a-d 10006
  180547. * 1.0.5e-r 10100 (not source compatible)
  180548. * 1.0.5s-v 10006 (not binary compatible)
  180549. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180550. * 1.0.6d-f 10007 (still binary incompatible)
  180551. * 1.0.6g 10007
  180552. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180553. * 1.0.6i 10007 10.6i
  180554. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180555. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180556. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180557. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180558. * 1.0.7 1 10007 (still compatible)
  180559. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180560. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180561. * 1.0.8 1 10008 2.1.0.8
  180562. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180563. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180564. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180565. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180566. * 1.0.9 1 10009 2.1.0.9
  180567. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180568. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180569. * 1.0.10 1 10010 2.1.0.10
  180570. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180571. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180572. * 1.0.11 1 10011 2.1.0.11
  180573. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180574. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180575. * 1.0.12 2 10012 2.1.0.12
  180576. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180577. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180578. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180579. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180580. * 1.2.0 3 10200 3.1.2.0
  180581. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180582. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180583. * 1.2.1 3 10201 3.1.2.1
  180584. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180585. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180586. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180587. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180588. * 1.0.13 10 10013 10.so.0.1.0.13
  180589. * 1.2.2 12 10202 12.so.0.1.2.2
  180590. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180591. * 1.2.3 12 10203 12.so.0.1.2.3
  180592. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180593. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180594. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180595. * 1.0.14 10 10014 10.so.0.1.0.14
  180596. * 1.2.4 13 10204 12.so.0.1.2.4
  180597. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180598. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180599. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180600. * 1.0.15 10 10015 10.so.0.1.0.15
  180601. * 1.2.5 13 10205 12.so.0.1.2.5
  180602. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180603. * 1.0.16 10 10016 10.so.0.1.0.16
  180604. * 1.2.6 13 10206 12.so.0.1.2.6
  180605. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180606. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180607. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180608. * 1.0.17 10 10017 10.so.0.1.0.17
  180609. * 1.2.7 13 10207 12.so.0.1.2.7
  180610. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180611. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180612. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180613. * 1.0.18 10 10018 10.so.0.1.0.18
  180614. * 1.2.8 13 10208 12.so.0.1.2.8
  180615. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180616. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180617. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180618. * 1.2.9 13 10209 12.so.0.9[.0]
  180619. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180620. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180621. * 1.2.10 13 10210 12.so.0.10[.0]
  180622. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180623. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180624. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180625. * 1.0.19 10 10019 10.so.0.19[.0]
  180626. * 1.2.11 13 10211 12.so.0.11[.0]
  180627. * 1.0.20 10 10020 10.so.0.20[.0]
  180628. * 1.2.12 13 10212 12.so.0.12[.0]
  180629. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180630. * 1.0.21 10 10021 10.so.0.21[.0]
  180631. * 1.2.13 13 10213 12.so.0.13[.0]
  180632. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180633. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180634. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180635. * 1.0.22 10 10022 10.so.0.22[.0]
  180636. * 1.2.14 13 10214 12.so.0.14[.0]
  180637. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180638. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180639. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180640. * 1.0.23 10 10023 10.so.0.23[.0]
  180641. * 1.2.15 13 10215 12.so.0.15[.0]
  180642. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180643. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180644. * 1.0.24 10 10024 10.so.0.24[.0]
  180645. * 1.2.16 13 10216 12.so.0.16[.0]
  180646. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180647. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180648. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180649. * 1.0.25 10 10025 10.so.0.25[.0]
  180650. * 1.2.17 13 10217 12.so.0.17[.0]
  180651. * 1.0.26 10 10026 10.so.0.26[.0]
  180652. * 1.2.18 13 10218 12.so.0.18[.0]
  180653. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180654. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180655. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180656. * 1.0.27 10 10027 10.so.0.27[.0]
  180657. * 1.2.19 13 10219 12.so.0.19[.0]
  180658. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180659. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180660. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180661. * 1.0.28 10 10028 10.so.0.28[.0]
  180662. * 1.2.20 13 10220 12.so.0.20[.0]
  180663. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180664. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180665. * 1.0.29 10 10029 10.so.0.29[.0]
  180666. * 1.2.21 13 10221 12.so.0.21[.0]
  180667. *
  180668. * Henceforth the source version will match the shared-library major
  180669. * and minor numbers; the shared-library major version number will be
  180670. * used for changes in backward compatibility, as it is intended. The
  180671. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180672. * for applications, is an unsigned integer of the form xyyzz corresponding
  180673. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180674. * were given the previous public release number plus a letter, until
  180675. * version 1.0.6j; from then on they were given the upcoming public
  180676. * release number plus "betaNN" or "rcN".
  180677. *
  180678. * Binary incompatibility exists only when applications make direct access
  180679. * to the info_ptr or png_ptr members through png.h, and the compiled
  180680. * application is loaded with a different version of the library.
  180681. *
  180682. * DLLNUM will change each time there are forward or backward changes
  180683. * in binary compatibility (e.g., when a new feature is added).
  180684. *
  180685. * See libpng.txt or libpng.3 for more information. The PNG specification
  180686. * is available as a W3C Recommendation and as an ISO Specification,
  180687. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180688. */
  180689. /*
  180690. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180691. *
  180692. * If you modify libpng you may insert additional notices immediately following
  180693. * this sentence.
  180694. *
  180695. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180696. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180697. * distributed according to the same disclaimer and license as libpng-1.2.5
  180698. * with the following individual added to the list of Contributing Authors:
  180699. *
  180700. * Cosmin Truta
  180701. *
  180702. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180703. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180704. * distributed according to the same disclaimer and license as libpng-1.0.6
  180705. * with the following individuals added to the list of Contributing Authors:
  180706. *
  180707. * Simon-Pierre Cadieux
  180708. * Eric S. Raymond
  180709. * Gilles Vollant
  180710. *
  180711. * and with the following additions to the disclaimer:
  180712. *
  180713. * There is no warranty against interference with your enjoyment of the
  180714. * library or against infringement. There is no warranty that our
  180715. * efforts or the library will fulfill any of your particular purposes
  180716. * or needs. This library is provided with all faults, and the entire
  180717. * risk of satisfactory quality, performance, accuracy, and effort is with
  180718. * the user.
  180719. *
  180720. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180721. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180722. * distributed according to the same disclaimer and license as libpng-0.96,
  180723. * with the following individuals added to the list of Contributing Authors:
  180724. *
  180725. * Tom Lane
  180726. * Glenn Randers-Pehrson
  180727. * Willem van Schaik
  180728. *
  180729. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180730. * Copyright (c) 1996, 1997 Andreas Dilger
  180731. * Distributed according to the same disclaimer and license as libpng-0.88,
  180732. * with the following individuals added to the list of Contributing Authors:
  180733. *
  180734. * John Bowler
  180735. * Kevin Bracey
  180736. * Sam Bushell
  180737. * Magnus Holmgren
  180738. * Greg Roelofs
  180739. * Tom Tanner
  180740. *
  180741. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180742. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180743. *
  180744. * For the purposes of this copyright and license, "Contributing Authors"
  180745. * is defined as the following set of individuals:
  180746. *
  180747. * Andreas Dilger
  180748. * Dave Martindale
  180749. * Guy Eric Schalnat
  180750. * Paul Schmidt
  180751. * Tim Wegner
  180752. *
  180753. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180754. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180755. * including, without limitation, the warranties of merchantability and of
  180756. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180757. * assume no liability for direct, indirect, incidental, special, exemplary,
  180758. * or consequential damages, which may result from the use of the PNG
  180759. * Reference Library, even if advised of the possibility of such damage.
  180760. *
  180761. * Permission is hereby granted to use, copy, modify, and distribute this
  180762. * source code, or portions hereof, for any purpose, without fee, subject
  180763. * to the following restrictions:
  180764. *
  180765. * 1. The origin of this source code must not be misrepresented.
  180766. *
  180767. * 2. Altered versions must be plainly marked as such and
  180768. * must not be misrepresented as being the original source.
  180769. *
  180770. * 3. This Copyright notice may not be removed or altered from
  180771. * any source or altered source distribution.
  180772. *
  180773. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180774. * fee, and encourage the use of this source code as a component to
  180775. * supporting the PNG file format in commercial products. If you use this
  180776. * source code in a product, acknowledgment is not required but would be
  180777. * appreciated.
  180778. */
  180779. /*
  180780. * A "png_get_copyright" function is available, for convenient use in "about"
  180781. * boxes and the like:
  180782. *
  180783. * printf("%s",png_get_copyright(NULL));
  180784. *
  180785. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180786. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180787. */
  180788. /*
  180789. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180790. * certification mark of the Open Source Initiative.
  180791. */
  180792. /*
  180793. * The contributing authors would like to thank all those who helped
  180794. * with testing, bug fixes, and patience. This wouldn't have been
  180795. * possible without all of you.
  180796. *
  180797. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180798. */
  180799. /*
  180800. * Y2K compliance in libpng:
  180801. * =========================
  180802. *
  180803. * October 4, 2007
  180804. *
  180805. * Since the PNG Development group is an ad-hoc body, we can't make
  180806. * an official declaration.
  180807. *
  180808. * This is your unofficial assurance that libpng from version 0.71 and
  180809. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180810. * versions were also Y2K compliant.
  180811. *
  180812. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180813. * that will hold years up to 65535. The other two hold the date in text
  180814. * format, and will hold years up to 9999.
  180815. *
  180816. * The integer is
  180817. * "png_uint_16 year" in png_time_struct.
  180818. *
  180819. * The strings are
  180820. * "png_charp time_buffer" in png_struct and
  180821. * "near_time_buffer", which is a local character string in png.c.
  180822. *
  180823. * There are seven time-related functions:
  180824. * png.c: png_convert_to_rfc_1123() in png.c
  180825. * (formerly png_convert_to_rfc_1152() in error)
  180826. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180827. * png_convert_from_time_t() in pngwrite.c
  180828. * png_get_tIME() in pngget.c
  180829. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180830. * png_set_tIME() in pngset.c
  180831. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180832. *
  180833. * All handle dates properly in a Y2K environment. The
  180834. * png_convert_from_time_t() function calls gmtime() to convert from system
  180835. * clock time, which returns (year - 1900), which we properly convert to
  180836. * the full 4-digit year. There is a possibility that applications using
  180837. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180838. * function, or that they are incorrectly passing only a 2-digit year
  180839. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180840. * but this is not under our control. The libpng documentation has always
  180841. * stated that it works with 4-digit years, and the APIs have been
  180842. * documented as such.
  180843. *
  180844. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180845. * integer to hold the year, and can hold years as large as 65535.
  180846. *
  180847. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180848. * no date-related code.
  180849. *
  180850. * Glenn Randers-Pehrson
  180851. * libpng maintainer
  180852. * PNG Development Group
  180853. */
  180854. #ifndef PNG_H
  180855. #define PNG_H
  180856. /* This is not the place to learn how to use libpng. The file libpng.txt
  180857. * describes how to use libpng, and the file example.c summarizes it
  180858. * with some code on which to build. This file is useful for looking
  180859. * at the actual function definitions and structure components.
  180860. */
  180861. /* Version information for png.h - this should match the version in png.c */
  180862. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180863. #define PNG_HEADER_VERSION_STRING \
  180864. " libpng version 1.2.21 - October 4, 2007\n"
  180865. #define PNG_LIBPNG_VER_SONUM 0
  180866. #define PNG_LIBPNG_VER_DLLNUM 13
  180867. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180868. #define PNG_LIBPNG_VER_MAJOR 1
  180869. #define PNG_LIBPNG_VER_MINOR 2
  180870. #define PNG_LIBPNG_VER_RELEASE 21
  180871. /* This should match the numeric part of the final component of
  180872. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180873. #define PNG_LIBPNG_VER_BUILD 0
  180874. /* Release Status */
  180875. #define PNG_LIBPNG_BUILD_ALPHA 1
  180876. #define PNG_LIBPNG_BUILD_BETA 2
  180877. #define PNG_LIBPNG_BUILD_RC 3
  180878. #define PNG_LIBPNG_BUILD_STABLE 4
  180879. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180880. /* Release-Specific Flags */
  180881. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180882. PNG_LIBPNG_BUILD_STABLE only */
  180883. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180884. PNG_LIBPNG_BUILD_SPECIAL */
  180885. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180886. PNG_LIBPNG_BUILD_PRIVATE */
  180887. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180888. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180889. * We must not include leading zeros.
  180890. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180891. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180892. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180893. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180894. #ifndef PNG_VERSION_INFO_ONLY
  180895. /* include the compression library's header */
  180896. #endif
  180897. /* include all user configurable info, including optional assembler routines */
  180898. /*** Start of inlined file: pngconf.h ***/
  180899. /* pngconf.h - machine configurable file for libpng
  180900. *
  180901. * libpng version 1.2.21 - October 4, 2007
  180902. * For conditions of distribution and use, see copyright notice in png.h
  180903. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180904. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180905. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180906. */
  180907. /* Any machine specific code is near the front of this file, so if you
  180908. * are configuring libpng for a machine, you may want to read the section
  180909. * starting here down to where it starts to typedef png_color, png_text,
  180910. * and png_info.
  180911. */
  180912. #ifndef PNGCONF_H
  180913. #define PNGCONF_H
  180914. #define PNG_1_2_X
  180915. // These are some Juce config settings that should remove any unnecessary code bloat..
  180916. #define PNG_NO_STDIO 1
  180917. #define PNG_DEBUG 0
  180918. #define PNG_NO_WARNINGS 1
  180919. #define PNG_NO_ERROR_TEXT 1
  180920. #define PNG_NO_ERROR_NUMBERS 1
  180921. #define PNG_NO_USER_MEM 1
  180922. #define PNG_NO_READ_iCCP 1
  180923. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180924. #define PNG_NO_READ_USER_CHUNKS 1
  180925. #define PNG_NO_READ_iTXt 1
  180926. #define PNG_NO_READ_sCAL 1
  180927. #define PNG_NO_READ_sPLT 1
  180928. #define png_error(a, b) png_err(a)
  180929. #define png_warning(a, b)
  180930. #define png_chunk_error(a, b) png_err(a)
  180931. #define png_chunk_warning(a, b)
  180932. /*
  180933. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180934. * includes the resource compiler for Windows DLL configurations.
  180935. */
  180936. #ifdef PNG_USER_CONFIG
  180937. # ifndef PNG_USER_PRIVATEBUILD
  180938. # define PNG_USER_PRIVATEBUILD
  180939. # endif
  180940. #include "pngusr.h"
  180941. #endif
  180942. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180943. #ifdef PNG_CONFIGURE_LIBPNG
  180944. #ifdef HAVE_CONFIG_H
  180945. #include "config.h"
  180946. #endif
  180947. #endif
  180948. /*
  180949. * Added at libpng-1.2.8
  180950. *
  180951. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180952. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180953. * the DLL was built>
  180954. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180955. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180956. * distinguish your DLL from those of the official release. These
  180957. * correspond to the trailing letters that come after the version
  180958. * number and must match your private DLL name>
  180959. * e.g. // private DLL "libpng13gx.dll"
  180960. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180961. *
  180962. * The following macros are also at your disposal if you want to complete the
  180963. * DLL VERSIONINFO structure.
  180964. * - PNG_USER_VERSIONINFO_COMMENTS
  180965. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180966. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180967. */
  180968. #ifdef __STDC__
  180969. #ifdef SPECIALBUILD
  180970. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180971. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180972. #endif
  180973. #ifdef PRIVATEBUILD
  180974. # pragma message("PRIVATEBUILD is deprecated.\
  180975. Use PNG_USER_PRIVATEBUILD instead.")
  180976. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180977. #endif
  180978. #endif /* __STDC__ */
  180979. #ifndef PNG_VERSION_INFO_ONLY
  180980. /* End of material added to libpng-1.2.8 */
  180981. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180982. Restored at libpng-1.2.21 */
  180983. # define PNG_WARN_UNINITIALIZED_ROW 1
  180984. /* End of material added at libpng-1.2.19/1.2.21 */
  180985. /* This is the size of the compression buffer, and thus the size of
  180986. * an IDAT chunk. Make this whatever size you feel is best for your
  180987. * machine. One of these will be allocated per png_struct. When this
  180988. * is full, it writes the data to the disk, and does some other
  180989. * calculations. Making this an extremely small size will slow
  180990. * the library down, but you may want to experiment to determine
  180991. * where it becomes significant, if you are concerned with memory
  180992. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180993. * this describes the size of the buffer available to read the data in.
  180994. * Unless this gets smaller than the size of a row (compressed),
  180995. * it should not make much difference how big this is.
  180996. */
  180997. #ifndef PNG_ZBUF_SIZE
  180998. # define PNG_ZBUF_SIZE 8192
  180999. #endif
  181000. /* Enable if you want a write-only libpng */
  181001. #ifndef PNG_NO_READ_SUPPORTED
  181002. # define PNG_READ_SUPPORTED
  181003. #endif
  181004. /* Enable if you want a read-only libpng */
  181005. #ifndef PNG_NO_WRITE_SUPPORTED
  181006. # define PNG_WRITE_SUPPORTED
  181007. #endif
  181008. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  181009. support PNGs that are embedded in MNG datastreams */
  181010. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  181011. # ifndef PNG_MNG_FEATURES_SUPPORTED
  181012. # define PNG_MNG_FEATURES_SUPPORTED
  181013. # endif
  181014. #endif
  181015. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  181016. # ifndef PNG_FLOATING_POINT_SUPPORTED
  181017. # define PNG_FLOATING_POINT_SUPPORTED
  181018. # endif
  181019. #endif
  181020. /* If you are running on a machine where you cannot allocate more
  181021. * than 64K of memory at once, uncomment this. While libpng will not
  181022. * normally need that much memory in a chunk (unless you load up a very
  181023. * large file), zlib needs to know how big of a chunk it can use, and
  181024. * libpng thus makes sure to check any memory allocation to verify it
  181025. * will fit into memory.
  181026. #define PNG_MAX_MALLOC_64K
  181027. */
  181028. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  181029. # define PNG_MAX_MALLOC_64K
  181030. #endif
  181031. /* Special munging to support doing things the 'cygwin' way:
  181032. * 'Normal' png-on-win32 defines/defaults:
  181033. * PNG_BUILD_DLL -- building dll
  181034. * PNG_USE_DLL -- building an application, linking to dll
  181035. * (no define) -- building static library, or building an
  181036. * application and linking to the static lib
  181037. * 'Cygwin' defines/defaults:
  181038. * PNG_BUILD_DLL -- (ignored) building the dll
  181039. * (no define) -- (ignored) building an application, linking to the dll
  181040. * PNG_STATIC -- (ignored) building the static lib, or building an
  181041. * application that links to the static lib.
  181042. * ALL_STATIC -- (ignored) building various static libs, or building an
  181043. * application that links to the static libs.
  181044. * Thus,
  181045. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  181046. * this bit of #ifdefs will define the 'correct' config variables based on
  181047. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  181048. * unnecessary.
  181049. *
  181050. * Also, the precedence order is:
  181051. * ALL_STATIC (since we can't #undef something outside our namespace)
  181052. * PNG_BUILD_DLL
  181053. * PNG_STATIC
  181054. * (nothing) == PNG_USE_DLL
  181055. *
  181056. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  181057. * of auto-import in binutils, we no longer need to worry about
  181058. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  181059. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  181060. * to __declspec() stuff. However, we DO need to worry about
  181061. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  181062. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  181063. */
  181064. #if defined(__CYGWIN__)
  181065. # if defined(ALL_STATIC)
  181066. # if defined(PNG_BUILD_DLL)
  181067. # undef PNG_BUILD_DLL
  181068. # endif
  181069. # if defined(PNG_USE_DLL)
  181070. # undef PNG_USE_DLL
  181071. # endif
  181072. # if defined(PNG_DLL)
  181073. # undef PNG_DLL
  181074. # endif
  181075. # if !defined(PNG_STATIC)
  181076. # define PNG_STATIC
  181077. # endif
  181078. # else
  181079. # if defined (PNG_BUILD_DLL)
  181080. # if defined(PNG_STATIC)
  181081. # undef PNG_STATIC
  181082. # endif
  181083. # if defined(PNG_USE_DLL)
  181084. # undef PNG_USE_DLL
  181085. # endif
  181086. # if !defined(PNG_DLL)
  181087. # define PNG_DLL
  181088. # endif
  181089. # else
  181090. # if defined(PNG_STATIC)
  181091. # if defined(PNG_USE_DLL)
  181092. # undef PNG_USE_DLL
  181093. # endif
  181094. # if defined(PNG_DLL)
  181095. # undef PNG_DLL
  181096. # endif
  181097. # else
  181098. # if !defined(PNG_USE_DLL)
  181099. # define PNG_USE_DLL
  181100. # endif
  181101. # if !defined(PNG_DLL)
  181102. # define PNG_DLL
  181103. # endif
  181104. # endif
  181105. # endif
  181106. # endif
  181107. #endif
  181108. /* This protects us against compilers that run on a windowing system
  181109. * and thus don't have or would rather us not use the stdio types:
  181110. * stdin, stdout, and stderr. The only one currently used is stderr
  181111. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  181112. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  181113. * will also prevent these, plus will prevent the entire set of stdio
  181114. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  181115. * unless (PNG_DEBUG > 0) has been #defined.
  181116. *
  181117. * #define PNG_NO_CONSOLE_IO
  181118. * #define PNG_NO_STDIO
  181119. */
  181120. #if defined(_WIN32_WCE)
  181121. # include <windows.h>
  181122. /* Console I/O functions are not supported on WindowsCE */
  181123. # define PNG_NO_CONSOLE_IO
  181124. # ifdef PNG_DEBUG
  181125. # undef PNG_DEBUG
  181126. # endif
  181127. #endif
  181128. #ifdef PNG_BUILD_DLL
  181129. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181130. # ifndef PNG_NO_CONSOLE_IO
  181131. # define PNG_NO_CONSOLE_IO
  181132. # endif
  181133. # endif
  181134. #endif
  181135. # ifdef PNG_NO_STDIO
  181136. # ifndef PNG_NO_CONSOLE_IO
  181137. # define PNG_NO_CONSOLE_IO
  181138. # endif
  181139. # ifdef PNG_DEBUG
  181140. # if (PNG_DEBUG > 0)
  181141. # include <stdio.h>
  181142. # endif
  181143. # endif
  181144. # else
  181145. # if !defined(_WIN32_WCE)
  181146. /* "stdio.h" functions are not supported on WindowsCE */
  181147. # include <stdio.h>
  181148. # endif
  181149. # endif
  181150. /* This macro protects us against machines that don't have function
  181151. * prototypes (ie K&R style headers). If your compiler does not handle
  181152. * function prototypes, define this macro and use the included ansi2knr.
  181153. * I've always been able to use _NO_PROTO as the indicator, but you may
  181154. * need to drag the empty declaration out in front of here, or change the
  181155. * ifdef to suit your own needs.
  181156. */
  181157. #ifndef PNGARG
  181158. #ifdef OF /* zlib prototype munger */
  181159. # define PNGARG(arglist) OF(arglist)
  181160. #else
  181161. #ifdef _NO_PROTO
  181162. # define PNGARG(arglist) ()
  181163. # ifndef PNG_TYPECAST_NULL
  181164. # define PNG_TYPECAST_NULL
  181165. # endif
  181166. #else
  181167. # define PNGARG(arglist) arglist
  181168. #endif /* _NO_PROTO */
  181169. #endif /* OF */
  181170. #endif /* PNGARG */
  181171. /* Try to determine if we are compiling on a Mac. Note that testing for
  181172. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181173. * on non-Mac platforms.
  181174. */
  181175. #ifndef MACOS
  181176. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181177. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181178. # define MACOS
  181179. # endif
  181180. #endif
  181181. /* enough people need this for various reasons to include it here */
  181182. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181183. # include <sys/types.h>
  181184. #endif
  181185. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181186. # define PNG_SETJMP_SUPPORTED
  181187. #endif
  181188. #ifdef PNG_SETJMP_SUPPORTED
  181189. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181190. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181191. */
  181192. # ifdef __linux__
  181193. # ifdef _BSD_SOURCE
  181194. # define PNG_SAVE_BSD_SOURCE
  181195. # undef _BSD_SOURCE
  181196. # endif
  181197. # ifdef _SETJMP_H
  181198. /* If you encounter a compiler error here, see the explanation
  181199. * near the end of INSTALL.
  181200. */
  181201. __png.h__ already includes setjmp.h;
  181202. __dont__ include it again.;
  181203. # endif
  181204. # endif /* __linux__ */
  181205. /* include setjmp.h for error handling */
  181206. # include <setjmp.h>
  181207. # ifdef __linux__
  181208. # ifdef PNG_SAVE_BSD_SOURCE
  181209. # define _BSD_SOURCE
  181210. # undef PNG_SAVE_BSD_SOURCE
  181211. # endif
  181212. # endif /* __linux__ */
  181213. #endif /* PNG_SETJMP_SUPPORTED */
  181214. #ifdef BSD
  181215. #if ! JUCE_MAC
  181216. # include <strings.h>
  181217. #endif
  181218. #else
  181219. # include <string.h>
  181220. #endif
  181221. /* Other defines for things like memory and the like can go here. */
  181222. #ifdef PNG_INTERNAL
  181223. #include <stdlib.h>
  181224. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181225. * aren't usually used outside the library (as far as I know), so it is
  181226. * debatable if they should be exported at all. In the future, when it is
  181227. * possible to have run-time registry of chunk-handling functions, some of
  181228. * these will be made available again.
  181229. #define PNG_EXTERN extern
  181230. */
  181231. #define PNG_EXTERN
  181232. /* Other defines specific to compilers can go here. Try to keep
  181233. * them inside an appropriate ifdef/endif pair for portability.
  181234. */
  181235. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181236. # if defined(MACOS)
  181237. /* We need to check that <math.h> hasn't already been included earlier
  181238. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181239. * <fp.h> if possible.
  181240. */
  181241. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181242. # include <fp.h>
  181243. # endif
  181244. # else
  181245. # include <math.h>
  181246. # endif
  181247. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181248. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181249. * MATH=68881
  181250. */
  181251. # include <m68881.h>
  181252. # endif
  181253. #endif
  181254. /* Codewarrior on NT has linking problems without this. */
  181255. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181256. # define PNG_ALWAYS_EXTERN
  181257. #endif
  181258. /* This provides the non-ANSI (far) memory allocation routines. */
  181259. #if defined(__TURBOC__) && defined(__MSDOS__)
  181260. # include <mem.h>
  181261. # include <alloc.h>
  181262. #endif
  181263. /* I have no idea why is this necessary... */
  181264. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181265. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181266. # include <malloc.h>
  181267. #endif
  181268. /* This controls how fine the dithering gets. As this allocates
  181269. * a largish chunk of memory (32K), those who are not as concerned
  181270. * with dithering quality can decrease some or all of these.
  181271. */
  181272. #ifndef PNG_DITHER_RED_BITS
  181273. # define PNG_DITHER_RED_BITS 5
  181274. #endif
  181275. #ifndef PNG_DITHER_GREEN_BITS
  181276. # define PNG_DITHER_GREEN_BITS 5
  181277. #endif
  181278. #ifndef PNG_DITHER_BLUE_BITS
  181279. # define PNG_DITHER_BLUE_BITS 5
  181280. #endif
  181281. /* This controls how fine the gamma correction becomes when you
  181282. * are only interested in 8 bits anyway. Increasing this value
  181283. * results in more memory being used, and more pow() functions
  181284. * being called to fill in the gamma tables. Don't set this value
  181285. * less then 8, and even that may not work (I haven't tested it).
  181286. */
  181287. #ifndef PNG_MAX_GAMMA_8
  181288. # define PNG_MAX_GAMMA_8 11
  181289. #endif
  181290. /* This controls how much a difference in gamma we can tolerate before
  181291. * we actually start doing gamma conversion.
  181292. */
  181293. #ifndef PNG_GAMMA_THRESHOLD
  181294. # define PNG_GAMMA_THRESHOLD 0.05
  181295. #endif
  181296. #endif /* PNG_INTERNAL */
  181297. /* The following uses const char * instead of char * for error
  181298. * and warning message functions, so some compilers won't complain.
  181299. * If you do not want to use const, define PNG_NO_CONST here.
  181300. */
  181301. #ifndef PNG_NO_CONST
  181302. # define PNG_CONST const
  181303. #else
  181304. # define PNG_CONST
  181305. #endif
  181306. /* The following defines give you the ability to remove code from the
  181307. * library that you will not be using. I wish I could figure out how to
  181308. * automate this, but I can't do that without making it seriously hard
  181309. * on the users. So if you are not using an ability, change the #define
  181310. * to and #undef, and that part of the library will not be compiled. If
  181311. * your linker can't find a function, you may want to make sure the
  181312. * ability is defined here. Some of these depend upon some others being
  181313. * defined. I haven't figured out all the interactions here, so you may
  181314. * have to experiment awhile to get everything to compile. If you are
  181315. * creating or using a shared library, you probably shouldn't touch this,
  181316. * as it will affect the size of the structures, and this will cause bad
  181317. * things to happen if the library and/or application ever change.
  181318. */
  181319. /* Any features you will not be using can be undef'ed here */
  181320. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181321. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181322. * on the compile line, then pick and choose which ones to define without
  181323. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181324. * if you only want to have a png-compliant reader/writer but don't need
  181325. * any of the extra transformations. This saves about 80 kbytes in a
  181326. * typical installation of the library. (PNG_NO_* form added in version
  181327. * 1.0.1c, for consistency)
  181328. */
  181329. /* The size of the png_text structure changed in libpng-1.0.6 when
  181330. * iTXt support was added. iTXt support was turned off by default through
  181331. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181332. * instead of calling png_set_text() and letting libpng malloc it. It
  181333. * was turned on by default in libpng-1.3.0.
  181334. */
  181335. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181336. # ifndef PNG_NO_iTXt_SUPPORTED
  181337. # define PNG_NO_iTXt_SUPPORTED
  181338. # endif
  181339. # ifndef PNG_NO_READ_iTXt
  181340. # define PNG_NO_READ_iTXt
  181341. # endif
  181342. # ifndef PNG_NO_WRITE_iTXt
  181343. # define PNG_NO_WRITE_iTXt
  181344. # endif
  181345. #endif
  181346. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181347. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181348. # define PNG_READ_iTXt
  181349. # endif
  181350. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181351. # define PNG_WRITE_iTXt
  181352. # endif
  181353. #endif
  181354. /* The following support, added after version 1.0.0, can be turned off here en
  181355. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181356. * with old applications that require the length of png_struct and png_info
  181357. * to remain unchanged.
  181358. */
  181359. #ifdef PNG_LEGACY_SUPPORTED
  181360. # define PNG_NO_FREE_ME
  181361. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181362. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181363. # define PNG_NO_READ_USER_CHUNKS
  181364. # define PNG_NO_READ_iCCP
  181365. # define PNG_NO_WRITE_iCCP
  181366. # define PNG_NO_READ_iTXt
  181367. # define PNG_NO_WRITE_iTXt
  181368. # define PNG_NO_READ_sCAL
  181369. # define PNG_NO_WRITE_sCAL
  181370. # define PNG_NO_READ_sPLT
  181371. # define PNG_NO_WRITE_sPLT
  181372. # define PNG_NO_INFO_IMAGE
  181373. # define PNG_NO_READ_RGB_TO_GRAY
  181374. # define PNG_NO_READ_USER_TRANSFORM
  181375. # define PNG_NO_WRITE_USER_TRANSFORM
  181376. # define PNG_NO_USER_MEM
  181377. # define PNG_NO_READ_EMPTY_PLTE
  181378. # define PNG_NO_MNG_FEATURES
  181379. # define PNG_NO_FIXED_POINT_SUPPORTED
  181380. #endif
  181381. /* Ignore attempt to turn off both floating and fixed point support */
  181382. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181383. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181384. # define PNG_FIXED_POINT_SUPPORTED
  181385. #endif
  181386. #ifndef PNG_NO_FREE_ME
  181387. # define PNG_FREE_ME_SUPPORTED
  181388. #endif
  181389. #if defined(PNG_READ_SUPPORTED)
  181390. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181391. !defined(PNG_NO_READ_TRANSFORMS)
  181392. # define PNG_READ_TRANSFORMS_SUPPORTED
  181393. #endif
  181394. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181395. # ifndef PNG_NO_READ_EXPAND
  181396. # define PNG_READ_EXPAND_SUPPORTED
  181397. # endif
  181398. # ifndef PNG_NO_READ_SHIFT
  181399. # define PNG_READ_SHIFT_SUPPORTED
  181400. # endif
  181401. # ifndef PNG_NO_READ_PACK
  181402. # define PNG_READ_PACK_SUPPORTED
  181403. # endif
  181404. # ifndef PNG_NO_READ_BGR
  181405. # define PNG_READ_BGR_SUPPORTED
  181406. # endif
  181407. # ifndef PNG_NO_READ_SWAP
  181408. # define PNG_READ_SWAP_SUPPORTED
  181409. # endif
  181410. # ifndef PNG_NO_READ_PACKSWAP
  181411. # define PNG_READ_PACKSWAP_SUPPORTED
  181412. # endif
  181413. # ifndef PNG_NO_READ_INVERT
  181414. # define PNG_READ_INVERT_SUPPORTED
  181415. # endif
  181416. # ifndef PNG_NO_READ_DITHER
  181417. # define PNG_READ_DITHER_SUPPORTED
  181418. # endif
  181419. # ifndef PNG_NO_READ_BACKGROUND
  181420. # define PNG_READ_BACKGROUND_SUPPORTED
  181421. # endif
  181422. # ifndef PNG_NO_READ_16_TO_8
  181423. # define PNG_READ_16_TO_8_SUPPORTED
  181424. # endif
  181425. # ifndef PNG_NO_READ_FILLER
  181426. # define PNG_READ_FILLER_SUPPORTED
  181427. # endif
  181428. # ifndef PNG_NO_READ_GAMMA
  181429. # define PNG_READ_GAMMA_SUPPORTED
  181430. # endif
  181431. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181432. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181433. # endif
  181434. # ifndef PNG_NO_READ_SWAP_ALPHA
  181435. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181436. # endif
  181437. # ifndef PNG_NO_READ_INVERT_ALPHA
  181438. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181439. # endif
  181440. # ifndef PNG_NO_READ_STRIP_ALPHA
  181441. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181442. # endif
  181443. # ifndef PNG_NO_READ_USER_TRANSFORM
  181444. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181445. # endif
  181446. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181447. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181448. # endif
  181449. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181450. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181451. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181452. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181453. #endif /* about interlacing capability! You'll */
  181454. /* still have interlacing unless you change the following line: */
  181455. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181456. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181457. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181458. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181459. # endif
  181460. #endif
  181461. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181462. /* Deprecated, will be removed from version 2.0.0.
  181463. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181464. #ifndef PNG_NO_READ_EMPTY_PLTE
  181465. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181466. #endif
  181467. #endif
  181468. #endif /* PNG_READ_SUPPORTED */
  181469. #if defined(PNG_WRITE_SUPPORTED)
  181470. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181471. !defined(PNG_NO_WRITE_TRANSFORMS)
  181472. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181473. #endif
  181474. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181475. # ifndef PNG_NO_WRITE_SHIFT
  181476. # define PNG_WRITE_SHIFT_SUPPORTED
  181477. # endif
  181478. # ifndef PNG_NO_WRITE_PACK
  181479. # define PNG_WRITE_PACK_SUPPORTED
  181480. # endif
  181481. # ifndef PNG_NO_WRITE_BGR
  181482. # define PNG_WRITE_BGR_SUPPORTED
  181483. # endif
  181484. # ifndef PNG_NO_WRITE_SWAP
  181485. # define PNG_WRITE_SWAP_SUPPORTED
  181486. # endif
  181487. # ifndef PNG_NO_WRITE_PACKSWAP
  181488. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181489. # endif
  181490. # ifndef PNG_NO_WRITE_INVERT
  181491. # define PNG_WRITE_INVERT_SUPPORTED
  181492. # endif
  181493. # ifndef PNG_NO_WRITE_FILLER
  181494. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181495. # endif
  181496. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181497. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181498. # endif
  181499. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181500. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181501. # endif
  181502. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181503. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181504. # endif
  181505. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181506. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181507. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181508. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181509. encoders, but can cause trouble
  181510. if left undefined */
  181511. #endif
  181512. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181513. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181514. defined(PNG_FLOATING_POINT_SUPPORTED)
  181515. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181516. #endif
  181517. #ifndef PNG_NO_WRITE_FLUSH
  181518. # define PNG_WRITE_FLUSH_SUPPORTED
  181519. #endif
  181520. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181521. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181522. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181523. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181524. #endif
  181525. #endif
  181526. #endif /* PNG_WRITE_SUPPORTED */
  181527. #ifndef PNG_1_0_X
  181528. # ifndef PNG_NO_ERROR_NUMBERS
  181529. # define PNG_ERROR_NUMBERS_SUPPORTED
  181530. # endif
  181531. #endif /* PNG_1_0_X */
  181532. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181533. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181534. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181535. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181536. # endif
  181537. #endif
  181538. #ifndef PNG_NO_STDIO
  181539. # define PNG_TIME_RFC1123_SUPPORTED
  181540. #endif
  181541. /* This adds extra functions in pngget.c for accessing data from the
  181542. * info pointer (added in version 0.99)
  181543. * png_get_image_width()
  181544. * png_get_image_height()
  181545. * png_get_bit_depth()
  181546. * png_get_color_type()
  181547. * png_get_compression_type()
  181548. * png_get_filter_type()
  181549. * png_get_interlace_type()
  181550. * png_get_pixel_aspect_ratio()
  181551. * png_get_pixels_per_meter()
  181552. * png_get_x_offset_pixels()
  181553. * png_get_y_offset_pixels()
  181554. * png_get_x_offset_microns()
  181555. * png_get_y_offset_microns()
  181556. */
  181557. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181558. # define PNG_EASY_ACCESS_SUPPORTED
  181559. #endif
  181560. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181561. * and removed from version 1.2.20. The following will be removed
  181562. * from libpng-1.4.0
  181563. */
  181564. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181565. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181566. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181567. # endif
  181568. #endif
  181569. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181570. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181571. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181572. # endif
  181573. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181574. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181575. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181576. # define PNG_NO_MMX_CODE
  181577. # endif
  181578. # endif
  181579. # if defined(__APPLE__)
  181580. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181581. # define PNG_NO_MMX_CODE
  181582. # endif
  181583. # endif
  181584. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181585. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181586. # define PNG_NO_MMX_CODE
  181587. # endif
  181588. # endif
  181589. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181590. # define PNG_MMX_CODE_SUPPORTED
  181591. # endif
  181592. #endif
  181593. /* end of obsolete code to be removed from libpng-1.4.0 */
  181594. #if !defined(PNG_1_0_X)
  181595. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181596. # define PNG_USER_MEM_SUPPORTED
  181597. #endif
  181598. #endif /* PNG_1_0_X */
  181599. /* Added at libpng-1.2.6 */
  181600. #if !defined(PNG_1_0_X)
  181601. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181602. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181603. # define PNG_SET_USER_LIMITS_SUPPORTED
  181604. #endif
  181605. #endif
  181606. #endif /* PNG_1_0_X */
  181607. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181608. * how large, set these limits to 0x7fffffffL
  181609. */
  181610. #ifndef PNG_USER_WIDTH_MAX
  181611. # define PNG_USER_WIDTH_MAX 1000000L
  181612. #endif
  181613. #ifndef PNG_USER_HEIGHT_MAX
  181614. # define PNG_USER_HEIGHT_MAX 1000000L
  181615. #endif
  181616. /* These are currently experimental features, define them if you want */
  181617. /* very little testing */
  181618. /*
  181619. #ifdef PNG_READ_SUPPORTED
  181620. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181621. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181622. # endif
  181623. #endif
  181624. */
  181625. /* This is only for PowerPC big-endian and 680x0 systems */
  181626. /* some testing */
  181627. /*
  181628. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181629. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181630. #endif
  181631. */
  181632. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181633. /*
  181634. #define PNG_NO_POINTER_INDEXING
  181635. */
  181636. /* These functions are turned off by default, as they will be phased out. */
  181637. /*
  181638. #define PNG_USELESS_TESTS_SUPPORTED
  181639. #define PNG_CORRECT_PALETTE_SUPPORTED
  181640. */
  181641. /* Any chunks you are not interested in, you can undef here. The
  181642. * ones that allocate memory may be expecially important (hIST,
  181643. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181644. * a bit smaller.
  181645. */
  181646. #if defined(PNG_READ_SUPPORTED) && \
  181647. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181648. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181649. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181650. #endif
  181651. #if defined(PNG_WRITE_SUPPORTED) && \
  181652. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181653. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181654. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181655. #endif
  181656. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181657. #ifdef PNG_NO_READ_TEXT
  181658. # define PNG_NO_READ_iTXt
  181659. # define PNG_NO_READ_tEXt
  181660. # define PNG_NO_READ_zTXt
  181661. #endif
  181662. #ifndef PNG_NO_READ_bKGD
  181663. # define PNG_READ_bKGD_SUPPORTED
  181664. # define PNG_bKGD_SUPPORTED
  181665. #endif
  181666. #ifndef PNG_NO_READ_cHRM
  181667. # define PNG_READ_cHRM_SUPPORTED
  181668. # define PNG_cHRM_SUPPORTED
  181669. #endif
  181670. #ifndef PNG_NO_READ_gAMA
  181671. # define PNG_READ_gAMA_SUPPORTED
  181672. # define PNG_gAMA_SUPPORTED
  181673. #endif
  181674. #ifndef PNG_NO_READ_hIST
  181675. # define PNG_READ_hIST_SUPPORTED
  181676. # define PNG_hIST_SUPPORTED
  181677. #endif
  181678. #ifndef PNG_NO_READ_iCCP
  181679. # define PNG_READ_iCCP_SUPPORTED
  181680. # define PNG_iCCP_SUPPORTED
  181681. #endif
  181682. #ifndef PNG_NO_READ_iTXt
  181683. # ifndef PNG_READ_iTXt_SUPPORTED
  181684. # define PNG_READ_iTXt_SUPPORTED
  181685. # endif
  181686. # ifndef PNG_iTXt_SUPPORTED
  181687. # define PNG_iTXt_SUPPORTED
  181688. # endif
  181689. #endif
  181690. #ifndef PNG_NO_READ_oFFs
  181691. # define PNG_READ_oFFs_SUPPORTED
  181692. # define PNG_oFFs_SUPPORTED
  181693. #endif
  181694. #ifndef PNG_NO_READ_pCAL
  181695. # define PNG_READ_pCAL_SUPPORTED
  181696. # define PNG_pCAL_SUPPORTED
  181697. #endif
  181698. #ifndef PNG_NO_READ_sCAL
  181699. # define PNG_READ_sCAL_SUPPORTED
  181700. # define PNG_sCAL_SUPPORTED
  181701. #endif
  181702. #ifndef PNG_NO_READ_pHYs
  181703. # define PNG_READ_pHYs_SUPPORTED
  181704. # define PNG_pHYs_SUPPORTED
  181705. #endif
  181706. #ifndef PNG_NO_READ_sBIT
  181707. # define PNG_READ_sBIT_SUPPORTED
  181708. # define PNG_sBIT_SUPPORTED
  181709. #endif
  181710. #ifndef PNG_NO_READ_sPLT
  181711. # define PNG_READ_sPLT_SUPPORTED
  181712. # define PNG_sPLT_SUPPORTED
  181713. #endif
  181714. #ifndef PNG_NO_READ_sRGB
  181715. # define PNG_READ_sRGB_SUPPORTED
  181716. # define PNG_sRGB_SUPPORTED
  181717. #endif
  181718. #ifndef PNG_NO_READ_tEXt
  181719. # define PNG_READ_tEXt_SUPPORTED
  181720. # define PNG_tEXt_SUPPORTED
  181721. #endif
  181722. #ifndef PNG_NO_READ_tIME
  181723. # define PNG_READ_tIME_SUPPORTED
  181724. # define PNG_tIME_SUPPORTED
  181725. #endif
  181726. #ifndef PNG_NO_READ_tRNS
  181727. # define PNG_READ_tRNS_SUPPORTED
  181728. # define PNG_tRNS_SUPPORTED
  181729. #endif
  181730. #ifndef PNG_NO_READ_zTXt
  181731. # define PNG_READ_zTXt_SUPPORTED
  181732. # define PNG_zTXt_SUPPORTED
  181733. #endif
  181734. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181735. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181736. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181737. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181738. # endif
  181739. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181740. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181741. # endif
  181742. #endif
  181743. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181744. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181745. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181746. # define PNG_USER_CHUNKS_SUPPORTED
  181747. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181748. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181749. # endif
  181750. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181751. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181752. # endif
  181753. #endif
  181754. #ifndef PNG_NO_READ_OPT_PLTE
  181755. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181756. #endif /* optional PLTE chunk in RGB and RGBA images */
  181757. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181758. defined(PNG_READ_zTXt_SUPPORTED)
  181759. # define PNG_READ_TEXT_SUPPORTED
  181760. # define PNG_TEXT_SUPPORTED
  181761. #endif
  181762. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181763. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181764. #ifdef PNG_NO_WRITE_TEXT
  181765. # define PNG_NO_WRITE_iTXt
  181766. # define PNG_NO_WRITE_tEXt
  181767. # define PNG_NO_WRITE_zTXt
  181768. #endif
  181769. #ifndef PNG_NO_WRITE_bKGD
  181770. # define PNG_WRITE_bKGD_SUPPORTED
  181771. # ifndef PNG_bKGD_SUPPORTED
  181772. # define PNG_bKGD_SUPPORTED
  181773. # endif
  181774. #endif
  181775. #ifndef PNG_NO_WRITE_cHRM
  181776. # define PNG_WRITE_cHRM_SUPPORTED
  181777. # ifndef PNG_cHRM_SUPPORTED
  181778. # define PNG_cHRM_SUPPORTED
  181779. # endif
  181780. #endif
  181781. #ifndef PNG_NO_WRITE_gAMA
  181782. # define PNG_WRITE_gAMA_SUPPORTED
  181783. # ifndef PNG_gAMA_SUPPORTED
  181784. # define PNG_gAMA_SUPPORTED
  181785. # endif
  181786. #endif
  181787. #ifndef PNG_NO_WRITE_hIST
  181788. # define PNG_WRITE_hIST_SUPPORTED
  181789. # ifndef PNG_hIST_SUPPORTED
  181790. # define PNG_hIST_SUPPORTED
  181791. # endif
  181792. #endif
  181793. #ifndef PNG_NO_WRITE_iCCP
  181794. # define PNG_WRITE_iCCP_SUPPORTED
  181795. # ifndef PNG_iCCP_SUPPORTED
  181796. # define PNG_iCCP_SUPPORTED
  181797. # endif
  181798. #endif
  181799. #ifndef PNG_NO_WRITE_iTXt
  181800. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181801. # define PNG_WRITE_iTXt_SUPPORTED
  181802. # endif
  181803. # ifndef PNG_iTXt_SUPPORTED
  181804. # define PNG_iTXt_SUPPORTED
  181805. # endif
  181806. #endif
  181807. #ifndef PNG_NO_WRITE_oFFs
  181808. # define PNG_WRITE_oFFs_SUPPORTED
  181809. # ifndef PNG_oFFs_SUPPORTED
  181810. # define PNG_oFFs_SUPPORTED
  181811. # endif
  181812. #endif
  181813. #ifndef PNG_NO_WRITE_pCAL
  181814. # define PNG_WRITE_pCAL_SUPPORTED
  181815. # ifndef PNG_pCAL_SUPPORTED
  181816. # define PNG_pCAL_SUPPORTED
  181817. # endif
  181818. #endif
  181819. #ifndef PNG_NO_WRITE_sCAL
  181820. # define PNG_WRITE_sCAL_SUPPORTED
  181821. # ifndef PNG_sCAL_SUPPORTED
  181822. # define PNG_sCAL_SUPPORTED
  181823. # endif
  181824. #endif
  181825. #ifndef PNG_NO_WRITE_pHYs
  181826. # define PNG_WRITE_pHYs_SUPPORTED
  181827. # ifndef PNG_pHYs_SUPPORTED
  181828. # define PNG_pHYs_SUPPORTED
  181829. # endif
  181830. #endif
  181831. #ifndef PNG_NO_WRITE_sBIT
  181832. # define PNG_WRITE_sBIT_SUPPORTED
  181833. # ifndef PNG_sBIT_SUPPORTED
  181834. # define PNG_sBIT_SUPPORTED
  181835. # endif
  181836. #endif
  181837. #ifndef PNG_NO_WRITE_sPLT
  181838. # define PNG_WRITE_sPLT_SUPPORTED
  181839. # ifndef PNG_sPLT_SUPPORTED
  181840. # define PNG_sPLT_SUPPORTED
  181841. # endif
  181842. #endif
  181843. #ifndef PNG_NO_WRITE_sRGB
  181844. # define PNG_WRITE_sRGB_SUPPORTED
  181845. # ifndef PNG_sRGB_SUPPORTED
  181846. # define PNG_sRGB_SUPPORTED
  181847. # endif
  181848. #endif
  181849. #ifndef PNG_NO_WRITE_tEXt
  181850. # define PNG_WRITE_tEXt_SUPPORTED
  181851. # ifndef PNG_tEXt_SUPPORTED
  181852. # define PNG_tEXt_SUPPORTED
  181853. # endif
  181854. #endif
  181855. #ifndef PNG_NO_WRITE_tIME
  181856. # define PNG_WRITE_tIME_SUPPORTED
  181857. # ifndef PNG_tIME_SUPPORTED
  181858. # define PNG_tIME_SUPPORTED
  181859. # endif
  181860. #endif
  181861. #ifndef PNG_NO_WRITE_tRNS
  181862. # define PNG_WRITE_tRNS_SUPPORTED
  181863. # ifndef PNG_tRNS_SUPPORTED
  181864. # define PNG_tRNS_SUPPORTED
  181865. # endif
  181866. #endif
  181867. #ifndef PNG_NO_WRITE_zTXt
  181868. # define PNG_WRITE_zTXt_SUPPORTED
  181869. # ifndef PNG_zTXt_SUPPORTED
  181870. # define PNG_zTXt_SUPPORTED
  181871. # endif
  181872. #endif
  181873. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181874. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181875. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181876. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181877. # endif
  181878. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181879. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181880. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181881. # endif
  181882. # endif
  181883. #endif
  181884. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181885. defined(PNG_WRITE_zTXt_SUPPORTED)
  181886. # define PNG_WRITE_TEXT_SUPPORTED
  181887. # ifndef PNG_TEXT_SUPPORTED
  181888. # define PNG_TEXT_SUPPORTED
  181889. # endif
  181890. #endif
  181891. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181892. /* Turn this off to disable png_read_png() and
  181893. * png_write_png() and leave the row_pointers member
  181894. * out of the info structure.
  181895. */
  181896. #ifndef PNG_NO_INFO_IMAGE
  181897. # define PNG_INFO_IMAGE_SUPPORTED
  181898. #endif
  181899. /* need the time information for reading tIME chunks */
  181900. #if defined(PNG_tIME_SUPPORTED)
  181901. # if !defined(_WIN32_WCE)
  181902. /* "time.h" functions are not supported on WindowsCE */
  181903. # include <time.h>
  181904. # endif
  181905. #endif
  181906. /* Some typedefs to get us started. These should be safe on most of the
  181907. * common platforms. The typedefs should be at least as large as the
  181908. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181909. * don't have to be exactly that size. Some compilers dislike passing
  181910. * unsigned shorts as function parameters, so you may be better off using
  181911. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181912. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181913. */
  181914. typedef unsigned long png_uint_32;
  181915. typedef long png_int_32;
  181916. typedef unsigned short png_uint_16;
  181917. typedef short png_int_16;
  181918. typedef unsigned char png_byte;
  181919. /* This is usually size_t. It is typedef'ed just in case you need it to
  181920. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181921. #ifdef PNG_SIZE_T
  181922. typedef PNG_SIZE_T png_size_t;
  181923. # define png_sizeof(x) png_convert_size(sizeof (x))
  181924. #else
  181925. typedef size_t png_size_t;
  181926. # define png_sizeof(x) sizeof (x)
  181927. #endif
  181928. /* The following is needed for medium model support. It cannot be in the
  181929. * PNG_INTERNAL section. Needs modification for other compilers besides
  181930. * MSC. Model independent support declares all arrays and pointers to be
  181931. * large using the far keyword. The zlib version used must also support
  181932. * model independent data. As of version zlib 1.0.4, the necessary changes
  181933. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181934. * changes that are needed. (Tim Wegner)
  181935. */
  181936. /* Separate compiler dependencies (problem here is that zlib.h always
  181937. defines FAR. (SJT) */
  181938. #ifdef __BORLANDC__
  181939. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181940. # define LDATA 1
  181941. # else
  181942. # define LDATA 0
  181943. # endif
  181944. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181945. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181946. # define PNG_MAX_MALLOC_64K
  181947. # if (LDATA != 1)
  181948. # ifndef FAR
  181949. # define FAR __far
  181950. # endif
  181951. # define USE_FAR_KEYWORD
  181952. # endif /* LDATA != 1 */
  181953. /* Possibly useful for moving data out of default segment.
  181954. * Uncomment it if you want. Could also define FARDATA as
  181955. * const if your compiler supports it. (SJT)
  181956. # define FARDATA FAR
  181957. */
  181958. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181959. #endif /* __BORLANDC__ */
  181960. /* Suggest testing for specific compiler first before testing for
  181961. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181962. * making reliance oncertain keywords suspect. (SJT)
  181963. */
  181964. /* MSC Medium model */
  181965. #if defined(FAR)
  181966. # if defined(M_I86MM)
  181967. # define USE_FAR_KEYWORD
  181968. # define FARDATA FAR
  181969. # include <dos.h>
  181970. # endif
  181971. #endif
  181972. /* SJT: default case */
  181973. #ifndef FAR
  181974. # define FAR
  181975. #endif
  181976. /* At this point FAR is always defined */
  181977. #ifndef FARDATA
  181978. # define FARDATA
  181979. #endif
  181980. /* Typedef for floating-point numbers that are converted
  181981. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181982. typedef png_int_32 png_fixed_point;
  181983. /* Add typedefs for pointers */
  181984. typedef void FAR * png_voidp;
  181985. typedef png_byte FAR * png_bytep;
  181986. typedef png_uint_32 FAR * png_uint_32p;
  181987. typedef png_int_32 FAR * png_int_32p;
  181988. typedef png_uint_16 FAR * png_uint_16p;
  181989. typedef png_int_16 FAR * png_int_16p;
  181990. typedef PNG_CONST char FAR * png_const_charp;
  181991. typedef char FAR * png_charp;
  181992. typedef png_fixed_point FAR * png_fixed_point_p;
  181993. #ifndef PNG_NO_STDIO
  181994. #if defined(_WIN32_WCE)
  181995. typedef HANDLE png_FILE_p;
  181996. #else
  181997. typedef FILE * png_FILE_p;
  181998. #endif
  181999. #endif
  182000. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182001. typedef double FAR * png_doublep;
  182002. #endif
  182003. /* Pointers to pointers; i.e. arrays */
  182004. typedef png_byte FAR * FAR * png_bytepp;
  182005. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  182006. typedef png_int_32 FAR * FAR * png_int_32pp;
  182007. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  182008. typedef png_int_16 FAR * FAR * png_int_16pp;
  182009. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  182010. typedef char FAR * FAR * png_charpp;
  182011. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  182012. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182013. typedef double FAR * FAR * png_doublepp;
  182014. #endif
  182015. /* Pointers to pointers to pointers; i.e., pointer to array */
  182016. typedef char FAR * FAR * FAR * png_charppp;
  182017. #if 0
  182018. /* SPC - Is this stuff deprecated? */
  182019. /* It'll be removed as of libpng-1.3.0 - GR-P */
  182020. /* libpng typedefs for types in zlib. If zlib changes
  182021. * or another compression library is used, then change these.
  182022. * Eliminates need to change all the source files.
  182023. */
  182024. typedef charf * png_zcharp;
  182025. typedef charf * FAR * png_zcharpp;
  182026. typedef z_stream FAR * png_zstreamp;
  182027. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  182028. /*
  182029. * Define PNG_BUILD_DLL if the module being built is a Windows
  182030. * LIBPNG DLL.
  182031. *
  182032. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  182033. * It is equivalent to Microsoft predefined macro _DLL that is
  182034. * automatically defined when you compile using the share
  182035. * version of the CRT (C Run-Time library)
  182036. *
  182037. * The cygwin mods make this behavior a little different:
  182038. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  182039. * Define PNG_STATIC if you are building a static library for use with cygwin,
  182040. * -or- if you are building an application that you want to link to the
  182041. * static library.
  182042. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  182043. * the other flags is defined.
  182044. */
  182045. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  182046. # define PNG_DLL
  182047. #endif
  182048. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  182049. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  182050. * command-line override
  182051. */
  182052. #if defined(__CYGWIN__)
  182053. # if !defined(PNG_STATIC)
  182054. # if defined(PNG_USE_GLOBAL_ARRAYS)
  182055. # undef PNG_USE_GLOBAL_ARRAYS
  182056. # endif
  182057. # if !defined(PNG_USE_LOCAL_ARRAYS)
  182058. # define PNG_USE_LOCAL_ARRAYS
  182059. # endif
  182060. # else
  182061. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  182062. # if defined(PNG_USE_GLOBAL_ARRAYS)
  182063. # undef PNG_USE_GLOBAL_ARRAYS
  182064. # endif
  182065. # endif
  182066. # endif
  182067. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  182068. # define PNG_USE_LOCAL_ARRAYS
  182069. # endif
  182070. #endif
  182071. /* Do not use global arrays (helps with building DLL's)
  182072. * They are no longer used in libpng itself, since version 1.0.5c,
  182073. * but might be required for some pre-1.0.5c applications.
  182074. */
  182075. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  182076. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  182077. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  182078. # define PNG_USE_LOCAL_ARRAYS
  182079. # else
  182080. # define PNG_USE_GLOBAL_ARRAYS
  182081. # endif
  182082. #endif
  182083. #if defined(__CYGWIN__)
  182084. # undef PNGAPI
  182085. # define PNGAPI __cdecl
  182086. # undef PNG_IMPEXP
  182087. # define PNG_IMPEXP
  182088. #endif
  182089. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  182090. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  182091. * Don't ignore those warnings; you must also reset the default calling
  182092. * convention in your compiler to match your PNGAPI, and you must build
  182093. * zlib and your applications the same way you build libpng.
  182094. */
  182095. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  182096. # ifndef PNG_NO_MODULEDEF
  182097. # define PNG_NO_MODULEDEF
  182098. # endif
  182099. #endif
  182100. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  182101. # define PNG_IMPEXP
  182102. #endif
  182103. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  182104. (( defined(_Windows) || defined(_WINDOWS) || \
  182105. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  182106. # ifndef PNGAPI
  182107. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  182108. # define PNGAPI __cdecl
  182109. # else
  182110. # define PNGAPI _cdecl
  182111. # endif
  182112. # endif
  182113. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  182114. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  182115. # define PNG_IMPEXP
  182116. # endif
  182117. # if !defined(PNG_IMPEXP)
  182118. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182119. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182120. /* Borland/Microsoft */
  182121. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182122. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182123. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182124. # else
  182125. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182126. # if defined(PNG_BUILD_DLL)
  182127. # define PNG_IMPEXP __export
  182128. # else
  182129. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182130. VC++ */
  182131. # endif /* Exists in Borland C++ for
  182132. C++ classes (== huge) */
  182133. # endif
  182134. # endif
  182135. # if !defined(PNG_IMPEXP)
  182136. # if defined(PNG_BUILD_DLL)
  182137. # define PNG_IMPEXP __declspec(dllexport)
  182138. # else
  182139. # define PNG_IMPEXP __declspec(dllimport)
  182140. # endif
  182141. # endif
  182142. # endif /* PNG_IMPEXP */
  182143. #else /* !(DLL || non-cygwin WINDOWS) */
  182144. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182145. # ifndef PNGAPI
  182146. # define PNGAPI _System
  182147. # endif
  182148. # else
  182149. # if 0 /* ... other platforms, with other meanings */
  182150. # endif
  182151. # endif
  182152. #endif
  182153. #ifndef PNGAPI
  182154. # define PNGAPI
  182155. #endif
  182156. #ifndef PNG_IMPEXP
  182157. # define PNG_IMPEXP
  182158. #endif
  182159. #ifdef PNG_BUILDSYMS
  182160. # ifndef PNG_EXPORT
  182161. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182162. # endif
  182163. # ifdef PNG_USE_GLOBAL_ARRAYS
  182164. # ifndef PNG_EXPORT_VAR
  182165. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182166. # endif
  182167. # endif
  182168. #endif
  182169. #ifndef PNG_EXPORT
  182170. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182171. #endif
  182172. #ifdef PNG_USE_GLOBAL_ARRAYS
  182173. # ifndef PNG_EXPORT_VAR
  182174. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182175. # endif
  182176. #endif
  182177. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182178. * functions that are passed far data must be model independent.
  182179. */
  182180. #ifndef PNG_ABORT
  182181. # define PNG_ABORT() abort()
  182182. #endif
  182183. #ifdef PNG_SETJMP_SUPPORTED
  182184. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182185. #else
  182186. # define png_jmpbuf(png_ptr) \
  182187. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182188. #endif
  182189. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182190. /* use this to make far-to-near assignments */
  182191. # define CHECK 1
  182192. # define NOCHECK 0
  182193. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182194. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182195. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182196. # define png_strcpy _fstrcpy
  182197. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182198. # define png_strlen _fstrlen
  182199. # define png_memcmp _fmemcmp /* SJT: added */
  182200. # define png_memcpy _fmemcpy
  182201. # define png_memset _fmemset
  182202. #else /* use the usual functions */
  182203. # define CVT_PTR(ptr) (ptr)
  182204. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182205. # ifndef PNG_NO_SNPRINTF
  182206. # ifdef _MSC_VER
  182207. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182208. # define png_snprintf2 _snprintf
  182209. # define png_snprintf6 _snprintf
  182210. # else
  182211. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182212. # define png_snprintf2 snprintf
  182213. # define png_snprintf6 snprintf
  182214. # endif
  182215. # else
  182216. /* You don't have or don't want to use snprintf(). Caution: Using
  182217. * sprintf instead of snprintf exposes your application to accidental
  182218. * or malevolent buffer overflows. If you don't have snprintf()
  182219. * as a general rule you should provide one (you can get one from
  182220. * Portable OpenSSH). */
  182221. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182222. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182223. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182224. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182225. # endif
  182226. # define png_strcpy strcpy
  182227. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182228. # define png_strlen strlen
  182229. # define png_memcmp memcmp /* SJT: added */
  182230. # define png_memcpy memcpy
  182231. # define png_memset memset
  182232. #endif
  182233. /* End of memory model independent support */
  182234. /* Just a little check that someone hasn't tried to define something
  182235. * contradictory.
  182236. */
  182237. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182238. # undef PNG_ZBUF_SIZE
  182239. # define PNG_ZBUF_SIZE 65536L
  182240. #endif
  182241. /* Added at libpng-1.2.8 */
  182242. #endif /* PNG_VERSION_INFO_ONLY */
  182243. #endif /* PNGCONF_H */
  182244. /*** End of inlined file: pngconf.h ***/
  182245. #ifdef _MSC_VER
  182246. #pragma warning (disable: 4996 4100)
  182247. #endif
  182248. /*
  182249. * Added at libpng-1.2.8 */
  182250. /* Ref MSDN: Private as priority over Special
  182251. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182252. * procedures. If this value is given, the StringFileInfo block must
  182253. * contain a PrivateBuild string.
  182254. *
  182255. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182256. * standard release procedures but is a variation of the standard
  182257. * file of the same version number. If this value is given, the
  182258. * StringFileInfo block must contain a SpecialBuild string.
  182259. */
  182260. #if defined(PNG_USER_PRIVATEBUILD)
  182261. # define PNG_LIBPNG_BUILD_TYPE \
  182262. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182263. #else
  182264. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182265. # define PNG_LIBPNG_BUILD_TYPE \
  182266. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182267. # else
  182268. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182269. # endif
  182270. #endif
  182271. #ifndef PNG_VERSION_INFO_ONLY
  182272. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182273. #ifdef __cplusplus
  182274. //extern "C" {
  182275. #endif /* __cplusplus */
  182276. /* This file is arranged in several sections. The first section contains
  182277. * structure and type definitions. The second section contains the external
  182278. * library functions, while the third has the internal library functions,
  182279. * which applications aren't expected to use directly.
  182280. */
  182281. #ifndef PNG_NO_TYPECAST_NULL
  182282. #define int_p_NULL (int *)NULL
  182283. #define png_bytep_NULL (png_bytep)NULL
  182284. #define png_bytepp_NULL (png_bytepp)NULL
  182285. #define png_doublep_NULL (png_doublep)NULL
  182286. #define png_error_ptr_NULL (png_error_ptr)NULL
  182287. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182288. #define png_free_ptr_NULL (png_free_ptr)NULL
  182289. #define png_infopp_NULL (png_infopp)NULL
  182290. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182291. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182292. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182293. #define png_structp_NULL (png_structp)NULL
  182294. #define png_uint_16p_NULL (png_uint_16p)NULL
  182295. #define png_voidp_NULL (png_voidp)NULL
  182296. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182297. #else
  182298. #define int_p_NULL NULL
  182299. #define png_bytep_NULL NULL
  182300. #define png_bytepp_NULL NULL
  182301. #define png_doublep_NULL NULL
  182302. #define png_error_ptr_NULL NULL
  182303. #define png_flush_ptr_NULL NULL
  182304. #define png_free_ptr_NULL NULL
  182305. #define png_infopp_NULL NULL
  182306. #define png_malloc_ptr_NULL NULL
  182307. #define png_read_status_ptr_NULL NULL
  182308. #define png_rw_ptr_NULL NULL
  182309. #define png_structp_NULL NULL
  182310. #define png_uint_16p_NULL NULL
  182311. #define png_voidp_NULL NULL
  182312. #define png_write_status_ptr_NULL NULL
  182313. #endif
  182314. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182315. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182316. /* Version information for C files, stored in png.c. This had better match
  182317. * the version above.
  182318. */
  182319. #ifdef PNG_USE_GLOBAL_ARRAYS
  182320. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182321. /* need room for 99.99.99beta99z */
  182322. #else
  182323. #define png_libpng_ver png_get_header_ver(NULL)
  182324. #endif
  182325. #ifdef PNG_USE_GLOBAL_ARRAYS
  182326. /* This was removed in version 1.0.5c */
  182327. /* Structures to facilitate easy interlacing. See png.c for more details */
  182328. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182329. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182330. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182331. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182332. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182333. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182334. /* This isn't currently used. If you need it, see png.c for more details.
  182335. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182336. */
  182337. #endif
  182338. #endif /* PNG_NO_EXTERN */
  182339. /* Three color definitions. The order of the red, green, and blue, (and the
  182340. * exact size) is not important, although the size of the fields need to
  182341. * be png_byte or png_uint_16 (as defined below).
  182342. */
  182343. typedef struct png_color_struct
  182344. {
  182345. png_byte red;
  182346. png_byte green;
  182347. png_byte blue;
  182348. } png_color;
  182349. typedef png_color FAR * png_colorp;
  182350. typedef png_color FAR * FAR * png_colorpp;
  182351. typedef struct png_color_16_struct
  182352. {
  182353. png_byte index; /* used for palette files */
  182354. png_uint_16 red; /* for use in red green blue files */
  182355. png_uint_16 green;
  182356. png_uint_16 blue;
  182357. png_uint_16 gray; /* for use in grayscale files */
  182358. } png_color_16;
  182359. typedef png_color_16 FAR * png_color_16p;
  182360. typedef png_color_16 FAR * FAR * png_color_16pp;
  182361. typedef struct png_color_8_struct
  182362. {
  182363. png_byte red; /* for use in red green blue files */
  182364. png_byte green;
  182365. png_byte blue;
  182366. png_byte gray; /* for use in grayscale files */
  182367. png_byte alpha; /* for alpha channel files */
  182368. } png_color_8;
  182369. typedef png_color_8 FAR * png_color_8p;
  182370. typedef png_color_8 FAR * FAR * png_color_8pp;
  182371. /*
  182372. * The following two structures are used for the in-core representation
  182373. * of sPLT chunks.
  182374. */
  182375. typedef struct png_sPLT_entry_struct
  182376. {
  182377. png_uint_16 red;
  182378. png_uint_16 green;
  182379. png_uint_16 blue;
  182380. png_uint_16 alpha;
  182381. png_uint_16 frequency;
  182382. } png_sPLT_entry;
  182383. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182384. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182385. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182386. * occupy the LSB of their respective members, and the MSB of each member
  182387. * is zero-filled. The frequency member always occupies the full 16 bits.
  182388. */
  182389. typedef struct png_sPLT_struct
  182390. {
  182391. png_charp name; /* palette name */
  182392. png_byte depth; /* depth of palette samples */
  182393. png_sPLT_entryp entries; /* palette entries */
  182394. png_int_32 nentries; /* number of palette entries */
  182395. } png_sPLT_t;
  182396. typedef png_sPLT_t FAR * png_sPLT_tp;
  182397. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182398. #ifdef PNG_TEXT_SUPPORTED
  182399. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182400. * and whether that contents is compressed or not. The "key" field
  182401. * points to a regular zero-terminated C string. The "text", "lang", and
  182402. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182403. * However, the * structure returned by png_get_text() will always contain
  182404. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182405. * so they can be safely used in printf() and other string-handling functions.
  182406. */
  182407. typedef struct png_text_struct
  182408. {
  182409. int compression; /* compression value:
  182410. -1: tEXt, none
  182411. 0: zTXt, deflate
  182412. 1: iTXt, none
  182413. 2: iTXt, deflate */
  182414. png_charp key; /* keyword, 1-79 character description of "text" */
  182415. png_charp text; /* comment, may be an empty string (ie "")
  182416. or a NULL pointer */
  182417. png_size_t text_length; /* length of the text string */
  182418. #ifdef PNG_iTXt_SUPPORTED
  182419. png_size_t itxt_length; /* length of the itxt string */
  182420. png_charp lang; /* language code, 0-79 characters
  182421. or a NULL pointer */
  182422. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182423. chars or a NULL pointer */
  182424. #endif
  182425. } png_text;
  182426. typedef png_text FAR * png_textp;
  182427. typedef png_text FAR * FAR * png_textpp;
  182428. #endif
  182429. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182430. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182431. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182432. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182433. #define PNG_TEXT_COMPRESSION_NONE -1
  182434. #define PNG_TEXT_COMPRESSION_zTXt 0
  182435. #define PNG_ITXT_COMPRESSION_NONE 1
  182436. #define PNG_ITXT_COMPRESSION_zTXt 2
  182437. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182438. /* png_time is a way to hold the time in an machine independent way.
  182439. * Two conversions are provided, both from time_t and struct tm. There
  182440. * is no portable way to convert to either of these structures, as far
  182441. * as I know. If you know of a portable way, send it to me. As a side
  182442. * note - PNG has always been Year 2000 compliant!
  182443. */
  182444. typedef struct png_time_struct
  182445. {
  182446. png_uint_16 year; /* full year, as in, 1995 */
  182447. png_byte month; /* month of year, 1 - 12 */
  182448. png_byte day; /* day of month, 1 - 31 */
  182449. png_byte hour; /* hour of day, 0 - 23 */
  182450. png_byte minute; /* minute of hour, 0 - 59 */
  182451. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182452. } png_time;
  182453. typedef png_time FAR * png_timep;
  182454. typedef png_time FAR * FAR * png_timepp;
  182455. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182456. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182457. * no specific support. The idea is that we can use this to queue
  182458. * up private chunks for output even though the library doesn't actually
  182459. * know about their semantics.
  182460. */
  182461. typedef struct png_unknown_chunk_t
  182462. {
  182463. png_byte name[5];
  182464. png_byte *data;
  182465. png_size_t size;
  182466. /* libpng-using applications should NOT directly modify this byte. */
  182467. png_byte location; /* mode of operation at read time */
  182468. }
  182469. png_unknown_chunk;
  182470. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182471. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182472. #endif
  182473. /* png_info is a structure that holds the information in a PNG file so
  182474. * that the application can find out the characteristics of the image.
  182475. * If you are reading the file, this structure will tell you what is
  182476. * in the PNG file. If you are writing the file, fill in the information
  182477. * you want to put into the PNG file, then call png_write_info().
  182478. * The names chosen should be very close to the PNG specification, so
  182479. * consult that document for information about the meaning of each field.
  182480. *
  182481. * With libpng < 0.95, it was only possible to directly set and read the
  182482. * the values in the png_info_struct, which meant that the contents and
  182483. * order of the values had to remain fixed. With libpng 0.95 and later,
  182484. * however, there are now functions that abstract the contents of
  182485. * png_info_struct from the application, so this makes it easier to use
  182486. * libpng with dynamic libraries, and even makes it possible to use
  182487. * libraries that don't have all of the libpng ancillary chunk-handing
  182488. * functionality.
  182489. *
  182490. * In any case, the order of the parameters in png_info_struct should NOT
  182491. * be changed for as long as possible to keep compatibility with applications
  182492. * that use the old direct-access method with png_info_struct.
  182493. *
  182494. * The following members may have allocated storage attached that should be
  182495. * cleaned up before the structure is discarded: palette, trans, text,
  182496. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182497. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182498. * are automatically freed when the info structure is deallocated, if they were
  182499. * allocated internally by libpng. This behavior can be changed by means
  182500. * of the png_data_freer() function.
  182501. *
  182502. * More allocation details: all the chunk-reading functions that
  182503. * change these members go through the corresponding png_set_*
  182504. * functions. A function to clear these members is available: see
  182505. * png_free_data(). The png_set_* functions do not depend on being
  182506. * able to point info structure members to any of the storage they are
  182507. * passed (they make their own copies), EXCEPT that the png_set_text
  182508. * functions use the same storage passed to them in the text_ptr or
  182509. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182510. * functions do not make their own copies.
  182511. */
  182512. typedef struct png_info_struct
  182513. {
  182514. /* the following are necessary for every PNG file */
  182515. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182516. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182517. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182518. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182519. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182520. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182521. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182522. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182523. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182524. /* The following three should have been named *_method not *_type */
  182525. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182526. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182527. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182528. /* The following is informational only on read, and not used on writes. */
  182529. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182530. png_byte pixel_depth; /* number of bits per pixel */
  182531. png_byte spare_byte; /* to align the data, and for future use */
  182532. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182533. /* The rest of the data is optional. If you are reading, check the
  182534. * valid field to see if the information in these are valid. If you
  182535. * are writing, set the valid field to those chunks you want written,
  182536. * and initialize the appropriate fields below.
  182537. */
  182538. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182539. /* The gAMA chunk describes the gamma characteristics of the system
  182540. * on which the image was created, normally in the range [1.0, 2.5].
  182541. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182542. */
  182543. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182544. #endif
  182545. #if defined(PNG_sRGB_SUPPORTED)
  182546. /* GR-P, 0.96a */
  182547. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182548. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182549. #endif
  182550. #if defined(PNG_TEXT_SUPPORTED)
  182551. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182552. * uncompressed, compressed, and optionally compressed forms, respectively.
  182553. * The data in "text" is an array of pointers to uncompressed,
  182554. * null-terminated C strings. Each chunk has a keyword that describes the
  182555. * textual data contained in that chunk. Keywords are not required to be
  182556. * unique, and the text string may be empty. Any number of text chunks may
  182557. * be in an image.
  182558. */
  182559. int num_text; /* number of comments read/to write */
  182560. int max_text; /* current size of text array */
  182561. png_textp text; /* array of comments read/to write */
  182562. #endif /* PNG_TEXT_SUPPORTED */
  182563. #if defined(PNG_tIME_SUPPORTED)
  182564. /* The tIME chunk holds the last time the displayed image data was
  182565. * modified. See the png_time struct for the contents of this struct.
  182566. */
  182567. png_time mod_time;
  182568. #endif
  182569. #if defined(PNG_sBIT_SUPPORTED)
  182570. /* The sBIT chunk specifies the number of significant high-order bits
  182571. * in the pixel data. Values are in the range [1, bit_depth], and are
  182572. * only specified for the channels in the pixel data. The contents of
  182573. * the low-order bits is not specified. Data is valid if
  182574. * (valid & PNG_INFO_sBIT) is non-zero.
  182575. */
  182576. png_color_8 sig_bit; /* significant bits in color channels */
  182577. #endif
  182578. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182579. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182580. /* The tRNS chunk supplies transparency data for paletted images and
  182581. * other image types that don't need a full alpha channel. There are
  182582. * "num_trans" transparency values for a paletted image, stored in the
  182583. * same order as the palette colors, starting from index 0. Values
  182584. * for the data are in the range [0, 255], ranging from fully transparent
  182585. * to fully opaque, respectively. For non-paletted images, there is a
  182586. * single color specified that should be treated as fully transparent.
  182587. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182588. */
  182589. png_bytep trans; /* transparent values for paletted image */
  182590. png_color_16 trans_values; /* transparent color for non-palette image */
  182591. #endif
  182592. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182593. /* The bKGD chunk gives the suggested image background color if the
  182594. * display program does not have its own background color and the image
  182595. * is needs to composited onto a background before display. The colors
  182596. * in "background" are normally in the same color space/depth as the
  182597. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182598. */
  182599. png_color_16 background;
  182600. #endif
  182601. #if defined(PNG_oFFs_SUPPORTED)
  182602. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182603. * and downwards from the top-left corner of the display, page, or other
  182604. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182605. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182606. */
  182607. png_int_32 x_offset; /* x offset on page */
  182608. png_int_32 y_offset; /* y offset on page */
  182609. png_byte offset_unit_type; /* offset units type */
  182610. #endif
  182611. #if defined(PNG_pHYs_SUPPORTED)
  182612. /* The pHYs chunk gives the physical pixel density of the image for
  182613. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182614. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182615. */
  182616. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182617. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182618. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182619. #endif
  182620. #if defined(PNG_hIST_SUPPORTED)
  182621. /* The hIST chunk contains the relative frequency or importance of the
  182622. * various palette entries, so that a viewer can intelligently select a
  182623. * reduced-color palette, if required. Data is an array of "num_palette"
  182624. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182625. * is non-zero.
  182626. */
  182627. png_uint_16p hist;
  182628. #endif
  182629. #ifdef PNG_cHRM_SUPPORTED
  182630. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182631. * on which the PNG was created. This data allows the viewer to do gamut
  182632. * mapping of the input image to ensure that the viewer sees the same
  182633. * colors in the image as the creator. Values are in the range
  182634. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182635. */
  182636. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182637. float x_white;
  182638. float y_white;
  182639. float x_red;
  182640. float y_red;
  182641. float x_green;
  182642. float y_green;
  182643. float x_blue;
  182644. float y_blue;
  182645. #endif
  182646. #endif
  182647. #if defined(PNG_pCAL_SUPPORTED)
  182648. /* The pCAL chunk describes a transformation between the stored pixel
  182649. * values and original physical data values used to create the image.
  182650. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182651. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182652. * (possibly non-linear) transformation function given by "pcal_type"
  182653. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182654. * defines below, and the PNG-Group's PNG extensions document for a
  182655. * complete description of the transformations and how they should be
  182656. * implemented, and for a description of the ASCII parameter strings.
  182657. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182658. */
  182659. png_charp pcal_purpose; /* pCAL chunk description string */
  182660. png_int_32 pcal_X0; /* minimum value */
  182661. png_int_32 pcal_X1; /* maximum value */
  182662. png_charp pcal_units; /* Latin-1 string giving physical units */
  182663. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182664. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182665. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182666. #endif
  182667. /* New members added in libpng-1.0.6 */
  182668. #ifdef PNG_FREE_ME_SUPPORTED
  182669. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182670. #endif
  182671. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182672. /* storage for unknown chunks that the library doesn't recognize. */
  182673. png_unknown_chunkp unknown_chunks;
  182674. png_size_t unknown_chunks_num;
  182675. #endif
  182676. #if defined(PNG_iCCP_SUPPORTED)
  182677. /* iCCP chunk data. */
  182678. png_charp iccp_name; /* profile name */
  182679. png_charp iccp_profile; /* International Color Consortium profile data */
  182680. /* Note to maintainer: should be png_bytep */
  182681. png_uint_32 iccp_proflen; /* ICC profile data length */
  182682. png_byte iccp_compression; /* Always zero */
  182683. #endif
  182684. #if defined(PNG_sPLT_SUPPORTED)
  182685. /* data on sPLT chunks (there may be more than one). */
  182686. png_sPLT_tp splt_palettes;
  182687. png_uint_32 splt_palettes_num;
  182688. #endif
  182689. #if defined(PNG_sCAL_SUPPORTED)
  182690. /* The sCAL chunk describes the actual physical dimensions of the
  182691. * subject matter of the graphic. The chunk contains a unit specification
  182692. * a byte value, and two ASCII strings representing floating-point
  182693. * values. The values are width and height corresponsing to one pixel
  182694. * in the image. This external representation is converted to double
  182695. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182696. */
  182697. png_byte scal_unit; /* unit of physical scale */
  182698. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182699. double scal_pixel_width; /* width of one pixel */
  182700. double scal_pixel_height; /* height of one pixel */
  182701. #endif
  182702. #ifdef PNG_FIXED_POINT_SUPPORTED
  182703. png_charp scal_s_width; /* string containing height */
  182704. png_charp scal_s_height; /* string containing width */
  182705. #endif
  182706. #endif
  182707. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182708. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182709. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182710. png_bytepp row_pointers; /* the image bits */
  182711. #endif
  182712. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182713. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182714. #endif
  182715. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182716. png_fixed_point int_x_white;
  182717. png_fixed_point int_y_white;
  182718. png_fixed_point int_x_red;
  182719. png_fixed_point int_y_red;
  182720. png_fixed_point int_x_green;
  182721. png_fixed_point int_y_green;
  182722. png_fixed_point int_x_blue;
  182723. png_fixed_point int_y_blue;
  182724. #endif
  182725. } png_info;
  182726. typedef png_info FAR * png_infop;
  182727. typedef png_info FAR * FAR * png_infopp;
  182728. /* Maximum positive integer used in PNG is (2^31)-1 */
  182729. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182730. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182731. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182732. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182733. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182734. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182735. #endif
  182736. /* These describe the color_type field in png_info. */
  182737. /* color type masks */
  182738. #define PNG_COLOR_MASK_PALETTE 1
  182739. #define PNG_COLOR_MASK_COLOR 2
  182740. #define PNG_COLOR_MASK_ALPHA 4
  182741. /* color types. Note that not all combinations are legal */
  182742. #define PNG_COLOR_TYPE_GRAY 0
  182743. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182744. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182745. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182746. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182747. /* aliases */
  182748. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182749. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182750. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182751. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182752. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182753. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182754. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182755. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182756. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182757. /* These are for the interlacing type. These values should NOT be changed. */
  182758. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182759. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182760. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182761. /* These are for the oFFs chunk. These values should NOT be changed. */
  182762. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182763. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182764. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182765. /* These are for the pCAL chunk. These values should NOT be changed. */
  182766. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182767. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182768. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182769. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182770. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182771. /* These are for the sCAL chunk. These values should NOT be changed. */
  182772. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182773. #define PNG_SCALE_METER 1 /* meters per pixel */
  182774. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182775. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182776. /* These are for the pHYs chunk. These values should NOT be changed. */
  182777. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182778. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182779. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182780. /* These are for the sRGB chunk. These values should NOT be changed. */
  182781. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182782. #define PNG_sRGB_INTENT_RELATIVE 1
  182783. #define PNG_sRGB_INTENT_SATURATION 2
  182784. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182785. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182786. /* This is for text chunks */
  182787. #define PNG_KEYWORD_MAX_LENGTH 79
  182788. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182789. #define PNG_MAX_PALETTE_LENGTH 256
  182790. /* These determine if an ancillary chunk's data has been successfully read
  182791. * from the PNG header, or if the application has filled in the corresponding
  182792. * data in the info_struct to be written into the output file. The values
  182793. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182794. */
  182795. #define PNG_INFO_gAMA 0x0001
  182796. #define PNG_INFO_sBIT 0x0002
  182797. #define PNG_INFO_cHRM 0x0004
  182798. #define PNG_INFO_PLTE 0x0008
  182799. #define PNG_INFO_tRNS 0x0010
  182800. #define PNG_INFO_bKGD 0x0020
  182801. #define PNG_INFO_hIST 0x0040
  182802. #define PNG_INFO_pHYs 0x0080
  182803. #define PNG_INFO_oFFs 0x0100
  182804. #define PNG_INFO_tIME 0x0200
  182805. #define PNG_INFO_pCAL 0x0400
  182806. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182807. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182808. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182809. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182810. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182811. /* This is used for the transformation routines, as some of them
  182812. * change these values for the row. It also should enable using
  182813. * the routines for other purposes.
  182814. */
  182815. typedef struct png_row_info_struct
  182816. {
  182817. png_uint_32 width; /* width of row */
  182818. png_uint_32 rowbytes; /* number of bytes in row */
  182819. png_byte color_type; /* color type of row */
  182820. png_byte bit_depth; /* bit depth of row */
  182821. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182822. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182823. } png_row_info;
  182824. typedef png_row_info FAR * png_row_infop;
  182825. typedef png_row_info FAR * FAR * png_row_infopp;
  182826. /* These are the function types for the I/O functions and for the functions
  182827. * that allow the user to override the default I/O functions with his or her
  182828. * own. The png_error_ptr type should match that of user-supplied warning
  182829. * and error functions, while the png_rw_ptr type should match that of the
  182830. * user read/write data functions.
  182831. */
  182832. typedef struct png_struct_def png_struct;
  182833. typedef png_struct FAR * png_structp;
  182834. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182835. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182836. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182837. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182838. int));
  182839. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182840. int));
  182841. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182842. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182843. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182844. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182845. png_uint_32, int));
  182846. #endif
  182847. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182848. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182849. defined(PNG_LEGACY_SUPPORTED)
  182850. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182851. png_row_infop, png_bytep));
  182852. #endif
  182853. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182854. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182855. #endif
  182856. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182857. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182858. #endif
  182859. /* Transform masks for the high-level interface */
  182860. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182861. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182862. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182863. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182864. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182865. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182866. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182867. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182868. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182869. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182870. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182871. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182872. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182873. /* Flags for MNG supported features */
  182874. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182875. #define PNG_FLAG_MNG_FILTER_64 0x04
  182876. #define PNG_ALL_MNG_FEATURES 0x05
  182877. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182878. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182879. /* The structure that holds the information to read and write PNG files.
  182880. * The only people who need to care about what is inside of this are the
  182881. * people who will be modifying the library for their own special needs.
  182882. * It should NOT be accessed directly by an application, except to store
  182883. * the jmp_buf.
  182884. */
  182885. struct png_struct_def
  182886. {
  182887. #ifdef PNG_SETJMP_SUPPORTED
  182888. jmp_buf jmpbuf; /* used in png_error */
  182889. #endif
  182890. png_error_ptr error_fn; /* function for printing errors and aborting */
  182891. png_error_ptr warning_fn; /* function for printing warnings */
  182892. png_voidp error_ptr; /* user supplied struct for error functions */
  182893. png_rw_ptr write_data_fn; /* function for writing output data */
  182894. png_rw_ptr read_data_fn; /* function for reading input data */
  182895. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182896. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182897. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182898. #endif
  182899. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182900. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182901. #endif
  182902. /* These were added in libpng-1.0.2 */
  182903. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182904. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182905. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182906. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182907. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182908. png_byte user_transform_channels; /* channels in user transformed pixels */
  182909. #endif
  182910. #endif
  182911. png_uint_32 mode; /* tells us where we are in the PNG file */
  182912. png_uint_32 flags; /* flags indicating various things to libpng */
  182913. png_uint_32 transformations; /* which transformations to perform */
  182914. z_stream zstream; /* pointer to decompression structure (below) */
  182915. png_bytep zbuf; /* buffer for zlib */
  182916. png_size_t zbuf_size; /* size of zbuf */
  182917. int zlib_level; /* holds zlib compression level */
  182918. int zlib_method; /* holds zlib compression method */
  182919. int zlib_window_bits; /* holds zlib compression window bits */
  182920. int zlib_mem_level; /* holds zlib compression memory level */
  182921. int zlib_strategy; /* holds zlib compression strategy */
  182922. png_uint_32 width; /* width of image in pixels */
  182923. png_uint_32 height; /* height of image in pixels */
  182924. png_uint_32 num_rows; /* number of rows in current pass */
  182925. png_uint_32 usr_width; /* width of row at start of write */
  182926. png_uint_32 rowbytes; /* size of row in bytes */
  182927. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182928. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182929. png_uint_32 row_number; /* current row in interlace pass */
  182930. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182931. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182932. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182933. png_bytep up_row; /* buffer to save "up" row when filtering */
  182934. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182935. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182936. png_row_info row_info; /* used for transformation routines */
  182937. png_uint_32 idat_size; /* current IDAT size for read */
  182938. png_uint_32 crc; /* current chunk CRC value */
  182939. png_colorp palette; /* palette from the input file */
  182940. png_uint_16 num_palette; /* number of color entries in palette */
  182941. png_uint_16 num_trans; /* number of transparency values */
  182942. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182943. png_byte compression; /* file compression type (always 0) */
  182944. png_byte filter; /* file filter type (always 0) */
  182945. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182946. png_byte pass; /* current interlace pass (0 - 6) */
  182947. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182948. png_byte color_type; /* color type of file */
  182949. png_byte bit_depth; /* bit depth of file */
  182950. png_byte usr_bit_depth; /* bit depth of users row */
  182951. png_byte pixel_depth; /* number of bits per pixel */
  182952. png_byte channels; /* number of channels in file */
  182953. png_byte usr_channels; /* channels at start of write */
  182954. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182955. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182956. #ifdef PNG_LEGACY_SUPPORTED
  182957. png_byte filler; /* filler byte for pixel expansion */
  182958. #else
  182959. png_uint_16 filler; /* filler bytes for pixel expansion */
  182960. #endif
  182961. #endif
  182962. #if defined(PNG_bKGD_SUPPORTED)
  182963. png_byte background_gamma_type;
  182964. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182965. float background_gamma;
  182966. # endif
  182967. png_color_16 background; /* background color in screen gamma space */
  182968. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182969. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182970. #endif
  182971. #endif /* PNG_bKGD_SUPPORTED */
  182972. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182973. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182974. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182975. png_uint_32 flush_rows; /* number of rows written since last flush */
  182976. #endif
  182977. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182978. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182979. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182980. float gamma; /* file gamma value */
  182981. float screen_gamma; /* screen gamma value (display_exponent) */
  182982. #endif
  182983. #endif
  182984. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182985. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182986. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182987. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182988. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182989. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182990. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182991. #endif
  182992. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182993. png_color_8 sig_bit; /* significant bits in each available channel */
  182994. #endif
  182995. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182996. png_color_8 shift; /* shift for significant bit tranformation */
  182997. #endif
  182998. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182999. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183000. png_bytep trans; /* transparency values for paletted files */
  183001. png_color_16 trans_values; /* transparency values for non-paletted files */
  183002. #endif
  183003. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  183004. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  183005. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183006. png_progressive_info_ptr info_fn; /* called after header data fully read */
  183007. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  183008. png_progressive_end_ptr end_fn; /* called after image is complete */
  183009. png_bytep save_buffer_ptr; /* current location in save_buffer */
  183010. png_bytep save_buffer; /* buffer for previously read data */
  183011. png_bytep current_buffer_ptr; /* current location in current_buffer */
  183012. png_bytep current_buffer; /* buffer for recently used data */
  183013. png_uint_32 push_length; /* size of current input chunk */
  183014. png_uint_32 skip_length; /* bytes to skip in input data */
  183015. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  183016. png_size_t save_buffer_max; /* total size of save_buffer */
  183017. png_size_t buffer_size; /* total amount of available input data */
  183018. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  183019. int process_mode; /* what push library is currently doing */
  183020. int cur_palette; /* current push library palette index */
  183021. # if defined(PNG_TEXT_SUPPORTED)
  183022. png_size_t current_text_size; /* current size of text input data */
  183023. png_size_t current_text_left; /* how much text left to read in input */
  183024. png_charp current_text; /* current text chunk buffer */
  183025. png_charp current_text_ptr; /* current location in current_text */
  183026. # endif /* PNG_TEXT_SUPPORTED */
  183027. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183028. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  183029. /* for the Borland special 64K segment handler */
  183030. png_bytepp offset_table_ptr;
  183031. png_bytep offset_table;
  183032. png_uint_16 offset_table_number;
  183033. png_uint_16 offset_table_count;
  183034. png_uint_16 offset_table_count_free;
  183035. #endif
  183036. #if defined(PNG_READ_DITHER_SUPPORTED)
  183037. png_bytep palette_lookup; /* lookup table for dithering */
  183038. png_bytep dither_index; /* index translation for palette files */
  183039. #endif
  183040. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  183041. png_uint_16p hist; /* histogram */
  183042. #endif
  183043. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  183044. png_byte heuristic_method; /* heuristic for row filter selection */
  183045. png_byte num_prev_filters; /* number of weights for previous rows */
  183046. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  183047. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  183048. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  183049. png_uint_16p filter_costs; /* relative filter calculation cost */
  183050. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  183051. #endif
  183052. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183053. png_charp time_buffer; /* String to hold RFC 1123 time text */
  183054. #endif
  183055. /* New members added in libpng-1.0.6 */
  183056. #ifdef PNG_FREE_ME_SUPPORTED
  183057. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  183058. #endif
  183059. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  183060. png_voidp user_chunk_ptr;
  183061. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  183062. #endif
  183063. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183064. int num_chunk_list;
  183065. png_bytep chunk_list;
  183066. #endif
  183067. /* New members added in libpng-1.0.3 */
  183068. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183069. png_byte rgb_to_gray_status;
  183070. /* These were changed from png_byte in libpng-1.0.6 */
  183071. png_uint_16 rgb_to_gray_red_coeff;
  183072. png_uint_16 rgb_to_gray_green_coeff;
  183073. png_uint_16 rgb_to_gray_blue_coeff;
  183074. #endif
  183075. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  183076. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  183077. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183078. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183079. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  183080. #ifdef PNG_1_0_X
  183081. png_byte mng_features_permitted;
  183082. #else
  183083. png_uint_32 mng_features_permitted;
  183084. #endif /* PNG_1_0_X */
  183085. #endif
  183086. /* New member added in libpng-1.0.7 */
  183087. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183088. png_fixed_point int_gamma;
  183089. #endif
  183090. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  183091. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183092. png_byte filter_type;
  183093. #endif
  183094. #if defined(PNG_1_0_X)
  183095. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  183096. png_uint_32 row_buf_size;
  183097. #endif
  183098. /* New members added in libpng-1.2.0 */
  183099. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183100. # if !defined(PNG_1_0_X)
  183101. # if defined(PNG_MMX_CODE_SUPPORTED)
  183102. png_byte mmx_bitdepth_threshold;
  183103. png_uint_32 mmx_rowbytes_threshold;
  183104. # endif
  183105. png_uint_32 asm_flags;
  183106. # endif
  183107. #endif
  183108. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  183109. #ifdef PNG_USER_MEM_SUPPORTED
  183110. png_voidp mem_ptr; /* user supplied struct for mem functions */
  183111. png_malloc_ptr malloc_fn; /* function for allocating memory */
  183112. png_free_ptr free_fn; /* function for freeing memory */
  183113. #endif
  183114. /* New member added in libpng-1.0.13 and 1.2.0 */
  183115. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  183116. #if defined(PNG_READ_DITHER_SUPPORTED)
  183117. /* The following three members were added at version 1.0.14 and 1.2.4 */
  183118. png_bytep dither_sort; /* working sort array */
  183119. png_bytep index_to_palette; /* where the original index currently is */
  183120. /* in the palette */
  183121. png_bytep palette_to_index; /* which original index points to this */
  183122. /* palette color */
  183123. #endif
  183124. /* New members added in libpng-1.0.16 and 1.2.6 */
  183125. png_byte compression_type;
  183126. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183127. png_uint_32 user_width_max;
  183128. png_uint_32 user_height_max;
  183129. #endif
  183130. /* New member added in libpng-1.0.25 and 1.2.17 */
  183131. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183132. /* storage for unknown chunk that the library doesn't recognize. */
  183133. png_unknown_chunk unknown_chunk;
  183134. #endif
  183135. };
  183136. /* This triggers a compiler error in png.c, if png.c and png.h
  183137. * do not agree upon the version number.
  183138. */
  183139. typedef png_structp version_1_2_21;
  183140. typedef png_struct FAR * FAR * png_structpp;
  183141. /* Here are the function definitions most commonly used. This is not
  183142. * the place to find out how to use libpng. See libpng.txt for the
  183143. * full explanation, see example.c for the summary. This just provides
  183144. * a simple one line description of the use of each function.
  183145. */
  183146. /* Returns the version number of the library */
  183147. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183148. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183149. * Handling more than 8 bytes from the beginning of the file is an error.
  183150. */
  183151. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183152. int num_bytes));
  183153. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183154. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183155. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183156. * start > 7 will always fail (ie return non-zero).
  183157. */
  183158. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183159. png_size_t num_to_check));
  183160. /* Simple signature checking function. This is the same as calling
  183161. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183162. */
  183163. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183164. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183165. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183166. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183167. png_error_ptr error_fn, png_error_ptr warn_fn));
  183168. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183169. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183170. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183171. png_error_ptr error_fn, png_error_ptr warn_fn));
  183172. #ifdef PNG_WRITE_SUPPORTED
  183173. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183174. PNGARG((png_structp png_ptr));
  183175. #endif
  183176. #ifdef PNG_WRITE_SUPPORTED
  183177. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183178. PNGARG((png_structp png_ptr, png_uint_32 size));
  183179. #endif
  183180. /* Reset the compression stream */
  183181. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183182. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183183. #ifdef PNG_USER_MEM_SUPPORTED
  183184. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183185. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183186. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183187. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183188. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183189. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183190. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183191. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183192. #endif
  183193. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183194. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183195. png_bytep chunk_name, png_bytep data, png_size_t length));
  183196. /* Write the start of a PNG chunk - length and chunk name. */
  183197. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183198. png_bytep chunk_name, png_uint_32 length));
  183199. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183200. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183201. png_bytep data, png_size_t length));
  183202. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183203. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183204. /* Allocate and initialize the info structure */
  183205. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183206. PNGARG((png_structp png_ptr));
  183207. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183208. /* Initialize the info structure (old interface - DEPRECATED) */
  183209. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183210. #undef png_info_init
  183211. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183212. png_sizeof(png_info));
  183213. #endif
  183214. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183215. png_size_t png_info_struct_size));
  183216. /* Writes all the PNG information before the image. */
  183217. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183218. png_infop info_ptr));
  183219. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183220. png_infop info_ptr));
  183221. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183222. /* read the information before the actual image data. */
  183223. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183224. png_infop info_ptr));
  183225. #endif
  183226. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183227. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183228. PNGARG((png_structp png_ptr, png_timep ptime));
  183229. #endif
  183230. #if !defined(_WIN32_WCE)
  183231. /* "time.h" functions are not supported on WindowsCE */
  183232. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183233. /* convert from a struct tm to png_time */
  183234. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183235. struct tm FAR * ttime));
  183236. /* convert from time_t to png_time. Uses gmtime() */
  183237. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183238. time_t ttime));
  183239. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183240. #endif /* _WIN32_WCE */
  183241. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183242. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183243. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183244. #if !defined(PNG_1_0_X)
  183245. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183246. png_ptr));
  183247. #endif
  183248. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183249. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183250. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183251. /* Deprecated */
  183252. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183253. #endif
  183254. #endif
  183255. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183256. /* Use blue, green, red order for pixels. */
  183257. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183258. #endif
  183259. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183260. /* Expand the grayscale to 24-bit RGB if necessary. */
  183261. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183262. #endif
  183263. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183264. /* Reduce RGB to grayscale. */
  183265. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183266. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183267. int error_action, double red, double green ));
  183268. #endif
  183269. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183270. int error_action, png_fixed_point red, png_fixed_point green ));
  183271. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183272. png_ptr));
  183273. #endif
  183274. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183275. png_colorp palette));
  183276. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183277. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183278. #endif
  183279. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183280. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183281. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183282. #endif
  183283. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183284. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183285. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183286. #endif
  183287. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183288. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183289. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183290. png_uint_32 filler, int flags));
  183291. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183292. #define PNG_FILLER_BEFORE 0
  183293. #define PNG_FILLER_AFTER 1
  183294. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183295. #if !defined(PNG_1_0_X)
  183296. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183297. png_uint_32 filler, int flags));
  183298. #endif
  183299. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183300. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183301. /* Swap bytes in 16-bit depth files. */
  183302. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183303. #endif
  183304. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183305. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183306. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183307. #endif
  183308. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183309. /* Swap packing order of pixels in bytes. */
  183310. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183311. #endif
  183312. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183313. /* Converts files to legal bit depths. */
  183314. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183315. png_color_8p true_bits));
  183316. #endif
  183317. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183318. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183319. /* Have the code handle the interlacing. Returns the number of passes. */
  183320. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183321. #endif
  183322. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183323. /* Invert monochrome files */
  183324. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183325. #endif
  183326. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183327. /* Handle alpha and tRNS by replacing with a background color. */
  183328. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183329. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183330. png_color_16p background_color, int background_gamma_code,
  183331. int need_expand, double background_gamma));
  183332. #endif
  183333. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183334. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183335. #define PNG_BACKGROUND_GAMMA_FILE 2
  183336. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183337. #endif
  183338. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183339. /* strip the second byte of information from a 16-bit depth file. */
  183340. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183341. #endif
  183342. #if defined(PNG_READ_DITHER_SUPPORTED)
  183343. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183344. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183345. png_colorp palette, int num_palette, int maximum_colors,
  183346. png_uint_16p histogram, int full_dither));
  183347. #endif
  183348. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183349. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183350. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183351. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183352. double screen_gamma, double default_file_gamma));
  183353. #endif
  183354. #endif
  183355. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183356. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183357. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183358. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183359. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183360. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183361. int empty_plte_permitted));
  183362. #endif
  183363. #endif
  183364. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183365. /* Set how many lines between output flushes - 0 for no flushing */
  183366. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183367. /* Flush the current PNG output buffer */
  183368. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183369. #endif
  183370. /* optional update palette with requested transformations */
  183371. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183372. /* optional call to update the users info structure */
  183373. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183374. png_infop info_ptr));
  183375. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183376. /* read one or more rows of image data. */
  183377. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183378. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183379. #endif
  183380. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183381. /* read a row of data. */
  183382. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183383. png_bytep row,
  183384. png_bytep display_row));
  183385. #endif
  183386. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183387. /* read the whole image into memory at once. */
  183388. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183389. png_bytepp image));
  183390. #endif
  183391. /* write a row of image data */
  183392. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183393. png_bytep row));
  183394. /* write a few rows of image data */
  183395. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183396. png_bytepp row, png_uint_32 num_rows));
  183397. /* write the image data */
  183398. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183399. png_bytepp image));
  183400. /* writes the end of the PNG file. */
  183401. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183402. png_infop info_ptr));
  183403. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183404. /* read the end of the PNG file. */
  183405. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183406. png_infop info_ptr));
  183407. #endif
  183408. /* free any memory associated with the png_info_struct */
  183409. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183410. png_infopp info_ptr_ptr));
  183411. /* free any memory associated with the png_struct and the png_info_structs */
  183412. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183413. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183414. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183415. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183416. png_infop end_info_ptr));
  183417. /* free any memory associated with the png_struct and the png_info_structs */
  183418. extern PNG_EXPORT(void,png_destroy_write_struct)
  183419. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183420. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183421. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183422. /* set the libpng method of handling chunk CRC errors */
  183423. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183424. int crit_action, int ancil_action));
  183425. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183426. * ancillary and critical chunks, and whether to use the data contained
  183427. * therein. Note that it is impossible to "discard" data in a critical
  183428. * chunk. For versions prior to 0.90, the action was always error/quit,
  183429. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183430. * chunks is warn/discard. These values should NOT be changed.
  183431. *
  183432. * value action:critical action:ancillary
  183433. */
  183434. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183435. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183436. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183437. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183438. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183439. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183440. /* These functions give the user control over the scan-line filtering in
  183441. * libpng and the compression methods used by zlib. These functions are
  183442. * mainly useful for testing, as the defaults should work with most users.
  183443. * Those users who are tight on memory or want faster performance at the
  183444. * expense of compression can modify them. See the compression library
  183445. * header file (zlib.h) for an explination of the compression functions.
  183446. */
  183447. /* set the filtering method(s) used by libpng. Currently, the only valid
  183448. * value for "method" is 0.
  183449. */
  183450. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183451. int filters));
  183452. /* Flags for png_set_filter() to say which filters to use. The flags
  183453. * are chosen so that they don't conflict with real filter types
  183454. * below, in case they are supplied instead of the #defined constants.
  183455. * These values should NOT be changed.
  183456. */
  183457. #define PNG_NO_FILTERS 0x00
  183458. #define PNG_FILTER_NONE 0x08
  183459. #define PNG_FILTER_SUB 0x10
  183460. #define PNG_FILTER_UP 0x20
  183461. #define PNG_FILTER_AVG 0x40
  183462. #define PNG_FILTER_PAETH 0x80
  183463. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183464. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183465. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183466. * These defines should NOT be changed.
  183467. */
  183468. #define PNG_FILTER_VALUE_NONE 0
  183469. #define PNG_FILTER_VALUE_SUB 1
  183470. #define PNG_FILTER_VALUE_UP 2
  183471. #define PNG_FILTER_VALUE_AVG 3
  183472. #define PNG_FILTER_VALUE_PAETH 4
  183473. #define PNG_FILTER_VALUE_LAST 5
  183474. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183475. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183476. * defines, either the default (minimum-sum-of-absolute-differences), or
  183477. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183478. *
  183479. * Weights are factors >= 1.0, indicating how important it is to keep the
  183480. * filter type consistent between rows. Larger numbers mean the current
  183481. * filter is that many times as likely to be the same as the "num_weights"
  183482. * previous filters. This is cumulative for each previous row with a weight.
  183483. * There needs to be "num_weights" values in "filter_weights", or it can be
  183484. * NULL if the weights aren't being specified. Weights have no influence on
  183485. * the selection of the first row filter. Well chosen weights can (in theory)
  183486. * improve the compression for a given image.
  183487. *
  183488. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183489. * filter type. Higher costs indicate more decoding expense, and are
  183490. * therefore less likely to be selected over a filter with lower computational
  183491. * costs. There needs to be a value in "filter_costs" for each valid filter
  183492. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183493. * setting the costs. Costs try to improve the speed of decompression without
  183494. * unduly increasing the compressed image size.
  183495. *
  183496. * A negative weight or cost indicates the default value is to be used, and
  183497. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183498. * The default values for both weights and costs are currently 1.0, but may
  183499. * change if good general weighting/cost heuristics can be found. If both
  183500. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183501. * to the UNWEIGHTED method, but with added encoding time/computation.
  183502. */
  183503. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183504. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183505. int heuristic_method, int num_weights, png_doublep filter_weights,
  183506. png_doublep filter_costs));
  183507. #endif
  183508. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183509. /* Heuristic used for row filter selection. These defines should NOT be
  183510. * changed.
  183511. */
  183512. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183513. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183514. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183515. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183516. /* Set the library compression level. Currently, valid values range from
  183517. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183518. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183519. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183520. * for PNG images, and do considerably fewer caclulations. In the future,
  183521. * these values may not correspond directly to the zlib compression levels.
  183522. */
  183523. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183524. int level));
  183525. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183526. PNGARG((png_structp png_ptr, int mem_level));
  183527. extern PNG_EXPORT(void,png_set_compression_strategy)
  183528. PNGARG((png_structp png_ptr, int strategy));
  183529. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183530. PNGARG((png_structp png_ptr, int window_bits));
  183531. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183532. int method));
  183533. /* These next functions are called for input/output, memory, and error
  183534. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183535. * and call standard C I/O routines such as fread(), fwrite(), and
  183536. * fprintf(). These functions can be made to use other I/O routines
  183537. * at run time for those applications that need to handle I/O in a
  183538. * different manner by calling png_set_???_fn(). See libpng.txt for
  183539. * more information.
  183540. */
  183541. #if !defined(PNG_NO_STDIO)
  183542. /* Initialize the input/output for the PNG file to the default functions. */
  183543. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183544. #endif
  183545. /* Replace the (error and abort), and warning functions with user
  183546. * supplied functions. If no messages are to be printed you must still
  183547. * write and use replacement functions. The replacement error_fn should
  183548. * still do a longjmp to the last setjmp location if you are using this
  183549. * method of error handling. If error_fn or warning_fn is NULL, the
  183550. * default function will be used.
  183551. */
  183552. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183553. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183554. /* Return the user pointer associated with the error functions */
  183555. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183556. /* Replace the default data output functions with a user supplied one(s).
  183557. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183558. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183559. * output_flush_fn will be ignored (and thus can be NULL).
  183560. */
  183561. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183562. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183563. /* Replace the default data input function with a user supplied one. */
  183564. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183565. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183566. /* Return the user pointer associated with the I/O functions */
  183567. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183568. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183569. png_read_status_ptr read_row_fn));
  183570. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183571. png_write_status_ptr write_row_fn));
  183572. #ifdef PNG_USER_MEM_SUPPORTED
  183573. /* Replace the default memory allocation functions with user supplied one(s). */
  183574. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183575. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183576. /* Return the user pointer associated with the memory functions */
  183577. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183578. #endif
  183579. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183580. defined(PNG_LEGACY_SUPPORTED)
  183581. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183582. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183583. #endif
  183584. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183585. defined(PNG_LEGACY_SUPPORTED)
  183586. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183587. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183588. #endif
  183589. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183590. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183591. defined(PNG_LEGACY_SUPPORTED)
  183592. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183593. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183594. int user_transform_channels));
  183595. /* Return the user pointer associated with the user transform functions */
  183596. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183597. PNGARG((png_structp png_ptr));
  183598. #endif
  183599. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183600. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183601. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183602. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183603. png_ptr));
  183604. #endif
  183605. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183606. /* Sets the function callbacks for the push reader, and a pointer to a
  183607. * user-defined structure available to the callback functions.
  183608. */
  183609. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183610. png_voidp progressive_ptr,
  183611. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183612. png_progressive_end_ptr end_fn));
  183613. /* returns the user pointer associated with the push read functions */
  183614. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183615. PNGARG((png_structp png_ptr));
  183616. /* function to be called when data becomes available */
  183617. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183618. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183619. /* function that combines rows. Not very much different than the
  183620. * png_combine_row() call. Is this even used?????
  183621. */
  183622. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183623. png_bytep old_row, png_bytep new_row));
  183624. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183625. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183626. png_uint_32 size));
  183627. #if defined(PNG_1_0_X)
  183628. # define png_malloc_warn png_malloc
  183629. #else
  183630. /* Added at libpng version 1.2.4 */
  183631. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183632. png_uint_32 size));
  183633. #endif
  183634. /* frees a pointer allocated by png_malloc() */
  183635. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183636. #if defined(PNG_1_0_X)
  183637. /* Function to allocate memory for zlib. */
  183638. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183639. uInt size));
  183640. /* Function to free memory for zlib */
  183641. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183642. #endif
  183643. /* Free data that was allocated internally */
  183644. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183645. png_infop info_ptr, png_uint_32 free_me, int num));
  183646. #ifdef PNG_FREE_ME_SUPPORTED
  183647. /* Reassign responsibility for freeing existing data, whether allocated
  183648. * by libpng or by the application */
  183649. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183650. png_infop info_ptr, int freer, png_uint_32 mask));
  183651. #endif
  183652. /* assignments for png_data_freer */
  183653. #define PNG_DESTROY_WILL_FREE_DATA 1
  183654. #define PNG_SET_WILL_FREE_DATA 1
  183655. #define PNG_USER_WILL_FREE_DATA 2
  183656. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183657. #define PNG_FREE_HIST 0x0008
  183658. #define PNG_FREE_ICCP 0x0010
  183659. #define PNG_FREE_SPLT 0x0020
  183660. #define PNG_FREE_ROWS 0x0040
  183661. #define PNG_FREE_PCAL 0x0080
  183662. #define PNG_FREE_SCAL 0x0100
  183663. #define PNG_FREE_UNKN 0x0200
  183664. #define PNG_FREE_LIST 0x0400
  183665. #define PNG_FREE_PLTE 0x1000
  183666. #define PNG_FREE_TRNS 0x2000
  183667. #define PNG_FREE_TEXT 0x4000
  183668. #define PNG_FREE_ALL 0x7fff
  183669. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183670. #ifdef PNG_USER_MEM_SUPPORTED
  183671. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183672. png_uint_32 size));
  183673. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183674. png_voidp ptr));
  183675. #endif
  183676. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183677. png_voidp s1, png_voidp s2, png_uint_32 size));
  183678. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183679. png_voidp s1, int value, png_uint_32 size));
  183680. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183681. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183682. int check));
  183683. #endif /* USE_FAR_KEYWORD */
  183684. #ifndef PNG_NO_ERROR_TEXT
  183685. /* Fatal error in PNG image of libpng - can't continue */
  183686. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183687. png_const_charp error_message));
  183688. /* The same, but the chunk name is prepended to the error string. */
  183689. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183690. png_const_charp error_message));
  183691. #else
  183692. /* Fatal error in PNG image of libpng - can't continue */
  183693. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183694. #endif
  183695. #ifndef PNG_NO_WARNINGS
  183696. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183697. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183698. png_const_charp warning_message));
  183699. #ifdef PNG_READ_SUPPORTED
  183700. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183701. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183702. png_const_charp warning_message));
  183703. #endif /* PNG_READ_SUPPORTED */
  183704. #endif /* PNG_NO_WARNINGS */
  183705. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183706. * Similarly, the png_get_<chunk> calls are used to read values from the
  183707. * png_info_struct, either storing the parameters in the passed variables, or
  183708. * setting pointers into the png_info_struct where the data is stored. The
  183709. * png_get_<chunk> functions return a non-zero value if the data was available
  183710. * in info_ptr, or return zero and do not change any of the parameters if the
  183711. * data was not available.
  183712. *
  183713. * These functions should be used instead of directly accessing png_info
  183714. * to avoid problems with future changes in the size and internal layout of
  183715. * png_info_struct.
  183716. */
  183717. /* Returns "flag" if chunk data is valid in info_ptr. */
  183718. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183719. png_infop info_ptr, png_uint_32 flag));
  183720. /* Returns number of bytes needed to hold a transformed row. */
  183721. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183722. png_infop info_ptr));
  183723. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183724. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183725. returned from png_read_png(). */
  183726. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183727. png_infop info_ptr));
  183728. /* Set row_pointers, which is an array of pointers to scanlines for use
  183729. by png_write_png(). */
  183730. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183731. png_infop info_ptr, png_bytepp row_pointers));
  183732. #endif
  183733. /* Returns number of color channels in image. */
  183734. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183735. png_infop info_ptr));
  183736. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183737. /* Returns image width in pixels. */
  183738. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183739. png_ptr, png_infop info_ptr));
  183740. /* Returns image height in pixels. */
  183741. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183742. png_ptr, png_infop info_ptr));
  183743. /* Returns image bit_depth. */
  183744. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183745. png_ptr, png_infop info_ptr));
  183746. /* Returns image color_type. */
  183747. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183748. png_ptr, png_infop info_ptr));
  183749. /* Returns image filter_type. */
  183750. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183751. png_ptr, png_infop info_ptr));
  183752. /* Returns image interlace_type. */
  183753. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183754. png_ptr, png_infop info_ptr));
  183755. /* Returns image compression_type. */
  183756. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183757. png_ptr, png_infop info_ptr));
  183758. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183759. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183760. png_ptr, png_infop info_ptr));
  183761. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183762. png_ptr, png_infop info_ptr));
  183763. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183764. png_ptr, png_infop info_ptr));
  183765. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183766. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183767. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183768. png_ptr, png_infop info_ptr));
  183769. #endif
  183770. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183771. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183772. png_ptr, png_infop info_ptr));
  183773. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183774. png_ptr, png_infop info_ptr));
  183775. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183776. png_ptr, png_infop info_ptr));
  183777. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183778. png_ptr, png_infop info_ptr));
  183779. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183780. /* Returns pointer to signature string read from PNG header */
  183781. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183782. png_infop info_ptr));
  183783. #if defined(PNG_bKGD_SUPPORTED)
  183784. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183785. png_infop info_ptr, png_color_16p *background));
  183786. #endif
  183787. #if defined(PNG_bKGD_SUPPORTED)
  183788. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183789. png_infop info_ptr, png_color_16p background));
  183790. #endif
  183791. #if defined(PNG_cHRM_SUPPORTED)
  183792. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183793. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183794. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183795. double *red_y, double *green_x, double *green_y, double *blue_x,
  183796. double *blue_y));
  183797. #endif
  183798. #ifdef PNG_FIXED_POINT_SUPPORTED
  183799. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183800. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183801. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183802. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183803. *int_blue_x, png_fixed_point *int_blue_y));
  183804. #endif
  183805. #endif
  183806. #if defined(PNG_cHRM_SUPPORTED)
  183807. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183808. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183809. png_infop info_ptr, double white_x, double white_y, double red_x,
  183810. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183811. #endif
  183812. #ifdef PNG_FIXED_POINT_SUPPORTED
  183813. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183814. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183815. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183816. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183817. png_fixed_point int_blue_y));
  183818. #endif
  183819. #endif
  183820. #if defined(PNG_gAMA_SUPPORTED)
  183821. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183822. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183823. png_infop info_ptr, double *file_gamma));
  183824. #endif
  183825. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183826. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183827. #endif
  183828. #if defined(PNG_gAMA_SUPPORTED)
  183829. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183830. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183831. png_infop info_ptr, double file_gamma));
  183832. #endif
  183833. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183834. png_infop info_ptr, png_fixed_point int_file_gamma));
  183835. #endif
  183836. #if defined(PNG_hIST_SUPPORTED)
  183837. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183838. png_infop info_ptr, png_uint_16p *hist));
  183839. #endif
  183840. #if defined(PNG_hIST_SUPPORTED)
  183841. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183842. png_infop info_ptr, png_uint_16p hist));
  183843. #endif
  183844. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183845. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183846. int *bit_depth, int *color_type, int *interlace_method,
  183847. int *compression_method, int *filter_method));
  183848. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183849. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183850. int color_type, int interlace_method, int compression_method,
  183851. int filter_method));
  183852. #if defined(PNG_oFFs_SUPPORTED)
  183853. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183854. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183855. int *unit_type));
  183856. #endif
  183857. #if defined(PNG_oFFs_SUPPORTED)
  183858. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183859. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183860. int unit_type));
  183861. #endif
  183862. #if defined(PNG_pCAL_SUPPORTED)
  183863. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183864. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183865. int *type, int *nparams, png_charp *units, png_charpp *params));
  183866. #endif
  183867. #if defined(PNG_pCAL_SUPPORTED)
  183868. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183869. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183870. int type, int nparams, png_charp units, png_charpp params));
  183871. #endif
  183872. #if defined(PNG_pHYs_SUPPORTED)
  183873. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183874. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183875. #endif
  183876. #if defined(PNG_pHYs_SUPPORTED)
  183877. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183878. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183879. #endif
  183880. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183881. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183882. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183883. png_infop info_ptr, png_colorp palette, int num_palette));
  183884. #if defined(PNG_sBIT_SUPPORTED)
  183885. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183886. png_infop info_ptr, png_color_8p *sig_bit));
  183887. #endif
  183888. #if defined(PNG_sBIT_SUPPORTED)
  183889. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183890. png_infop info_ptr, png_color_8p sig_bit));
  183891. #endif
  183892. #if defined(PNG_sRGB_SUPPORTED)
  183893. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183894. png_infop info_ptr, int *intent));
  183895. #endif
  183896. #if defined(PNG_sRGB_SUPPORTED)
  183897. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183898. png_infop info_ptr, int intent));
  183899. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183900. png_infop info_ptr, int intent));
  183901. #endif
  183902. #if defined(PNG_iCCP_SUPPORTED)
  183903. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183904. png_infop info_ptr, png_charpp name, int *compression_type,
  183905. png_charpp profile, png_uint_32 *proflen));
  183906. /* Note to maintainer: profile should be png_bytepp */
  183907. #endif
  183908. #if defined(PNG_iCCP_SUPPORTED)
  183909. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183910. png_infop info_ptr, png_charp name, int compression_type,
  183911. png_charp profile, png_uint_32 proflen));
  183912. /* Note to maintainer: profile should be png_bytep */
  183913. #endif
  183914. #if defined(PNG_sPLT_SUPPORTED)
  183915. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183916. png_infop info_ptr, png_sPLT_tpp entries));
  183917. #endif
  183918. #if defined(PNG_sPLT_SUPPORTED)
  183919. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183920. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183921. #endif
  183922. #if defined(PNG_TEXT_SUPPORTED)
  183923. /* png_get_text also returns the number of text chunks in *num_text */
  183924. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183925. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183926. #endif
  183927. /*
  183928. * Note while png_set_text() will accept a structure whose text,
  183929. * language, and translated keywords are NULL pointers, the structure
  183930. * returned by png_get_text will always contain regular
  183931. * zero-terminated C strings. They might be empty strings but
  183932. * they will never be NULL pointers.
  183933. */
  183934. #if defined(PNG_TEXT_SUPPORTED)
  183935. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183936. png_infop info_ptr, png_textp text_ptr, int num_text));
  183937. #endif
  183938. #if defined(PNG_tIME_SUPPORTED)
  183939. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183940. png_infop info_ptr, png_timep *mod_time));
  183941. #endif
  183942. #if defined(PNG_tIME_SUPPORTED)
  183943. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183944. png_infop info_ptr, png_timep mod_time));
  183945. #endif
  183946. #if defined(PNG_tRNS_SUPPORTED)
  183947. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183948. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183949. png_color_16p *trans_values));
  183950. #endif
  183951. #if defined(PNG_tRNS_SUPPORTED)
  183952. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183953. png_infop info_ptr, png_bytep trans, int num_trans,
  183954. png_color_16p trans_values));
  183955. #endif
  183956. #if defined(PNG_tRNS_SUPPORTED)
  183957. #endif
  183958. #if defined(PNG_sCAL_SUPPORTED)
  183959. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183960. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183961. png_infop info_ptr, int *unit, double *width, double *height));
  183962. #else
  183963. #ifdef PNG_FIXED_POINT_SUPPORTED
  183964. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183965. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183966. #endif
  183967. #endif
  183968. #endif /* PNG_sCAL_SUPPORTED */
  183969. #if defined(PNG_sCAL_SUPPORTED)
  183970. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183971. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183972. png_infop info_ptr, int unit, double width, double height));
  183973. #else
  183974. #ifdef PNG_FIXED_POINT_SUPPORTED
  183975. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183976. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183977. #endif
  183978. #endif
  183979. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183980. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183981. /* provide a list of chunks and how they are to be handled, if the built-in
  183982. handling or default unknown chunk handling is not desired. Any chunks not
  183983. listed will be handled in the default manner. The IHDR and IEND chunks
  183984. must not be listed.
  183985. keep = 0: follow default behaviour
  183986. = 1: do not keep
  183987. = 2: keep only if safe-to-copy
  183988. = 3: keep even if unsafe-to-copy
  183989. */
  183990. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183991. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183992. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183993. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183994. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183995. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183996. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183997. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183998. #endif
  183999. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184000. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  184001. chunk_name));
  184002. #endif
  184003. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  184004. If you need to turn it off for a chunk that your application has freed,
  184005. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  184006. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  184007. png_infop info_ptr, int mask));
  184008. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184009. /* The "params" pointer is currently not used and is for future expansion. */
  184010. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  184011. png_infop info_ptr,
  184012. int transforms,
  184013. png_voidp params));
  184014. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  184015. png_infop info_ptr,
  184016. int transforms,
  184017. png_voidp params));
  184018. #endif
  184019. /* Define PNG_DEBUG at compile time for debugging information. Higher
  184020. * numbers for PNG_DEBUG mean more debugging information. This has
  184021. * only been added since version 0.95 so it is not implemented throughout
  184022. * libpng yet, but more support will be added as needed.
  184023. */
  184024. #ifdef PNG_DEBUG
  184025. #if (PNG_DEBUG > 0)
  184026. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  184027. #include <crtdbg.h>
  184028. #if (PNG_DEBUG > 1)
  184029. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  184030. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  184031. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  184032. #endif
  184033. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  184034. #ifndef PNG_DEBUG_FILE
  184035. #define PNG_DEBUG_FILE stderr
  184036. #endif /* PNG_DEBUG_FILE */
  184037. #if (PNG_DEBUG > 1)
  184038. #define png_debug(l,m) \
  184039. { \
  184040. int num_tabs=l; \
  184041. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  184042. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  184043. }
  184044. #define png_debug1(l,m,p1) \
  184045. { \
  184046. int num_tabs=l; \
  184047. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  184048. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  184049. }
  184050. #define png_debug2(l,m,p1,p2) \
  184051. { \
  184052. int num_tabs=l; \
  184053. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  184054. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  184055. }
  184056. #endif /* (PNG_DEBUG > 1) */
  184057. #endif /* _MSC_VER */
  184058. #endif /* (PNG_DEBUG > 0) */
  184059. #endif /* PNG_DEBUG */
  184060. #ifndef png_debug
  184061. #define png_debug(l, m)
  184062. #endif
  184063. #ifndef png_debug1
  184064. #define png_debug1(l, m, p1)
  184065. #endif
  184066. #ifndef png_debug2
  184067. #define png_debug2(l, m, p1, p2)
  184068. #endif
  184069. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  184070. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  184071. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  184072. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  184073. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184074. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  184075. png_ptr, png_uint_32 mng_features_permitted));
  184076. #endif
  184077. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  184078. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  184079. #define PNG_HANDLE_CHUNK_NEVER 1
  184080. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  184081. #define PNG_HANDLE_CHUNK_ALWAYS 3
  184082. /* Added to version 1.2.0 */
  184083. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184084. #if defined(PNG_MMX_CODE_SUPPORTED)
  184085. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  184086. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  184087. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  184088. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  184089. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  184090. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  184091. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  184092. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  184093. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  184094. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  184095. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  184096. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  184097. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  184098. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  184099. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  184100. #define PNG_MMX_WRITE_FLAGS ( 0 )
  184101. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  184102. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  184103. | PNG_MMX_READ_FLAGS \
  184104. | PNG_MMX_WRITE_FLAGS )
  184105. #define PNG_SELECT_READ 1
  184106. #define PNG_SELECT_WRITE 2
  184107. #endif /* PNG_MMX_CODE_SUPPORTED */
  184108. #if !defined(PNG_1_0_X)
  184109. /* pngget.c */
  184110. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  184111. PNGARG((int flag_select, int *compilerID));
  184112. /* pngget.c */
  184113. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  184114. PNGARG((int flag_select));
  184115. /* pngget.c */
  184116. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  184117. PNGARG((png_structp png_ptr));
  184118. /* pngget.c */
  184119. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184120. PNGARG((png_structp png_ptr));
  184121. /* pngget.c */
  184122. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184123. PNGARG((png_structp png_ptr));
  184124. /* pngset.c */
  184125. extern PNG_EXPORT(void,png_set_asm_flags)
  184126. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184127. /* pngset.c */
  184128. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184129. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184130. png_uint_32 mmx_rowbytes_threshold));
  184131. #endif /* PNG_1_0_X */
  184132. #if !defined(PNG_1_0_X)
  184133. /* png.c, pnggccrd.c, or pngvcrd.c */
  184134. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184135. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184136. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184137. * messages before passing them to the error or warning handler. */
  184138. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184139. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184140. png_ptr, png_uint_32 strip_mode));
  184141. #endif
  184142. #endif /* PNG_1_0_X */
  184143. /* Added at libpng-1.2.6 */
  184144. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184145. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184146. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184147. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184148. png_ptr));
  184149. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184150. png_ptr));
  184151. #endif
  184152. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184153. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184154. /* With these routines we avoid an integer divide, which will be slower on
  184155. * most machines. However, it does take more operations than the corresponding
  184156. * divide method, so it may be slower on a few RISC systems. There are two
  184157. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184158. *
  184159. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184160. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184161. * standard method.
  184162. *
  184163. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184164. */
  184165. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184166. # define png_composite(composite, fg, alpha, bg) \
  184167. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184168. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184169. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184170. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184171. # define png_composite_16(composite, fg, alpha, bg) \
  184172. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184173. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184174. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184175. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184176. #else /* standard method using integer division */
  184177. # define png_composite(composite, fg, alpha, bg) \
  184178. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184179. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184180. (png_uint_16)127) / 255)
  184181. # define png_composite_16(composite, fg, alpha, bg) \
  184182. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184183. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184184. (png_uint_32)32767) / (png_uint_32)65535L)
  184185. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184186. /* Inline macros to do direct reads of bytes from the input buffer. These
  184187. * require that you are using an architecture that uses PNG byte ordering
  184188. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184189. * in big-endian mode and 680x0 are the only ones that will support this.
  184190. * The x86 line of processors definitely do not. The png_get_int_32()
  184191. * routine also assumes we are using two's complement format for negative
  184192. * values, which is almost certainly true.
  184193. */
  184194. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184195. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184196. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184197. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184198. #else
  184199. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184200. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184201. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184202. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184203. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184204. PNGARG((png_structp png_ptr, png_bytep buf));
  184205. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184206. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184207. */
  184208. extern PNG_EXPORT(void,png_save_uint_32)
  184209. PNGARG((png_bytep buf, png_uint_32 i));
  184210. extern PNG_EXPORT(void,png_save_int_32)
  184211. PNGARG((png_bytep buf, png_int_32 i));
  184212. /* Place a 16-bit number into a buffer in PNG byte order.
  184213. * The parameter is declared unsigned int, not png_uint_16,
  184214. * just to avoid potential problems on pre-ANSI C compilers.
  184215. */
  184216. extern PNG_EXPORT(void,png_save_uint_16)
  184217. PNGARG((png_bytep buf, unsigned int i));
  184218. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184219. /* ************************************************************************* */
  184220. /* These next functions are used internally in the code. They generally
  184221. * shouldn't be used unless you are writing code to add or replace some
  184222. * functionality in libpng. More information about most functions can
  184223. * be found in the files where the functions are located.
  184224. */
  184225. /* Various modes of operation, that are visible to applications because
  184226. * they are used for unknown chunk location.
  184227. */
  184228. #define PNG_HAVE_IHDR 0x01
  184229. #define PNG_HAVE_PLTE 0x02
  184230. #define PNG_HAVE_IDAT 0x04
  184231. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184232. #define PNG_HAVE_IEND 0x10
  184233. #if defined(PNG_INTERNAL)
  184234. /* More modes of operation. Note that after an init, mode is set to
  184235. * zero automatically when the structure is created.
  184236. */
  184237. #define PNG_HAVE_gAMA 0x20
  184238. #define PNG_HAVE_cHRM 0x40
  184239. #define PNG_HAVE_sRGB 0x80
  184240. #define PNG_HAVE_CHUNK_HEADER 0x100
  184241. #define PNG_WROTE_tIME 0x200
  184242. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184243. #define PNG_BACKGROUND_IS_GRAY 0x800
  184244. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184245. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184246. /* flags for the transformations the PNG library does on the image data */
  184247. #define PNG_BGR 0x0001
  184248. #define PNG_INTERLACE 0x0002
  184249. #define PNG_PACK 0x0004
  184250. #define PNG_SHIFT 0x0008
  184251. #define PNG_SWAP_BYTES 0x0010
  184252. #define PNG_INVERT_MONO 0x0020
  184253. #define PNG_DITHER 0x0040
  184254. #define PNG_BACKGROUND 0x0080
  184255. #define PNG_BACKGROUND_EXPAND 0x0100
  184256. /* 0x0200 unused */
  184257. #define PNG_16_TO_8 0x0400
  184258. #define PNG_RGBA 0x0800
  184259. #define PNG_EXPAND 0x1000
  184260. #define PNG_GAMMA 0x2000
  184261. #define PNG_GRAY_TO_RGB 0x4000
  184262. #define PNG_FILLER 0x8000L
  184263. #define PNG_PACKSWAP 0x10000L
  184264. #define PNG_SWAP_ALPHA 0x20000L
  184265. #define PNG_STRIP_ALPHA 0x40000L
  184266. #define PNG_INVERT_ALPHA 0x80000L
  184267. #define PNG_USER_TRANSFORM 0x100000L
  184268. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184269. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184270. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184271. /* 0x800000L Unused */
  184272. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184273. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184274. /* 0x4000000L unused */
  184275. /* 0x8000000L unused */
  184276. /* 0x10000000L unused */
  184277. /* 0x20000000L unused */
  184278. /* 0x40000000L unused */
  184279. /* flags for png_create_struct */
  184280. #define PNG_STRUCT_PNG 0x0001
  184281. #define PNG_STRUCT_INFO 0x0002
  184282. /* Scaling factor for filter heuristic weighting calculations */
  184283. #define PNG_WEIGHT_SHIFT 8
  184284. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184285. #define PNG_COST_SHIFT 3
  184286. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184287. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184288. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184289. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184290. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184291. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184292. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184293. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184294. #define PNG_FLAG_ROW_INIT 0x0040
  184295. #define PNG_FLAG_FILLER_AFTER 0x0080
  184296. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184297. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184298. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184299. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184300. #define PNG_FLAG_FREE_PLTE 0x1000
  184301. #define PNG_FLAG_FREE_TRNS 0x2000
  184302. #define PNG_FLAG_FREE_HIST 0x4000
  184303. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184304. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184305. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184306. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184307. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184308. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184309. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184310. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184311. /* 0x800000L unused */
  184312. /* 0x1000000L unused */
  184313. /* 0x2000000L unused */
  184314. /* 0x4000000L unused */
  184315. /* 0x8000000L unused */
  184316. /* 0x10000000L unused */
  184317. /* 0x20000000L unused */
  184318. /* 0x40000000L unused */
  184319. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184320. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184321. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184322. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184323. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184324. PNG_FLAG_CRC_CRITICAL_MASK)
  184325. /* save typing and make code easier to understand */
  184326. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184327. abs((int)((c1).green) - (int)((c2).green)) + \
  184328. abs((int)((c1).blue) - (int)((c2).blue)))
  184329. /* Added to libpng-1.2.6 JB */
  184330. #define PNG_ROWBYTES(pixel_bits, width) \
  184331. ((pixel_bits) >= 8 ? \
  184332. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184333. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184334. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184335. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184336. "ideal" and "delta" should be constants, normally simple
  184337. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184338. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184339. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184340. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184341. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184342. /* place to hold the signature string for a PNG file. */
  184343. #ifdef PNG_USE_GLOBAL_ARRAYS
  184344. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184345. #else
  184346. #endif
  184347. #endif /* PNG_NO_EXTERN */
  184348. /* Constant strings for known chunk types. If you need to add a chunk,
  184349. * define the name here, and add an invocation of the macro in png.c and
  184350. * wherever it's needed.
  184351. */
  184352. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184353. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184354. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184355. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184356. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184357. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184358. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184359. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184360. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184361. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184362. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184363. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184364. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184365. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184366. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184367. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184368. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184369. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184370. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184371. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184372. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184373. #ifdef PNG_USE_GLOBAL_ARRAYS
  184374. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184375. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184376. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184377. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184378. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184379. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184380. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184381. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184382. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184383. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184384. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184385. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184386. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184387. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184388. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184389. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184390. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184391. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184392. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184393. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184394. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184395. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184396. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184397. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184398. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184399. */
  184400. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184401. #undef png_read_init
  184402. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184403. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184404. #endif
  184405. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184406. png_const_charp user_png_ver, png_size_t png_struct_size));
  184407. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184408. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184409. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184410. png_info_size));
  184411. #endif
  184412. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184413. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184414. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184415. */
  184416. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184417. #undef png_write_init
  184418. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184419. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184420. #endif
  184421. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184422. png_const_charp user_png_ver, png_size_t png_struct_size));
  184423. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184424. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184425. png_info_size));
  184426. /* Allocate memory for an internal libpng struct */
  184427. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184428. /* Free memory from internal libpng struct */
  184429. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184430. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184431. malloc_fn, png_voidp mem_ptr));
  184432. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184433. png_free_ptr free_fn, png_voidp mem_ptr));
  184434. /* Free any memory that info_ptr points to and reset struct. */
  184435. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184436. png_infop info_ptr));
  184437. #ifndef PNG_1_0_X
  184438. /* Function to allocate memory for zlib. */
  184439. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184440. /* Function to free memory for zlib */
  184441. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184442. #ifdef PNG_SIZE_T
  184443. /* Function to convert a sizeof an item to png_sizeof item */
  184444. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184445. #endif
  184446. /* Next four functions are used internally as callbacks. PNGAPI is required
  184447. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184448. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184449. png_bytep data, png_size_t length));
  184450. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184451. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184452. png_bytep buffer, png_size_t length));
  184453. #endif
  184454. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184455. png_bytep data, png_size_t length));
  184456. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184457. #if !defined(PNG_NO_STDIO)
  184458. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184459. #endif
  184460. #endif
  184461. #else /* PNG_1_0_X */
  184462. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184463. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184464. png_bytep buffer, png_size_t length));
  184465. #endif
  184466. #endif /* PNG_1_0_X */
  184467. /* Reset the CRC variable */
  184468. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184469. /* Write the "data" buffer to whatever output you are using. */
  184470. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184471. png_size_t length));
  184472. /* Read data from whatever input you are using into the "data" buffer */
  184473. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184474. png_size_t length));
  184475. /* Read bytes into buf, and update png_ptr->crc */
  184476. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184477. png_size_t length));
  184478. /* Decompress data in a chunk that uses compression */
  184479. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184480. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184481. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184482. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184483. png_size_t prefix_length, png_size_t *data_length));
  184484. #endif
  184485. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184486. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184487. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184488. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184489. /* Calculate the CRC over a section of data. Note that we are only
  184490. * passing a maximum of 64K on systems that have this as a memory limit,
  184491. * since this is the maximum buffer size we can specify.
  184492. */
  184493. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184494. png_size_t length));
  184495. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184496. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184497. #endif
  184498. /* simple function to write the signature */
  184499. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184500. /* write various chunks */
  184501. /* Write the IHDR chunk, and update the png_struct with the necessary
  184502. * information.
  184503. */
  184504. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184505. png_uint_32 height,
  184506. int bit_depth, int color_type, int compression_method, int filter_method,
  184507. int interlace_method));
  184508. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184509. png_uint_32 num_pal));
  184510. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184511. png_size_t length));
  184512. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184513. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184514. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184515. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184516. #endif
  184517. #ifdef PNG_FIXED_POINT_SUPPORTED
  184518. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184519. file_gamma));
  184520. #endif
  184521. #endif
  184522. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184523. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184524. int color_type));
  184525. #endif
  184526. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184527. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184528. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184529. double white_x, double white_y,
  184530. double red_x, double red_y, double green_x, double green_y,
  184531. double blue_x, double blue_y));
  184532. #endif
  184533. #ifdef PNG_FIXED_POINT_SUPPORTED
  184534. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184535. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184536. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184537. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184538. png_fixed_point int_blue_y));
  184539. #endif
  184540. #endif
  184541. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184542. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184543. int intent));
  184544. #endif
  184545. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184546. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184547. png_charp name, int compression_type,
  184548. png_charp profile, int proflen));
  184549. /* Note to maintainer: profile should be png_bytep */
  184550. #endif
  184551. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184552. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184553. png_sPLT_tp palette));
  184554. #endif
  184555. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184556. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184557. png_color_16p values, int number, int color_type));
  184558. #endif
  184559. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184560. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184561. png_color_16p values, int color_type));
  184562. #endif
  184563. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184564. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184565. int num_hist));
  184566. #endif
  184567. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184568. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184569. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184570. png_charp key, png_charpp new_key));
  184571. #endif
  184572. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184573. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184574. png_charp text, png_size_t text_len));
  184575. #endif
  184576. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184577. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184578. png_charp text, png_size_t text_len, int compression));
  184579. #endif
  184580. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184581. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184582. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184583. png_charp text));
  184584. #endif
  184585. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184586. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184587. png_infop info_ptr, png_textp text_ptr, int num_text));
  184588. #endif
  184589. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184590. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184591. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184592. #endif
  184593. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184594. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184595. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184596. png_charp units, png_charpp params));
  184597. #endif
  184598. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184599. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184600. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184601. int unit_type));
  184602. #endif
  184603. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184604. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184605. png_timep mod_time));
  184606. #endif
  184607. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184608. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184609. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184610. int unit, double width, double height));
  184611. #else
  184612. #ifdef PNG_FIXED_POINT_SUPPORTED
  184613. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184614. int unit, png_charp width, png_charp height));
  184615. #endif
  184616. #endif
  184617. #endif
  184618. /* Called when finished processing a row of data */
  184619. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184620. /* Internal use only. Called before first row of data */
  184621. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184622. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184623. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184624. #endif
  184625. /* combine a row of data, dealing with alpha, etc. if requested */
  184626. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184627. int mask));
  184628. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184629. /* expand an interlaced row */
  184630. /* OLD pre-1.0.9 interface:
  184631. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184632. png_bytep row, int pass, png_uint_32 transformations));
  184633. */
  184634. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184635. #endif
  184636. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184637. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184638. /* grab pixels out of a row for an interlaced pass */
  184639. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184640. png_bytep row, int pass));
  184641. #endif
  184642. /* unfilter a row */
  184643. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184644. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184645. /* Choose the best filter to use and filter the row data */
  184646. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184647. png_row_infop row_info));
  184648. /* Write out the filtered row. */
  184649. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184650. png_bytep filtered_row));
  184651. /* finish a row while reading, dealing with interlacing passes, etc. */
  184652. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184653. /* initialize the row buffers, etc. */
  184654. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184655. /* optional call to update the users info structure */
  184656. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184657. png_infop info_ptr));
  184658. /* these are the functions that do the transformations */
  184659. #if defined(PNG_READ_FILLER_SUPPORTED)
  184660. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184661. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184662. #endif
  184663. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184664. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184665. png_bytep row));
  184666. #endif
  184667. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184668. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184669. png_bytep row));
  184670. #endif
  184671. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184672. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184673. png_bytep row));
  184674. #endif
  184675. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184676. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184677. png_bytep row));
  184678. #endif
  184679. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184680. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184681. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184682. png_bytep row, png_uint_32 flags));
  184683. #endif
  184684. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184685. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184686. #endif
  184687. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184688. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184689. #endif
  184690. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184691. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184692. row_info, png_bytep row));
  184693. #endif
  184694. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184695. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184696. png_bytep row));
  184697. #endif
  184698. #if defined(PNG_READ_PACK_SUPPORTED)
  184699. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184700. #endif
  184701. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184702. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184703. png_color_8p sig_bits));
  184704. #endif
  184705. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184706. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184707. #endif
  184708. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184709. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184710. #endif
  184711. #if defined(PNG_READ_DITHER_SUPPORTED)
  184712. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184713. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184714. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184715. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184716. png_colorp palette, int num_palette));
  184717. # endif
  184718. #endif
  184719. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184720. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184721. #endif
  184722. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184723. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184724. png_bytep row, png_uint_32 bit_depth));
  184725. #endif
  184726. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184727. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184728. png_color_8p bit_depth));
  184729. #endif
  184730. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184731. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184732. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184733. png_color_16p trans_values, png_color_16p background,
  184734. png_color_16p background_1,
  184735. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184736. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184737. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184738. #else
  184739. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184740. png_color_16p trans_values, png_color_16p background));
  184741. #endif
  184742. #endif
  184743. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184744. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184745. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184746. int gamma_shift));
  184747. #endif
  184748. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184749. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184750. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184751. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184752. png_bytep row, png_color_16p trans_value));
  184753. #endif
  184754. /* The following decodes the appropriate chunks, and does error correction,
  184755. * then calls the appropriate callback for the chunk if it is valid.
  184756. */
  184757. /* decode the IHDR chunk */
  184758. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184759. png_uint_32 length));
  184760. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184761. png_uint_32 length));
  184762. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184763. png_uint_32 length));
  184764. #if defined(PNG_READ_bKGD_SUPPORTED)
  184765. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184766. png_uint_32 length));
  184767. #endif
  184768. #if defined(PNG_READ_cHRM_SUPPORTED)
  184769. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184770. png_uint_32 length));
  184771. #endif
  184772. #if defined(PNG_READ_gAMA_SUPPORTED)
  184773. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184774. png_uint_32 length));
  184775. #endif
  184776. #if defined(PNG_READ_hIST_SUPPORTED)
  184777. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184778. png_uint_32 length));
  184779. #endif
  184780. #if defined(PNG_READ_iCCP_SUPPORTED)
  184781. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184782. png_uint_32 length));
  184783. #endif /* PNG_READ_iCCP_SUPPORTED */
  184784. #if defined(PNG_READ_iTXt_SUPPORTED)
  184785. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184786. png_uint_32 length));
  184787. #endif
  184788. #if defined(PNG_READ_oFFs_SUPPORTED)
  184789. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184790. png_uint_32 length));
  184791. #endif
  184792. #if defined(PNG_READ_pCAL_SUPPORTED)
  184793. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184794. png_uint_32 length));
  184795. #endif
  184796. #if defined(PNG_READ_pHYs_SUPPORTED)
  184797. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184798. png_uint_32 length));
  184799. #endif
  184800. #if defined(PNG_READ_sBIT_SUPPORTED)
  184801. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184802. png_uint_32 length));
  184803. #endif
  184804. #if defined(PNG_READ_sCAL_SUPPORTED)
  184805. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184806. png_uint_32 length));
  184807. #endif
  184808. #if defined(PNG_READ_sPLT_SUPPORTED)
  184809. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184810. png_uint_32 length));
  184811. #endif /* PNG_READ_sPLT_SUPPORTED */
  184812. #if defined(PNG_READ_sRGB_SUPPORTED)
  184813. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184814. png_uint_32 length));
  184815. #endif
  184816. #if defined(PNG_READ_tEXt_SUPPORTED)
  184817. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184818. png_uint_32 length));
  184819. #endif
  184820. #if defined(PNG_READ_tIME_SUPPORTED)
  184821. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184822. png_uint_32 length));
  184823. #endif
  184824. #if defined(PNG_READ_tRNS_SUPPORTED)
  184825. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184826. png_uint_32 length));
  184827. #endif
  184828. #if defined(PNG_READ_zTXt_SUPPORTED)
  184829. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184830. png_uint_32 length));
  184831. #endif
  184832. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184833. png_infop info_ptr, png_uint_32 length));
  184834. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184835. png_bytep chunk_name));
  184836. /* handle the transformations for reading and writing */
  184837. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184838. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184839. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184840. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184841. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184842. png_infop info_ptr));
  184843. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184844. png_infop info_ptr));
  184845. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184846. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184847. png_uint_32 length));
  184848. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184849. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184850. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184851. png_bytep buffer, png_size_t buffer_length));
  184852. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184853. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184854. png_bytep buffer, png_size_t buffer_length));
  184855. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184856. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184857. png_infop info_ptr, png_uint_32 length));
  184858. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184859. png_infop info_ptr));
  184860. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184861. png_infop info_ptr));
  184862. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184863. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184864. png_infop info_ptr));
  184865. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184866. png_infop info_ptr));
  184867. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184868. #if defined(PNG_READ_tEXt_SUPPORTED)
  184869. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184870. png_infop info_ptr, png_uint_32 length));
  184871. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184872. png_infop info_ptr));
  184873. #endif
  184874. #if defined(PNG_READ_zTXt_SUPPORTED)
  184875. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184876. png_infop info_ptr, png_uint_32 length));
  184877. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184878. png_infop info_ptr));
  184879. #endif
  184880. #if defined(PNG_READ_iTXt_SUPPORTED)
  184881. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184882. png_infop info_ptr, png_uint_32 length));
  184883. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184884. png_infop info_ptr));
  184885. #endif
  184886. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184887. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184888. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184889. png_bytep row));
  184890. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184891. png_bytep row));
  184892. #endif
  184893. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184894. #if defined(PNG_MMX_CODE_SUPPORTED)
  184895. /* png.c */ /* PRIVATE */
  184896. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184897. #endif
  184898. #endif
  184899. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184900. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184901. png_infop info_ptr));
  184902. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184903. png_infop info_ptr));
  184904. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184905. png_infop info_ptr));
  184906. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184907. png_infop info_ptr));
  184908. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184909. png_infop info_ptr));
  184910. #if defined(PNG_pHYs_SUPPORTED)
  184911. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184912. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184913. #endif /* PNG_pHYs_SUPPORTED */
  184914. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184915. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184916. #endif /* PNG_INTERNAL */
  184917. #ifdef __cplusplus
  184918. //}
  184919. #endif
  184920. #endif /* PNG_VERSION_INFO_ONLY */
  184921. /* do not put anything past this line */
  184922. #endif /* PNG_H */
  184923. /*** End of inlined file: png.h ***/
  184924. #define PNG_NO_EXTERN
  184925. /*** Start of inlined file: png.c ***/
  184926. /* png.c - location for general purpose libpng functions
  184927. *
  184928. * Last changed in libpng 1.2.21 [October 4, 2007]
  184929. * For conditions of distribution and use, see copyright notice in png.h
  184930. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184931. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184932. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184933. */
  184934. #define PNG_INTERNAL
  184935. #define PNG_NO_EXTERN
  184936. /* Generate a compiler error if there is an old png.h in the search path. */
  184937. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184938. /* Version information for C files. This had better match the version
  184939. * string defined in png.h. */
  184940. #ifdef PNG_USE_GLOBAL_ARRAYS
  184941. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184942. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184943. #ifdef PNG_READ_SUPPORTED
  184944. /* png_sig was changed to a function in version 1.0.5c */
  184945. /* Place to hold the signature string for a PNG file. */
  184946. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184947. #endif /* PNG_READ_SUPPORTED */
  184948. /* Invoke global declarations for constant strings for known chunk types */
  184949. PNG_IHDR;
  184950. PNG_IDAT;
  184951. PNG_IEND;
  184952. PNG_PLTE;
  184953. PNG_bKGD;
  184954. PNG_cHRM;
  184955. PNG_gAMA;
  184956. PNG_hIST;
  184957. PNG_iCCP;
  184958. PNG_iTXt;
  184959. PNG_oFFs;
  184960. PNG_pCAL;
  184961. PNG_sCAL;
  184962. PNG_pHYs;
  184963. PNG_sBIT;
  184964. PNG_sPLT;
  184965. PNG_sRGB;
  184966. PNG_tEXt;
  184967. PNG_tIME;
  184968. PNG_tRNS;
  184969. PNG_zTXt;
  184970. #ifdef PNG_READ_SUPPORTED
  184971. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184972. /* start of interlace block */
  184973. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184974. /* offset to next interlace block */
  184975. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184976. /* start of interlace block in the y direction */
  184977. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184978. /* offset to next interlace block in the y direction */
  184979. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184980. /* Height of interlace block. This is not currently used - if you need
  184981. * it, uncomment it here and in png.h
  184982. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184983. */
  184984. /* Mask to determine which pixels are valid in a pass */
  184985. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184986. /* Mask to determine which pixels to overwrite while displaying */
  184987. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184988. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184989. #endif /* PNG_READ_SUPPORTED */
  184990. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184991. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184992. * of the PNG file signature. If the PNG data is embedded into another
  184993. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184994. * or write any of the magic bytes before it starts on the IHDR.
  184995. */
  184996. #ifdef PNG_READ_SUPPORTED
  184997. void PNGAPI
  184998. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184999. {
  185000. if(png_ptr == NULL) return;
  185001. png_debug(1, "in png_set_sig_bytes\n");
  185002. if (num_bytes > 8)
  185003. png_error(png_ptr, "Too many bytes for PNG signature.");
  185004. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  185005. }
  185006. /* Checks whether the supplied bytes match the PNG signature. We allow
  185007. * checking less than the full 8-byte signature so that those apps that
  185008. * already read the first few bytes of a file to determine the file type
  185009. * can simply check the remaining bytes for extra assurance. Returns
  185010. * an integer less than, equal to, or greater than zero if sig is found,
  185011. * respectively, to be less than, to match, or be greater than the correct
  185012. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  185013. */
  185014. int PNGAPI
  185015. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  185016. {
  185017. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  185018. if (num_to_check > 8)
  185019. num_to_check = 8;
  185020. else if (num_to_check < 1)
  185021. return (-1);
  185022. if (start > 7)
  185023. return (-1);
  185024. if (start + num_to_check > 8)
  185025. num_to_check = 8 - start;
  185026. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  185027. }
  185028. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185029. /* (Obsolete) function to check signature bytes. It does not allow one
  185030. * to check a partial signature. This function might be removed in the
  185031. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  185032. */
  185033. int PNGAPI
  185034. png_check_sig(png_bytep sig, int num)
  185035. {
  185036. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  185037. }
  185038. #endif
  185039. #endif /* PNG_READ_SUPPORTED */
  185040. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185041. /* Function to allocate memory for zlib and clear it to 0. */
  185042. #ifdef PNG_1_0_X
  185043. voidpf PNGAPI
  185044. #else
  185045. voidpf /* private */
  185046. #endif
  185047. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  185048. {
  185049. png_voidp ptr;
  185050. png_structp p=(png_structp)png_ptr;
  185051. png_uint_32 save_flags=p->flags;
  185052. png_uint_32 num_bytes;
  185053. if(png_ptr == NULL) return (NULL);
  185054. if (items > PNG_UINT_32_MAX/size)
  185055. {
  185056. png_warning (p, "Potential overflow in png_zalloc()");
  185057. return (NULL);
  185058. }
  185059. num_bytes = (png_uint_32)items * size;
  185060. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  185061. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  185062. p->flags=save_flags;
  185063. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  185064. if (ptr == NULL)
  185065. return ((voidpf)ptr);
  185066. if (num_bytes > (png_uint_32)0x8000L)
  185067. {
  185068. png_memset(ptr, 0, (png_size_t)0x8000L);
  185069. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  185070. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  185071. }
  185072. else
  185073. {
  185074. png_memset(ptr, 0, (png_size_t)num_bytes);
  185075. }
  185076. #endif
  185077. return ((voidpf)ptr);
  185078. }
  185079. /* function to free memory for zlib */
  185080. #ifdef PNG_1_0_X
  185081. void PNGAPI
  185082. #else
  185083. void /* private */
  185084. #endif
  185085. png_zfree(voidpf png_ptr, voidpf ptr)
  185086. {
  185087. png_free((png_structp)png_ptr, (png_voidp)ptr);
  185088. }
  185089. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  185090. * in case CRC is > 32 bits to leave the top bits 0.
  185091. */
  185092. void /* PRIVATE */
  185093. png_reset_crc(png_structp png_ptr)
  185094. {
  185095. png_ptr->crc = crc32(0, Z_NULL, 0);
  185096. }
  185097. /* Calculate the CRC over a section of data. We can only pass as
  185098. * much data to this routine as the largest single buffer size. We
  185099. * also check that this data will actually be used before going to the
  185100. * trouble of calculating it.
  185101. */
  185102. void /* PRIVATE */
  185103. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  185104. {
  185105. int need_crc = 1;
  185106. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  185107. {
  185108. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  185109. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  185110. need_crc = 0;
  185111. }
  185112. else /* critical */
  185113. {
  185114. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  185115. need_crc = 0;
  185116. }
  185117. if (need_crc)
  185118. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185119. }
  185120. /* Allocate the memory for an info_struct for the application. We don't
  185121. * really need the png_ptr, but it could potentially be useful in the
  185122. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185123. * and png_info_init() so that applications that want to use a shared
  185124. * libpng don't have to be recompiled if png_info changes size.
  185125. */
  185126. png_infop PNGAPI
  185127. png_create_info_struct(png_structp png_ptr)
  185128. {
  185129. png_infop info_ptr;
  185130. png_debug(1, "in png_create_info_struct\n");
  185131. if(png_ptr == NULL) return (NULL);
  185132. #ifdef PNG_USER_MEM_SUPPORTED
  185133. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185134. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185135. #else
  185136. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185137. #endif
  185138. if (info_ptr != NULL)
  185139. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185140. return (info_ptr);
  185141. }
  185142. /* This function frees the memory associated with a single info struct.
  185143. * Normally, one would use either png_destroy_read_struct() or
  185144. * png_destroy_write_struct() to free an info struct, but this may be
  185145. * useful for some applications.
  185146. */
  185147. void PNGAPI
  185148. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185149. {
  185150. png_infop info_ptr = NULL;
  185151. if(png_ptr == NULL) return;
  185152. png_debug(1, "in png_destroy_info_struct\n");
  185153. if (info_ptr_ptr != NULL)
  185154. info_ptr = *info_ptr_ptr;
  185155. if (info_ptr != NULL)
  185156. {
  185157. png_info_destroy(png_ptr, info_ptr);
  185158. #ifdef PNG_USER_MEM_SUPPORTED
  185159. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185160. png_ptr->mem_ptr);
  185161. #else
  185162. png_destroy_struct((png_voidp)info_ptr);
  185163. #endif
  185164. *info_ptr_ptr = NULL;
  185165. }
  185166. }
  185167. /* Initialize the info structure. This is now an internal function (0.89)
  185168. * and applications using it are urged to use png_create_info_struct()
  185169. * instead.
  185170. */
  185171. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185172. #undef png_info_init
  185173. void PNGAPI
  185174. png_info_init(png_infop info_ptr)
  185175. {
  185176. /* We only come here via pre-1.0.12-compiled applications */
  185177. png_info_init_3(&info_ptr, 0);
  185178. }
  185179. #endif
  185180. void PNGAPI
  185181. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185182. {
  185183. png_infop info_ptr = *ptr_ptr;
  185184. if(info_ptr == NULL) return;
  185185. png_debug(1, "in png_info_init_3\n");
  185186. if(png_sizeof(png_info) > png_info_struct_size)
  185187. {
  185188. png_destroy_struct(info_ptr);
  185189. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185190. *ptr_ptr = info_ptr;
  185191. }
  185192. /* set everything to 0 */
  185193. png_memset(info_ptr, 0, png_sizeof (png_info));
  185194. }
  185195. #ifdef PNG_FREE_ME_SUPPORTED
  185196. void PNGAPI
  185197. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185198. int freer, png_uint_32 mask)
  185199. {
  185200. png_debug(1, "in png_data_freer\n");
  185201. if (png_ptr == NULL || info_ptr == NULL)
  185202. return;
  185203. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185204. info_ptr->free_me |= mask;
  185205. else if(freer == PNG_USER_WILL_FREE_DATA)
  185206. info_ptr->free_me &= ~mask;
  185207. else
  185208. png_warning(png_ptr,
  185209. "Unknown freer parameter in png_data_freer.");
  185210. }
  185211. #endif
  185212. void PNGAPI
  185213. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185214. int num)
  185215. {
  185216. png_debug(1, "in png_free_data\n");
  185217. if (png_ptr == NULL || info_ptr == NULL)
  185218. return;
  185219. #if defined(PNG_TEXT_SUPPORTED)
  185220. /* free text item num or (if num == -1) all text items */
  185221. #ifdef PNG_FREE_ME_SUPPORTED
  185222. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185223. #else
  185224. if (mask & PNG_FREE_TEXT)
  185225. #endif
  185226. {
  185227. if (num != -1)
  185228. {
  185229. if (info_ptr->text && info_ptr->text[num].key)
  185230. {
  185231. png_free(png_ptr, info_ptr->text[num].key);
  185232. info_ptr->text[num].key = NULL;
  185233. }
  185234. }
  185235. else
  185236. {
  185237. int i;
  185238. for (i = 0; i < info_ptr->num_text; i++)
  185239. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185240. png_free(png_ptr, info_ptr->text);
  185241. info_ptr->text = NULL;
  185242. info_ptr->num_text=0;
  185243. }
  185244. }
  185245. #endif
  185246. #if defined(PNG_tRNS_SUPPORTED)
  185247. /* free any tRNS entry */
  185248. #ifdef PNG_FREE_ME_SUPPORTED
  185249. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185250. #else
  185251. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185252. #endif
  185253. {
  185254. png_free(png_ptr, info_ptr->trans);
  185255. info_ptr->valid &= ~PNG_INFO_tRNS;
  185256. #ifndef PNG_FREE_ME_SUPPORTED
  185257. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185258. #endif
  185259. info_ptr->trans = NULL;
  185260. }
  185261. #endif
  185262. #if defined(PNG_sCAL_SUPPORTED)
  185263. /* free any sCAL entry */
  185264. #ifdef PNG_FREE_ME_SUPPORTED
  185265. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185266. #else
  185267. if (mask & PNG_FREE_SCAL)
  185268. #endif
  185269. {
  185270. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185271. png_free(png_ptr, info_ptr->scal_s_width);
  185272. png_free(png_ptr, info_ptr->scal_s_height);
  185273. info_ptr->scal_s_width = NULL;
  185274. info_ptr->scal_s_height = NULL;
  185275. #endif
  185276. info_ptr->valid &= ~PNG_INFO_sCAL;
  185277. }
  185278. #endif
  185279. #if defined(PNG_pCAL_SUPPORTED)
  185280. /* free any pCAL entry */
  185281. #ifdef PNG_FREE_ME_SUPPORTED
  185282. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185283. #else
  185284. if (mask & PNG_FREE_PCAL)
  185285. #endif
  185286. {
  185287. png_free(png_ptr, info_ptr->pcal_purpose);
  185288. png_free(png_ptr, info_ptr->pcal_units);
  185289. info_ptr->pcal_purpose = NULL;
  185290. info_ptr->pcal_units = NULL;
  185291. if (info_ptr->pcal_params != NULL)
  185292. {
  185293. int i;
  185294. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185295. {
  185296. png_free(png_ptr, info_ptr->pcal_params[i]);
  185297. info_ptr->pcal_params[i]=NULL;
  185298. }
  185299. png_free(png_ptr, info_ptr->pcal_params);
  185300. info_ptr->pcal_params = NULL;
  185301. }
  185302. info_ptr->valid &= ~PNG_INFO_pCAL;
  185303. }
  185304. #endif
  185305. #if defined(PNG_iCCP_SUPPORTED)
  185306. /* free any iCCP entry */
  185307. #ifdef PNG_FREE_ME_SUPPORTED
  185308. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185309. #else
  185310. if (mask & PNG_FREE_ICCP)
  185311. #endif
  185312. {
  185313. png_free(png_ptr, info_ptr->iccp_name);
  185314. png_free(png_ptr, info_ptr->iccp_profile);
  185315. info_ptr->iccp_name = NULL;
  185316. info_ptr->iccp_profile = NULL;
  185317. info_ptr->valid &= ~PNG_INFO_iCCP;
  185318. }
  185319. #endif
  185320. #if defined(PNG_sPLT_SUPPORTED)
  185321. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185322. #ifdef PNG_FREE_ME_SUPPORTED
  185323. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185324. #else
  185325. if (mask & PNG_FREE_SPLT)
  185326. #endif
  185327. {
  185328. if (num != -1)
  185329. {
  185330. if(info_ptr->splt_palettes)
  185331. {
  185332. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185333. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185334. info_ptr->splt_palettes[num].name = NULL;
  185335. info_ptr->splt_palettes[num].entries = NULL;
  185336. }
  185337. }
  185338. else
  185339. {
  185340. if(info_ptr->splt_palettes_num)
  185341. {
  185342. int i;
  185343. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185344. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185345. png_free(png_ptr, info_ptr->splt_palettes);
  185346. info_ptr->splt_palettes = NULL;
  185347. info_ptr->splt_palettes_num = 0;
  185348. }
  185349. info_ptr->valid &= ~PNG_INFO_sPLT;
  185350. }
  185351. }
  185352. #endif
  185353. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185354. if(png_ptr->unknown_chunk.data)
  185355. {
  185356. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185357. png_ptr->unknown_chunk.data = NULL;
  185358. }
  185359. #ifdef PNG_FREE_ME_SUPPORTED
  185360. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185361. #else
  185362. if (mask & PNG_FREE_UNKN)
  185363. #endif
  185364. {
  185365. if (num != -1)
  185366. {
  185367. if(info_ptr->unknown_chunks)
  185368. {
  185369. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185370. info_ptr->unknown_chunks[num].data = NULL;
  185371. }
  185372. }
  185373. else
  185374. {
  185375. int i;
  185376. if(info_ptr->unknown_chunks_num)
  185377. {
  185378. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185379. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185380. png_free(png_ptr, info_ptr->unknown_chunks);
  185381. info_ptr->unknown_chunks = NULL;
  185382. info_ptr->unknown_chunks_num = 0;
  185383. }
  185384. }
  185385. }
  185386. #endif
  185387. #if defined(PNG_hIST_SUPPORTED)
  185388. /* free any hIST entry */
  185389. #ifdef PNG_FREE_ME_SUPPORTED
  185390. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185391. #else
  185392. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185393. #endif
  185394. {
  185395. png_free(png_ptr, info_ptr->hist);
  185396. info_ptr->hist = NULL;
  185397. info_ptr->valid &= ~PNG_INFO_hIST;
  185398. #ifndef PNG_FREE_ME_SUPPORTED
  185399. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185400. #endif
  185401. }
  185402. #endif
  185403. /* free any PLTE entry that was internally allocated */
  185404. #ifdef PNG_FREE_ME_SUPPORTED
  185405. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185406. #else
  185407. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185408. #endif
  185409. {
  185410. png_zfree(png_ptr, info_ptr->palette);
  185411. info_ptr->palette = NULL;
  185412. info_ptr->valid &= ~PNG_INFO_PLTE;
  185413. #ifndef PNG_FREE_ME_SUPPORTED
  185414. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185415. #endif
  185416. info_ptr->num_palette = 0;
  185417. }
  185418. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185419. /* free any image bits attached to the info structure */
  185420. #ifdef PNG_FREE_ME_SUPPORTED
  185421. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185422. #else
  185423. if (mask & PNG_FREE_ROWS)
  185424. #endif
  185425. {
  185426. if(info_ptr->row_pointers)
  185427. {
  185428. int row;
  185429. for (row = 0; row < (int)info_ptr->height; row++)
  185430. {
  185431. png_free(png_ptr, info_ptr->row_pointers[row]);
  185432. info_ptr->row_pointers[row]=NULL;
  185433. }
  185434. png_free(png_ptr, info_ptr->row_pointers);
  185435. info_ptr->row_pointers=NULL;
  185436. }
  185437. info_ptr->valid &= ~PNG_INFO_IDAT;
  185438. }
  185439. #endif
  185440. #ifdef PNG_FREE_ME_SUPPORTED
  185441. if(num == -1)
  185442. info_ptr->free_me &= ~mask;
  185443. else
  185444. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185445. #endif
  185446. }
  185447. /* This is an internal routine to free any memory that the info struct is
  185448. * pointing to before re-using it or freeing the struct itself. Recall
  185449. * that png_free() checks for NULL pointers for us.
  185450. */
  185451. void /* PRIVATE */
  185452. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185453. {
  185454. png_debug(1, "in png_info_destroy\n");
  185455. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185456. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185457. if (png_ptr->num_chunk_list)
  185458. {
  185459. png_free(png_ptr, png_ptr->chunk_list);
  185460. png_ptr->chunk_list=NULL;
  185461. png_ptr->num_chunk_list=0;
  185462. }
  185463. #endif
  185464. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185465. }
  185466. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185467. /* This function returns a pointer to the io_ptr associated with the user
  185468. * functions. The application should free any memory associated with this
  185469. * pointer before png_write_destroy() or png_read_destroy() are called.
  185470. */
  185471. png_voidp PNGAPI
  185472. png_get_io_ptr(png_structp png_ptr)
  185473. {
  185474. if(png_ptr == NULL) return (NULL);
  185475. return (png_ptr->io_ptr);
  185476. }
  185477. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185478. #if !defined(PNG_NO_STDIO)
  185479. /* Initialize the default input/output functions for the PNG file. If you
  185480. * use your own read or write routines, you can call either png_set_read_fn()
  185481. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185482. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185483. * necessarily available.
  185484. */
  185485. void PNGAPI
  185486. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185487. {
  185488. png_debug(1, "in png_init_io\n");
  185489. if(png_ptr == NULL) return;
  185490. png_ptr->io_ptr = (png_voidp)fp;
  185491. }
  185492. #endif
  185493. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185494. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185495. * a "Creation Time" or other text-based time string.
  185496. */
  185497. png_charp PNGAPI
  185498. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185499. {
  185500. static PNG_CONST char short_months[12][4] =
  185501. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185502. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185503. if(png_ptr == NULL) return (NULL);
  185504. if (png_ptr->time_buffer == NULL)
  185505. {
  185506. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185507. png_sizeof(char)));
  185508. }
  185509. #if defined(_WIN32_WCE)
  185510. {
  185511. wchar_t time_buf[29];
  185512. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185513. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185514. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185515. ptime->second % 61);
  185516. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185517. NULL, NULL);
  185518. }
  185519. #else
  185520. #ifdef USE_FAR_KEYWORD
  185521. {
  185522. char near_time_buf[29];
  185523. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185524. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185525. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185526. ptime->second % 61);
  185527. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185528. 29*png_sizeof(char));
  185529. }
  185530. #else
  185531. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185532. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185533. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185534. ptime->second % 61);
  185535. #endif
  185536. #endif /* _WIN32_WCE */
  185537. return ((png_charp)png_ptr->time_buffer);
  185538. }
  185539. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185540. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185541. png_charp PNGAPI
  185542. png_get_copyright(png_structp png_ptr)
  185543. {
  185544. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185545. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185546. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185547. Copyright (c) 1996-1997 Andreas Dilger\n\
  185548. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185549. }
  185550. /* The following return the library version as a short string in the
  185551. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185552. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185553. * is defined in png.h.
  185554. * Note: now there is no difference between png_get_libpng_ver() and
  185555. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185556. * it is guaranteed that png.c uses the correct version of png.h.
  185557. */
  185558. png_charp PNGAPI
  185559. png_get_libpng_ver(png_structp png_ptr)
  185560. {
  185561. /* Version of *.c files used when building libpng */
  185562. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185563. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185564. }
  185565. png_charp PNGAPI
  185566. png_get_header_ver(png_structp png_ptr)
  185567. {
  185568. /* Version of *.h files used when building libpng */
  185569. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185570. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185571. }
  185572. png_charp PNGAPI
  185573. png_get_header_version(png_structp png_ptr)
  185574. {
  185575. /* Returns longer string containing both version and date */
  185576. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185577. return ((png_charp) PNG_HEADER_VERSION_STRING
  185578. #ifndef PNG_READ_SUPPORTED
  185579. " (NO READ SUPPORT)"
  185580. #endif
  185581. "\n");
  185582. }
  185583. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185584. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185585. int PNGAPI
  185586. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185587. {
  185588. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185589. int i;
  185590. png_bytep p;
  185591. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185592. return 0;
  185593. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185594. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185595. if (!png_memcmp(chunk_name, p, 4))
  185596. return ((int)*(p+4));
  185597. return 0;
  185598. }
  185599. #endif
  185600. /* This function, added to libpng-1.0.6g, is untested. */
  185601. int PNGAPI
  185602. png_reset_zstream(png_structp png_ptr)
  185603. {
  185604. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185605. return (inflateReset(&png_ptr->zstream));
  185606. }
  185607. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185608. /* This function was added to libpng-1.0.7 */
  185609. png_uint_32 PNGAPI
  185610. png_access_version_number(void)
  185611. {
  185612. /* Version of *.c files used when building libpng */
  185613. return((png_uint_32) PNG_LIBPNG_VER);
  185614. }
  185615. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185616. #if !defined(PNG_1_0_X)
  185617. /* this function was added to libpng 1.2.0 */
  185618. int PNGAPI
  185619. png_mmx_support(void)
  185620. {
  185621. /* obsolete, to be removed from libpng-1.4.0 */
  185622. return -1;
  185623. }
  185624. #endif /* PNG_1_0_X */
  185625. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185626. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185627. #ifdef PNG_SIZE_T
  185628. /* Added at libpng version 1.2.6 */
  185629. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185630. png_size_t PNGAPI
  185631. png_convert_size(size_t size)
  185632. {
  185633. if (size > (png_size_t)-1)
  185634. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185635. return ((png_size_t)size);
  185636. }
  185637. #endif /* PNG_SIZE_T */
  185638. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185639. /*** End of inlined file: png.c ***/
  185640. /*** Start of inlined file: pngerror.c ***/
  185641. /* pngerror.c - stub functions for i/o and memory allocation
  185642. *
  185643. * Last changed in libpng 1.2.20 October 4, 2007
  185644. * For conditions of distribution and use, see copyright notice in png.h
  185645. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185646. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185647. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185648. *
  185649. * This file provides a location for all error handling. Users who
  185650. * need special error handling are expected to write replacement functions
  185651. * and use png_set_error_fn() to use those functions. See the instructions
  185652. * at each function.
  185653. */
  185654. #define PNG_INTERNAL
  185655. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185656. static void /* PRIVATE */
  185657. png_default_error PNGARG((png_structp png_ptr,
  185658. png_const_charp error_message));
  185659. #ifndef PNG_NO_WARNINGS
  185660. static void /* PRIVATE */
  185661. png_default_warning PNGARG((png_structp png_ptr,
  185662. png_const_charp warning_message));
  185663. #endif /* PNG_NO_WARNINGS */
  185664. /* This function is called whenever there is a fatal error. This function
  185665. * should not be changed. If there is a need to handle errors differently,
  185666. * you should supply a replacement error function and use png_set_error_fn()
  185667. * to replace the error function at run-time.
  185668. */
  185669. #ifndef PNG_NO_ERROR_TEXT
  185670. void PNGAPI
  185671. png_error(png_structp png_ptr, png_const_charp error_message)
  185672. {
  185673. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185674. char msg[16];
  185675. if (png_ptr != NULL)
  185676. {
  185677. if (png_ptr->flags&
  185678. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185679. {
  185680. if (*error_message == '#')
  185681. {
  185682. int offset;
  185683. for (offset=1; offset<15; offset++)
  185684. if (*(error_message+offset) == ' ')
  185685. break;
  185686. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185687. {
  185688. int i;
  185689. for (i=0; i<offset-1; i++)
  185690. msg[i]=error_message[i+1];
  185691. msg[i]='\0';
  185692. error_message=msg;
  185693. }
  185694. else
  185695. error_message+=offset;
  185696. }
  185697. else
  185698. {
  185699. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185700. {
  185701. msg[0]='0';
  185702. msg[1]='\0';
  185703. error_message=msg;
  185704. }
  185705. }
  185706. }
  185707. }
  185708. #endif
  185709. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185710. (*(png_ptr->error_fn))(png_ptr, error_message);
  185711. /* If the custom handler doesn't exist, or if it returns,
  185712. use the default handler, which will not return. */
  185713. png_default_error(png_ptr, error_message);
  185714. }
  185715. #else
  185716. void PNGAPI
  185717. png_err(png_structp png_ptr)
  185718. {
  185719. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185720. (*(png_ptr->error_fn))(png_ptr, '\0');
  185721. /* If the custom handler doesn't exist, or if it returns,
  185722. use the default handler, which will not return. */
  185723. png_default_error(png_ptr, '\0');
  185724. }
  185725. #endif /* PNG_NO_ERROR_TEXT */
  185726. #ifndef PNG_NO_WARNINGS
  185727. /* This function is called whenever there is a non-fatal error. This function
  185728. * should not be changed. If there is a need to handle warnings differently,
  185729. * you should supply a replacement warning function and use
  185730. * png_set_error_fn() to replace the warning function at run-time.
  185731. */
  185732. void PNGAPI
  185733. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185734. {
  185735. int offset = 0;
  185736. if (png_ptr != NULL)
  185737. {
  185738. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185739. if (png_ptr->flags&
  185740. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185741. #endif
  185742. {
  185743. if (*warning_message == '#')
  185744. {
  185745. for (offset=1; offset<15; offset++)
  185746. if (*(warning_message+offset) == ' ')
  185747. break;
  185748. }
  185749. }
  185750. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185751. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185752. }
  185753. else
  185754. png_default_warning(png_ptr, warning_message+offset);
  185755. }
  185756. #endif /* PNG_NO_WARNINGS */
  185757. /* These utilities are used internally to build an error message that relates
  185758. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185759. * this is used to prefix the message. The message is limited in length
  185760. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185761. * if the character is invalid.
  185762. */
  185763. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185764. /*static PNG_CONST char png_digit[16] = {
  185765. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185766. 'A', 'B', 'C', 'D', 'E', 'F'
  185767. };*/
  185768. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185769. static void /* PRIVATE */
  185770. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185771. error_message)
  185772. {
  185773. int iout = 0, iin = 0;
  185774. while (iin < 4)
  185775. {
  185776. int c = png_ptr->chunk_name[iin++];
  185777. if (isnonalpha(c))
  185778. {
  185779. buffer[iout++] = '[';
  185780. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185781. buffer[iout++] = png_digit[c & 0x0f];
  185782. buffer[iout++] = ']';
  185783. }
  185784. else
  185785. {
  185786. buffer[iout++] = (png_byte)c;
  185787. }
  185788. }
  185789. if (error_message == NULL)
  185790. buffer[iout] = 0;
  185791. else
  185792. {
  185793. buffer[iout++] = ':';
  185794. buffer[iout++] = ' ';
  185795. png_strncpy(buffer+iout, error_message, 63);
  185796. buffer[iout+63] = 0;
  185797. }
  185798. }
  185799. #ifdef PNG_READ_SUPPORTED
  185800. void PNGAPI
  185801. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185802. {
  185803. char msg[18+64];
  185804. if (png_ptr == NULL)
  185805. png_error(png_ptr, error_message);
  185806. else
  185807. {
  185808. png_format_buffer(png_ptr, msg, error_message);
  185809. png_error(png_ptr, msg);
  185810. }
  185811. }
  185812. #endif /* PNG_READ_SUPPORTED */
  185813. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185814. #ifndef PNG_NO_WARNINGS
  185815. void PNGAPI
  185816. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185817. {
  185818. char msg[18+64];
  185819. if (png_ptr == NULL)
  185820. png_warning(png_ptr, warning_message);
  185821. else
  185822. {
  185823. png_format_buffer(png_ptr, msg, warning_message);
  185824. png_warning(png_ptr, msg);
  185825. }
  185826. }
  185827. #endif /* PNG_NO_WARNINGS */
  185828. /* This is the default error handling function. Note that replacements for
  185829. * this function MUST NOT RETURN, or the program will likely crash. This
  185830. * function is used by default, or if the program supplies NULL for the
  185831. * error function pointer in png_set_error_fn().
  185832. */
  185833. static void /* PRIVATE */
  185834. png_default_error(png_structp, png_const_charp error_message)
  185835. {
  185836. #ifndef PNG_NO_CONSOLE_IO
  185837. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185838. if (*error_message == '#')
  185839. {
  185840. int offset;
  185841. char error_number[16];
  185842. for (offset=0; offset<15; offset++)
  185843. {
  185844. error_number[offset] = *(error_message+offset+1);
  185845. if (*(error_message+offset) == ' ')
  185846. break;
  185847. }
  185848. if((offset > 1) && (offset < 15))
  185849. {
  185850. error_number[offset-1]='\0';
  185851. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185852. error_message+offset);
  185853. }
  185854. else
  185855. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185856. }
  185857. else
  185858. #endif
  185859. fprintf(stderr, "libpng error: %s\n", error_message);
  185860. #endif
  185861. #ifdef PNG_SETJMP_SUPPORTED
  185862. if (png_ptr)
  185863. {
  185864. # ifdef USE_FAR_KEYWORD
  185865. {
  185866. jmp_buf jmpbuf;
  185867. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185868. longjmp(jmpbuf, 1);
  185869. }
  185870. # else
  185871. longjmp(png_ptr->jmpbuf, 1);
  185872. # endif
  185873. }
  185874. #else
  185875. PNG_ABORT();
  185876. #endif
  185877. #ifdef PNG_NO_CONSOLE_IO
  185878. error_message = error_message; /* make compiler happy */
  185879. #endif
  185880. }
  185881. #ifndef PNG_NO_WARNINGS
  185882. /* This function is called when there is a warning, but the library thinks
  185883. * it can continue anyway. Replacement functions don't have to do anything
  185884. * here if you don't want them to. In the default configuration, png_ptr is
  185885. * not used, but it is passed in case it may be useful.
  185886. */
  185887. static void /* PRIVATE */
  185888. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185889. {
  185890. #ifndef PNG_NO_CONSOLE_IO
  185891. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185892. if (*warning_message == '#')
  185893. {
  185894. int offset;
  185895. char warning_number[16];
  185896. for (offset=0; offset<15; offset++)
  185897. {
  185898. warning_number[offset]=*(warning_message+offset+1);
  185899. if (*(warning_message+offset) == ' ')
  185900. break;
  185901. }
  185902. if((offset > 1) && (offset < 15))
  185903. {
  185904. warning_number[offset-1]='\0';
  185905. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185906. warning_message+offset);
  185907. }
  185908. else
  185909. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185910. }
  185911. else
  185912. # endif
  185913. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185914. #else
  185915. warning_message = warning_message; /* make compiler happy */
  185916. #endif
  185917. png_ptr = png_ptr; /* make compiler happy */
  185918. }
  185919. #endif /* PNG_NO_WARNINGS */
  185920. /* This function is called when the application wants to use another method
  185921. * of handling errors and warnings. Note that the error function MUST NOT
  185922. * return to the calling routine or serious problems will occur. The return
  185923. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185924. */
  185925. void PNGAPI
  185926. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185927. png_error_ptr error_fn, png_error_ptr warning_fn)
  185928. {
  185929. if (png_ptr == NULL)
  185930. return;
  185931. png_ptr->error_ptr = error_ptr;
  185932. png_ptr->error_fn = error_fn;
  185933. png_ptr->warning_fn = warning_fn;
  185934. }
  185935. /* This function returns a pointer to the error_ptr associated with the user
  185936. * functions. The application should free any memory associated with this
  185937. * pointer before png_write_destroy and png_read_destroy are called.
  185938. */
  185939. png_voidp PNGAPI
  185940. png_get_error_ptr(png_structp png_ptr)
  185941. {
  185942. if (png_ptr == NULL)
  185943. return NULL;
  185944. return ((png_voidp)png_ptr->error_ptr);
  185945. }
  185946. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185947. void PNGAPI
  185948. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185949. {
  185950. if(png_ptr != NULL)
  185951. {
  185952. png_ptr->flags &=
  185953. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185954. }
  185955. }
  185956. #endif
  185957. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185958. /*** End of inlined file: pngerror.c ***/
  185959. /*** Start of inlined file: pngget.c ***/
  185960. /* pngget.c - retrieval of values from info struct
  185961. *
  185962. * Last changed in libpng 1.2.15 January 5, 2007
  185963. * For conditions of distribution and use, see copyright notice in png.h
  185964. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185965. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185966. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185967. */
  185968. #define PNG_INTERNAL
  185969. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185970. png_uint_32 PNGAPI
  185971. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185972. {
  185973. if (png_ptr != NULL && info_ptr != NULL)
  185974. return(info_ptr->valid & flag);
  185975. else
  185976. return(0);
  185977. }
  185978. png_uint_32 PNGAPI
  185979. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185980. {
  185981. if (png_ptr != NULL && info_ptr != NULL)
  185982. return(info_ptr->rowbytes);
  185983. else
  185984. return(0);
  185985. }
  185986. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185987. png_bytepp PNGAPI
  185988. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185989. {
  185990. if (png_ptr != NULL && info_ptr != NULL)
  185991. return(info_ptr->row_pointers);
  185992. else
  185993. return(0);
  185994. }
  185995. #endif
  185996. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185997. /* easy access to info, added in libpng-0.99 */
  185998. png_uint_32 PNGAPI
  185999. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  186000. {
  186001. if (png_ptr != NULL && info_ptr != NULL)
  186002. {
  186003. return info_ptr->width;
  186004. }
  186005. return (0);
  186006. }
  186007. png_uint_32 PNGAPI
  186008. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  186009. {
  186010. if (png_ptr != NULL && info_ptr != NULL)
  186011. {
  186012. return info_ptr->height;
  186013. }
  186014. return (0);
  186015. }
  186016. png_byte PNGAPI
  186017. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  186018. {
  186019. if (png_ptr != NULL && info_ptr != NULL)
  186020. {
  186021. return info_ptr->bit_depth;
  186022. }
  186023. return (0);
  186024. }
  186025. png_byte PNGAPI
  186026. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  186027. {
  186028. if (png_ptr != NULL && info_ptr != NULL)
  186029. {
  186030. return info_ptr->color_type;
  186031. }
  186032. return (0);
  186033. }
  186034. png_byte PNGAPI
  186035. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  186036. {
  186037. if (png_ptr != NULL && info_ptr != NULL)
  186038. {
  186039. return info_ptr->filter_type;
  186040. }
  186041. return (0);
  186042. }
  186043. png_byte PNGAPI
  186044. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  186045. {
  186046. if (png_ptr != NULL && info_ptr != NULL)
  186047. {
  186048. return info_ptr->interlace_type;
  186049. }
  186050. return (0);
  186051. }
  186052. png_byte PNGAPI
  186053. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  186054. {
  186055. if (png_ptr != NULL && info_ptr != NULL)
  186056. {
  186057. return info_ptr->compression_type;
  186058. }
  186059. return (0);
  186060. }
  186061. png_uint_32 PNGAPI
  186062. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186063. {
  186064. if (png_ptr != NULL && info_ptr != NULL)
  186065. #if defined(PNG_pHYs_SUPPORTED)
  186066. if (info_ptr->valid & PNG_INFO_pHYs)
  186067. {
  186068. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  186069. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186070. return (0);
  186071. else return (info_ptr->x_pixels_per_unit);
  186072. }
  186073. #else
  186074. return (0);
  186075. #endif
  186076. return (0);
  186077. }
  186078. png_uint_32 PNGAPI
  186079. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186080. {
  186081. if (png_ptr != NULL && info_ptr != NULL)
  186082. #if defined(PNG_pHYs_SUPPORTED)
  186083. if (info_ptr->valid & PNG_INFO_pHYs)
  186084. {
  186085. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  186086. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186087. return (0);
  186088. else return (info_ptr->y_pixels_per_unit);
  186089. }
  186090. #else
  186091. return (0);
  186092. #endif
  186093. return (0);
  186094. }
  186095. png_uint_32 PNGAPI
  186096. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186097. {
  186098. if (png_ptr != NULL && info_ptr != NULL)
  186099. #if defined(PNG_pHYs_SUPPORTED)
  186100. if (info_ptr->valid & PNG_INFO_pHYs)
  186101. {
  186102. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  186103. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  186104. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  186105. return (0);
  186106. else return (info_ptr->x_pixels_per_unit);
  186107. }
  186108. #else
  186109. return (0);
  186110. #endif
  186111. return (0);
  186112. }
  186113. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186114. float PNGAPI
  186115. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  186116. {
  186117. if (png_ptr != NULL && info_ptr != NULL)
  186118. #if defined(PNG_pHYs_SUPPORTED)
  186119. if (info_ptr->valid & PNG_INFO_pHYs)
  186120. {
  186121. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186122. if (info_ptr->x_pixels_per_unit == 0)
  186123. return ((float)0.0);
  186124. else
  186125. return ((float)((float)info_ptr->y_pixels_per_unit
  186126. /(float)info_ptr->x_pixels_per_unit));
  186127. }
  186128. #else
  186129. return (0.0);
  186130. #endif
  186131. return ((float)0.0);
  186132. }
  186133. #endif
  186134. png_int_32 PNGAPI
  186135. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186136. {
  186137. if (png_ptr != NULL && info_ptr != NULL)
  186138. #if defined(PNG_oFFs_SUPPORTED)
  186139. if (info_ptr->valid & PNG_INFO_oFFs)
  186140. {
  186141. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186142. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186143. return (0);
  186144. else return (info_ptr->x_offset);
  186145. }
  186146. #else
  186147. return (0);
  186148. #endif
  186149. return (0);
  186150. }
  186151. png_int_32 PNGAPI
  186152. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186153. {
  186154. if (png_ptr != NULL && info_ptr != NULL)
  186155. #if defined(PNG_oFFs_SUPPORTED)
  186156. if (info_ptr->valid & PNG_INFO_oFFs)
  186157. {
  186158. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186159. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186160. return (0);
  186161. else return (info_ptr->y_offset);
  186162. }
  186163. #else
  186164. return (0);
  186165. #endif
  186166. return (0);
  186167. }
  186168. png_int_32 PNGAPI
  186169. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186170. {
  186171. if (png_ptr != NULL && info_ptr != NULL)
  186172. #if defined(PNG_oFFs_SUPPORTED)
  186173. if (info_ptr->valid & PNG_INFO_oFFs)
  186174. {
  186175. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186176. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186177. return (0);
  186178. else return (info_ptr->x_offset);
  186179. }
  186180. #else
  186181. return (0);
  186182. #endif
  186183. return (0);
  186184. }
  186185. png_int_32 PNGAPI
  186186. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186187. {
  186188. if (png_ptr != NULL && info_ptr != NULL)
  186189. #if defined(PNG_oFFs_SUPPORTED)
  186190. if (info_ptr->valid & PNG_INFO_oFFs)
  186191. {
  186192. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186193. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186194. return (0);
  186195. else return (info_ptr->y_offset);
  186196. }
  186197. #else
  186198. return (0);
  186199. #endif
  186200. return (0);
  186201. }
  186202. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186203. png_uint_32 PNGAPI
  186204. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186205. {
  186206. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186207. *.0254 +.5));
  186208. }
  186209. png_uint_32 PNGAPI
  186210. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186211. {
  186212. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186213. *.0254 +.5));
  186214. }
  186215. png_uint_32 PNGAPI
  186216. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186217. {
  186218. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186219. *.0254 +.5));
  186220. }
  186221. float PNGAPI
  186222. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186223. {
  186224. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186225. *.00003937);
  186226. }
  186227. float PNGAPI
  186228. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186229. {
  186230. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186231. *.00003937);
  186232. }
  186233. #if defined(PNG_pHYs_SUPPORTED)
  186234. png_uint_32 PNGAPI
  186235. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186236. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186237. {
  186238. png_uint_32 retval = 0;
  186239. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186240. {
  186241. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186242. if (res_x != NULL)
  186243. {
  186244. *res_x = info_ptr->x_pixels_per_unit;
  186245. retval |= PNG_INFO_pHYs;
  186246. }
  186247. if (res_y != NULL)
  186248. {
  186249. *res_y = info_ptr->y_pixels_per_unit;
  186250. retval |= PNG_INFO_pHYs;
  186251. }
  186252. if (unit_type != NULL)
  186253. {
  186254. *unit_type = (int)info_ptr->phys_unit_type;
  186255. retval |= PNG_INFO_pHYs;
  186256. if(*unit_type == 1)
  186257. {
  186258. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186259. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186260. }
  186261. }
  186262. }
  186263. return (retval);
  186264. }
  186265. #endif /* PNG_pHYs_SUPPORTED */
  186266. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186267. /* png_get_channels really belongs in here, too, but it's been around longer */
  186268. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186269. png_byte PNGAPI
  186270. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186271. {
  186272. if (png_ptr != NULL && info_ptr != NULL)
  186273. return(info_ptr->channels);
  186274. else
  186275. return (0);
  186276. }
  186277. png_bytep PNGAPI
  186278. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186279. {
  186280. if (png_ptr != NULL && info_ptr != NULL)
  186281. return(info_ptr->signature);
  186282. else
  186283. return (NULL);
  186284. }
  186285. #if defined(PNG_bKGD_SUPPORTED)
  186286. png_uint_32 PNGAPI
  186287. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186288. png_color_16p *background)
  186289. {
  186290. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186291. && background != NULL)
  186292. {
  186293. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186294. *background = &(info_ptr->background);
  186295. return (PNG_INFO_bKGD);
  186296. }
  186297. return (0);
  186298. }
  186299. #endif
  186300. #if defined(PNG_cHRM_SUPPORTED)
  186301. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186302. png_uint_32 PNGAPI
  186303. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186304. double *white_x, double *white_y, double *red_x, double *red_y,
  186305. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186306. {
  186307. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186308. {
  186309. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186310. if (white_x != NULL)
  186311. *white_x = (double)info_ptr->x_white;
  186312. if (white_y != NULL)
  186313. *white_y = (double)info_ptr->y_white;
  186314. if (red_x != NULL)
  186315. *red_x = (double)info_ptr->x_red;
  186316. if (red_y != NULL)
  186317. *red_y = (double)info_ptr->y_red;
  186318. if (green_x != NULL)
  186319. *green_x = (double)info_ptr->x_green;
  186320. if (green_y != NULL)
  186321. *green_y = (double)info_ptr->y_green;
  186322. if (blue_x != NULL)
  186323. *blue_x = (double)info_ptr->x_blue;
  186324. if (blue_y != NULL)
  186325. *blue_y = (double)info_ptr->y_blue;
  186326. return (PNG_INFO_cHRM);
  186327. }
  186328. return (0);
  186329. }
  186330. #endif
  186331. #ifdef PNG_FIXED_POINT_SUPPORTED
  186332. png_uint_32 PNGAPI
  186333. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186334. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186335. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186336. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186337. {
  186338. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186339. {
  186340. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186341. if (white_x != NULL)
  186342. *white_x = info_ptr->int_x_white;
  186343. if (white_y != NULL)
  186344. *white_y = info_ptr->int_y_white;
  186345. if (red_x != NULL)
  186346. *red_x = info_ptr->int_x_red;
  186347. if (red_y != NULL)
  186348. *red_y = info_ptr->int_y_red;
  186349. if (green_x != NULL)
  186350. *green_x = info_ptr->int_x_green;
  186351. if (green_y != NULL)
  186352. *green_y = info_ptr->int_y_green;
  186353. if (blue_x != NULL)
  186354. *blue_x = info_ptr->int_x_blue;
  186355. if (blue_y != NULL)
  186356. *blue_y = info_ptr->int_y_blue;
  186357. return (PNG_INFO_cHRM);
  186358. }
  186359. return (0);
  186360. }
  186361. #endif
  186362. #endif
  186363. #if defined(PNG_gAMA_SUPPORTED)
  186364. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186365. png_uint_32 PNGAPI
  186366. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186367. {
  186368. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186369. && file_gamma != NULL)
  186370. {
  186371. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186372. *file_gamma = (double)info_ptr->gamma;
  186373. return (PNG_INFO_gAMA);
  186374. }
  186375. return (0);
  186376. }
  186377. #endif
  186378. #ifdef PNG_FIXED_POINT_SUPPORTED
  186379. png_uint_32 PNGAPI
  186380. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186381. png_fixed_point *int_file_gamma)
  186382. {
  186383. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186384. && int_file_gamma != NULL)
  186385. {
  186386. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186387. *int_file_gamma = info_ptr->int_gamma;
  186388. return (PNG_INFO_gAMA);
  186389. }
  186390. return (0);
  186391. }
  186392. #endif
  186393. #endif
  186394. #if defined(PNG_sRGB_SUPPORTED)
  186395. png_uint_32 PNGAPI
  186396. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186397. {
  186398. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186399. && file_srgb_intent != NULL)
  186400. {
  186401. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186402. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186403. return (PNG_INFO_sRGB);
  186404. }
  186405. return (0);
  186406. }
  186407. #endif
  186408. #if defined(PNG_iCCP_SUPPORTED)
  186409. png_uint_32 PNGAPI
  186410. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186411. png_charpp name, int *compression_type,
  186412. png_charpp profile, png_uint_32 *proflen)
  186413. {
  186414. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186415. && name != NULL && profile != NULL && proflen != NULL)
  186416. {
  186417. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186418. *name = info_ptr->iccp_name;
  186419. *profile = info_ptr->iccp_profile;
  186420. /* compression_type is a dummy so the API won't have to change
  186421. if we introduce multiple compression types later. */
  186422. *proflen = (int)info_ptr->iccp_proflen;
  186423. *compression_type = (int)info_ptr->iccp_compression;
  186424. return (PNG_INFO_iCCP);
  186425. }
  186426. return (0);
  186427. }
  186428. #endif
  186429. #if defined(PNG_sPLT_SUPPORTED)
  186430. png_uint_32 PNGAPI
  186431. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186432. png_sPLT_tpp spalettes)
  186433. {
  186434. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186435. {
  186436. *spalettes = info_ptr->splt_palettes;
  186437. return ((png_uint_32)info_ptr->splt_palettes_num);
  186438. }
  186439. return (0);
  186440. }
  186441. #endif
  186442. #if defined(PNG_hIST_SUPPORTED)
  186443. png_uint_32 PNGAPI
  186444. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186445. {
  186446. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186447. && hist != NULL)
  186448. {
  186449. png_debug1(1, "in %s retrieval function\n", "hIST");
  186450. *hist = info_ptr->hist;
  186451. return (PNG_INFO_hIST);
  186452. }
  186453. return (0);
  186454. }
  186455. #endif
  186456. png_uint_32 PNGAPI
  186457. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186458. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186459. int *color_type, int *interlace_type, int *compression_type,
  186460. int *filter_type)
  186461. {
  186462. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186463. bit_depth != NULL && color_type != NULL)
  186464. {
  186465. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186466. *width = info_ptr->width;
  186467. *height = info_ptr->height;
  186468. *bit_depth = info_ptr->bit_depth;
  186469. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186470. png_error(png_ptr, "Invalid bit depth");
  186471. *color_type = info_ptr->color_type;
  186472. if (info_ptr->color_type > 6)
  186473. png_error(png_ptr, "Invalid color type");
  186474. if (compression_type != NULL)
  186475. *compression_type = info_ptr->compression_type;
  186476. if (filter_type != NULL)
  186477. *filter_type = info_ptr->filter_type;
  186478. if (interlace_type != NULL)
  186479. *interlace_type = info_ptr->interlace_type;
  186480. /* check for potential overflow of rowbytes */
  186481. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186482. png_error(png_ptr, "Invalid image width");
  186483. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186484. png_error(png_ptr, "Invalid image height");
  186485. if (info_ptr->width > (PNG_UINT_32_MAX
  186486. >> 3) /* 8-byte RGBA pixels */
  186487. - 64 /* bigrowbuf hack */
  186488. - 1 /* filter byte */
  186489. - 7*8 /* rounding of width to multiple of 8 pixels */
  186490. - 8) /* extra max_pixel_depth pad */
  186491. {
  186492. png_warning(png_ptr,
  186493. "Width too large for libpng to process image data.");
  186494. }
  186495. return (1);
  186496. }
  186497. return (0);
  186498. }
  186499. #if defined(PNG_oFFs_SUPPORTED)
  186500. png_uint_32 PNGAPI
  186501. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186502. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186503. {
  186504. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186505. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186506. {
  186507. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186508. *offset_x = info_ptr->x_offset;
  186509. *offset_y = info_ptr->y_offset;
  186510. *unit_type = (int)info_ptr->offset_unit_type;
  186511. return (PNG_INFO_oFFs);
  186512. }
  186513. return (0);
  186514. }
  186515. #endif
  186516. #if defined(PNG_pCAL_SUPPORTED)
  186517. png_uint_32 PNGAPI
  186518. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186519. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186520. png_charp *units, png_charpp *params)
  186521. {
  186522. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186523. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186524. nparams != NULL && units != NULL && params != NULL)
  186525. {
  186526. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186527. *purpose = info_ptr->pcal_purpose;
  186528. *X0 = info_ptr->pcal_X0;
  186529. *X1 = info_ptr->pcal_X1;
  186530. *type = (int)info_ptr->pcal_type;
  186531. *nparams = (int)info_ptr->pcal_nparams;
  186532. *units = info_ptr->pcal_units;
  186533. *params = info_ptr->pcal_params;
  186534. return (PNG_INFO_pCAL);
  186535. }
  186536. return (0);
  186537. }
  186538. #endif
  186539. #if defined(PNG_sCAL_SUPPORTED)
  186540. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186541. png_uint_32 PNGAPI
  186542. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186543. int *unit, double *width, double *height)
  186544. {
  186545. if (png_ptr != NULL && info_ptr != NULL &&
  186546. (info_ptr->valid & PNG_INFO_sCAL))
  186547. {
  186548. *unit = info_ptr->scal_unit;
  186549. *width = info_ptr->scal_pixel_width;
  186550. *height = info_ptr->scal_pixel_height;
  186551. return (PNG_INFO_sCAL);
  186552. }
  186553. return(0);
  186554. }
  186555. #else
  186556. #ifdef PNG_FIXED_POINT_SUPPORTED
  186557. png_uint_32 PNGAPI
  186558. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186559. int *unit, png_charpp width, png_charpp height)
  186560. {
  186561. if (png_ptr != NULL && info_ptr != NULL &&
  186562. (info_ptr->valid & PNG_INFO_sCAL))
  186563. {
  186564. *unit = info_ptr->scal_unit;
  186565. *width = info_ptr->scal_s_width;
  186566. *height = info_ptr->scal_s_height;
  186567. return (PNG_INFO_sCAL);
  186568. }
  186569. return(0);
  186570. }
  186571. #endif
  186572. #endif
  186573. #endif
  186574. #if defined(PNG_pHYs_SUPPORTED)
  186575. png_uint_32 PNGAPI
  186576. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186577. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186578. {
  186579. png_uint_32 retval = 0;
  186580. if (png_ptr != NULL && info_ptr != NULL &&
  186581. (info_ptr->valid & PNG_INFO_pHYs))
  186582. {
  186583. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186584. if (res_x != NULL)
  186585. {
  186586. *res_x = info_ptr->x_pixels_per_unit;
  186587. retval |= PNG_INFO_pHYs;
  186588. }
  186589. if (res_y != NULL)
  186590. {
  186591. *res_y = info_ptr->y_pixels_per_unit;
  186592. retval |= PNG_INFO_pHYs;
  186593. }
  186594. if (unit_type != NULL)
  186595. {
  186596. *unit_type = (int)info_ptr->phys_unit_type;
  186597. retval |= PNG_INFO_pHYs;
  186598. }
  186599. }
  186600. return (retval);
  186601. }
  186602. #endif
  186603. png_uint_32 PNGAPI
  186604. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186605. int *num_palette)
  186606. {
  186607. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186608. && palette != NULL)
  186609. {
  186610. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186611. *palette = info_ptr->palette;
  186612. *num_palette = info_ptr->num_palette;
  186613. png_debug1(3, "num_palette = %d\n", *num_palette);
  186614. return (PNG_INFO_PLTE);
  186615. }
  186616. return (0);
  186617. }
  186618. #if defined(PNG_sBIT_SUPPORTED)
  186619. png_uint_32 PNGAPI
  186620. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186621. {
  186622. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186623. && sig_bit != NULL)
  186624. {
  186625. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186626. *sig_bit = &(info_ptr->sig_bit);
  186627. return (PNG_INFO_sBIT);
  186628. }
  186629. return (0);
  186630. }
  186631. #endif
  186632. #if defined(PNG_TEXT_SUPPORTED)
  186633. png_uint_32 PNGAPI
  186634. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186635. int *num_text)
  186636. {
  186637. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186638. {
  186639. png_debug1(1, "in %s retrieval function\n",
  186640. (png_ptr->chunk_name[0] == '\0' ? "text"
  186641. : (png_const_charp)png_ptr->chunk_name));
  186642. if (text_ptr != NULL)
  186643. *text_ptr = info_ptr->text;
  186644. if (num_text != NULL)
  186645. *num_text = info_ptr->num_text;
  186646. return ((png_uint_32)info_ptr->num_text);
  186647. }
  186648. if (num_text != NULL)
  186649. *num_text = 0;
  186650. return(0);
  186651. }
  186652. #endif
  186653. #if defined(PNG_tIME_SUPPORTED)
  186654. png_uint_32 PNGAPI
  186655. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186656. {
  186657. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186658. && mod_time != NULL)
  186659. {
  186660. png_debug1(1, "in %s retrieval function\n", "tIME");
  186661. *mod_time = &(info_ptr->mod_time);
  186662. return (PNG_INFO_tIME);
  186663. }
  186664. return (0);
  186665. }
  186666. #endif
  186667. #if defined(PNG_tRNS_SUPPORTED)
  186668. png_uint_32 PNGAPI
  186669. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186670. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186671. {
  186672. png_uint_32 retval = 0;
  186673. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186674. {
  186675. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186676. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186677. {
  186678. if (trans != NULL)
  186679. {
  186680. *trans = info_ptr->trans;
  186681. retval |= PNG_INFO_tRNS;
  186682. }
  186683. if (trans_values != NULL)
  186684. *trans_values = &(info_ptr->trans_values);
  186685. }
  186686. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186687. {
  186688. if (trans_values != NULL)
  186689. {
  186690. *trans_values = &(info_ptr->trans_values);
  186691. retval |= PNG_INFO_tRNS;
  186692. }
  186693. if(trans != NULL)
  186694. *trans = NULL;
  186695. }
  186696. if(num_trans != NULL)
  186697. {
  186698. *num_trans = info_ptr->num_trans;
  186699. retval |= PNG_INFO_tRNS;
  186700. }
  186701. }
  186702. return (retval);
  186703. }
  186704. #endif
  186705. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186706. png_uint_32 PNGAPI
  186707. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186708. png_unknown_chunkpp unknowns)
  186709. {
  186710. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186711. {
  186712. *unknowns = info_ptr->unknown_chunks;
  186713. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186714. }
  186715. return (0);
  186716. }
  186717. #endif
  186718. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186719. png_byte PNGAPI
  186720. png_get_rgb_to_gray_status (png_structp png_ptr)
  186721. {
  186722. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186723. }
  186724. #endif
  186725. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186726. png_voidp PNGAPI
  186727. png_get_user_chunk_ptr(png_structp png_ptr)
  186728. {
  186729. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186730. }
  186731. #endif
  186732. #ifdef PNG_WRITE_SUPPORTED
  186733. png_uint_32 PNGAPI
  186734. png_get_compression_buffer_size(png_structp png_ptr)
  186735. {
  186736. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186737. }
  186738. #endif
  186739. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186740. #ifndef PNG_1_0_X
  186741. /* this function was added to libpng 1.2.0 and should exist by default */
  186742. png_uint_32 PNGAPI
  186743. png_get_asm_flags (png_structp png_ptr)
  186744. {
  186745. /* obsolete, to be removed from libpng-1.4.0 */
  186746. return (png_ptr? 0L: 0L);
  186747. }
  186748. /* this function was added to libpng 1.2.0 and should exist by default */
  186749. png_uint_32 PNGAPI
  186750. png_get_asm_flagmask (int flag_select)
  186751. {
  186752. /* obsolete, to be removed from libpng-1.4.0 */
  186753. flag_select=flag_select;
  186754. return 0L;
  186755. }
  186756. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186757. /* this function was added to libpng 1.2.0 */
  186758. png_uint_32 PNGAPI
  186759. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186760. {
  186761. /* obsolete, to be removed from libpng-1.4.0 */
  186762. flag_select=flag_select;
  186763. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186764. return 0L;
  186765. }
  186766. /* this function was added to libpng 1.2.0 */
  186767. png_byte PNGAPI
  186768. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186769. {
  186770. /* obsolete, to be removed from libpng-1.4.0 */
  186771. return (png_ptr? 0: 0);
  186772. }
  186773. /* this function was added to libpng 1.2.0 */
  186774. png_uint_32 PNGAPI
  186775. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186776. {
  186777. /* obsolete, to be removed from libpng-1.4.0 */
  186778. return (png_ptr? 0L: 0L);
  186779. }
  186780. #endif /* ?PNG_1_0_X */
  186781. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186782. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186783. /* these functions were added to libpng 1.2.6 */
  186784. png_uint_32 PNGAPI
  186785. png_get_user_width_max (png_structp png_ptr)
  186786. {
  186787. return (png_ptr? png_ptr->user_width_max : 0);
  186788. }
  186789. png_uint_32 PNGAPI
  186790. png_get_user_height_max (png_structp png_ptr)
  186791. {
  186792. return (png_ptr? png_ptr->user_height_max : 0);
  186793. }
  186794. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186795. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186796. /*** End of inlined file: pngget.c ***/
  186797. /*** Start of inlined file: pngmem.c ***/
  186798. /* pngmem.c - stub functions for memory allocation
  186799. *
  186800. * Last changed in libpng 1.2.13 November 13, 2006
  186801. * For conditions of distribution and use, see copyright notice in png.h
  186802. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186803. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186804. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186805. *
  186806. * This file provides a location for all memory allocation. Users who
  186807. * need special memory handling are expected to supply replacement
  186808. * functions for png_malloc() and png_free(), and to use
  186809. * png_create_read_struct_2() and png_create_write_struct_2() to
  186810. * identify the replacement functions.
  186811. */
  186812. #define PNG_INTERNAL
  186813. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186814. /* Borland DOS special memory handler */
  186815. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186816. /* if you change this, be sure to change the one in png.h also */
  186817. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186818. by a single call to calloc() if this is thought to improve performance. */
  186819. png_voidp /* PRIVATE */
  186820. png_create_struct(int type)
  186821. {
  186822. #ifdef PNG_USER_MEM_SUPPORTED
  186823. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186824. }
  186825. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186826. png_voidp /* PRIVATE */
  186827. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186828. {
  186829. #endif /* PNG_USER_MEM_SUPPORTED */
  186830. png_size_t size;
  186831. png_voidp struct_ptr;
  186832. if (type == PNG_STRUCT_INFO)
  186833. size = png_sizeof(png_info);
  186834. else if (type == PNG_STRUCT_PNG)
  186835. size = png_sizeof(png_struct);
  186836. else
  186837. return (png_get_copyright(NULL));
  186838. #ifdef PNG_USER_MEM_SUPPORTED
  186839. if(malloc_fn != NULL)
  186840. {
  186841. png_struct dummy_struct;
  186842. png_structp png_ptr = &dummy_struct;
  186843. png_ptr->mem_ptr=mem_ptr;
  186844. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186845. }
  186846. else
  186847. #endif /* PNG_USER_MEM_SUPPORTED */
  186848. struct_ptr = (png_voidp)farmalloc(size);
  186849. if (struct_ptr != NULL)
  186850. png_memset(struct_ptr, 0, size);
  186851. return (struct_ptr);
  186852. }
  186853. /* Free memory allocated by a png_create_struct() call */
  186854. void /* PRIVATE */
  186855. png_destroy_struct(png_voidp struct_ptr)
  186856. {
  186857. #ifdef PNG_USER_MEM_SUPPORTED
  186858. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186859. }
  186860. /* Free memory allocated by a png_create_struct() call */
  186861. void /* PRIVATE */
  186862. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186863. png_voidp mem_ptr)
  186864. {
  186865. #endif
  186866. if (struct_ptr != NULL)
  186867. {
  186868. #ifdef PNG_USER_MEM_SUPPORTED
  186869. if(free_fn != NULL)
  186870. {
  186871. png_struct dummy_struct;
  186872. png_structp png_ptr = &dummy_struct;
  186873. png_ptr->mem_ptr=mem_ptr;
  186874. (*(free_fn))(png_ptr, struct_ptr);
  186875. return;
  186876. }
  186877. #endif /* PNG_USER_MEM_SUPPORTED */
  186878. farfree (struct_ptr);
  186879. }
  186880. }
  186881. /* Allocate memory. For reasonable files, size should never exceed
  186882. * 64K. However, zlib may allocate more then 64K if you don't tell
  186883. * it not to. See zconf.h and png.h for more information. zlib does
  186884. * need to allocate exactly 64K, so whatever you call here must
  186885. * have the ability to do that.
  186886. *
  186887. * Borland seems to have a problem in DOS mode for exactly 64K.
  186888. * It gives you a segment with an offset of 8 (perhaps to store its
  186889. * memory stuff). zlib doesn't like this at all, so we have to
  186890. * detect and deal with it. This code should not be needed in
  186891. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186892. * been updated by Alexander Lehmann for version 0.89 to waste less
  186893. * memory.
  186894. *
  186895. * Note that we can't use png_size_t for the "size" declaration,
  186896. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186897. * result, we would be truncating potentially larger memory requests
  186898. * (which should cause a fatal error) and introducing major problems.
  186899. */
  186900. png_voidp PNGAPI
  186901. png_malloc(png_structp png_ptr, png_uint_32 size)
  186902. {
  186903. png_voidp ret;
  186904. if (png_ptr == NULL || size == 0)
  186905. return (NULL);
  186906. #ifdef PNG_USER_MEM_SUPPORTED
  186907. if(png_ptr->malloc_fn != NULL)
  186908. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186909. else
  186910. ret = (png_malloc_default(png_ptr, size));
  186911. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186912. png_error(png_ptr, "Out of memory!");
  186913. return (ret);
  186914. }
  186915. png_voidp PNGAPI
  186916. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186917. {
  186918. png_voidp ret;
  186919. #endif /* PNG_USER_MEM_SUPPORTED */
  186920. if (png_ptr == NULL || size == 0)
  186921. return (NULL);
  186922. #ifdef PNG_MAX_MALLOC_64K
  186923. if (size > (png_uint_32)65536L)
  186924. {
  186925. png_warning(png_ptr, "Cannot Allocate > 64K");
  186926. ret = NULL;
  186927. }
  186928. else
  186929. #endif
  186930. if (size != (size_t)size)
  186931. ret = NULL;
  186932. else if (size == (png_uint_32)65536L)
  186933. {
  186934. if (png_ptr->offset_table == NULL)
  186935. {
  186936. /* try to see if we need to do any of this fancy stuff */
  186937. ret = farmalloc(size);
  186938. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186939. {
  186940. int num_blocks;
  186941. png_uint_32 total_size;
  186942. png_bytep table;
  186943. int i;
  186944. png_byte huge * hptr;
  186945. if (ret != NULL)
  186946. {
  186947. farfree(ret);
  186948. ret = NULL;
  186949. }
  186950. if(png_ptr->zlib_window_bits > 14)
  186951. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186952. else
  186953. num_blocks = 1;
  186954. if (png_ptr->zlib_mem_level >= 7)
  186955. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186956. else
  186957. num_blocks++;
  186958. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186959. table = farmalloc(total_size);
  186960. if (table == NULL)
  186961. {
  186962. #ifndef PNG_USER_MEM_SUPPORTED
  186963. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186964. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186965. else
  186966. png_warning(png_ptr, "Out Of Memory.");
  186967. #endif
  186968. return (NULL);
  186969. }
  186970. if ((png_size_t)table & 0xfff0)
  186971. {
  186972. #ifndef PNG_USER_MEM_SUPPORTED
  186973. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186974. png_error(png_ptr,
  186975. "Farmalloc didn't return normalized pointer");
  186976. else
  186977. png_warning(png_ptr,
  186978. "Farmalloc didn't return normalized pointer");
  186979. #endif
  186980. return (NULL);
  186981. }
  186982. png_ptr->offset_table = table;
  186983. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186984. png_sizeof (png_bytep));
  186985. if (png_ptr->offset_table_ptr == NULL)
  186986. {
  186987. #ifndef PNG_USER_MEM_SUPPORTED
  186988. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186989. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186990. else
  186991. png_warning(png_ptr, "Out Of memory.");
  186992. #endif
  186993. return (NULL);
  186994. }
  186995. hptr = (png_byte huge *)table;
  186996. if ((png_size_t)hptr & 0xf)
  186997. {
  186998. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186999. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  187000. }
  187001. for (i = 0; i < num_blocks; i++)
  187002. {
  187003. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  187004. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  187005. }
  187006. png_ptr->offset_table_number = num_blocks;
  187007. png_ptr->offset_table_count = 0;
  187008. png_ptr->offset_table_count_free = 0;
  187009. }
  187010. }
  187011. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  187012. {
  187013. #ifndef PNG_USER_MEM_SUPPORTED
  187014. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187015. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  187016. else
  187017. png_warning(png_ptr, "Out of Memory.");
  187018. #endif
  187019. return (NULL);
  187020. }
  187021. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  187022. }
  187023. else
  187024. ret = farmalloc(size);
  187025. #ifndef PNG_USER_MEM_SUPPORTED
  187026. if (ret == NULL)
  187027. {
  187028. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187029. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  187030. else
  187031. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  187032. }
  187033. #endif
  187034. return (ret);
  187035. }
  187036. /* free a pointer allocated by png_malloc(). In the default
  187037. configuration, png_ptr is not used, but is passed in case it
  187038. is needed. If ptr is NULL, return without taking any action. */
  187039. void PNGAPI
  187040. png_free(png_structp png_ptr, png_voidp ptr)
  187041. {
  187042. if (png_ptr == NULL || ptr == NULL)
  187043. return;
  187044. #ifdef PNG_USER_MEM_SUPPORTED
  187045. if (png_ptr->free_fn != NULL)
  187046. {
  187047. (*(png_ptr->free_fn))(png_ptr, ptr);
  187048. return;
  187049. }
  187050. else png_free_default(png_ptr, ptr);
  187051. }
  187052. void PNGAPI
  187053. png_free_default(png_structp png_ptr, png_voidp ptr)
  187054. {
  187055. #endif /* PNG_USER_MEM_SUPPORTED */
  187056. if(png_ptr == NULL) return;
  187057. if (png_ptr->offset_table != NULL)
  187058. {
  187059. int i;
  187060. for (i = 0; i < png_ptr->offset_table_count; i++)
  187061. {
  187062. if (ptr == png_ptr->offset_table_ptr[i])
  187063. {
  187064. ptr = NULL;
  187065. png_ptr->offset_table_count_free++;
  187066. break;
  187067. }
  187068. }
  187069. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  187070. {
  187071. farfree(png_ptr->offset_table);
  187072. farfree(png_ptr->offset_table_ptr);
  187073. png_ptr->offset_table = NULL;
  187074. png_ptr->offset_table_ptr = NULL;
  187075. }
  187076. }
  187077. if (ptr != NULL)
  187078. {
  187079. farfree(ptr);
  187080. }
  187081. }
  187082. #else /* Not the Borland DOS special memory handler */
  187083. /* Allocate memory for a png_struct or a png_info. The malloc and
  187084. memset can be replaced by a single call to calloc() if this is thought
  187085. to improve performance noticably. */
  187086. png_voidp /* PRIVATE */
  187087. png_create_struct(int type)
  187088. {
  187089. #ifdef PNG_USER_MEM_SUPPORTED
  187090. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187091. }
  187092. /* Allocate memory for a png_struct or a png_info. The malloc and
  187093. memset can be replaced by a single call to calloc() if this is thought
  187094. to improve performance noticably. */
  187095. png_voidp /* PRIVATE */
  187096. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187097. {
  187098. #endif /* PNG_USER_MEM_SUPPORTED */
  187099. png_size_t size;
  187100. png_voidp struct_ptr;
  187101. if (type == PNG_STRUCT_INFO)
  187102. size = png_sizeof(png_info);
  187103. else if (type == PNG_STRUCT_PNG)
  187104. size = png_sizeof(png_struct);
  187105. else
  187106. return (NULL);
  187107. #ifdef PNG_USER_MEM_SUPPORTED
  187108. if(malloc_fn != NULL)
  187109. {
  187110. png_struct dummy_struct;
  187111. png_structp png_ptr = &dummy_struct;
  187112. png_ptr->mem_ptr=mem_ptr;
  187113. struct_ptr = (*(malloc_fn))(png_ptr, size);
  187114. if (struct_ptr != NULL)
  187115. png_memset(struct_ptr, 0, size);
  187116. return (struct_ptr);
  187117. }
  187118. #endif /* PNG_USER_MEM_SUPPORTED */
  187119. #if defined(__TURBOC__) && !defined(__FLAT__)
  187120. struct_ptr = (png_voidp)farmalloc(size);
  187121. #else
  187122. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187123. struct_ptr = (png_voidp)halloc(size,1);
  187124. # else
  187125. struct_ptr = (png_voidp)malloc(size);
  187126. # endif
  187127. #endif
  187128. if (struct_ptr != NULL)
  187129. png_memset(struct_ptr, 0, size);
  187130. return (struct_ptr);
  187131. }
  187132. /* Free memory allocated by a png_create_struct() call */
  187133. void /* PRIVATE */
  187134. png_destroy_struct(png_voidp struct_ptr)
  187135. {
  187136. #ifdef PNG_USER_MEM_SUPPORTED
  187137. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187138. }
  187139. /* Free memory allocated by a png_create_struct() call */
  187140. void /* PRIVATE */
  187141. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187142. png_voidp mem_ptr)
  187143. {
  187144. #endif /* PNG_USER_MEM_SUPPORTED */
  187145. if (struct_ptr != NULL)
  187146. {
  187147. #ifdef PNG_USER_MEM_SUPPORTED
  187148. if(free_fn != NULL)
  187149. {
  187150. png_struct dummy_struct;
  187151. png_structp png_ptr = &dummy_struct;
  187152. png_ptr->mem_ptr=mem_ptr;
  187153. (*(free_fn))(png_ptr, struct_ptr);
  187154. return;
  187155. }
  187156. #endif /* PNG_USER_MEM_SUPPORTED */
  187157. #if defined(__TURBOC__) && !defined(__FLAT__)
  187158. farfree(struct_ptr);
  187159. #else
  187160. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187161. hfree(struct_ptr);
  187162. # else
  187163. free(struct_ptr);
  187164. # endif
  187165. #endif
  187166. }
  187167. }
  187168. /* Allocate memory. For reasonable files, size should never exceed
  187169. 64K. However, zlib may allocate more then 64K if you don't tell
  187170. it not to. See zconf.h and png.h for more information. zlib does
  187171. need to allocate exactly 64K, so whatever you call here must
  187172. have the ability to do that. */
  187173. png_voidp PNGAPI
  187174. png_malloc(png_structp png_ptr, png_uint_32 size)
  187175. {
  187176. png_voidp ret;
  187177. #ifdef PNG_USER_MEM_SUPPORTED
  187178. if (png_ptr == NULL || size == 0)
  187179. return (NULL);
  187180. if(png_ptr->malloc_fn != NULL)
  187181. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187182. else
  187183. ret = (png_malloc_default(png_ptr, size));
  187184. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187185. png_error(png_ptr, "Out of Memory!");
  187186. return (ret);
  187187. }
  187188. png_voidp PNGAPI
  187189. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187190. {
  187191. png_voidp ret;
  187192. #endif /* PNG_USER_MEM_SUPPORTED */
  187193. if (png_ptr == NULL || size == 0)
  187194. return (NULL);
  187195. #ifdef PNG_MAX_MALLOC_64K
  187196. if (size > (png_uint_32)65536L)
  187197. {
  187198. #ifndef PNG_USER_MEM_SUPPORTED
  187199. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187200. png_error(png_ptr, "Cannot Allocate > 64K");
  187201. else
  187202. #endif
  187203. return NULL;
  187204. }
  187205. #endif
  187206. /* Check for overflow */
  187207. #if defined(__TURBOC__) && !defined(__FLAT__)
  187208. if (size != (unsigned long)size)
  187209. ret = NULL;
  187210. else
  187211. ret = farmalloc(size);
  187212. #else
  187213. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187214. if (size != (unsigned long)size)
  187215. ret = NULL;
  187216. else
  187217. ret = halloc(size, 1);
  187218. # else
  187219. if (size != (size_t)size)
  187220. ret = NULL;
  187221. else
  187222. ret = malloc((size_t)size);
  187223. # endif
  187224. #endif
  187225. #ifndef PNG_USER_MEM_SUPPORTED
  187226. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187227. png_error(png_ptr, "Out of Memory");
  187228. #endif
  187229. return (ret);
  187230. }
  187231. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187232. without taking any action. */
  187233. void PNGAPI
  187234. png_free(png_structp png_ptr, png_voidp ptr)
  187235. {
  187236. if (png_ptr == NULL || ptr == NULL)
  187237. return;
  187238. #ifdef PNG_USER_MEM_SUPPORTED
  187239. if (png_ptr->free_fn != NULL)
  187240. {
  187241. (*(png_ptr->free_fn))(png_ptr, ptr);
  187242. return;
  187243. }
  187244. else png_free_default(png_ptr, ptr);
  187245. }
  187246. void PNGAPI
  187247. png_free_default(png_structp png_ptr, png_voidp ptr)
  187248. {
  187249. if (png_ptr == NULL || ptr == NULL)
  187250. return;
  187251. #endif /* PNG_USER_MEM_SUPPORTED */
  187252. #if defined(__TURBOC__) && !defined(__FLAT__)
  187253. farfree(ptr);
  187254. #else
  187255. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187256. hfree(ptr);
  187257. # else
  187258. free(ptr);
  187259. # endif
  187260. #endif
  187261. }
  187262. #endif /* Not Borland DOS special memory handler */
  187263. #if defined(PNG_1_0_X)
  187264. # define png_malloc_warn png_malloc
  187265. #else
  187266. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187267. * function will set up png_malloc() to issue a png_warning and return NULL
  187268. * instead of issuing a png_error, if it fails to allocate the requested
  187269. * memory.
  187270. */
  187271. png_voidp PNGAPI
  187272. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187273. {
  187274. png_voidp ptr;
  187275. png_uint_32 save_flags;
  187276. if(png_ptr == NULL) return (NULL);
  187277. save_flags=png_ptr->flags;
  187278. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187279. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187280. png_ptr->flags=save_flags;
  187281. return(ptr);
  187282. }
  187283. #endif
  187284. png_voidp PNGAPI
  187285. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187286. png_uint_32 length)
  187287. {
  187288. png_size_t size;
  187289. size = (png_size_t)length;
  187290. if ((png_uint_32)size != length)
  187291. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187292. return(png_memcpy (s1, s2, size));
  187293. }
  187294. png_voidp PNGAPI
  187295. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187296. png_uint_32 length)
  187297. {
  187298. png_size_t size;
  187299. size = (png_size_t)length;
  187300. if ((png_uint_32)size != length)
  187301. png_error(png_ptr,"Overflow in png_memset_check.");
  187302. return (png_memset (s1, value, size));
  187303. }
  187304. #ifdef PNG_USER_MEM_SUPPORTED
  187305. /* This function is called when the application wants to use another method
  187306. * of allocating and freeing memory.
  187307. */
  187308. void PNGAPI
  187309. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187310. malloc_fn, png_free_ptr free_fn)
  187311. {
  187312. if(png_ptr != NULL) {
  187313. png_ptr->mem_ptr = mem_ptr;
  187314. png_ptr->malloc_fn = malloc_fn;
  187315. png_ptr->free_fn = free_fn;
  187316. }
  187317. }
  187318. /* This function returns a pointer to the mem_ptr associated with the user
  187319. * functions. The application should free any memory associated with this
  187320. * pointer before png_write_destroy and png_read_destroy are called.
  187321. */
  187322. png_voidp PNGAPI
  187323. png_get_mem_ptr(png_structp png_ptr)
  187324. {
  187325. if(png_ptr == NULL) return (NULL);
  187326. return ((png_voidp)png_ptr->mem_ptr);
  187327. }
  187328. #endif /* PNG_USER_MEM_SUPPORTED */
  187329. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187330. /*** End of inlined file: pngmem.c ***/
  187331. /*** Start of inlined file: pngread.c ***/
  187332. /* pngread.c - read a PNG file
  187333. *
  187334. * Last changed in libpng 1.2.20 September 7, 2007
  187335. * For conditions of distribution and use, see copyright notice in png.h
  187336. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187337. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187338. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187339. *
  187340. * This file contains routines that an application calls directly to
  187341. * read a PNG file or stream.
  187342. */
  187343. #define PNG_INTERNAL
  187344. #if defined(PNG_READ_SUPPORTED)
  187345. /* Create a PNG structure for reading, and allocate any memory needed. */
  187346. png_structp PNGAPI
  187347. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187348. png_error_ptr error_fn, png_error_ptr warn_fn)
  187349. {
  187350. #ifdef PNG_USER_MEM_SUPPORTED
  187351. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187352. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187353. }
  187354. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187355. png_structp PNGAPI
  187356. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187357. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187358. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187359. {
  187360. #endif /* PNG_USER_MEM_SUPPORTED */
  187361. png_structp png_ptr;
  187362. #ifdef PNG_SETJMP_SUPPORTED
  187363. #ifdef USE_FAR_KEYWORD
  187364. jmp_buf jmpbuf;
  187365. #endif
  187366. #endif
  187367. int i;
  187368. png_debug(1, "in png_create_read_struct\n");
  187369. #ifdef PNG_USER_MEM_SUPPORTED
  187370. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187371. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187372. #else
  187373. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187374. #endif
  187375. if (png_ptr == NULL)
  187376. return (NULL);
  187377. /* added at libpng-1.2.6 */
  187378. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187379. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187380. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187381. #endif
  187382. #ifdef PNG_SETJMP_SUPPORTED
  187383. #ifdef USE_FAR_KEYWORD
  187384. if (setjmp(jmpbuf))
  187385. #else
  187386. if (setjmp(png_ptr->jmpbuf))
  187387. #endif
  187388. {
  187389. png_free(png_ptr, png_ptr->zbuf);
  187390. png_ptr->zbuf=NULL;
  187391. #ifdef PNG_USER_MEM_SUPPORTED
  187392. png_destroy_struct_2((png_voidp)png_ptr,
  187393. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187394. #else
  187395. png_destroy_struct((png_voidp)png_ptr);
  187396. #endif
  187397. return (NULL);
  187398. }
  187399. #ifdef USE_FAR_KEYWORD
  187400. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187401. #endif
  187402. #endif
  187403. #ifdef PNG_USER_MEM_SUPPORTED
  187404. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187405. #endif
  187406. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187407. i=0;
  187408. do
  187409. {
  187410. if(user_png_ver[i] != png_libpng_ver[i])
  187411. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187412. } while (png_libpng_ver[i++]);
  187413. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187414. {
  187415. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187416. * we must recompile any applications that use any older library version.
  187417. * For versions after libpng 1.0, we will be compatible, so we need
  187418. * only check the first digit.
  187419. */
  187420. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187421. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187422. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187423. {
  187424. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187425. char msg[80];
  187426. if (user_png_ver)
  187427. {
  187428. png_snprintf(msg, 80,
  187429. "Application was compiled with png.h from libpng-%.20s",
  187430. user_png_ver);
  187431. png_warning(png_ptr, msg);
  187432. }
  187433. png_snprintf(msg, 80,
  187434. "Application is running with png.c from libpng-%.20s",
  187435. png_libpng_ver);
  187436. png_warning(png_ptr, msg);
  187437. #endif
  187438. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187439. png_ptr->flags=0;
  187440. #endif
  187441. png_error(png_ptr,
  187442. "Incompatible libpng version in application and library");
  187443. }
  187444. }
  187445. /* initialize zbuf - compression buffer */
  187446. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187447. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187448. (png_uint_32)png_ptr->zbuf_size);
  187449. png_ptr->zstream.zalloc = png_zalloc;
  187450. png_ptr->zstream.zfree = png_zfree;
  187451. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187452. switch (inflateInit(&png_ptr->zstream))
  187453. {
  187454. case Z_OK: /* Do nothing */ break;
  187455. case Z_MEM_ERROR:
  187456. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187457. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187458. default: png_error(png_ptr, "Unknown zlib error");
  187459. }
  187460. png_ptr->zstream.next_out = png_ptr->zbuf;
  187461. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187462. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187463. #ifdef PNG_SETJMP_SUPPORTED
  187464. /* Applications that neglect to set up their own setjmp() and then encounter
  187465. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187466. abort instead of returning. */
  187467. #ifdef USE_FAR_KEYWORD
  187468. if (setjmp(jmpbuf))
  187469. PNG_ABORT();
  187470. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187471. #else
  187472. if (setjmp(png_ptr->jmpbuf))
  187473. PNG_ABORT();
  187474. #endif
  187475. #endif
  187476. return (png_ptr);
  187477. }
  187478. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187479. /* Initialize PNG structure for reading, and allocate any memory needed.
  187480. This interface is deprecated in favour of the png_create_read_struct(),
  187481. and it will disappear as of libpng-1.3.0. */
  187482. #undef png_read_init
  187483. void PNGAPI
  187484. png_read_init(png_structp png_ptr)
  187485. {
  187486. /* We only come here via pre-1.0.7-compiled applications */
  187487. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187488. }
  187489. void PNGAPI
  187490. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187491. png_size_t png_struct_size, png_size_t png_info_size)
  187492. {
  187493. /* We only come here via pre-1.0.12-compiled applications */
  187494. if(png_ptr == NULL) return;
  187495. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187496. if(png_sizeof(png_struct) > png_struct_size ||
  187497. png_sizeof(png_info) > png_info_size)
  187498. {
  187499. char msg[80];
  187500. png_ptr->warning_fn=NULL;
  187501. if (user_png_ver)
  187502. {
  187503. png_snprintf(msg, 80,
  187504. "Application was compiled with png.h from libpng-%.20s",
  187505. user_png_ver);
  187506. png_warning(png_ptr, msg);
  187507. }
  187508. png_snprintf(msg, 80,
  187509. "Application is running with png.c from libpng-%.20s",
  187510. png_libpng_ver);
  187511. png_warning(png_ptr, msg);
  187512. }
  187513. #endif
  187514. if(png_sizeof(png_struct) > png_struct_size)
  187515. {
  187516. png_ptr->error_fn=NULL;
  187517. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187518. png_ptr->flags=0;
  187519. #endif
  187520. png_error(png_ptr,
  187521. "The png struct allocated by the application for reading is too small.");
  187522. }
  187523. if(png_sizeof(png_info) > png_info_size)
  187524. {
  187525. png_ptr->error_fn=NULL;
  187526. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187527. png_ptr->flags=0;
  187528. #endif
  187529. png_error(png_ptr,
  187530. "The info struct allocated by application for reading is too small.");
  187531. }
  187532. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187533. }
  187534. #endif /* PNG_1_0_X || PNG_1_2_X */
  187535. void PNGAPI
  187536. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187537. png_size_t png_struct_size)
  187538. {
  187539. #ifdef PNG_SETJMP_SUPPORTED
  187540. jmp_buf tmp_jmp; /* to save current jump buffer */
  187541. #endif
  187542. int i=0;
  187543. png_structp png_ptr=*ptr_ptr;
  187544. if(png_ptr == NULL) return;
  187545. do
  187546. {
  187547. if(user_png_ver[i] != png_libpng_ver[i])
  187548. {
  187549. #ifdef PNG_LEGACY_SUPPORTED
  187550. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187551. #else
  187552. png_ptr->warning_fn=NULL;
  187553. png_warning(png_ptr,
  187554. "Application uses deprecated png_read_init() and should be recompiled.");
  187555. break;
  187556. #endif
  187557. }
  187558. } while (png_libpng_ver[i++]);
  187559. png_debug(1, "in png_read_init_3\n");
  187560. #ifdef PNG_SETJMP_SUPPORTED
  187561. /* save jump buffer and error functions */
  187562. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187563. #endif
  187564. if(png_sizeof(png_struct) > png_struct_size)
  187565. {
  187566. png_destroy_struct(png_ptr);
  187567. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187568. png_ptr = *ptr_ptr;
  187569. }
  187570. /* reset all variables to 0 */
  187571. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187572. #ifdef PNG_SETJMP_SUPPORTED
  187573. /* restore jump buffer */
  187574. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187575. #endif
  187576. /* added at libpng-1.2.6 */
  187577. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187578. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187579. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187580. #endif
  187581. /* initialize zbuf - compression buffer */
  187582. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187583. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187584. (png_uint_32)png_ptr->zbuf_size);
  187585. png_ptr->zstream.zalloc = png_zalloc;
  187586. png_ptr->zstream.zfree = png_zfree;
  187587. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187588. switch (inflateInit(&png_ptr->zstream))
  187589. {
  187590. case Z_OK: /* Do nothing */ break;
  187591. case Z_MEM_ERROR:
  187592. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187593. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187594. default: png_error(png_ptr, "Unknown zlib error");
  187595. }
  187596. png_ptr->zstream.next_out = png_ptr->zbuf;
  187597. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187598. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187599. }
  187600. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187601. /* Read the information before the actual image data. This has been
  187602. * changed in v0.90 to allow reading a file that already has the magic
  187603. * bytes read from the stream. You can tell libpng how many bytes have
  187604. * been read from the beginning of the stream (up to the maximum of 8)
  187605. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187606. * here. The application can then have access to the signature bytes we
  187607. * read if it is determined that this isn't a valid PNG file.
  187608. */
  187609. void PNGAPI
  187610. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187611. {
  187612. if(png_ptr == NULL) return;
  187613. png_debug(1, "in png_read_info\n");
  187614. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187615. if (png_ptr->sig_bytes < 8)
  187616. {
  187617. png_size_t num_checked = png_ptr->sig_bytes,
  187618. num_to_check = 8 - num_checked;
  187619. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187620. png_ptr->sig_bytes = 8;
  187621. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187622. {
  187623. if (num_checked < 4 &&
  187624. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187625. png_error(png_ptr, "Not a PNG file");
  187626. else
  187627. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187628. }
  187629. if (num_checked < 3)
  187630. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187631. }
  187632. for(;;)
  187633. {
  187634. #ifdef PNG_USE_LOCAL_ARRAYS
  187635. PNG_CONST PNG_IHDR;
  187636. PNG_CONST PNG_IDAT;
  187637. PNG_CONST PNG_IEND;
  187638. PNG_CONST PNG_PLTE;
  187639. #if defined(PNG_READ_bKGD_SUPPORTED)
  187640. PNG_CONST PNG_bKGD;
  187641. #endif
  187642. #if defined(PNG_READ_cHRM_SUPPORTED)
  187643. PNG_CONST PNG_cHRM;
  187644. #endif
  187645. #if defined(PNG_READ_gAMA_SUPPORTED)
  187646. PNG_CONST PNG_gAMA;
  187647. #endif
  187648. #if defined(PNG_READ_hIST_SUPPORTED)
  187649. PNG_CONST PNG_hIST;
  187650. #endif
  187651. #if defined(PNG_READ_iCCP_SUPPORTED)
  187652. PNG_CONST PNG_iCCP;
  187653. #endif
  187654. #if defined(PNG_READ_iTXt_SUPPORTED)
  187655. PNG_CONST PNG_iTXt;
  187656. #endif
  187657. #if defined(PNG_READ_oFFs_SUPPORTED)
  187658. PNG_CONST PNG_oFFs;
  187659. #endif
  187660. #if defined(PNG_READ_pCAL_SUPPORTED)
  187661. PNG_CONST PNG_pCAL;
  187662. #endif
  187663. #if defined(PNG_READ_pHYs_SUPPORTED)
  187664. PNG_CONST PNG_pHYs;
  187665. #endif
  187666. #if defined(PNG_READ_sBIT_SUPPORTED)
  187667. PNG_CONST PNG_sBIT;
  187668. #endif
  187669. #if defined(PNG_READ_sCAL_SUPPORTED)
  187670. PNG_CONST PNG_sCAL;
  187671. #endif
  187672. #if defined(PNG_READ_sPLT_SUPPORTED)
  187673. PNG_CONST PNG_sPLT;
  187674. #endif
  187675. #if defined(PNG_READ_sRGB_SUPPORTED)
  187676. PNG_CONST PNG_sRGB;
  187677. #endif
  187678. #if defined(PNG_READ_tEXt_SUPPORTED)
  187679. PNG_CONST PNG_tEXt;
  187680. #endif
  187681. #if defined(PNG_READ_tIME_SUPPORTED)
  187682. PNG_CONST PNG_tIME;
  187683. #endif
  187684. #if defined(PNG_READ_tRNS_SUPPORTED)
  187685. PNG_CONST PNG_tRNS;
  187686. #endif
  187687. #if defined(PNG_READ_zTXt_SUPPORTED)
  187688. PNG_CONST PNG_zTXt;
  187689. #endif
  187690. #endif /* PNG_USE_LOCAL_ARRAYS */
  187691. png_byte chunk_length[4];
  187692. png_uint_32 length;
  187693. png_read_data(png_ptr, chunk_length, 4);
  187694. length = png_get_uint_31(png_ptr,chunk_length);
  187695. png_reset_crc(png_ptr);
  187696. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187697. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187698. length);
  187699. /* This should be a binary subdivision search or a hash for
  187700. * matching the chunk name rather than a linear search.
  187701. */
  187702. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187703. if(png_ptr->mode & PNG_AFTER_IDAT)
  187704. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187705. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187706. png_handle_IHDR(png_ptr, info_ptr, length);
  187707. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187708. png_handle_IEND(png_ptr, info_ptr, length);
  187709. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187710. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187711. {
  187712. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187713. png_ptr->mode |= PNG_HAVE_IDAT;
  187714. png_handle_unknown(png_ptr, info_ptr, length);
  187715. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187716. png_ptr->mode |= PNG_HAVE_PLTE;
  187717. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187718. {
  187719. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187720. png_error(png_ptr, "Missing IHDR before IDAT");
  187721. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187722. !(png_ptr->mode & PNG_HAVE_PLTE))
  187723. png_error(png_ptr, "Missing PLTE before IDAT");
  187724. break;
  187725. }
  187726. }
  187727. #endif
  187728. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187729. png_handle_PLTE(png_ptr, info_ptr, length);
  187730. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187731. {
  187732. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187733. png_error(png_ptr, "Missing IHDR before IDAT");
  187734. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187735. !(png_ptr->mode & PNG_HAVE_PLTE))
  187736. png_error(png_ptr, "Missing PLTE before IDAT");
  187737. png_ptr->idat_size = length;
  187738. png_ptr->mode |= PNG_HAVE_IDAT;
  187739. break;
  187740. }
  187741. #if defined(PNG_READ_bKGD_SUPPORTED)
  187742. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187743. png_handle_bKGD(png_ptr, info_ptr, length);
  187744. #endif
  187745. #if defined(PNG_READ_cHRM_SUPPORTED)
  187746. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187747. png_handle_cHRM(png_ptr, info_ptr, length);
  187748. #endif
  187749. #if defined(PNG_READ_gAMA_SUPPORTED)
  187750. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187751. png_handle_gAMA(png_ptr, info_ptr, length);
  187752. #endif
  187753. #if defined(PNG_READ_hIST_SUPPORTED)
  187754. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187755. png_handle_hIST(png_ptr, info_ptr, length);
  187756. #endif
  187757. #if defined(PNG_READ_oFFs_SUPPORTED)
  187758. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187759. png_handle_oFFs(png_ptr, info_ptr, length);
  187760. #endif
  187761. #if defined(PNG_READ_pCAL_SUPPORTED)
  187762. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187763. png_handle_pCAL(png_ptr, info_ptr, length);
  187764. #endif
  187765. #if defined(PNG_READ_sCAL_SUPPORTED)
  187766. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187767. png_handle_sCAL(png_ptr, info_ptr, length);
  187768. #endif
  187769. #if defined(PNG_READ_pHYs_SUPPORTED)
  187770. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187771. png_handle_pHYs(png_ptr, info_ptr, length);
  187772. #endif
  187773. #if defined(PNG_READ_sBIT_SUPPORTED)
  187774. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187775. png_handle_sBIT(png_ptr, info_ptr, length);
  187776. #endif
  187777. #if defined(PNG_READ_sRGB_SUPPORTED)
  187778. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187779. png_handle_sRGB(png_ptr, info_ptr, length);
  187780. #endif
  187781. #if defined(PNG_READ_iCCP_SUPPORTED)
  187782. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187783. png_handle_iCCP(png_ptr, info_ptr, length);
  187784. #endif
  187785. #if defined(PNG_READ_sPLT_SUPPORTED)
  187786. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187787. png_handle_sPLT(png_ptr, info_ptr, length);
  187788. #endif
  187789. #if defined(PNG_READ_tEXt_SUPPORTED)
  187790. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187791. png_handle_tEXt(png_ptr, info_ptr, length);
  187792. #endif
  187793. #if defined(PNG_READ_tIME_SUPPORTED)
  187794. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187795. png_handle_tIME(png_ptr, info_ptr, length);
  187796. #endif
  187797. #if defined(PNG_READ_tRNS_SUPPORTED)
  187798. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187799. png_handle_tRNS(png_ptr, info_ptr, length);
  187800. #endif
  187801. #if defined(PNG_READ_zTXt_SUPPORTED)
  187802. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187803. png_handle_zTXt(png_ptr, info_ptr, length);
  187804. #endif
  187805. #if defined(PNG_READ_iTXt_SUPPORTED)
  187806. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187807. png_handle_iTXt(png_ptr, info_ptr, length);
  187808. #endif
  187809. else
  187810. png_handle_unknown(png_ptr, info_ptr, length);
  187811. }
  187812. }
  187813. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187814. /* optional call to update the users info_ptr structure */
  187815. void PNGAPI
  187816. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187817. {
  187818. png_debug(1, "in png_read_update_info\n");
  187819. if(png_ptr == NULL) return;
  187820. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187821. png_read_start_row(png_ptr);
  187822. else
  187823. png_warning(png_ptr,
  187824. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187825. png_read_transform_info(png_ptr, info_ptr);
  187826. }
  187827. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187828. /* Initialize palette, background, etc, after transformations
  187829. * are set, but before any reading takes place. This allows
  187830. * the user to obtain a gamma-corrected palette, for example.
  187831. * If the user doesn't call this, we will do it ourselves.
  187832. */
  187833. void PNGAPI
  187834. png_start_read_image(png_structp png_ptr)
  187835. {
  187836. png_debug(1, "in png_start_read_image\n");
  187837. if(png_ptr == NULL) return;
  187838. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187839. png_read_start_row(png_ptr);
  187840. }
  187841. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187842. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187843. void PNGAPI
  187844. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187845. {
  187846. #ifdef PNG_USE_LOCAL_ARRAYS
  187847. PNG_CONST PNG_IDAT;
  187848. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187849. 0xff};
  187850. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187851. #endif
  187852. int ret;
  187853. if(png_ptr == NULL) return;
  187854. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187855. png_ptr->row_number, png_ptr->pass);
  187856. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187857. png_read_start_row(png_ptr);
  187858. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187859. {
  187860. /* check for transforms that have been set but were defined out */
  187861. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187862. if (png_ptr->transformations & PNG_INVERT_MONO)
  187863. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187864. #endif
  187865. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187866. if (png_ptr->transformations & PNG_FILLER)
  187867. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187868. #endif
  187869. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187870. if (png_ptr->transformations & PNG_PACKSWAP)
  187871. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187872. #endif
  187873. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187874. if (png_ptr->transformations & PNG_PACK)
  187875. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187876. #endif
  187877. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187878. if (png_ptr->transformations & PNG_SHIFT)
  187879. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187880. #endif
  187881. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187882. if (png_ptr->transformations & PNG_BGR)
  187883. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187884. #endif
  187885. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187886. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187887. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187888. #endif
  187889. }
  187890. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187891. /* if interlaced and we do not need a new row, combine row and return */
  187892. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187893. {
  187894. switch (png_ptr->pass)
  187895. {
  187896. case 0:
  187897. if (png_ptr->row_number & 0x07)
  187898. {
  187899. if (dsp_row != NULL)
  187900. png_combine_row(png_ptr, dsp_row,
  187901. png_pass_dsp_mask[png_ptr->pass]);
  187902. png_read_finish_row(png_ptr);
  187903. return;
  187904. }
  187905. break;
  187906. case 1:
  187907. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187908. {
  187909. if (dsp_row != NULL)
  187910. png_combine_row(png_ptr, dsp_row,
  187911. png_pass_dsp_mask[png_ptr->pass]);
  187912. png_read_finish_row(png_ptr);
  187913. return;
  187914. }
  187915. break;
  187916. case 2:
  187917. if ((png_ptr->row_number & 0x07) != 4)
  187918. {
  187919. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187920. png_combine_row(png_ptr, dsp_row,
  187921. png_pass_dsp_mask[png_ptr->pass]);
  187922. png_read_finish_row(png_ptr);
  187923. return;
  187924. }
  187925. break;
  187926. case 3:
  187927. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187928. {
  187929. if (dsp_row != NULL)
  187930. png_combine_row(png_ptr, dsp_row,
  187931. png_pass_dsp_mask[png_ptr->pass]);
  187932. png_read_finish_row(png_ptr);
  187933. return;
  187934. }
  187935. break;
  187936. case 4:
  187937. if ((png_ptr->row_number & 3) != 2)
  187938. {
  187939. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187940. png_combine_row(png_ptr, dsp_row,
  187941. png_pass_dsp_mask[png_ptr->pass]);
  187942. png_read_finish_row(png_ptr);
  187943. return;
  187944. }
  187945. break;
  187946. case 5:
  187947. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187948. {
  187949. if (dsp_row != NULL)
  187950. png_combine_row(png_ptr, dsp_row,
  187951. png_pass_dsp_mask[png_ptr->pass]);
  187952. png_read_finish_row(png_ptr);
  187953. return;
  187954. }
  187955. break;
  187956. case 6:
  187957. if (!(png_ptr->row_number & 1))
  187958. {
  187959. png_read_finish_row(png_ptr);
  187960. return;
  187961. }
  187962. break;
  187963. }
  187964. }
  187965. #endif
  187966. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187967. png_error(png_ptr, "Invalid attempt to read row data");
  187968. png_ptr->zstream.next_out = png_ptr->row_buf;
  187969. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187970. do
  187971. {
  187972. if (!(png_ptr->zstream.avail_in))
  187973. {
  187974. while (!png_ptr->idat_size)
  187975. {
  187976. png_byte chunk_length[4];
  187977. png_crc_finish(png_ptr, 0);
  187978. png_read_data(png_ptr, chunk_length, 4);
  187979. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187980. png_reset_crc(png_ptr);
  187981. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187982. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187983. png_error(png_ptr, "Not enough image data");
  187984. }
  187985. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187986. png_ptr->zstream.next_in = png_ptr->zbuf;
  187987. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187988. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187989. png_crc_read(png_ptr, png_ptr->zbuf,
  187990. (png_size_t)png_ptr->zstream.avail_in);
  187991. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187992. }
  187993. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187994. if (ret == Z_STREAM_END)
  187995. {
  187996. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187997. png_ptr->idat_size)
  187998. png_error(png_ptr, "Extra compressed data");
  187999. png_ptr->mode |= PNG_AFTER_IDAT;
  188000. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188001. break;
  188002. }
  188003. if (ret != Z_OK)
  188004. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  188005. "Decompression error");
  188006. } while (png_ptr->zstream.avail_out);
  188007. png_ptr->row_info.color_type = png_ptr->color_type;
  188008. png_ptr->row_info.width = png_ptr->iwidth;
  188009. png_ptr->row_info.channels = png_ptr->channels;
  188010. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188011. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188012. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188013. png_ptr->row_info.width);
  188014. if(png_ptr->row_buf[0])
  188015. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188016. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188017. (int)(png_ptr->row_buf[0]));
  188018. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188019. png_ptr->rowbytes + 1);
  188020. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  188021. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  188022. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  188023. {
  188024. /* Intrapixel differencing */
  188025. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188026. }
  188027. #endif
  188028. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188029. png_do_read_transformations(png_ptr);
  188030. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188031. /* blow up interlaced rows to full size */
  188032. if (png_ptr->interlaced &&
  188033. (png_ptr->transformations & PNG_INTERLACE))
  188034. {
  188035. if (png_ptr->pass < 6)
  188036. /* old interface (pre-1.0.9):
  188037. png_do_read_interlace(&(png_ptr->row_info),
  188038. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188039. */
  188040. png_do_read_interlace(png_ptr);
  188041. if (dsp_row != NULL)
  188042. png_combine_row(png_ptr, dsp_row,
  188043. png_pass_dsp_mask[png_ptr->pass]);
  188044. if (row != NULL)
  188045. png_combine_row(png_ptr, row,
  188046. png_pass_mask[png_ptr->pass]);
  188047. }
  188048. else
  188049. #endif
  188050. {
  188051. if (row != NULL)
  188052. png_combine_row(png_ptr, row, 0xff);
  188053. if (dsp_row != NULL)
  188054. png_combine_row(png_ptr, dsp_row, 0xff);
  188055. }
  188056. png_read_finish_row(png_ptr);
  188057. if (png_ptr->read_row_fn != NULL)
  188058. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  188059. }
  188060. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188061. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188062. /* Read one or more rows of image data. If the image is interlaced,
  188063. * and png_set_interlace_handling() has been called, the rows need to
  188064. * contain the contents of the rows from the previous pass. If the
  188065. * image has alpha or transparency, and png_handle_alpha()[*] has been
  188066. * called, the rows contents must be initialized to the contents of the
  188067. * screen.
  188068. *
  188069. * "row" holds the actual image, and pixels are placed in it
  188070. * as they arrive. If the image is displayed after each pass, it will
  188071. * appear to "sparkle" in. "display_row" can be used to display a
  188072. * "chunky" progressive image, with finer detail added as it becomes
  188073. * available. If you do not want this "chunky" display, you may pass
  188074. * NULL for display_row. If you do not want the sparkle display, and
  188075. * you have not called png_handle_alpha(), you may pass NULL for rows.
  188076. * If you have called png_handle_alpha(), and the image has either an
  188077. * alpha channel or a transparency chunk, you must provide a buffer for
  188078. * rows. In this case, you do not have to provide a display_row buffer
  188079. * also, but you may. If the image is not interlaced, or if you have
  188080. * not called png_set_interlace_handling(), the display_row buffer will
  188081. * be ignored, so pass NULL to it.
  188082. *
  188083. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188084. */
  188085. void PNGAPI
  188086. png_read_rows(png_structp png_ptr, png_bytepp row,
  188087. png_bytepp display_row, png_uint_32 num_rows)
  188088. {
  188089. png_uint_32 i;
  188090. png_bytepp rp;
  188091. png_bytepp dp;
  188092. png_debug(1, "in png_read_rows\n");
  188093. if(png_ptr == NULL) return;
  188094. rp = row;
  188095. dp = display_row;
  188096. if (rp != NULL && dp != NULL)
  188097. for (i = 0; i < num_rows; i++)
  188098. {
  188099. png_bytep rptr = *rp++;
  188100. png_bytep dptr = *dp++;
  188101. png_read_row(png_ptr, rptr, dptr);
  188102. }
  188103. else if(rp != NULL)
  188104. for (i = 0; i < num_rows; i++)
  188105. {
  188106. png_bytep rptr = *rp;
  188107. png_read_row(png_ptr, rptr, png_bytep_NULL);
  188108. rp++;
  188109. }
  188110. else if(dp != NULL)
  188111. for (i = 0; i < num_rows; i++)
  188112. {
  188113. png_bytep dptr = *dp;
  188114. png_read_row(png_ptr, png_bytep_NULL, dptr);
  188115. dp++;
  188116. }
  188117. }
  188118. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188119. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188120. /* Read the entire image. If the image has an alpha channel or a tRNS
  188121. * chunk, and you have called png_handle_alpha()[*], you will need to
  188122. * initialize the image to the current image that PNG will be overlaying.
  188123. * We set the num_rows again here, in case it was incorrectly set in
  188124. * png_read_start_row() by a call to png_read_update_info() or
  188125. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188126. * prior to either of these functions like it should have been. You can
  188127. * only call this function once. If you desire to have an image for
  188128. * each pass of a interlaced image, use png_read_rows() instead.
  188129. *
  188130. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188131. */
  188132. void PNGAPI
  188133. png_read_image(png_structp png_ptr, png_bytepp image)
  188134. {
  188135. png_uint_32 i,image_height;
  188136. int pass, j;
  188137. png_bytepp rp;
  188138. png_debug(1, "in png_read_image\n");
  188139. if(png_ptr == NULL) return;
  188140. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188141. pass = png_set_interlace_handling(png_ptr);
  188142. #else
  188143. if (png_ptr->interlaced)
  188144. png_error(png_ptr,
  188145. "Cannot read interlaced image -- interlace handler disabled.");
  188146. pass = 1;
  188147. #endif
  188148. image_height=png_ptr->height;
  188149. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188150. for (j = 0; j < pass; j++)
  188151. {
  188152. rp = image;
  188153. for (i = 0; i < image_height; i++)
  188154. {
  188155. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188156. rp++;
  188157. }
  188158. }
  188159. }
  188160. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188161. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188162. /* Read the end of the PNG file. Will not read past the end of the
  188163. * file, will verify the end is accurate, and will read any comments
  188164. * or time information at the end of the file, if info is not NULL.
  188165. */
  188166. void PNGAPI
  188167. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188168. {
  188169. png_byte chunk_length[4];
  188170. png_uint_32 length;
  188171. png_debug(1, "in png_read_end\n");
  188172. if(png_ptr == NULL) return;
  188173. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188174. do
  188175. {
  188176. #ifdef PNG_USE_LOCAL_ARRAYS
  188177. PNG_CONST PNG_IHDR;
  188178. PNG_CONST PNG_IDAT;
  188179. PNG_CONST PNG_IEND;
  188180. PNG_CONST PNG_PLTE;
  188181. #if defined(PNG_READ_bKGD_SUPPORTED)
  188182. PNG_CONST PNG_bKGD;
  188183. #endif
  188184. #if defined(PNG_READ_cHRM_SUPPORTED)
  188185. PNG_CONST PNG_cHRM;
  188186. #endif
  188187. #if defined(PNG_READ_gAMA_SUPPORTED)
  188188. PNG_CONST PNG_gAMA;
  188189. #endif
  188190. #if defined(PNG_READ_hIST_SUPPORTED)
  188191. PNG_CONST PNG_hIST;
  188192. #endif
  188193. #if defined(PNG_READ_iCCP_SUPPORTED)
  188194. PNG_CONST PNG_iCCP;
  188195. #endif
  188196. #if defined(PNG_READ_iTXt_SUPPORTED)
  188197. PNG_CONST PNG_iTXt;
  188198. #endif
  188199. #if defined(PNG_READ_oFFs_SUPPORTED)
  188200. PNG_CONST PNG_oFFs;
  188201. #endif
  188202. #if defined(PNG_READ_pCAL_SUPPORTED)
  188203. PNG_CONST PNG_pCAL;
  188204. #endif
  188205. #if defined(PNG_READ_pHYs_SUPPORTED)
  188206. PNG_CONST PNG_pHYs;
  188207. #endif
  188208. #if defined(PNG_READ_sBIT_SUPPORTED)
  188209. PNG_CONST PNG_sBIT;
  188210. #endif
  188211. #if defined(PNG_READ_sCAL_SUPPORTED)
  188212. PNG_CONST PNG_sCAL;
  188213. #endif
  188214. #if defined(PNG_READ_sPLT_SUPPORTED)
  188215. PNG_CONST PNG_sPLT;
  188216. #endif
  188217. #if defined(PNG_READ_sRGB_SUPPORTED)
  188218. PNG_CONST PNG_sRGB;
  188219. #endif
  188220. #if defined(PNG_READ_tEXt_SUPPORTED)
  188221. PNG_CONST PNG_tEXt;
  188222. #endif
  188223. #if defined(PNG_READ_tIME_SUPPORTED)
  188224. PNG_CONST PNG_tIME;
  188225. #endif
  188226. #if defined(PNG_READ_tRNS_SUPPORTED)
  188227. PNG_CONST PNG_tRNS;
  188228. #endif
  188229. #if defined(PNG_READ_zTXt_SUPPORTED)
  188230. PNG_CONST PNG_zTXt;
  188231. #endif
  188232. #endif /* PNG_USE_LOCAL_ARRAYS */
  188233. png_read_data(png_ptr, chunk_length, 4);
  188234. length = png_get_uint_31(png_ptr,chunk_length);
  188235. png_reset_crc(png_ptr);
  188236. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188237. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188238. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188239. png_handle_IHDR(png_ptr, info_ptr, length);
  188240. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188241. png_handle_IEND(png_ptr, info_ptr, length);
  188242. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188243. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188244. {
  188245. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188246. {
  188247. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188248. png_error(png_ptr, "Too many IDAT's found");
  188249. }
  188250. png_handle_unknown(png_ptr, info_ptr, length);
  188251. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188252. png_ptr->mode |= PNG_HAVE_PLTE;
  188253. }
  188254. #endif
  188255. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188256. {
  188257. /* Zero length IDATs are legal after the last IDAT has been
  188258. * read, but not after other chunks have been read.
  188259. */
  188260. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188261. png_error(png_ptr, "Too many IDAT's found");
  188262. png_crc_finish(png_ptr, length);
  188263. }
  188264. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188265. png_handle_PLTE(png_ptr, info_ptr, length);
  188266. #if defined(PNG_READ_bKGD_SUPPORTED)
  188267. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188268. png_handle_bKGD(png_ptr, info_ptr, length);
  188269. #endif
  188270. #if defined(PNG_READ_cHRM_SUPPORTED)
  188271. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188272. png_handle_cHRM(png_ptr, info_ptr, length);
  188273. #endif
  188274. #if defined(PNG_READ_gAMA_SUPPORTED)
  188275. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188276. png_handle_gAMA(png_ptr, info_ptr, length);
  188277. #endif
  188278. #if defined(PNG_READ_hIST_SUPPORTED)
  188279. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188280. png_handle_hIST(png_ptr, info_ptr, length);
  188281. #endif
  188282. #if defined(PNG_READ_oFFs_SUPPORTED)
  188283. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188284. png_handle_oFFs(png_ptr, info_ptr, length);
  188285. #endif
  188286. #if defined(PNG_READ_pCAL_SUPPORTED)
  188287. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188288. png_handle_pCAL(png_ptr, info_ptr, length);
  188289. #endif
  188290. #if defined(PNG_READ_sCAL_SUPPORTED)
  188291. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188292. png_handle_sCAL(png_ptr, info_ptr, length);
  188293. #endif
  188294. #if defined(PNG_READ_pHYs_SUPPORTED)
  188295. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188296. png_handle_pHYs(png_ptr, info_ptr, length);
  188297. #endif
  188298. #if defined(PNG_READ_sBIT_SUPPORTED)
  188299. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188300. png_handle_sBIT(png_ptr, info_ptr, length);
  188301. #endif
  188302. #if defined(PNG_READ_sRGB_SUPPORTED)
  188303. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188304. png_handle_sRGB(png_ptr, info_ptr, length);
  188305. #endif
  188306. #if defined(PNG_READ_iCCP_SUPPORTED)
  188307. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188308. png_handle_iCCP(png_ptr, info_ptr, length);
  188309. #endif
  188310. #if defined(PNG_READ_sPLT_SUPPORTED)
  188311. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188312. png_handle_sPLT(png_ptr, info_ptr, length);
  188313. #endif
  188314. #if defined(PNG_READ_tEXt_SUPPORTED)
  188315. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188316. png_handle_tEXt(png_ptr, info_ptr, length);
  188317. #endif
  188318. #if defined(PNG_READ_tIME_SUPPORTED)
  188319. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188320. png_handle_tIME(png_ptr, info_ptr, length);
  188321. #endif
  188322. #if defined(PNG_READ_tRNS_SUPPORTED)
  188323. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188324. png_handle_tRNS(png_ptr, info_ptr, length);
  188325. #endif
  188326. #if defined(PNG_READ_zTXt_SUPPORTED)
  188327. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188328. png_handle_zTXt(png_ptr, info_ptr, length);
  188329. #endif
  188330. #if defined(PNG_READ_iTXt_SUPPORTED)
  188331. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188332. png_handle_iTXt(png_ptr, info_ptr, length);
  188333. #endif
  188334. else
  188335. png_handle_unknown(png_ptr, info_ptr, length);
  188336. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188337. }
  188338. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188339. /* free all memory used by the read */
  188340. void PNGAPI
  188341. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188342. png_infopp end_info_ptr_ptr)
  188343. {
  188344. png_structp png_ptr = NULL;
  188345. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188346. #ifdef PNG_USER_MEM_SUPPORTED
  188347. png_free_ptr free_fn;
  188348. png_voidp mem_ptr;
  188349. #endif
  188350. png_debug(1, "in png_destroy_read_struct\n");
  188351. if (png_ptr_ptr != NULL)
  188352. png_ptr = *png_ptr_ptr;
  188353. if (info_ptr_ptr != NULL)
  188354. info_ptr = *info_ptr_ptr;
  188355. if (end_info_ptr_ptr != NULL)
  188356. end_info_ptr = *end_info_ptr_ptr;
  188357. #ifdef PNG_USER_MEM_SUPPORTED
  188358. free_fn = png_ptr->free_fn;
  188359. mem_ptr = png_ptr->mem_ptr;
  188360. #endif
  188361. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188362. if (info_ptr != NULL)
  188363. {
  188364. #if defined(PNG_TEXT_SUPPORTED)
  188365. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188366. #endif
  188367. #ifdef PNG_USER_MEM_SUPPORTED
  188368. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188369. (png_voidp)mem_ptr);
  188370. #else
  188371. png_destroy_struct((png_voidp)info_ptr);
  188372. #endif
  188373. *info_ptr_ptr = NULL;
  188374. }
  188375. if (end_info_ptr != NULL)
  188376. {
  188377. #if defined(PNG_READ_TEXT_SUPPORTED)
  188378. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188379. #endif
  188380. #ifdef PNG_USER_MEM_SUPPORTED
  188381. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188382. (png_voidp)mem_ptr);
  188383. #else
  188384. png_destroy_struct((png_voidp)end_info_ptr);
  188385. #endif
  188386. *end_info_ptr_ptr = NULL;
  188387. }
  188388. if (png_ptr != NULL)
  188389. {
  188390. #ifdef PNG_USER_MEM_SUPPORTED
  188391. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188392. (png_voidp)mem_ptr);
  188393. #else
  188394. png_destroy_struct((png_voidp)png_ptr);
  188395. #endif
  188396. *png_ptr_ptr = NULL;
  188397. }
  188398. }
  188399. /* free all memory used by the read (old method) */
  188400. void /* PRIVATE */
  188401. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188402. {
  188403. #ifdef PNG_SETJMP_SUPPORTED
  188404. jmp_buf tmp_jmp;
  188405. #endif
  188406. png_error_ptr error_fn;
  188407. png_error_ptr warning_fn;
  188408. png_voidp error_ptr;
  188409. #ifdef PNG_USER_MEM_SUPPORTED
  188410. png_free_ptr free_fn;
  188411. #endif
  188412. png_debug(1, "in png_read_destroy\n");
  188413. if (info_ptr != NULL)
  188414. png_info_destroy(png_ptr, info_ptr);
  188415. if (end_info_ptr != NULL)
  188416. png_info_destroy(png_ptr, end_info_ptr);
  188417. png_free(png_ptr, png_ptr->zbuf);
  188418. png_free(png_ptr, png_ptr->big_row_buf);
  188419. png_free(png_ptr, png_ptr->prev_row);
  188420. #if defined(PNG_READ_DITHER_SUPPORTED)
  188421. png_free(png_ptr, png_ptr->palette_lookup);
  188422. png_free(png_ptr, png_ptr->dither_index);
  188423. #endif
  188424. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188425. png_free(png_ptr, png_ptr->gamma_table);
  188426. #endif
  188427. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188428. png_free(png_ptr, png_ptr->gamma_from_1);
  188429. png_free(png_ptr, png_ptr->gamma_to_1);
  188430. #endif
  188431. #ifdef PNG_FREE_ME_SUPPORTED
  188432. if (png_ptr->free_me & PNG_FREE_PLTE)
  188433. png_zfree(png_ptr, png_ptr->palette);
  188434. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188435. #else
  188436. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188437. png_zfree(png_ptr, png_ptr->palette);
  188438. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188439. #endif
  188440. #if defined(PNG_tRNS_SUPPORTED) || \
  188441. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188442. #ifdef PNG_FREE_ME_SUPPORTED
  188443. if (png_ptr->free_me & PNG_FREE_TRNS)
  188444. png_free(png_ptr, png_ptr->trans);
  188445. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188446. #else
  188447. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188448. png_free(png_ptr, png_ptr->trans);
  188449. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188450. #endif
  188451. #endif
  188452. #if defined(PNG_READ_hIST_SUPPORTED)
  188453. #ifdef PNG_FREE_ME_SUPPORTED
  188454. if (png_ptr->free_me & PNG_FREE_HIST)
  188455. png_free(png_ptr, png_ptr->hist);
  188456. png_ptr->free_me &= ~PNG_FREE_HIST;
  188457. #else
  188458. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188459. png_free(png_ptr, png_ptr->hist);
  188460. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188461. #endif
  188462. #endif
  188463. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188464. if (png_ptr->gamma_16_table != NULL)
  188465. {
  188466. int i;
  188467. int istop = (1 << (8 - png_ptr->gamma_shift));
  188468. for (i = 0; i < istop; i++)
  188469. {
  188470. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188471. }
  188472. png_free(png_ptr, png_ptr->gamma_16_table);
  188473. }
  188474. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188475. if (png_ptr->gamma_16_from_1 != NULL)
  188476. {
  188477. int i;
  188478. int istop = (1 << (8 - png_ptr->gamma_shift));
  188479. for (i = 0; i < istop; i++)
  188480. {
  188481. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188482. }
  188483. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188484. }
  188485. if (png_ptr->gamma_16_to_1 != NULL)
  188486. {
  188487. int i;
  188488. int istop = (1 << (8 - png_ptr->gamma_shift));
  188489. for (i = 0; i < istop; i++)
  188490. {
  188491. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188492. }
  188493. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188494. }
  188495. #endif
  188496. #endif
  188497. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188498. png_free(png_ptr, png_ptr->time_buffer);
  188499. #endif
  188500. inflateEnd(&png_ptr->zstream);
  188501. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188502. png_free(png_ptr, png_ptr->save_buffer);
  188503. #endif
  188504. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188505. #ifdef PNG_TEXT_SUPPORTED
  188506. png_free(png_ptr, png_ptr->current_text);
  188507. #endif /* PNG_TEXT_SUPPORTED */
  188508. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188509. /* Save the important info out of the png_struct, in case it is
  188510. * being used again.
  188511. */
  188512. #ifdef PNG_SETJMP_SUPPORTED
  188513. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188514. #endif
  188515. error_fn = png_ptr->error_fn;
  188516. warning_fn = png_ptr->warning_fn;
  188517. error_ptr = png_ptr->error_ptr;
  188518. #ifdef PNG_USER_MEM_SUPPORTED
  188519. free_fn = png_ptr->free_fn;
  188520. #endif
  188521. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188522. png_ptr->error_fn = error_fn;
  188523. png_ptr->warning_fn = warning_fn;
  188524. png_ptr->error_ptr = error_ptr;
  188525. #ifdef PNG_USER_MEM_SUPPORTED
  188526. png_ptr->free_fn = free_fn;
  188527. #endif
  188528. #ifdef PNG_SETJMP_SUPPORTED
  188529. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188530. #endif
  188531. }
  188532. void PNGAPI
  188533. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188534. {
  188535. if(png_ptr == NULL) return;
  188536. png_ptr->read_row_fn = read_row_fn;
  188537. }
  188538. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188539. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188540. void PNGAPI
  188541. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188542. int transforms,
  188543. voidp params)
  188544. {
  188545. int row;
  188546. if(png_ptr == NULL) return;
  188547. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188548. /* invert the alpha channel from opacity to transparency
  188549. */
  188550. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188551. png_set_invert_alpha(png_ptr);
  188552. #endif
  188553. /* png_read_info() gives us all of the information from the
  188554. * PNG file before the first IDAT (image data chunk).
  188555. */
  188556. png_read_info(png_ptr, info_ptr);
  188557. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188558. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188559. /* -------------- image transformations start here ------------------- */
  188560. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188561. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188562. */
  188563. if (transforms & PNG_TRANSFORM_STRIP_16)
  188564. png_set_strip_16(png_ptr);
  188565. #endif
  188566. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188567. /* Strip alpha bytes from the input data without combining with
  188568. * the background (not recommended).
  188569. */
  188570. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188571. png_set_strip_alpha(png_ptr);
  188572. #endif
  188573. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188574. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188575. * byte into separate bytes (useful for paletted and grayscale images).
  188576. */
  188577. if (transforms & PNG_TRANSFORM_PACKING)
  188578. png_set_packing(png_ptr);
  188579. #endif
  188580. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188581. /* Change the order of packed pixels to least significant bit first
  188582. * (not useful if you are using png_set_packing).
  188583. */
  188584. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188585. png_set_packswap(png_ptr);
  188586. #endif
  188587. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188588. /* Expand paletted colors into true RGB triplets
  188589. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188590. * Expand paletted or RGB images with transparency to full alpha
  188591. * channels so the data will be available as RGBA quartets.
  188592. */
  188593. if (transforms & PNG_TRANSFORM_EXPAND)
  188594. if ((png_ptr->bit_depth < 8) ||
  188595. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188596. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188597. png_set_expand(png_ptr);
  188598. #endif
  188599. /* We don't handle background color or gamma transformation or dithering.
  188600. */
  188601. #if defined(PNG_READ_INVERT_SUPPORTED)
  188602. /* invert monochrome files to have 0 as white and 1 as black
  188603. */
  188604. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188605. png_set_invert_mono(png_ptr);
  188606. #endif
  188607. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188608. /* If you want to shift the pixel values from the range [0,255] or
  188609. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188610. * colors were originally in:
  188611. */
  188612. if ((transforms & PNG_TRANSFORM_SHIFT)
  188613. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188614. {
  188615. png_color_8p sig_bit;
  188616. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188617. png_set_shift(png_ptr, sig_bit);
  188618. }
  188619. #endif
  188620. #if defined(PNG_READ_BGR_SUPPORTED)
  188621. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188622. */
  188623. if (transforms & PNG_TRANSFORM_BGR)
  188624. png_set_bgr(png_ptr);
  188625. #endif
  188626. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188627. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188628. */
  188629. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188630. png_set_swap_alpha(png_ptr);
  188631. #endif
  188632. #if defined(PNG_READ_SWAP_SUPPORTED)
  188633. /* swap bytes of 16 bit files to least significant byte first
  188634. */
  188635. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188636. png_set_swap(png_ptr);
  188637. #endif
  188638. /* We don't handle adding filler bytes */
  188639. /* Optional call to gamma correct and add the background to the palette
  188640. * and update info structure. REQUIRED if you are expecting libpng to
  188641. * update the palette for you (i.e., you selected such a transform above).
  188642. */
  188643. png_read_update_info(png_ptr, info_ptr);
  188644. /* -------------- image transformations end here ------------------- */
  188645. #ifdef PNG_FREE_ME_SUPPORTED
  188646. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188647. #endif
  188648. if(info_ptr->row_pointers == NULL)
  188649. {
  188650. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188651. info_ptr->height * png_sizeof(png_bytep));
  188652. #ifdef PNG_FREE_ME_SUPPORTED
  188653. info_ptr->free_me |= PNG_FREE_ROWS;
  188654. #endif
  188655. for (row = 0; row < (int)info_ptr->height; row++)
  188656. {
  188657. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188658. png_get_rowbytes(png_ptr, info_ptr));
  188659. }
  188660. }
  188661. png_read_image(png_ptr, info_ptr->row_pointers);
  188662. info_ptr->valid |= PNG_INFO_IDAT;
  188663. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188664. png_read_end(png_ptr, info_ptr);
  188665. transforms = transforms; /* quiet compiler warnings */
  188666. params = params;
  188667. }
  188668. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188669. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188670. #endif /* PNG_READ_SUPPORTED */
  188671. /*** End of inlined file: pngread.c ***/
  188672. /*** Start of inlined file: pngpread.c ***/
  188673. /* pngpread.c - read a png file in push mode
  188674. *
  188675. * Last changed in libpng 1.2.21 October 4, 2007
  188676. * For conditions of distribution and use, see copyright notice in png.h
  188677. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188678. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188679. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188680. */
  188681. #define PNG_INTERNAL
  188682. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188683. /* push model modes */
  188684. #define PNG_READ_SIG_MODE 0
  188685. #define PNG_READ_CHUNK_MODE 1
  188686. #define PNG_READ_IDAT_MODE 2
  188687. #define PNG_SKIP_MODE 3
  188688. #define PNG_READ_tEXt_MODE 4
  188689. #define PNG_READ_zTXt_MODE 5
  188690. #define PNG_READ_DONE_MODE 6
  188691. #define PNG_READ_iTXt_MODE 7
  188692. #define PNG_ERROR_MODE 8
  188693. void PNGAPI
  188694. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188695. png_bytep buffer, png_size_t buffer_size)
  188696. {
  188697. if(png_ptr == NULL) return;
  188698. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188699. while (png_ptr->buffer_size)
  188700. {
  188701. png_process_some_data(png_ptr, info_ptr);
  188702. }
  188703. }
  188704. /* What we do with the incoming data depends on what we were previously
  188705. * doing before we ran out of data...
  188706. */
  188707. void /* PRIVATE */
  188708. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188709. {
  188710. if(png_ptr == NULL) return;
  188711. switch (png_ptr->process_mode)
  188712. {
  188713. case PNG_READ_SIG_MODE:
  188714. {
  188715. png_push_read_sig(png_ptr, info_ptr);
  188716. break;
  188717. }
  188718. case PNG_READ_CHUNK_MODE:
  188719. {
  188720. png_push_read_chunk(png_ptr, info_ptr);
  188721. break;
  188722. }
  188723. case PNG_READ_IDAT_MODE:
  188724. {
  188725. png_push_read_IDAT(png_ptr);
  188726. break;
  188727. }
  188728. #if defined(PNG_READ_tEXt_SUPPORTED)
  188729. case PNG_READ_tEXt_MODE:
  188730. {
  188731. png_push_read_tEXt(png_ptr, info_ptr);
  188732. break;
  188733. }
  188734. #endif
  188735. #if defined(PNG_READ_zTXt_SUPPORTED)
  188736. case PNG_READ_zTXt_MODE:
  188737. {
  188738. png_push_read_zTXt(png_ptr, info_ptr);
  188739. break;
  188740. }
  188741. #endif
  188742. #if defined(PNG_READ_iTXt_SUPPORTED)
  188743. case PNG_READ_iTXt_MODE:
  188744. {
  188745. png_push_read_iTXt(png_ptr, info_ptr);
  188746. break;
  188747. }
  188748. #endif
  188749. case PNG_SKIP_MODE:
  188750. {
  188751. png_push_crc_finish(png_ptr);
  188752. break;
  188753. }
  188754. default:
  188755. {
  188756. png_ptr->buffer_size = 0;
  188757. break;
  188758. }
  188759. }
  188760. }
  188761. /* Read any remaining signature bytes from the stream and compare them with
  188762. * the correct PNG signature. It is possible that this routine is called
  188763. * with bytes already read from the signature, either because they have been
  188764. * checked by the calling application, or because of multiple calls to this
  188765. * routine.
  188766. */
  188767. void /* PRIVATE */
  188768. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188769. {
  188770. png_size_t num_checked = png_ptr->sig_bytes,
  188771. num_to_check = 8 - num_checked;
  188772. if (png_ptr->buffer_size < num_to_check)
  188773. {
  188774. num_to_check = png_ptr->buffer_size;
  188775. }
  188776. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188777. num_to_check);
  188778. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188779. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188780. {
  188781. if (num_checked < 4 &&
  188782. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188783. png_error(png_ptr, "Not a PNG file");
  188784. else
  188785. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188786. }
  188787. else
  188788. {
  188789. if (png_ptr->sig_bytes >= 8)
  188790. {
  188791. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188792. }
  188793. }
  188794. }
  188795. void /* PRIVATE */
  188796. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188797. {
  188798. #ifdef PNG_USE_LOCAL_ARRAYS
  188799. PNG_CONST PNG_IHDR;
  188800. PNG_CONST PNG_IDAT;
  188801. PNG_CONST PNG_IEND;
  188802. PNG_CONST PNG_PLTE;
  188803. #if defined(PNG_READ_bKGD_SUPPORTED)
  188804. PNG_CONST PNG_bKGD;
  188805. #endif
  188806. #if defined(PNG_READ_cHRM_SUPPORTED)
  188807. PNG_CONST PNG_cHRM;
  188808. #endif
  188809. #if defined(PNG_READ_gAMA_SUPPORTED)
  188810. PNG_CONST PNG_gAMA;
  188811. #endif
  188812. #if defined(PNG_READ_hIST_SUPPORTED)
  188813. PNG_CONST PNG_hIST;
  188814. #endif
  188815. #if defined(PNG_READ_iCCP_SUPPORTED)
  188816. PNG_CONST PNG_iCCP;
  188817. #endif
  188818. #if defined(PNG_READ_iTXt_SUPPORTED)
  188819. PNG_CONST PNG_iTXt;
  188820. #endif
  188821. #if defined(PNG_READ_oFFs_SUPPORTED)
  188822. PNG_CONST PNG_oFFs;
  188823. #endif
  188824. #if defined(PNG_READ_pCAL_SUPPORTED)
  188825. PNG_CONST PNG_pCAL;
  188826. #endif
  188827. #if defined(PNG_READ_pHYs_SUPPORTED)
  188828. PNG_CONST PNG_pHYs;
  188829. #endif
  188830. #if defined(PNG_READ_sBIT_SUPPORTED)
  188831. PNG_CONST PNG_sBIT;
  188832. #endif
  188833. #if defined(PNG_READ_sCAL_SUPPORTED)
  188834. PNG_CONST PNG_sCAL;
  188835. #endif
  188836. #if defined(PNG_READ_sRGB_SUPPORTED)
  188837. PNG_CONST PNG_sRGB;
  188838. #endif
  188839. #if defined(PNG_READ_sPLT_SUPPORTED)
  188840. PNG_CONST PNG_sPLT;
  188841. #endif
  188842. #if defined(PNG_READ_tEXt_SUPPORTED)
  188843. PNG_CONST PNG_tEXt;
  188844. #endif
  188845. #if defined(PNG_READ_tIME_SUPPORTED)
  188846. PNG_CONST PNG_tIME;
  188847. #endif
  188848. #if defined(PNG_READ_tRNS_SUPPORTED)
  188849. PNG_CONST PNG_tRNS;
  188850. #endif
  188851. #if defined(PNG_READ_zTXt_SUPPORTED)
  188852. PNG_CONST PNG_zTXt;
  188853. #endif
  188854. #endif /* PNG_USE_LOCAL_ARRAYS */
  188855. /* First we make sure we have enough data for the 4 byte chunk name
  188856. * and the 4 byte chunk length before proceeding with decoding the
  188857. * chunk data. To fully decode each of these chunks, we also make
  188858. * sure we have enough data in the buffer for the 4 byte CRC at the
  188859. * end of every chunk (except IDAT, which is handled separately).
  188860. */
  188861. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188862. {
  188863. png_byte chunk_length[4];
  188864. if (png_ptr->buffer_size < 8)
  188865. {
  188866. png_push_save_buffer(png_ptr);
  188867. return;
  188868. }
  188869. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188870. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188871. png_reset_crc(png_ptr);
  188872. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188873. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188874. }
  188875. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188876. if(png_ptr->mode & PNG_AFTER_IDAT)
  188877. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188878. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188879. {
  188880. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188881. {
  188882. png_push_save_buffer(png_ptr);
  188883. return;
  188884. }
  188885. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188886. }
  188887. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188888. {
  188889. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188890. {
  188891. png_push_save_buffer(png_ptr);
  188892. return;
  188893. }
  188894. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188895. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188896. png_push_have_end(png_ptr, info_ptr);
  188897. }
  188898. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188899. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188900. {
  188901. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188902. {
  188903. png_push_save_buffer(png_ptr);
  188904. return;
  188905. }
  188906. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188907. png_ptr->mode |= PNG_HAVE_IDAT;
  188908. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188909. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188910. png_ptr->mode |= PNG_HAVE_PLTE;
  188911. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188912. {
  188913. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188914. png_error(png_ptr, "Missing IHDR before IDAT");
  188915. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188916. !(png_ptr->mode & PNG_HAVE_PLTE))
  188917. png_error(png_ptr, "Missing PLTE before IDAT");
  188918. }
  188919. }
  188920. #endif
  188921. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188922. {
  188923. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188924. {
  188925. png_push_save_buffer(png_ptr);
  188926. return;
  188927. }
  188928. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188929. }
  188930. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188931. {
  188932. /* If we reach an IDAT chunk, this means we have read all of the
  188933. * header chunks, and we can start reading the image (or if this
  188934. * is called after the image has been read - we have an error).
  188935. */
  188936. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188937. png_error(png_ptr, "Missing IHDR before IDAT");
  188938. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188939. !(png_ptr->mode & PNG_HAVE_PLTE))
  188940. png_error(png_ptr, "Missing PLTE before IDAT");
  188941. if (png_ptr->mode & PNG_HAVE_IDAT)
  188942. {
  188943. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188944. if (png_ptr->push_length == 0)
  188945. return;
  188946. if (png_ptr->mode & PNG_AFTER_IDAT)
  188947. png_error(png_ptr, "Too many IDAT's found");
  188948. }
  188949. png_ptr->idat_size = png_ptr->push_length;
  188950. png_ptr->mode |= PNG_HAVE_IDAT;
  188951. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188952. png_push_have_info(png_ptr, info_ptr);
  188953. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188954. png_ptr->zstream.next_out = png_ptr->row_buf;
  188955. return;
  188956. }
  188957. #if defined(PNG_READ_gAMA_SUPPORTED)
  188958. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188959. {
  188960. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188961. {
  188962. png_push_save_buffer(png_ptr);
  188963. return;
  188964. }
  188965. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188966. }
  188967. #endif
  188968. #if defined(PNG_READ_sBIT_SUPPORTED)
  188969. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188970. {
  188971. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188972. {
  188973. png_push_save_buffer(png_ptr);
  188974. return;
  188975. }
  188976. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188977. }
  188978. #endif
  188979. #if defined(PNG_READ_cHRM_SUPPORTED)
  188980. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188981. {
  188982. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188983. {
  188984. png_push_save_buffer(png_ptr);
  188985. return;
  188986. }
  188987. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188988. }
  188989. #endif
  188990. #if defined(PNG_READ_sRGB_SUPPORTED)
  188991. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188992. {
  188993. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188994. {
  188995. png_push_save_buffer(png_ptr);
  188996. return;
  188997. }
  188998. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188999. }
  189000. #endif
  189001. #if defined(PNG_READ_iCCP_SUPPORTED)
  189002. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  189003. {
  189004. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189005. {
  189006. png_push_save_buffer(png_ptr);
  189007. return;
  189008. }
  189009. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  189010. }
  189011. #endif
  189012. #if defined(PNG_READ_sPLT_SUPPORTED)
  189013. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  189014. {
  189015. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189016. {
  189017. png_push_save_buffer(png_ptr);
  189018. return;
  189019. }
  189020. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  189021. }
  189022. #endif
  189023. #if defined(PNG_READ_tRNS_SUPPORTED)
  189024. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  189025. {
  189026. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189027. {
  189028. png_push_save_buffer(png_ptr);
  189029. return;
  189030. }
  189031. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  189032. }
  189033. #endif
  189034. #if defined(PNG_READ_bKGD_SUPPORTED)
  189035. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  189036. {
  189037. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189038. {
  189039. png_push_save_buffer(png_ptr);
  189040. return;
  189041. }
  189042. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  189043. }
  189044. #endif
  189045. #if defined(PNG_READ_hIST_SUPPORTED)
  189046. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  189047. {
  189048. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189049. {
  189050. png_push_save_buffer(png_ptr);
  189051. return;
  189052. }
  189053. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  189054. }
  189055. #endif
  189056. #if defined(PNG_READ_pHYs_SUPPORTED)
  189057. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  189058. {
  189059. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189060. {
  189061. png_push_save_buffer(png_ptr);
  189062. return;
  189063. }
  189064. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  189065. }
  189066. #endif
  189067. #if defined(PNG_READ_oFFs_SUPPORTED)
  189068. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  189069. {
  189070. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189071. {
  189072. png_push_save_buffer(png_ptr);
  189073. return;
  189074. }
  189075. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  189076. }
  189077. #endif
  189078. #if defined(PNG_READ_pCAL_SUPPORTED)
  189079. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  189080. {
  189081. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189082. {
  189083. png_push_save_buffer(png_ptr);
  189084. return;
  189085. }
  189086. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  189087. }
  189088. #endif
  189089. #if defined(PNG_READ_sCAL_SUPPORTED)
  189090. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  189091. {
  189092. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189093. {
  189094. png_push_save_buffer(png_ptr);
  189095. return;
  189096. }
  189097. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  189098. }
  189099. #endif
  189100. #if defined(PNG_READ_tIME_SUPPORTED)
  189101. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  189102. {
  189103. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189104. {
  189105. png_push_save_buffer(png_ptr);
  189106. return;
  189107. }
  189108. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  189109. }
  189110. #endif
  189111. #if defined(PNG_READ_tEXt_SUPPORTED)
  189112. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  189113. {
  189114. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189115. {
  189116. png_push_save_buffer(png_ptr);
  189117. return;
  189118. }
  189119. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189120. }
  189121. #endif
  189122. #if defined(PNG_READ_zTXt_SUPPORTED)
  189123. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189124. {
  189125. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189126. {
  189127. png_push_save_buffer(png_ptr);
  189128. return;
  189129. }
  189130. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189131. }
  189132. #endif
  189133. #if defined(PNG_READ_iTXt_SUPPORTED)
  189134. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189135. {
  189136. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189137. {
  189138. png_push_save_buffer(png_ptr);
  189139. return;
  189140. }
  189141. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189142. }
  189143. #endif
  189144. else
  189145. {
  189146. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189147. {
  189148. png_push_save_buffer(png_ptr);
  189149. return;
  189150. }
  189151. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189152. }
  189153. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189154. }
  189155. void /* PRIVATE */
  189156. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189157. {
  189158. png_ptr->process_mode = PNG_SKIP_MODE;
  189159. png_ptr->skip_length = skip;
  189160. }
  189161. void /* PRIVATE */
  189162. png_push_crc_finish(png_structp png_ptr)
  189163. {
  189164. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189165. {
  189166. png_size_t save_size;
  189167. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189168. save_size = (png_size_t)png_ptr->skip_length;
  189169. else
  189170. save_size = png_ptr->save_buffer_size;
  189171. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189172. png_ptr->skip_length -= save_size;
  189173. png_ptr->buffer_size -= save_size;
  189174. png_ptr->save_buffer_size -= save_size;
  189175. png_ptr->save_buffer_ptr += save_size;
  189176. }
  189177. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189178. {
  189179. png_size_t save_size;
  189180. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189181. save_size = (png_size_t)png_ptr->skip_length;
  189182. else
  189183. save_size = png_ptr->current_buffer_size;
  189184. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189185. png_ptr->skip_length -= save_size;
  189186. png_ptr->buffer_size -= save_size;
  189187. png_ptr->current_buffer_size -= save_size;
  189188. png_ptr->current_buffer_ptr += save_size;
  189189. }
  189190. if (!png_ptr->skip_length)
  189191. {
  189192. if (png_ptr->buffer_size < 4)
  189193. {
  189194. png_push_save_buffer(png_ptr);
  189195. return;
  189196. }
  189197. png_crc_finish(png_ptr, 0);
  189198. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189199. }
  189200. }
  189201. void PNGAPI
  189202. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189203. {
  189204. png_bytep ptr;
  189205. if(png_ptr == NULL) return;
  189206. ptr = buffer;
  189207. if (png_ptr->save_buffer_size)
  189208. {
  189209. png_size_t save_size;
  189210. if (length < png_ptr->save_buffer_size)
  189211. save_size = length;
  189212. else
  189213. save_size = png_ptr->save_buffer_size;
  189214. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189215. length -= save_size;
  189216. ptr += save_size;
  189217. png_ptr->buffer_size -= save_size;
  189218. png_ptr->save_buffer_size -= save_size;
  189219. png_ptr->save_buffer_ptr += save_size;
  189220. }
  189221. if (length && png_ptr->current_buffer_size)
  189222. {
  189223. png_size_t save_size;
  189224. if (length < png_ptr->current_buffer_size)
  189225. save_size = length;
  189226. else
  189227. save_size = png_ptr->current_buffer_size;
  189228. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189229. png_ptr->buffer_size -= save_size;
  189230. png_ptr->current_buffer_size -= save_size;
  189231. png_ptr->current_buffer_ptr += save_size;
  189232. }
  189233. }
  189234. void /* PRIVATE */
  189235. png_push_save_buffer(png_structp png_ptr)
  189236. {
  189237. if (png_ptr->save_buffer_size)
  189238. {
  189239. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189240. {
  189241. png_size_t i,istop;
  189242. png_bytep sp;
  189243. png_bytep dp;
  189244. istop = png_ptr->save_buffer_size;
  189245. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189246. i < istop; i++, sp++, dp++)
  189247. {
  189248. *dp = *sp;
  189249. }
  189250. }
  189251. }
  189252. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189253. png_ptr->save_buffer_max)
  189254. {
  189255. png_size_t new_max;
  189256. png_bytep old_buffer;
  189257. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189258. (png_ptr->current_buffer_size + 256))
  189259. {
  189260. png_error(png_ptr, "Potential overflow of save_buffer");
  189261. }
  189262. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189263. old_buffer = png_ptr->save_buffer;
  189264. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189265. (png_uint_32)new_max);
  189266. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189267. png_free(png_ptr, old_buffer);
  189268. png_ptr->save_buffer_max = new_max;
  189269. }
  189270. if (png_ptr->current_buffer_size)
  189271. {
  189272. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189273. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189274. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189275. png_ptr->current_buffer_size = 0;
  189276. }
  189277. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189278. png_ptr->buffer_size = 0;
  189279. }
  189280. void /* PRIVATE */
  189281. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189282. png_size_t buffer_length)
  189283. {
  189284. png_ptr->current_buffer = buffer;
  189285. png_ptr->current_buffer_size = buffer_length;
  189286. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189287. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189288. }
  189289. void /* PRIVATE */
  189290. png_push_read_IDAT(png_structp png_ptr)
  189291. {
  189292. #ifdef PNG_USE_LOCAL_ARRAYS
  189293. PNG_CONST PNG_IDAT;
  189294. #endif
  189295. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189296. {
  189297. png_byte chunk_length[4];
  189298. if (png_ptr->buffer_size < 8)
  189299. {
  189300. png_push_save_buffer(png_ptr);
  189301. return;
  189302. }
  189303. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189304. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189305. png_reset_crc(png_ptr);
  189306. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189307. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189308. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189309. {
  189310. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189311. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189312. png_error(png_ptr, "Not enough compressed data");
  189313. return;
  189314. }
  189315. png_ptr->idat_size = png_ptr->push_length;
  189316. }
  189317. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189318. {
  189319. png_size_t save_size;
  189320. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189321. {
  189322. save_size = (png_size_t)png_ptr->idat_size;
  189323. /* check for overflow */
  189324. if((png_uint_32)save_size != png_ptr->idat_size)
  189325. png_error(png_ptr, "save_size overflowed in pngpread");
  189326. }
  189327. else
  189328. save_size = png_ptr->save_buffer_size;
  189329. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189330. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189331. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189332. png_ptr->idat_size -= save_size;
  189333. png_ptr->buffer_size -= save_size;
  189334. png_ptr->save_buffer_size -= save_size;
  189335. png_ptr->save_buffer_ptr += save_size;
  189336. }
  189337. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189338. {
  189339. png_size_t save_size;
  189340. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189341. {
  189342. save_size = (png_size_t)png_ptr->idat_size;
  189343. /* check for overflow */
  189344. if((png_uint_32)save_size != png_ptr->idat_size)
  189345. png_error(png_ptr, "save_size overflowed in pngpread");
  189346. }
  189347. else
  189348. save_size = png_ptr->current_buffer_size;
  189349. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189350. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189351. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189352. png_ptr->idat_size -= save_size;
  189353. png_ptr->buffer_size -= save_size;
  189354. png_ptr->current_buffer_size -= save_size;
  189355. png_ptr->current_buffer_ptr += save_size;
  189356. }
  189357. if (!png_ptr->idat_size)
  189358. {
  189359. if (png_ptr->buffer_size < 4)
  189360. {
  189361. png_push_save_buffer(png_ptr);
  189362. return;
  189363. }
  189364. png_crc_finish(png_ptr, 0);
  189365. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189366. png_ptr->mode |= PNG_AFTER_IDAT;
  189367. }
  189368. }
  189369. void /* PRIVATE */
  189370. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189371. png_size_t buffer_length)
  189372. {
  189373. int ret;
  189374. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189375. png_error(png_ptr, "Extra compression data");
  189376. png_ptr->zstream.next_in = buffer;
  189377. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189378. for(;;)
  189379. {
  189380. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189381. if (ret != Z_OK)
  189382. {
  189383. if (ret == Z_STREAM_END)
  189384. {
  189385. if (png_ptr->zstream.avail_in)
  189386. png_error(png_ptr, "Extra compressed data");
  189387. if (!(png_ptr->zstream.avail_out))
  189388. {
  189389. png_push_process_row(png_ptr);
  189390. }
  189391. png_ptr->mode |= PNG_AFTER_IDAT;
  189392. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189393. break;
  189394. }
  189395. else if (ret == Z_BUF_ERROR)
  189396. break;
  189397. else
  189398. png_error(png_ptr, "Decompression Error");
  189399. }
  189400. if (!(png_ptr->zstream.avail_out))
  189401. {
  189402. if ((
  189403. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189404. png_ptr->interlaced && png_ptr->pass > 6) ||
  189405. (!png_ptr->interlaced &&
  189406. #endif
  189407. png_ptr->row_number == png_ptr->num_rows))
  189408. {
  189409. if (png_ptr->zstream.avail_in)
  189410. {
  189411. png_warning(png_ptr, "Too much data in IDAT chunks");
  189412. }
  189413. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189414. break;
  189415. }
  189416. png_push_process_row(png_ptr);
  189417. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189418. png_ptr->zstream.next_out = png_ptr->row_buf;
  189419. }
  189420. else
  189421. break;
  189422. }
  189423. }
  189424. void /* PRIVATE */
  189425. png_push_process_row(png_structp png_ptr)
  189426. {
  189427. png_ptr->row_info.color_type = png_ptr->color_type;
  189428. png_ptr->row_info.width = png_ptr->iwidth;
  189429. png_ptr->row_info.channels = png_ptr->channels;
  189430. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189431. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189432. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189433. png_ptr->row_info.width);
  189434. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189435. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189436. (int)(png_ptr->row_buf[0]));
  189437. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189438. png_ptr->rowbytes + 1);
  189439. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189440. png_do_read_transformations(png_ptr);
  189441. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189442. /* blow up interlaced rows to full size */
  189443. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189444. {
  189445. if (png_ptr->pass < 6)
  189446. /* old interface (pre-1.0.9):
  189447. png_do_read_interlace(&(png_ptr->row_info),
  189448. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189449. */
  189450. png_do_read_interlace(png_ptr);
  189451. switch (png_ptr->pass)
  189452. {
  189453. case 0:
  189454. {
  189455. int i;
  189456. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189457. {
  189458. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189459. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189460. }
  189461. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189462. {
  189463. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189464. {
  189465. png_push_have_row(png_ptr, png_bytep_NULL);
  189466. png_read_push_finish_row(png_ptr);
  189467. }
  189468. }
  189469. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189470. {
  189471. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189472. {
  189473. png_push_have_row(png_ptr, png_bytep_NULL);
  189474. png_read_push_finish_row(png_ptr);
  189475. }
  189476. }
  189477. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189478. {
  189479. png_push_have_row(png_ptr, png_bytep_NULL);
  189480. png_read_push_finish_row(png_ptr);
  189481. }
  189482. break;
  189483. }
  189484. case 1:
  189485. {
  189486. int i;
  189487. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189488. {
  189489. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189490. png_read_push_finish_row(png_ptr);
  189491. }
  189492. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189493. {
  189494. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189495. {
  189496. png_push_have_row(png_ptr, png_bytep_NULL);
  189497. png_read_push_finish_row(png_ptr);
  189498. }
  189499. }
  189500. break;
  189501. }
  189502. case 2:
  189503. {
  189504. int i;
  189505. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189506. {
  189507. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189508. png_read_push_finish_row(png_ptr);
  189509. }
  189510. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189511. {
  189512. png_push_have_row(png_ptr, png_bytep_NULL);
  189513. png_read_push_finish_row(png_ptr);
  189514. }
  189515. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189516. {
  189517. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189518. {
  189519. png_push_have_row(png_ptr, png_bytep_NULL);
  189520. png_read_push_finish_row(png_ptr);
  189521. }
  189522. }
  189523. break;
  189524. }
  189525. case 3:
  189526. {
  189527. int i;
  189528. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189529. {
  189530. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189531. png_read_push_finish_row(png_ptr);
  189532. }
  189533. if (png_ptr->pass == 4) /* skip top two generated rows */
  189534. {
  189535. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189536. {
  189537. png_push_have_row(png_ptr, png_bytep_NULL);
  189538. png_read_push_finish_row(png_ptr);
  189539. }
  189540. }
  189541. break;
  189542. }
  189543. case 4:
  189544. {
  189545. int i;
  189546. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189547. {
  189548. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189549. png_read_push_finish_row(png_ptr);
  189550. }
  189551. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189552. {
  189553. png_push_have_row(png_ptr, png_bytep_NULL);
  189554. png_read_push_finish_row(png_ptr);
  189555. }
  189556. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189557. {
  189558. png_push_have_row(png_ptr, png_bytep_NULL);
  189559. png_read_push_finish_row(png_ptr);
  189560. }
  189561. break;
  189562. }
  189563. case 5:
  189564. {
  189565. int i;
  189566. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189567. {
  189568. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189569. png_read_push_finish_row(png_ptr);
  189570. }
  189571. if (png_ptr->pass == 6) /* skip top generated row */
  189572. {
  189573. png_push_have_row(png_ptr, png_bytep_NULL);
  189574. png_read_push_finish_row(png_ptr);
  189575. }
  189576. break;
  189577. }
  189578. case 6:
  189579. {
  189580. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189581. png_read_push_finish_row(png_ptr);
  189582. if (png_ptr->pass != 6)
  189583. break;
  189584. png_push_have_row(png_ptr, png_bytep_NULL);
  189585. png_read_push_finish_row(png_ptr);
  189586. }
  189587. }
  189588. }
  189589. else
  189590. #endif
  189591. {
  189592. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189593. png_read_push_finish_row(png_ptr);
  189594. }
  189595. }
  189596. void /* PRIVATE */
  189597. png_read_push_finish_row(png_structp png_ptr)
  189598. {
  189599. #ifdef PNG_USE_LOCAL_ARRAYS
  189600. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189601. /* start of interlace block */
  189602. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189603. /* offset to next interlace block */
  189604. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189605. /* start of interlace block in the y direction */
  189606. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189607. /* offset to next interlace block in the y direction */
  189608. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189609. /* Height of interlace block. This is not currently used - if you need
  189610. * it, uncomment it here and in png.h
  189611. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189612. */
  189613. #endif
  189614. png_ptr->row_number++;
  189615. if (png_ptr->row_number < png_ptr->num_rows)
  189616. return;
  189617. if (png_ptr->interlaced)
  189618. {
  189619. png_ptr->row_number = 0;
  189620. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189621. png_ptr->rowbytes + 1);
  189622. do
  189623. {
  189624. png_ptr->pass++;
  189625. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189626. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189627. (png_ptr->pass == 5 && png_ptr->width < 2))
  189628. png_ptr->pass++;
  189629. if (png_ptr->pass > 7)
  189630. png_ptr->pass--;
  189631. if (png_ptr->pass >= 7)
  189632. break;
  189633. png_ptr->iwidth = (png_ptr->width +
  189634. png_pass_inc[png_ptr->pass] - 1 -
  189635. png_pass_start[png_ptr->pass]) /
  189636. png_pass_inc[png_ptr->pass];
  189637. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189638. png_ptr->iwidth) + 1;
  189639. if (png_ptr->transformations & PNG_INTERLACE)
  189640. break;
  189641. png_ptr->num_rows = (png_ptr->height +
  189642. png_pass_yinc[png_ptr->pass] - 1 -
  189643. png_pass_ystart[png_ptr->pass]) /
  189644. png_pass_yinc[png_ptr->pass];
  189645. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189646. }
  189647. }
  189648. #if defined(PNG_READ_tEXt_SUPPORTED)
  189649. void /* PRIVATE */
  189650. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189651. length)
  189652. {
  189653. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189654. {
  189655. png_error(png_ptr, "Out of place tEXt");
  189656. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189657. }
  189658. #ifdef PNG_MAX_MALLOC_64K
  189659. png_ptr->skip_length = 0; /* This may not be necessary */
  189660. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189661. {
  189662. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189663. png_ptr->skip_length = length - (png_uint_32)65535L;
  189664. length = (png_uint_32)65535L;
  189665. }
  189666. #endif
  189667. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189668. (png_uint_32)(length+1));
  189669. png_ptr->current_text[length] = '\0';
  189670. png_ptr->current_text_ptr = png_ptr->current_text;
  189671. png_ptr->current_text_size = (png_size_t)length;
  189672. png_ptr->current_text_left = (png_size_t)length;
  189673. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189674. }
  189675. void /* PRIVATE */
  189676. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189677. {
  189678. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189679. {
  189680. png_size_t text_size;
  189681. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189682. text_size = png_ptr->buffer_size;
  189683. else
  189684. text_size = png_ptr->current_text_left;
  189685. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189686. png_ptr->current_text_left -= text_size;
  189687. png_ptr->current_text_ptr += text_size;
  189688. }
  189689. if (!(png_ptr->current_text_left))
  189690. {
  189691. png_textp text_ptr;
  189692. png_charp text;
  189693. png_charp key;
  189694. int ret;
  189695. if (png_ptr->buffer_size < 4)
  189696. {
  189697. png_push_save_buffer(png_ptr);
  189698. return;
  189699. }
  189700. png_push_crc_finish(png_ptr);
  189701. #if defined(PNG_MAX_MALLOC_64K)
  189702. if (png_ptr->skip_length)
  189703. return;
  189704. #endif
  189705. key = png_ptr->current_text;
  189706. for (text = key; *text; text++)
  189707. /* empty loop */ ;
  189708. if (text < key + png_ptr->current_text_size)
  189709. text++;
  189710. text_ptr = (png_textp)png_malloc(png_ptr,
  189711. (png_uint_32)png_sizeof(png_text));
  189712. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189713. text_ptr->key = key;
  189714. #ifdef PNG_iTXt_SUPPORTED
  189715. text_ptr->lang = NULL;
  189716. text_ptr->lang_key = NULL;
  189717. #endif
  189718. text_ptr->text = text;
  189719. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189720. png_free(png_ptr, key);
  189721. png_free(png_ptr, text_ptr);
  189722. png_ptr->current_text = NULL;
  189723. if (ret)
  189724. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189725. }
  189726. }
  189727. #endif
  189728. #if defined(PNG_READ_zTXt_SUPPORTED)
  189729. void /* PRIVATE */
  189730. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189731. length)
  189732. {
  189733. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189734. {
  189735. png_error(png_ptr, "Out of place zTXt");
  189736. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189737. }
  189738. #ifdef PNG_MAX_MALLOC_64K
  189739. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189740. * to be able to store the uncompressed data. Actually, the threshold
  189741. * is probably around 32K, but it isn't as definite as 64K is.
  189742. */
  189743. if (length > (png_uint_32)65535L)
  189744. {
  189745. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189746. png_push_crc_skip(png_ptr, length);
  189747. return;
  189748. }
  189749. #endif
  189750. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189751. (png_uint_32)(length+1));
  189752. png_ptr->current_text[length] = '\0';
  189753. png_ptr->current_text_ptr = png_ptr->current_text;
  189754. png_ptr->current_text_size = (png_size_t)length;
  189755. png_ptr->current_text_left = (png_size_t)length;
  189756. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189757. }
  189758. void /* PRIVATE */
  189759. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189760. {
  189761. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189762. {
  189763. png_size_t text_size;
  189764. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189765. text_size = png_ptr->buffer_size;
  189766. else
  189767. text_size = png_ptr->current_text_left;
  189768. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189769. png_ptr->current_text_left -= text_size;
  189770. png_ptr->current_text_ptr += text_size;
  189771. }
  189772. if (!(png_ptr->current_text_left))
  189773. {
  189774. png_textp text_ptr;
  189775. png_charp text;
  189776. png_charp key;
  189777. int ret;
  189778. png_size_t text_size, key_size;
  189779. if (png_ptr->buffer_size < 4)
  189780. {
  189781. png_push_save_buffer(png_ptr);
  189782. return;
  189783. }
  189784. png_push_crc_finish(png_ptr);
  189785. key = png_ptr->current_text;
  189786. for (text = key; *text; text++)
  189787. /* empty loop */ ;
  189788. /* zTXt can't have zero text */
  189789. if (text >= key + png_ptr->current_text_size)
  189790. {
  189791. png_ptr->current_text = NULL;
  189792. png_free(png_ptr, key);
  189793. return;
  189794. }
  189795. text++;
  189796. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189797. {
  189798. png_ptr->current_text = NULL;
  189799. png_free(png_ptr, key);
  189800. return;
  189801. }
  189802. text++;
  189803. png_ptr->zstream.next_in = (png_bytep )text;
  189804. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189805. (text - key));
  189806. png_ptr->zstream.next_out = png_ptr->zbuf;
  189807. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189808. key_size = text - key;
  189809. text_size = 0;
  189810. text = NULL;
  189811. ret = Z_STREAM_END;
  189812. while (png_ptr->zstream.avail_in)
  189813. {
  189814. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189815. if (ret != Z_OK && ret != Z_STREAM_END)
  189816. {
  189817. inflateReset(&png_ptr->zstream);
  189818. png_ptr->zstream.avail_in = 0;
  189819. png_ptr->current_text = NULL;
  189820. png_free(png_ptr, key);
  189821. png_free(png_ptr, text);
  189822. return;
  189823. }
  189824. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189825. {
  189826. if (text == NULL)
  189827. {
  189828. text = (png_charp)png_malloc(png_ptr,
  189829. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189830. + key_size + 1));
  189831. png_memcpy(text + key_size, png_ptr->zbuf,
  189832. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189833. png_memcpy(text, key, key_size);
  189834. text_size = key_size + png_ptr->zbuf_size -
  189835. png_ptr->zstream.avail_out;
  189836. *(text + text_size) = '\0';
  189837. }
  189838. else
  189839. {
  189840. png_charp tmp;
  189841. tmp = text;
  189842. text = (png_charp)png_malloc(png_ptr, text_size +
  189843. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189844. + 1));
  189845. png_memcpy(text, tmp, text_size);
  189846. png_free(png_ptr, tmp);
  189847. png_memcpy(text + text_size, png_ptr->zbuf,
  189848. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189849. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189850. *(text + text_size) = '\0';
  189851. }
  189852. if (ret != Z_STREAM_END)
  189853. {
  189854. png_ptr->zstream.next_out = png_ptr->zbuf;
  189855. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189856. }
  189857. }
  189858. else
  189859. {
  189860. break;
  189861. }
  189862. if (ret == Z_STREAM_END)
  189863. break;
  189864. }
  189865. inflateReset(&png_ptr->zstream);
  189866. png_ptr->zstream.avail_in = 0;
  189867. if (ret != Z_STREAM_END)
  189868. {
  189869. png_ptr->current_text = NULL;
  189870. png_free(png_ptr, key);
  189871. png_free(png_ptr, text);
  189872. return;
  189873. }
  189874. png_ptr->current_text = NULL;
  189875. png_free(png_ptr, key);
  189876. key = text;
  189877. text += key_size;
  189878. text_ptr = (png_textp)png_malloc(png_ptr,
  189879. (png_uint_32)png_sizeof(png_text));
  189880. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189881. text_ptr->key = key;
  189882. #ifdef PNG_iTXt_SUPPORTED
  189883. text_ptr->lang = NULL;
  189884. text_ptr->lang_key = NULL;
  189885. #endif
  189886. text_ptr->text = text;
  189887. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189888. png_free(png_ptr, key);
  189889. png_free(png_ptr, text_ptr);
  189890. if (ret)
  189891. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189892. }
  189893. }
  189894. #endif
  189895. #if defined(PNG_READ_iTXt_SUPPORTED)
  189896. void /* PRIVATE */
  189897. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189898. length)
  189899. {
  189900. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189901. {
  189902. png_error(png_ptr, "Out of place iTXt");
  189903. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189904. }
  189905. #ifdef PNG_MAX_MALLOC_64K
  189906. png_ptr->skip_length = 0; /* This may not be necessary */
  189907. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189908. {
  189909. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189910. png_ptr->skip_length = length - (png_uint_32)65535L;
  189911. length = (png_uint_32)65535L;
  189912. }
  189913. #endif
  189914. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189915. (png_uint_32)(length+1));
  189916. png_ptr->current_text[length] = '\0';
  189917. png_ptr->current_text_ptr = png_ptr->current_text;
  189918. png_ptr->current_text_size = (png_size_t)length;
  189919. png_ptr->current_text_left = (png_size_t)length;
  189920. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189921. }
  189922. void /* PRIVATE */
  189923. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189924. {
  189925. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189926. {
  189927. png_size_t text_size;
  189928. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189929. text_size = png_ptr->buffer_size;
  189930. else
  189931. text_size = png_ptr->current_text_left;
  189932. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189933. png_ptr->current_text_left -= text_size;
  189934. png_ptr->current_text_ptr += text_size;
  189935. }
  189936. if (!(png_ptr->current_text_left))
  189937. {
  189938. png_textp text_ptr;
  189939. png_charp key;
  189940. int comp_flag;
  189941. png_charp lang;
  189942. png_charp lang_key;
  189943. png_charp text;
  189944. int ret;
  189945. if (png_ptr->buffer_size < 4)
  189946. {
  189947. png_push_save_buffer(png_ptr);
  189948. return;
  189949. }
  189950. png_push_crc_finish(png_ptr);
  189951. #if defined(PNG_MAX_MALLOC_64K)
  189952. if (png_ptr->skip_length)
  189953. return;
  189954. #endif
  189955. key = png_ptr->current_text;
  189956. for (lang = key; *lang; lang++)
  189957. /* empty loop */ ;
  189958. if (lang < key + png_ptr->current_text_size - 3)
  189959. lang++;
  189960. comp_flag = *lang++;
  189961. lang++; /* skip comp_type, always zero */
  189962. for (lang_key = lang; *lang_key; lang_key++)
  189963. /* empty loop */ ;
  189964. lang_key++; /* skip NUL separator */
  189965. text=lang_key;
  189966. if (lang_key < key + png_ptr->current_text_size - 1)
  189967. {
  189968. for (; *text; text++)
  189969. /* empty loop */ ;
  189970. }
  189971. if (text < key + png_ptr->current_text_size)
  189972. text++;
  189973. text_ptr = (png_textp)png_malloc(png_ptr,
  189974. (png_uint_32)png_sizeof(png_text));
  189975. text_ptr->compression = comp_flag + 2;
  189976. text_ptr->key = key;
  189977. text_ptr->lang = lang;
  189978. text_ptr->lang_key = lang_key;
  189979. text_ptr->text = text;
  189980. text_ptr->text_length = 0;
  189981. text_ptr->itxt_length = png_strlen(text);
  189982. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189983. png_ptr->current_text = NULL;
  189984. png_free(png_ptr, text_ptr);
  189985. if (ret)
  189986. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189987. }
  189988. }
  189989. #endif
  189990. /* This function is called when we haven't found a handler for this
  189991. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189992. * name or a critical chunk), the chunk is (currently) silently ignored.
  189993. */
  189994. void /* PRIVATE */
  189995. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189996. length)
  189997. {
  189998. png_uint_32 skip=0;
  189999. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  190000. if (!(png_ptr->chunk_name[0] & 0x20))
  190001. {
  190002. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  190003. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  190004. PNG_HANDLE_CHUNK_ALWAYS
  190005. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190006. && png_ptr->read_user_chunk_fn == NULL
  190007. #endif
  190008. )
  190009. #endif
  190010. png_chunk_error(png_ptr, "unknown critical chunk");
  190011. info_ptr = info_ptr; /* to quiet some compiler warnings */
  190012. }
  190013. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  190014. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  190015. {
  190016. #ifdef PNG_MAX_MALLOC_64K
  190017. if (length > (png_uint_32)65535L)
  190018. {
  190019. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  190020. skip = length - (png_uint_32)65535L;
  190021. length = (png_uint_32)65535L;
  190022. }
  190023. #endif
  190024. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  190025. (png_charp)png_ptr->chunk_name, 5);
  190026. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  190027. png_ptr->unknown_chunk.size = (png_size_t)length;
  190028. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  190029. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190030. if(png_ptr->read_user_chunk_fn != NULL)
  190031. {
  190032. /* callback to user unknown chunk handler */
  190033. int ret;
  190034. ret = (*(png_ptr->read_user_chunk_fn))
  190035. (png_ptr, &png_ptr->unknown_chunk);
  190036. if (ret < 0)
  190037. png_chunk_error(png_ptr, "error in user chunk");
  190038. if (ret == 0)
  190039. {
  190040. if (!(png_ptr->chunk_name[0] & 0x20))
  190041. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  190042. PNG_HANDLE_CHUNK_ALWAYS)
  190043. png_chunk_error(png_ptr, "unknown critical chunk");
  190044. png_set_unknown_chunks(png_ptr, info_ptr,
  190045. &png_ptr->unknown_chunk, 1);
  190046. }
  190047. }
  190048. #else
  190049. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  190050. #endif
  190051. png_free(png_ptr, png_ptr->unknown_chunk.data);
  190052. png_ptr->unknown_chunk.data = NULL;
  190053. }
  190054. else
  190055. #endif
  190056. skip=length;
  190057. png_push_crc_skip(png_ptr, skip);
  190058. }
  190059. void /* PRIVATE */
  190060. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  190061. {
  190062. if (png_ptr->info_fn != NULL)
  190063. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  190064. }
  190065. void /* PRIVATE */
  190066. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  190067. {
  190068. if (png_ptr->end_fn != NULL)
  190069. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  190070. }
  190071. void /* PRIVATE */
  190072. png_push_have_row(png_structp png_ptr, png_bytep row)
  190073. {
  190074. if (png_ptr->row_fn != NULL)
  190075. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  190076. (int)png_ptr->pass);
  190077. }
  190078. void PNGAPI
  190079. png_progressive_combine_row (png_structp png_ptr,
  190080. png_bytep old_row, png_bytep new_row)
  190081. {
  190082. #ifdef PNG_USE_LOCAL_ARRAYS
  190083. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  190084. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  190085. #endif
  190086. if(png_ptr == NULL) return;
  190087. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  190088. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  190089. }
  190090. void PNGAPI
  190091. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  190092. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  190093. png_progressive_end_ptr end_fn)
  190094. {
  190095. if(png_ptr == NULL) return;
  190096. png_ptr->info_fn = info_fn;
  190097. png_ptr->row_fn = row_fn;
  190098. png_ptr->end_fn = end_fn;
  190099. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  190100. }
  190101. png_voidp PNGAPI
  190102. png_get_progressive_ptr(png_structp png_ptr)
  190103. {
  190104. if(png_ptr == NULL) return (NULL);
  190105. return png_ptr->io_ptr;
  190106. }
  190107. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  190108. /*** End of inlined file: pngpread.c ***/
  190109. /*** Start of inlined file: pngrio.c ***/
  190110. /* pngrio.c - functions for data input
  190111. *
  190112. * Last changed in libpng 1.2.13 November 13, 2006
  190113. * For conditions of distribution and use, see copyright notice in png.h
  190114. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  190115. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190116. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190117. *
  190118. * This file provides a location for all input. Users who need
  190119. * special handling are expected to write a function that has the same
  190120. * arguments as this and performs a similar function, but that possibly
  190121. * has a different input method. Note that you shouldn't change this
  190122. * function, but rather write a replacement function and then make
  190123. * libpng use it at run time with png_set_read_fn(...).
  190124. */
  190125. #define PNG_INTERNAL
  190126. #if defined(PNG_READ_SUPPORTED)
  190127. /* Read the data from whatever input you are using. The default routine
  190128. reads from a file pointer. Note that this routine sometimes gets called
  190129. with very small lengths, so you should implement some kind of simple
  190130. buffering if you are using unbuffered reads. This should never be asked
  190131. to read more then 64K on a 16 bit machine. */
  190132. void /* PRIVATE */
  190133. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190134. {
  190135. png_debug1(4,"reading %d bytes\n", (int)length);
  190136. if (png_ptr->read_data_fn != NULL)
  190137. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190138. else
  190139. png_error(png_ptr, "Call to NULL read function");
  190140. }
  190141. #if !defined(PNG_NO_STDIO)
  190142. /* This is the function that does the actual reading of data. If you are
  190143. not reading from a standard C stream, you should create a replacement
  190144. read_data function and use it at run time with png_set_read_fn(), rather
  190145. than changing the library. */
  190146. #ifndef USE_FAR_KEYWORD
  190147. void PNGAPI
  190148. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190149. {
  190150. png_size_t check;
  190151. if(png_ptr == NULL) return;
  190152. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190153. * instead of an int, which is what fread() actually returns.
  190154. */
  190155. #if defined(_WIN32_WCE)
  190156. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190157. check = 0;
  190158. #else
  190159. check = (png_size_t)fread(data, (png_size_t)1, length,
  190160. (png_FILE_p)png_ptr->io_ptr);
  190161. #endif
  190162. if (check != length)
  190163. png_error(png_ptr, "Read Error");
  190164. }
  190165. #else
  190166. /* this is the model-independent version. Since the standard I/O library
  190167. can't handle far buffers in the medium and small models, we have to copy
  190168. the data.
  190169. */
  190170. #define NEAR_BUF_SIZE 1024
  190171. #define MIN(a,b) (a <= b ? a : b)
  190172. static void PNGAPI
  190173. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190174. {
  190175. int check;
  190176. png_byte *n_data;
  190177. png_FILE_p io_ptr;
  190178. if(png_ptr == NULL) return;
  190179. /* Check if data really is near. If so, use usual code. */
  190180. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190181. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190182. if ((png_bytep)n_data == data)
  190183. {
  190184. #if defined(_WIN32_WCE)
  190185. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190186. check = 0;
  190187. #else
  190188. check = fread(n_data, 1, length, io_ptr);
  190189. #endif
  190190. }
  190191. else
  190192. {
  190193. png_byte buf[NEAR_BUF_SIZE];
  190194. png_size_t read, remaining, err;
  190195. check = 0;
  190196. remaining = length;
  190197. do
  190198. {
  190199. read = MIN(NEAR_BUF_SIZE, remaining);
  190200. #if defined(_WIN32_WCE)
  190201. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190202. err = 0;
  190203. #else
  190204. err = fread(buf, (png_size_t)1, read, io_ptr);
  190205. #endif
  190206. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190207. if(err != read)
  190208. break;
  190209. else
  190210. check += err;
  190211. data += read;
  190212. remaining -= read;
  190213. }
  190214. while (remaining != 0);
  190215. }
  190216. if ((png_uint_32)check != (png_uint_32)length)
  190217. png_error(png_ptr, "read Error");
  190218. }
  190219. #endif
  190220. #endif
  190221. /* This function allows the application to supply a new input function
  190222. for libpng if standard C streams aren't being used.
  190223. This function takes as its arguments:
  190224. png_ptr - pointer to a png input data structure
  190225. io_ptr - pointer to user supplied structure containing info about
  190226. the input functions. May be NULL.
  190227. read_data_fn - pointer to a new input function that takes as its
  190228. arguments a pointer to a png_struct, a pointer to
  190229. a location where input data can be stored, and a 32-bit
  190230. unsigned int that is the number of bytes to be read.
  190231. To exit and output any fatal error messages the new write
  190232. function should call png_error(png_ptr, "Error msg"). */
  190233. void PNGAPI
  190234. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190235. png_rw_ptr read_data_fn)
  190236. {
  190237. if(png_ptr == NULL) return;
  190238. png_ptr->io_ptr = io_ptr;
  190239. #if !defined(PNG_NO_STDIO)
  190240. if (read_data_fn != NULL)
  190241. png_ptr->read_data_fn = read_data_fn;
  190242. else
  190243. png_ptr->read_data_fn = png_default_read_data;
  190244. #else
  190245. png_ptr->read_data_fn = read_data_fn;
  190246. #endif
  190247. /* It is an error to write to a read device */
  190248. if (png_ptr->write_data_fn != NULL)
  190249. {
  190250. png_ptr->write_data_fn = NULL;
  190251. png_warning(png_ptr,
  190252. "It's an error to set both read_data_fn and write_data_fn in the ");
  190253. png_warning(png_ptr,
  190254. "same structure. Resetting write_data_fn to NULL.");
  190255. }
  190256. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190257. png_ptr->output_flush_fn = NULL;
  190258. #endif
  190259. }
  190260. #endif /* PNG_READ_SUPPORTED */
  190261. /*** End of inlined file: pngrio.c ***/
  190262. /*** Start of inlined file: pngrtran.c ***/
  190263. /* pngrtran.c - transforms the data in a row for PNG readers
  190264. *
  190265. * Last changed in libpng 1.2.21 [October 4, 2007]
  190266. * For conditions of distribution and use, see copyright notice in png.h
  190267. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190268. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190269. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190270. *
  190271. * This file contains functions optionally called by an application
  190272. * in order to tell libpng how to handle data when reading a PNG.
  190273. * Transformations that are used in both reading and writing are
  190274. * in pngtrans.c.
  190275. */
  190276. #define PNG_INTERNAL
  190277. #if defined(PNG_READ_SUPPORTED)
  190278. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190279. void PNGAPI
  190280. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190281. {
  190282. png_debug(1, "in png_set_crc_action\n");
  190283. /* Tell libpng how we react to CRC errors in critical chunks */
  190284. if(png_ptr == NULL) return;
  190285. switch (crit_action)
  190286. {
  190287. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190288. break;
  190289. case PNG_CRC_WARN_USE: /* warn/use data */
  190290. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190291. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190292. break;
  190293. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190294. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190295. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190296. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190297. break;
  190298. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190299. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190300. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190301. case PNG_CRC_DEFAULT:
  190302. default:
  190303. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190304. break;
  190305. }
  190306. switch (ancil_action)
  190307. {
  190308. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190309. break;
  190310. case PNG_CRC_WARN_USE: /* warn/use data */
  190311. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190312. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190313. break;
  190314. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190315. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190316. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190317. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190318. break;
  190319. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190320. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190321. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190322. break;
  190323. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190324. case PNG_CRC_DEFAULT:
  190325. default:
  190326. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190327. break;
  190328. }
  190329. }
  190330. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190331. defined(PNG_FLOATING_POINT_SUPPORTED)
  190332. /* handle alpha and tRNS via a background color */
  190333. void PNGAPI
  190334. png_set_background(png_structp png_ptr,
  190335. png_color_16p background_color, int background_gamma_code,
  190336. int need_expand, double background_gamma)
  190337. {
  190338. png_debug(1, "in png_set_background\n");
  190339. if(png_ptr == NULL) return;
  190340. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190341. {
  190342. png_warning(png_ptr, "Application must supply a known background gamma");
  190343. return;
  190344. }
  190345. png_ptr->transformations |= PNG_BACKGROUND;
  190346. png_memcpy(&(png_ptr->background), background_color,
  190347. png_sizeof(png_color_16));
  190348. png_ptr->background_gamma = (float)background_gamma;
  190349. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190350. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190351. }
  190352. #endif
  190353. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190354. /* strip 16 bit depth files to 8 bit depth */
  190355. void PNGAPI
  190356. png_set_strip_16(png_structp png_ptr)
  190357. {
  190358. png_debug(1, "in png_set_strip_16\n");
  190359. if(png_ptr == NULL) return;
  190360. png_ptr->transformations |= PNG_16_TO_8;
  190361. }
  190362. #endif
  190363. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190364. void PNGAPI
  190365. png_set_strip_alpha(png_structp png_ptr)
  190366. {
  190367. png_debug(1, "in png_set_strip_alpha\n");
  190368. if(png_ptr == NULL) return;
  190369. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190370. }
  190371. #endif
  190372. #if defined(PNG_READ_DITHER_SUPPORTED)
  190373. /* Dither file to 8 bit. Supply a palette, the current number
  190374. * of elements in the palette, the maximum number of elements
  190375. * allowed, and a histogram if possible. If the current number
  190376. * of colors is greater then the maximum number, the palette will be
  190377. * modified to fit in the maximum number. "full_dither" indicates
  190378. * whether we need a dithering cube set up for RGB images, or if we
  190379. * simply are reducing the number of colors in a paletted image.
  190380. */
  190381. typedef struct png_dsort_struct
  190382. {
  190383. struct png_dsort_struct FAR * next;
  190384. png_byte left;
  190385. png_byte right;
  190386. } png_dsort;
  190387. typedef png_dsort FAR * png_dsortp;
  190388. typedef png_dsort FAR * FAR * png_dsortpp;
  190389. void PNGAPI
  190390. png_set_dither(png_structp png_ptr, png_colorp palette,
  190391. int num_palette, int maximum_colors, png_uint_16p histogram,
  190392. int full_dither)
  190393. {
  190394. png_debug(1, "in png_set_dither\n");
  190395. if(png_ptr == NULL) return;
  190396. png_ptr->transformations |= PNG_DITHER;
  190397. if (!full_dither)
  190398. {
  190399. int i;
  190400. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190401. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190402. for (i = 0; i < num_palette; i++)
  190403. png_ptr->dither_index[i] = (png_byte)i;
  190404. }
  190405. if (num_palette > maximum_colors)
  190406. {
  190407. if (histogram != NULL)
  190408. {
  190409. /* This is easy enough, just throw out the least used colors.
  190410. Perhaps not the best solution, but good enough. */
  190411. int i;
  190412. /* initialize an array to sort colors */
  190413. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190414. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190415. /* initialize the dither_sort array */
  190416. for (i = 0; i < num_palette; i++)
  190417. png_ptr->dither_sort[i] = (png_byte)i;
  190418. /* Find the least used palette entries by starting a
  190419. bubble sort, and running it until we have sorted
  190420. out enough colors. Note that we don't care about
  190421. sorting all the colors, just finding which are
  190422. least used. */
  190423. for (i = num_palette - 1; i >= maximum_colors; i--)
  190424. {
  190425. int done; /* to stop early if the list is pre-sorted */
  190426. int j;
  190427. done = 1;
  190428. for (j = 0; j < i; j++)
  190429. {
  190430. if (histogram[png_ptr->dither_sort[j]]
  190431. < histogram[png_ptr->dither_sort[j + 1]])
  190432. {
  190433. png_byte t;
  190434. t = png_ptr->dither_sort[j];
  190435. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190436. png_ptr->dither_sort[j + 1] = t;
  190437. done = 0;
  190438. }
  190439. }
  190440. if (done)
  190441. break;
  190442. }
  190443. /* swap the palette around, and set up a table, if necessary */
  190444. if (full_dither)
  190445. {
  190446. int j = num_palette;
  190447. /* put all the useful colors within the max, but don't
  190448. move the others */
  190449. for (i = 0; i < maximum_colors; i++)
  190450. {
  190451. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190452. {
  190453. do
  190454. j--;
  190455. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190456. palette[i] = palette[j];
  190457. }
  190458. }
  190459. }
  190460. else
  190461. {
  190462. int j = num_palette;
  190463. /* move all the used colors inside the max limit, and
  190464. develop a translation table */
  190465. for (i = 0; i < maximum_colors; i++)
  190466. {
  190467. /* only move the colors we need to */
  190468. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190469. {
  190470. png_color tmp_color;
  190471. do
  190472. j--;
  190473. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190474. tmp_color = palette[j];
  190475. palette[j] = palette[i];
  190476. palette[i] = tmp_color;
  190477. /* indicate where the color went */
  190478. png_ptr->dither_index[j] = (png_byte)i;
  190479. png_ptr->dither_index[i] = (png_byte)j;
  190480. }
  190481. }
  190482. /* find closest color for those colors we are not using */
  190483. for (i = 0; i < num_palette; i++)
  190484. {
  190485. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190486. {
  190487. int min_d, k, min_k, d_index;
  190488. /* find the closest color to one we threw out */
  190489. d_index = png_ptr->dither_index[i];
  190490. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190491. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190492. {
  190493. int d;
  190494. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190495. if (d < min_d)
  190496. {
  190497. min_d = d;
  190498. min_k = k;
  190499. }
  190500. }
  190501. /* point to closest color */
  190502. png_ptr->dither_index[i] = (png_byte)min_k;
  190503. }
  190504. }
  190505. }
  190506. png_free(png_ptr, png_ptr->dither_sort);
  190507. png_ptr->dither_sort=NULL;
  190508. }
  190509. else
  190510. {
  190511. /* This is much harder to do simply (and quickly). Perhaps
  190512. we need to go through a median cut routine, but those
  190513. don't always behave themselves with only a few colors
  190514. as input. So we will just find the closest two colors,
  190515. and throw out one of them (chosen somewhat randomly).
  190516. [We don't understand this at all, so if someone wants to
  190517. work on improving it, be our guest - AED, GRP]
  190518. */
  190519. int i;
  190520. int max_d;
  190521. int num_new_palette;
  190522. png_dsortp t;
  190523. png_dsortpp hash;
  190524. t=NULL;
  190525. /* initialize palette index arrays */
  190526. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190527. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190528. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190529. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190530. /* initialize the sort array */
  190531. for (i = 0; i < num_palette; i++)
  190532. {
  190533. png_ptr->index_to_palette[i] = (png_byte)i;
  190534. png_ptr->palette_to_index[i] = (png_byte)i;
  190535. }
  190536. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190537. png_sizeof (png_dsortp)));
  190538. for (i = 0; i < 769; i++)
  190539. hash[i] = NULL;
  190540. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190541. num_new_palette = num_palette;
  190542. /* initial wild guess at how far apart the farthest pixel
  190543. pair we will be eliminating will be. Larger
  190544. numbers mean more areas will be allocated, Smaller
  190545. numbers run the risk of not saving enough data, and
  190546. having to do this all over again.
  190547. I have not done extensive checking on this number.
  190548. */
  190549. max_d = 96;
  190550. while (num_new_palette > maximum_colors)
  190551. {
  190552. for (i = 0; i < num_new_palette - 1; i++)
  190553. {
  190554. int j;
  190555. for (j = i + 1; j < num_new_palette; j++)
  190556. {
  190557. int d;
  190558. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190559. if (d <= max_d)
  190560. {
  190561. t = (png_dsortp)png_malloc_warn(png_ptr,
  190562. (png_uint_32)(png_sizeof(png_dsort)));
  190563. if (t == NULL)
  190564. break;
  190565. t->next = hash[d];
  190566. t->left = (png_byte)i;
  190567. t->right = (png_byte)j;
  190568. hash[d] = t;
  190569. }
  190570. }
  190571. if (t == NULL)
  190572. break;
  190573. }
  190574. if (t != NULL)
  190575. for (i = 0; i <= max_d; i++)
  190576. {
  190577. if (hash[i] != NULL)
  190578. {
  190579. png_dsortp p;
  190580. for (p = hash[i]; p; p = p->next)
  190581. {
  190582. if ((int)png_ptr->index_to_palette[p->left]
  190583. < num_new_palette &&
  190584. (int)png_ptr->index_to_palette[p->right]
  190585. < num_new_palette)
  190586. {
  190587. int j, next_j;
  190588. if (num_new_palette & 0x01)
  190589. {
  190590. j = p->left;
  190591. next_j = p->right;
  190592. }
  190593. else
  190594. {
  190595. j = p->right;
  190596. next_j = p->left;
  190597. }
  190598. num_new_palette--;
  190599. palette[png_ptr->index_to_palette[j]]
  190600. = palette[num_new_palette];
  190601. if (!full_dither)
  190602. {
  190603. int k;
  190604. for (k = 0; k < num_palette; k++)
  190605. {
  190606. if (png_ptr->dither_index[k] ==
  190607. png_ptr->index_to_palette[j])
  190608. png_ptr->dither_index[k] =
  190609. png_ptr->index_to_palette[next_j];
  190610. if ((int)png_ptr->dither_index[k] ==
  190611. num_new_palette)
  190612. png_ptr->dither_index[k] =
  190613. png_ptr->index_to_palette[j];
  190614. }
  190615. }
  190616. png_ptr->index_to_palette[png_ptr->palette_to_index
  190617. [num_new_palette]] = png_ptr->index_to_palette[j];
  190618. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190619. = png_ptr->palette_to_index[num_new_palette];
  190620. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190621. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190622. }
  190623. if (num_new_palette <= maximum_colors)
  190624. break;
  190625. }
  190626. if (num_new_palette <= maximum_colors)
  190627. break;
  190628. }
  190629. }
  190630. for (i = 0; i < 769; i++)
  190631. {
  190632. if (hash[i] != NULL)
  190633. {
  190634. png_dsortp p = hash[i];
  190635. while (p)
  190636. {
  190637. t = p->next;
  190638. png_free(png_ptr, p);
  190639. p = t;
  190640. }
  190641. }
  190642. hash[i] = 0;
  190643. }
  190644. max_d += 96;
  190645. }
  190646. png_free(png_ptr, hash);
  190647. png_free(png_ptr, png_ptr->palette_to_index);
  190648. png_free(png_ptr, png_ptr->index_to_palette);
  190649. png_ptr->palette_to_index=NULL;
  190650. png_ptr->index_to_palette=NULL;
  190651. }
  190652. num_palette = maximum_colors;
  190653. }
  190654. if (png_ptr->palette == NULL)
  190655. {
  190656. png_ptr->palette = palette;
  190657. }
  190658. png_ptr->num_palette = (png_uint_16)num_palette;
  190659. if (full_dither)
  190660. {
  190661. int i;
  190662. png_bytep distance;
  190663. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190664. PNG_DITHER_BLUE_BITS;
  190665. int num_red = (1 << PNG_DITHER_RED_BITS);
  190666. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190667. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190668. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190669. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190670. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190671. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190672. png_sizeof (png_byte));
  190673. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190674. png_sizeof(png_byte)));
  190675. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190676. for (i = 0; i < num_palette; i++)
  190677. {
  190678. int ir, ig, ib;
  190679. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190680. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190681. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190682. for (ir = 0; ir < num_red; ir++)
  190683. {
  190684. /* int dr = abs(ir - r); */
  190685. int dr = ((ir > r) ? ir - r : r - ir);
  190686. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190687. for (ig = 0; ig < num_green; ig++)
  190688. {
  190689. /* int dg = abs(ig - g); */
  190690. int dg = ((ig > g) ? ig - g : g - ig);
  190691. int dt = dr + dg;
  190692. int dm = ((dr > dg) ? dr : dg);
  190693. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190694. for (ib = 0; ib < num_blue; ib++)
  190695. {
  190696. int d_index = index_g | ib;
  190697. /* int db = abs(ib - b); */
  190698. int db = ((ib > b) ? ib - b : b - ib);
  190699. int dmax = ((dm > db) ? dm : db);
  190700. int d = dmax + dt + db;
  190701. if (d < (int)distance[d_index])
  190702. {
  190703. distance[d_index] = (png_byte)d;
  190704. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190705. }
  190706. }
  190707. }
  190708. }
  190709. }
  190710. png_free(png_ptr, distance);
  190711. }
  190712. }
  190713. #endif
  190714. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190715. /* Transform the image from the file_gamma to the screen_gamma. We
  190716. * only do transformations on images where the file_gamma and screen_gamma
  190717. * are not close reciprocals, otherwise it slows things down slightly, and
  190718. * also needlessly introduces small errors.
  190719. *
  190720. * We will turn off gamma transformation later if no semitransparent entries
  190721. * are present in the tRNS array for palette images. We can't do it here
  190722. * because we don't necessarily have the tRNS chunk yet.
  190723. */
  190724. void PNGAPI
  190725. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190726. {
  190727. png_debug(1, "in png_set_gamma\n");
  190728. if(png_ptr == NULL) return;
  190729. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190730. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190731. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190732. png_ptr->transformations |= PNG_GAMMA;
  190733. png_ptr->gamma = (float)file_gamma;
  190734. png_ptr->screen_gamma = (float)scrn_gamma;
  190735. }
  190736. #endif
  190737. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190738. /* Expand paletted images to RGB, expand grayscale images of
  190739. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190740. * to alpha channels.
  190741. */
  190742. void PNGAPI
  190743. png_set_expand(png_structp png_ptr)
  190744. {
  190745. png_debug(1, "in png_set_expand\n");
  190746. if(png_ptr == NULL) return;
  190747. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190748. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190749. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190750. #endif
  190751. }
  190752. /* GRR 19990627: the following three functions currently are identical
  190753. * to png_set_expand(). However, it is entirely reasonable that someone
  190754. * might wish to expand an indexed image to RGB but *not* expand a single,
  190755. * fully transparent palette entry to a full alpha channel--perhaps instead
  190756. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190757. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190758. * IOW, a future version of the library may make the transformations flag
  190759. * a bit more fine-grained, with separate bits for each of these three
  190760. * functions.
  190761. *
  190762. * More to the point, these functions make it obvious what libpng will be
  190763. * doing, whereas "expand" can (and does) mean any number of things.
  190764. *
  190765. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190766. * to expand only the sample depth but not to expand the tRNS to alpha.
  190767. */
  190768. /* Expand paletted images to RGB. */
  190769. void PNGAPI
  190770. png_set_palette_to_rgb(png_structp png_ptr)
  190771. {
  190772. png_debug(1, "in png_set_palette_to_rgb\n");
  190773. if(png_ptr == NULL) return;
  190774. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190775. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190776. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190777. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190778. #endif
  190779. }
  190780. #if !defined(PNG_1_0_X)
  190781. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190782. void PNGAPI
  190783. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190784. {
  190785. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190786. if(png_ptr == NULL) return;
  190787. png_ptr->transformations |= PNG_EXPAND;
  190788. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190789. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190790. #endif
  190791. }
  190792. #endif
  190793. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190794. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190795. /* Deprecated as of libpng-1.2.9 */
  190796. void PNGAPI
  190797. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190798. {
  190799. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190800. if(png_ptr == NULL) return;
  190801. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190802. }
  190803. #endif
  190804. /* Expand tRNS chunks to alpha channels. */
  190805. void PNGAPI
  190806. png_set_tRNS_to_alpha(png_structp png_ptr)
  190807. {
  190808. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190809. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190810. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190811. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190812. #endif
  190813. }
  190814. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190815. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190816. void PNGAPI
  190817. png_set_gray_to_rgb(png_structp png_ptr)
  190818. {
  190819. png_debug(1, "in png_set_gray_to_rgb\n");
  190820. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190821. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190822. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190823. #endif
  190824. }
  190825. #endif
  190826. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190827. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190828. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190829. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190830. */
  190831. void PNGAPI
  190832. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190833. double green)
  190834. {
  190835. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190836. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190837. if(png_ptr == NULL) return;
  190838. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190839. }
  190840. #endif
  190841. void PNGAPI
  190842. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190843. png_fixed_point red, png_fixed_point green)
  190844. {
  190845. png_debug(1, "in png_set_rgb_to_gray\n");
  190846. if(png_ptr == NULL) return;
  190847. switch(error_action)
  190848. {
  190849. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190850. break;
  190851. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190852. break;
  190853. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190854. }
  190855. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190856. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190857. png_ptr->transformations |= PNG_EXPAND;
  190858. #else
  190859. {
  190860. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190861. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190862. }
  190863. #endif
  190864. {
  190865. png_uint_16 red_int, green_int;
  190866. if(red < 0 || green < 0)
  190867. {
  190868. red_int = 6968; /* .212671 * 32768 + .5 */
  190869. green_int = 23434; /* .715160 * 32768 + .5 */
  190870. }
  190871. else if(red + green < 100000L)
  190872. {
  190873. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190874. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190875. }
  190876. else
  190877. {
  190878. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190879. red_int = 6968;
  190880. green_int = 23434;
  190881. }
  190882. png_ptr->rgb_to_gray_red_coeff = red_int;
  190883. png_ptr->rgb_to_gray_green_coeff = green_int;
  190884. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190885. }
  190886. }
  190887. #endif
  190888. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190889. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190890. defined(PNG_LEGACY_SUPPORTED)
  190891. void PNGAPI
  190892. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190893. read_user_transform_fn)
  190894. {
  190895. png_debug(1, "in png_set_read_user_transform_fn\n");
  190896. if(png_ptr == NULL) return;
  190897. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190898. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190899. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190900. #endif
  190901. #ifdef PNG_LEGACY_SUPPORTED
  190902. if(read_user_transform_fn)
  190903. png_warning(png_ptr,
  190904. "This version of libpng does not support user transforms");
  190905. #endif
  190906. }
  190907. #endif
  190908. /* Initialize everything needed for the read. This includes modifying
  190909. * the palette.
  190910. */
  190911. void /* PRIVATE */
  190912. png_init_read_transformations(png_structp png_ptr)
  190913. {
  190914. png_debug(1, "in png_init_read_transformations\n");
  190915. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190916. if(png_ptr != NULL)
  190917. #endif
  190918. {
  190919. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190920. || defined(PNG_READ_GAMMA_SUPPORTED)
  190921. int color_type = png_ptr->color_type;
  190922. #endif
  190923. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190924. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190925. /* Detect gray background and attempt to enable optimization
  190926. * for gray --> RGB case */
  190927. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190928. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190929. * background color might actually be gray yet not be flagged as such.
  190930. * This is not a problem for the current code, which uses
  190931. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190932. * png_do_gray_to_rgb() transformation.
  190933. */
  190934. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190935. !(color_type & PNG_COLOR_MASK_COLOR))
  190936. {
  190937. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190938. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190939. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190940. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190941. png_ptr->background.red == png_ptr->background.green &&
  190942. png_ptr->background.red == png_ptr->background.blue)
  190943. {
  190944. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190945. png_ptr->background.gray = png_ptr->background.red;
  190946. }
  190947. #endif
  190948. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190949. (png_ptr->transformations & PNG_EXPAND))
  190950. {
  190951. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190952. {
  190953. /* expand background and tRNS chunks */
  190954. switch (png_ptr->bit_depth)
  190955. {
  190956. case 1:
  190957. png_ptr->background.gray *= (png_uint_16)0xff;
  190958. png_ptr->background.red = png_ptr->background.green
  190959. = png_ptr->background.blue = png_ptr->background.gray;
  190960. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190961. {
  190962. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190963. png_ptr->trans_values.red = png_ptr->trans_values.green
  190964. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190965. }
  190966. break;
  190967. case 2:
  190968. png_ptr->background.gray *= (png_uint_16)0x55;
  190969. png_ptr->background.red = png_ptr->background.green
  190970. = png_ptr->background.blue = png_ptr->background.gray;
  190971. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190972. {
  190973. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190974. png_ptr->trans_values.red = png_ptr->trans_values.green
  190975. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190976. }
  190977. break;
  190978. case 4:
  190979. png_ptr->background.gray *= (png_uint_16)0x11;
  190980. png_ptr->background.red = png_ptr->background.green
  190981. = png_ptr->background.blue = png_ptr->background.gray;
  190982. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190983. {
  190984. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190985. png_ptr->trans_values.red = png_ptr->trans_values.green
  190986. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190987. }
  190988. break;
  190989. case 8:
  190990. case 16:
  190991. png_ptr->background.red = png_ptr->background.green
  190992. = png_ptr->background.blue = png_ptr->background.gray;
  190993. break;
  190994. }
  190995. }
  190996. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190997. {
  190998. png_ptr->background.red =
  190999. png_ptr->palette[png_ptr->background.index].red;
  191000. png_ptr->background.green =
  191001. png_ptr->palette[png_ptr->background.index].green;
  191002. png_ptr->background.blue =
  191003. png_ptr->palette[png_ptr->background.index].blue;
  191004. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191005. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191006. {
  191007. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191008. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  191009. #endif
  191010. {
  191011. /* invert the alpha channel (in tRNS) unless the pixels are
  191012. going to be expanded, in which case leave it for later */
  191013. int i,istop;
  191014. istop=(int)png_ptr->num_trans;
  191015. for (i=0; i<istop; i++)
  191016. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  191017. }
  191018. }
  191019. #endif
  191020. }
  191021. }
  191022. #endif
  191023. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  191024. png_ptr->background_1 = png_ptr->background;
  191025. #endif
  191026. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191027. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  191028. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  191029. < PNG_GAMMA_THRESHOLD))
  191030. {
  191031. int i,k;
  191032. k=0;
  191033. for (i=0; i<png_ptr->num_trans; i++)
  191034. {
  191035. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  191036. k=1; /* partial transparency is present */
  191037. }
  191038. if (k == 0)
  191039. png_ptr->transformations &= (~PNG_GAMMA);
  191040. }
  191041. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  191042. png_ptr->gamma != 0.0)
  191043. {
  191044. png_build_gamma_table(png_ptr);
  191045. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191046. if (png_ptr->transformations & PNG_BACKGROUND)
  191047. {
  191048. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191049. {
  191050. /* could skip if no transparency and
  191051. */
  191052. png_color back, back_1;
  191053. png_colorp palette = png_ptr->palette;
  191054. int num_palette = png_ptr->num_palette;
  191055. int i;
  191056. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191057. {
  191058. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191059. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191060. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191061. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191062. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191063. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191064. }
  191065. else
  191066. {
  191067. double g, gs;
  191068. switch (png_ptr->background_gamma_type)
  191069. {
  191070. case PNG_BACKGROUND_GAMMA_SCREEN:
  191071. g = (png_ptr->screen_gamma);
  191072. gs = 1.0;
  191073. break;
  191074. case PNG_BACKGROUND_GAMMA_FILE:
  191075. g = 1.0 / (png_ptr->gamma);
  191076. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191077. break;
  191078. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191079. g = 1.0 / (png_ptr->background_gamma);
  191080. gs = 1.0 / (png_ptr->background_gamma *
  191081. png_ptr->screen_gamma);
  191082. break;
  191083. default:
  191084. g = 1.0; /* back_1 */
  191085. gs = 1.0; /* back */
  191086. }
  191087. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  191088. {
  191089. back.red = (png_byte)png_ptr->background.red;
  191090. back.green = (png_byte)png_ptr->background.green;
  191091. back.blue = (png_byte)png_ptr->background.blue;
  191092. }
  191093. else
  191094. {
  191095. back.red = (png_byte)(pow(
  191096. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  191097. back.green = (png_byte)(pow(
  191098. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  191099. back.blue = (png_byte)(pow(
  191100. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  191101. }
  191102. back_1.red = (png_byte)(pow(
  191103. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  191104. back_1.green = (png_byte)(pow(
  191105. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  191106. back_1.blue = (png_byte)(pow(
  191107. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  191108. }
  191109. for (i = 0; i < num_palette; i++)
  191110. {
  191111. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191112. {
  191113. if (png_ptr->trans[i] == 0)
  191114. {
  191115. palette[i] = back;
  191116. }
  191117. else /* if (png_ptr->trans[i] != 0xff) */
  191118. {
  191119. png_byte v, w;
  191120. v = png_ptr->gamma_to_1[palette[i].red];
  191121. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191122. palette[i].red = png_ptr->gamma_from_1[w];
  191123. v = png_ptr->gamma_to_1[palette[i].green];
  191124. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191125. palette[i].green = png_ptr->gamma_from_1[w];
  191126. v = png_ptr->gamma_to_1[palette[i].blue];
  191127. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191128. palette[i].blue = png_ptr->gamma_from_1[w];
  191129. }
  191130. }
  191131. else
  191132. {
  191133. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191134. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191135. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191136. }
  191137. }
  191138. }
  191139. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191140. else
  191141. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191142. {
  191143. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191144. double g = 1.0;
  191145. double gs = 1.0;
  191146. switch (png_ptr->background_gamma_type)
  191147. {
  191148. case PNG_BACKGROUND_GAMMA_SCREEN:
  191149. g = (png_ptr->screen_gamma);
  191150. gs = 1.0;
  191151. break;
  191152. case PNG_BACKGROUND_GAMMA_FILE:
  191153. g = 1.0 / (png_ptr->gamma);
  191154. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191155. break;
  191156. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191157. g = 1.0 / (png_ptr->background_gamma);
  191158. gs = 1.0 / (png_ptr->background_gamma *
  191159. png_ptr->screen_gamma);
  191160. break;
  191161. }
  191162. png_ptr->background_1.gray = (png_uint_16)(pow(
  191163. (double)png_ptr->background.gray / m, g) * m + .5);
  191164. png_ptr->background.gray = (png_uint_16)(pow(
  191165. (double)png_ptr->background.gray / m, gs) * m + .5);
  191166. if ((png_ptr->background.red != png_ptr->background.green) ||
  191167. (png_ptr->background.red != png_ptr->background.blue) ||
  191168. (png_ptr->background.red != png_ptr->background.gray))
  191169. {
  191170. /* RGB or RGBA with color background */
  191171. png_ptr->background_1.red = (png_uint_16)(pow(
  191172. (double)png_ptr->background.red / m, g) * m + .5);
  191173. png_ptr->background_1.green = (png_uint_16)(pow(
  191174. (double)png_ptr->background.green / m, g) * m + .5);
  191175. png_ptr->background_1.blue = (png_uint_16)(pow(
  191176. (double)png_ptr->background.blue / m, g) * m + .5);
  191177. png_ptr->background.red = (png_uint_16)(pow(
  191178. (double)png_ptr->background.red / m, gs) * m + .5);
  191179. png_ptr->background.green = (png_uint_16)(pow(
  191180. (double)png_ptr->background.green / m, gs) * m + .5);
  191181. png_ptr->background.blue = (png_uint_16)(pow(
  191182. (double)png_ptr->background.blue / m, gs) * m + .5);
  191183. }
  191184. else
  191185. {
  191186. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191187. png_ptr->background_1.red = png_ptr->background_1.green
  191188. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191189. png_ptr->background.red = png_ptr->background.green
  191190. = png_ptr->background.blue = png_ptr->background.gray;
  191191. }
  191192. }
  191193. }
  191194. else
  191195. /* transformation does not include PNG_BACKGROUND */
  191196. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191197. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191198. {
  191199. png_colorp palette = png_ptr->palette;
  191200. int num_palette = png_ptr->num_palette;
  191201. int i;
  191202. for (i = 0; i < num_palette; i++)
  191203. {
  191204. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191205. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191206. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191207. }
  191208. }
  191209. }
  191210. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191211. else
  191212. #endif
  191213. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191214. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191215. /* No GAMMA transformation */
  191216. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191217. (color_type == PNG_COLOR_TYPE_PALETTE))
  191218. {
  191219. int i;
  191220. int istop = (int)png_ptr->num_trans;
  191221. png_color back;
  191222. png_colorp palette = png_ptr->palette;
  191223. back.red = (png_byte)png_ptr->background.red;
  191224. back.green = (png_byte)png_ptr->background.green;
  191225. back.blue = (png_byte)png_ptr->background.blue;
  191226. for (i = 0; i < istop; i++)
  191227. {
  191228. if (png_ptr->trans[i] == 0)
  191229. {
  191230. palette[i] = back;
  191231. }
  191232. else if (png_ptr->trans[i] != 0xff)
  191233. {
  191234. /* The png_composite() macro is defined in png.h */
  191235. png_composite(palette[i].red, palette[i].red,
  191236. png_ptr->trans[i], back.red);
  191237. png_composite(palette[i].green, palette[i].green,
  191238. png_ptr->trans[i], back.green);
  191239. png_composite(palette[i].blue, palette[i].blue,
  191240. png_ptr->trans[i], back.blue);
  191241. }
  191242. }
  191243. }
  191244. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191245. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191246. if ((png_ptr->transformations & PNG_SHIFT) &&
  191247. (color_type == PNG_COLOR_TYPE_PALETTE))
  191248. {
  191249. png_uint_16 i;
  191250. png_uint_16 istop = png_ptr->num_palette;
  191251. int sr = 8 - png_ptr->sig_bit.red;
  191252. int sg = 8 - png_ptr->sig_bit.green;
  191253. int sb = 8 - png_ptr->sig_bit.blue;
  191254. if (sr < 0 || sr > 8)
  191255. sr = 0;
  191256. if (sg < 0 || sg > 8)
  191257. sg = 0;
  191258. if (sb < 0 || sb > 8)
  191259. sb = 0;
  191260. for (i = 0; i < istop; i++)
  191261. {
  191262. png_ptr->palette[i].red >>= sr;
  191263. png_ptr->palette[i].green >>= sg;
  191264. png_ptr->palette[i].blue >>= sb;
  191265. }
  191266. }
  191267. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191268. }
  191269. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191270. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191271. if(png_ptr)
  191272. return;
  191273. #endif
  191274. }
  191275. /* Modify the info structure to reflect the transformations. The
  191276. * info should be updated so a PNG file could be written with it,
  191277. * assuming the transformations result in valid PNG data.
  191278. */
  191279. void /* PRIVATE */
  191280. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191281. {
  191282. png_debug(1, "in png_read_transform_info\n");
  191283. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191284. if (png_ptr->transformations & PNG_EXPAND)
  191285. {
  191286. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191287. {
  191288. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191289. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191290. else
  191291. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191292. info_ptr->bit_depth = 8;
  191293. info_ptr->num_trans = 0;
  191294. }
  191295. else
  191296. {
  191297. if (png_ptr->num_trans)
  191298. {
  191299. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191300. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191301. else
  191302. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191303. }
  191304. if (info_ptr->bit_depth < 8)
  191305. info_ptr->bit_depth = 8;
  191306. info_ptr->num_trans = 0;
  191307. }
  191308. }
  191309. #endif
  191310. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191311. if (png_ptr->transformations & PNG_BACKGROUND)
  191312. {
  191313. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191314. info_ptr->num_trans = 0;
  191315. info_ptr->background = png_ptr->background;
  191316. }
  191317. #endif
  191318. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191319. if (png_ptr->transformations & PNG_GAMMA)
  191320. {
  191321. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191322. info_ptr->gamma = png_ptr->gamma;
  191323. #endif
  191324. #ifdef PNG_FIXED_POINT_SUPPORTED
  191325. info_ptr->int_gamma = png_ptr->int_gamma;
  191326. #endif
  191327. }
  191328. #endif
  191329. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191330. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191331. info_ptr->bit_depth = 8;
  191332. #endif
  191333. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191334. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191335. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191336. #endif
  191337. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191338. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191339. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191340. #endif
  191341. #if defined(PNG_READ_DITHER_SUPPORTED)
  191342. if (png_ptr->transformations & PNG_DITHER)
  191343. {
  191344. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191345. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191346. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191347. {
  191348. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191349. }
  191350. }
  191351. #endif
  191352. #if defined(PNG_READ_PACK_SUPPORTED)
  191353. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191354. info_ptr->bit_depth = 8;
  191355. #endif
  191356. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191357. info_ptr->channels = 1;
  191358. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191359. info_ptr->channels = 3;
  191360. else
  191361. info_ptr->channels = 1;
  191362. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191363. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191364. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191365. #endif
  191366. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191367. info_ptr->channels++;
  191368. #if defined(PNG_READ_FILLER_SUPPORTED)
  191369. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191370. if ((png_ptr->transformations & PNG_FILLER) &&
  191371. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191372. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191373. {
  191374. info_ptr->channels++;
  191375. /* if adding a true alpha channel not just filler */
  191376. #if !defined(PNG_1_0_X)
  191377. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191378. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191379. #endif
  191380. }
  191381. #endif
  191382. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191383. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191384. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191385. {
  191386. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191387. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191388. if(info_ptr->channels < png_ptr->user_transform_channels)
  191389. info_ptr->channels = png_ptr->user_transform_channels;
  191390. }
  191391. #endif
  191392. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191393. info_ptr->bit_depth);
  191394. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191395. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191396. if(png_ptr)
  191397. return;
  191398. #endif
  191399. }
  191400. /* Transform the row. The order of transformations is significant,
  191401. * and is very touchy. If you add a transformation, take care to
  191402. * decide how it fits in with the other transformations here.
  191403. */
  191404. void /* PRIVATE */
  191405. png_do_read_transformations(png_structp png_ptr)
  191406. {
  191407. png_debug(1, "in png_do_read_transformations\n");
  191408. if (png_ptr->row_buf == NULL)
  191409. {
  191410. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191411. char msg[50];
  191412. png_snprintf2(msg, 50,
  191413. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191414. png_ptr->pass);
  191415. png_error(png_ptr, msg);
  191416. #else
  191417. png_error(png_ptr, "NULL row buffer");
  191418. #endif
  191419. }
  191420. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191421. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191422. /* Application has failed to call either png_read_start_image()
  191423. * or png_read_update_info() after setting transforms that expand
  191424. * pixels. This check added to libpng-1.2.19 */
  191425. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191426. png_error(png_ptr, "Uninitialized row");
  191427. #else
  191428. png_warning(png_ptr, "Uninitialized row");
  191429. #endif
  191430. #endif
  191431. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191432. if (png_ptr->transformations & PNG_EXPAND)
  191433. {
  191434. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191435. {
  191436. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191437. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191438. }
  191439. else
  191440. {
  191441. if (png_ptr->num_trans &&
  191442. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191443. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191444. &(png_ptr->trans_values));
  191445. else
  191446. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191447. NULL);
  191448. }
  191449. }
  191450. #endif
  191451. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191452. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191453. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191454. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191455. #endif
  191456. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191457. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191458. {
  191459. int rgb_error =
  191460. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191461. if(rgb_error)
  191462. {
  191463. png_ptr->rgb_to_gray_status=1;
  191464. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191465. PNG_RGB_TO_GRAY_WARN)
  191466. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191467. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191468. PNG_RGB_TO_GRAY_ERR)
  191469. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191470. }
  191471. }
  191472. #endif
  191473. /*
  191474. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191475. In most cases, the "simple transparency" should be done prior to doing
  191476. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191477. pixel is transparent. You would also need to make sure that the
  191478. transparency information is upgraded to RGB.
  191479. To summarize, the current flow is:
  191480. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191481. with background "in place" if transparent,
  191482. convert to RGB if necessary
  191483. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191484. convert to RGB if necessary
  191485. To support RGB backgrounds for gray images we need:
  191486. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191487. 3 or 6 bytes and composite with background
  191488. "in place" if transparent (3x compare/pixel
  191489. compared to doing composite with gray bkgrnd)
  191490. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191491. remove alpha bytes (3x float operations/pixel
  191492. compared with composite on gray background)
  191493. Greg's change will do this. The reason it wasn't done before is for
  191494. performance, as this increases the per-pixel operations. If we would check
  191495. in advance if the background was gray or RGB, and position the gray-to-RGB
  191496. transform appropriately, then it would save a lot of work/time.
  191497. */
  191498. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191499. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191500. * for performance reasons */
  191501. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191502. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191503. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191504. #endif
  191505. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191506. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191507. ((png_ptr->num_trans != 0 ) ||
  191508. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191509. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191510. &(png_ptr->trans_values), &(png_ptr->background)
  191511. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191512. , &(png_ptr->background_1),
  191513. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191514. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191515. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191516. png_ptr->gamma_shift
  191517. #endif
  191518. );
  191519. #endif
  191520. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191521. if ((png_ptr->transformations & PNG_GAMMA) &&
  191522. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191523. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191524. ((png_ptr->num_trans != 0) ||
  191525. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191526. #endif
  191527. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191528. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191529. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191530. png_ptr->gamma_shift);
  191531. #endif
  191532. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191533. if (png_ptr->transformations & PNG_16_TO_8)
  191534. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191535. #endif
  191536. #if defined(PNG_READ_DITHER_SUPPORTED)
  191537. if (png_ptr->transformations & PNG_DITHER)
  191538. {
  191539. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191540. png_ptr->palette_lookup, png_ptr->dither_index);
  191541. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191542. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191543. }
  191544. #endif
  191545. #if defined(PNG_READ_INVERT_SUPPORTED)
  191546. if (png_ptr->transformations & PNG_INVERT_MONO)
  191547. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191548. #endif
  191549. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191550. if (png_ptr->transformations & PNG_SHIFT)
  191551. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191552. &(png_ptr->shift));
  191553. #endif
  191554. #if defined(PNG_READ_PACK_SUPPORTED)
  191555. if (png_ptr->transformations & PNG_PACK)
  191556. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191557. #endif
  191558. #if defined(PNG_READ_BGR_SUPPORTED)
  191559. if (png_ptr->transformations & PNG_BGR)
  191560. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191561. #endif
  191562. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191563. if (png_ptr->transformations & PNG_PACKSWAP)
  191564. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191565. #endif
  191566. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191567. /* if gray -> RGB, do so now only if we did not do so above */
  191568. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191569. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191570. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191571. #endif
  191572. #if defined(PNG_READ_FILLER_SUPPORTED)
  191573. if (png_ptr->transformations & PNG_FILLER)
  191574. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191575. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191576. #endif
  191577. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191578. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191579. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191580. #endif
  191581. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191582. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191583. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191584. #endif
  191585. #if defined(PNG_READ_SWAP_SUPPORTED)
  191586. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191587. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191588. #endif
  191589. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191590. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191591. {
  191592. if(png_ptr->read_user_transform_fn != NULL)
  191593. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191594. (png_ptr, /* png_ptr */
  191595. &(png_ptr->row_info), /* row_info: */
  191596. /* png_uint_32 width; width of row */
  191597. /* png_uint_32 rowbytes; number of bytes in row */
  191598. /* png_byte color_type; color type of pixels */
  191599. /* png_byte bit_depth; bit depth of samples */
  191600. /* png_byte channels; number of channels (1-4) */
  191601. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191602. png_ptr->row_buf + 1); /* start of pixel data for row */
  191603. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191604. if(png_ptr->user_transform_depth)
  191605. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191606. if(png_ptr->user_transform_channels)
  191607. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191608. #endif
  191609. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191610. png_ptr->row_info.channels);
  191611. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191612. png_ptr->row_info.width);
  191613. }
  191614. #endif
  191615. }
  191616. #if defined(PNG_READ_PACK_SUPPORTED)
  191617. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191618. * without changing the actual values. Thus, if you had a row with
  191619. * a bit depth of 1, you would end up with bytes that only contained
  191620. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191621. * png_do_shift() after this.
  191622. */
  191623. void /* PRIVATE */
  191624. png_do_unpack(png_row_infop row_info, png_bytep row)
  191625. {
  191626. png_debug(1, "in png_do_unpack\n");
  191627. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191628. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191629. #else
  191630. if (row_info->bit_depth < 8)
  191631. #endif
  191632. {
  191633. png_uint_32 i;
  191634. png_uint_32 row_width=row_info->width;
  191635. switch (row_info->bit_depth)
  191636. {
  191637. case 1:
  191638. {
  191639. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191640. png_bytep dp = row + (png_size_t)row_width - 1;
  191641. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191642. for (i = 0; i < row_width; i++)
  191643. {
  191644. *dp = (png_byte)((*sp >> shift) & 0x01);
  191645. if (shift == 7)
  191646. {
  191647. shift = 0;
  191648. sp--;
  191649. }
  191650. else
  191651. shift++;
  191652. dp--;
  191653. }
  191654. break;
  191655. }
  191656. case 2:
  191657. {
  191658. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191659. png_bytep dp = row + (png_size_t)row_width - 1;
  191660. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191661. for (i = 0; i < row_width; i++)
  191662. {
  191663. *dp = (png_byte)((*sp >> shift) & 0x03);
  191664. if (shift == 6)
  191665. {
  191666. shift = 0;
  191667. sp--;
  191668. }
  191669. else
  191670. shift += 2;
  191671. dp--;
  191672. }
  191673. break;
  191674. }
  191675. case 4:
  191676. {
  191677. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191678. png_bytep dp = row + (png_size_t)row_width - 1;
  191679. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191680. for (i = 0; i < row_width; i++)
  191681. {
  191682. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191683. if (shift == 4)
  191684. {
  191685. shift = 0;
  191686. sp--;
  191687. }
  191688. else
  191689. shift = 4;
  191690. dp--;
  191691. }
  191692. break;
  191693. }
  191694. }
  191695. row_info->bit_depth = 8;
  191696. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191697. row_info->rowbytes = row_width * row_info->channels;
  191698. }
  191699. }
  191700. #endif
  191701. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191702. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191703. * pixels back to their significant bits values. Thus, if you have
  191704. * a row of bit depth 8, but only 5 are significant, this will shift
  191705. * the values back to 0 through 31.
  191706. */
  191707. void /* PRIVATE */
  191708. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191709. {
  191710. png_debug(1, "in png_do_unshift\n");
  191711. if (
  191712. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191713. row != NULL && row_info != NULL && sig_bits != NULL &&
  191714. #endif
  191715. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191716. {
  191717. int shift[4];
  191718. int channels = 0;
  191719. int c;
  191720. png_uint_16 value = 0;
  191721. png_uint_32 row_width = row_info->width;
  191722. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191723. {
  191724. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191725. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191726. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191727. }
  191728. else
  191729. {
  191730. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191731. }
  191732. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191733. {
  191734. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191735. }
  191736. for (c = 0; c < channels; c++)
  191737. {
  191738. if (shift[c] <= 0)
  191739. shift[c] = 0;
  191740. else
  191741. value = 1;
  191742. }
  191743. if (!value)
  191744. return;
  191745. switch (row_info->bit_depth)
  191746. {
  191747. case 2:
  191748. {
  191749. png_bytep bp;
  191750. png_uint_32 i;
  191751. png_uint_32 istop = row_info->rowbytes;
  191752. for (bp = row, i = 0; i < istop; i++)
  191753. {
  191754. *bp >>= 1;
  191755. *bp++ &= 0x55;
  191756. }
  191757. break;
  191758. }
  191759. case 4:
  191760. {
  191761. png_bytep bp = row;
  191762. png_uint_32 i;
  191763. png_uint_32 istop = row_info->rowbytes;
  191764. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191765. (png_byte)((int)0xf >> shift[0]));
  191766. for (i = 0; i < istop; i++)
  191767. {
  191768. *bp >>= shift[0];
  191769. *bp++ &= mask;
  191770. }
  191771. break;
  191772. }
  191773. case 8:
  191774. {
  191775. png_bytep bp = row;
  191776. png_uint_32 i;
  191777. png_uint_32 istop = row_width * channels;
  191778. for (i = 0; i < istop; i++)
  191779. {
  191780. *bp++ >>= shift[i%channels];
  191781. }
  191782. break;
  191783. }
  191784. case 16:
  191785. {
  191786. png_bytep bp = row;
  191787. png_uint_32 i;
  191788. png_uint_32 istop = channels * row_width;
  191789. for (i = 0; i < istop; i++)
  191790. {
  191791. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191792. value >>= shift[i%channels];
  191793. *bp++ = (png_byte)(value >> 8);
  191794. *bp++ = (png_byte)(value & 0xff);
  191795. }
  191796. break;
  191797. }
  191798. }
  191799. }
  191800. }
  191801. #endif
  191802. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191803. /* chop rows of bit depth 16 down to 8 */
  191804. void /* PRIVATE */
  191805. png_do_chop(png_row_infop row_info, png_bytep row)
  191806. {
  191807. png_debug(1, "in png_do_chop\n");
  191808. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191809. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191810. #else
  191811. if (row_info->bit_depth == 16)
  191812. #endif
  191813. {
  191814. png_bytep sp = row;
  191815. png_bytep dp = row;
  191816. png_uint_32 i;
  191817. png_uint_32 istop = row_info->width * row_info->channels;
  191818. for (i = 0; i<istop; i++, sp += 2, dp++)
  191819. {
  191820. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191821. /* This does a more accurate scaling of the 16-bit color
  191822. * value, rather than a simple low-byte truncation.
  191823. *
  191824. * What the ideal calculation should be:
  191825. * *dp = (((((png_uint_32)(*sp) << 8) |
  191826. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191827. *
  191828. * GRR: no, I think this is what it really should be:
  191829. * *dp = (((((png_uint_32)(*sp) << 8) |
  191830. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191831. *
  191832. * GRR: here's the exact calculation with shifts:
  191833. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191834. * *dp = (temp - (temp >> 8)) >> 8;
  191835. *
  191836. * Approximate calculation with shift/add instead of multiply/divide:
  191837. * *dp = ((((png_uint_32)(*sp) << 8) |
  191838. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191839. *
  191840. * What we actually do to avoid extra shifting and conversion:
  191841. */
  191842. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191843. #else
  191844. /* Simply discard the low order byte */
  191845. *dp = *sp;
  191846. #endif
  191847. }
  191848. row_info->bit_depth = 8;
  191849. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191850. row_info->rowbytes = row_info->width * row_info->channels;
  191851. }
  191852. }
  191853. #endif
  191854. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191855. void /* PRIVATE */
  191856. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191857. {
  191858. png_debug(1, "in png_do_read_swap_alpha\n");
  191859. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191860. if (row != NULL && row_info != NULL)
  191861. #endif
  191862. {
  191863. png_uint_32 row_width = row_info->width;
  191864. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191865. {
  191866. /* This converts from RGBA to ARGB */
  191867. if (row_info->bit_depth == 8)
  191868. {
  191869. png_bytep sp = row + row_info->rowbytes;
  191870. png_bytep dp = sp;
  191871. png_byte save;
  191872. png_uint_32 i;
  191873. for (i = 0; i < row_width; i++)
  191874. {
  191875. save = *(--sp);
  191876. *(--dp) = *(--sp);
  191877. *(--dp) = *(--sp);
  191878. *(--dp) = *(--sp);
  191879. *(--dp) = save;
  191880. }
  191881. }
  191882. /* This converts from RRGGBBAA to AARRGGBB */
  191883. else
  191884. {
  191885. png_bytep sp = row + row_info->rowbytes;
  191886. png_bytep dp = sp;
  191887. png_byte save[2];
  191888. png_uint_32 i;
  191889. for (i = 0; i < row_width; i++)
  191890. {
  191891. save[0] = *(--sp);
  191892. save[1] = *(--sp);
  191893. *(--dp) = *(--sp);
  191894. *(--dp) = *(--sp);
  191895. *(--dp) = *(--sp);
  191896. *(--dp) = *(--sp);
  191897. *(--dp) = *(--sp);
  191898. *(--dp) = *(--sp);
  191899. *(--dp) = save[0];
  191900. *(--dp) = save[1];
  191901. }
  191902. }
  191903. }
  191904. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191905. {
  191906. /* This converts from GA to AG */
  191907. if (row_info->bit_depth == 8)
  191908. {
  191909. png_bytep sp = row + row_info->rowbytes;
  191910. png_bytep dp = sp;
  191911. png_byte save;
  191912. png_uint_32 i;
  191913. for (i = 0; i < row_width; i++)
  191914. {
  191915. save = *(--sp);
  191916. *(--dp) = *(--sp);
  191917. *(--dp) = save;
  191918. }
  191919. }
  191920. /* This converts from GGAA to AAGG */
  191921. else
  191922. {
  191923. png_bytep sp = row + row_info->rowbytes;
  191924. png_bytep dp = sp;
  191925. png_byte save[2];
  191926. png_uint_32 i;
  191927. for (i = 0; i < row_width; i++)
  191928. {
  191929. save[0] = *(--sp);
  191930. save[1] = *(--sp);
  191931. *(--dp) = *(--sp);
  191932. *(--dp) = *(--sp);
  191933. *(--dp) = save[0];
  191934. *(--dp) = save[1];
  191935. }
  191936. }
  191937. }
  191938. }
  191939. }
  191940. #endif
  191941. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191942. void /* PRIVATE */
  191943. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191944. {
  191945. png_debug(1, "in png_do_read_invert_alpha\n");
  191946. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191947. if (row != NULL && row_info != NULL)
  191948. #endif
  191949. {
  191950. png_uint_32 row_width = row_info->width;
  191951. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191952. {
  191953. /* This inverts the alpha channel in RGBA */
  191954. if (row_info->bit_depth == 8)
  191955. {
  191956. png_bytep sp = row + row_info->rowbytes;
  191957. png_bytep dp = sp;
  191958. png_uint_32 i;
  191959. for (i = 0; i < row_width; i++)
  191960. {
  191961. *(--dp) = (png_byte)(255 - *(--sp));
  191962. /* This does nothing:
  191963. *(--dp) = *(--sp);
  191964. *(--dp) = *(--sp);
  191965. *(--dp) = *(--sp);
  191966. We can replace it with:
  191967. */
  191968. sp-=3;
  191969. dp=sp;
  191970. }
  191971. }
  191972. /* This inverts the alpha channel in RRGGBBAA */
  191973. else
  191974. {
  191975. png_bytep sp = row + row_info->rowbytes;
  191976. png_bytep dp = sp;
  191977. png_uint_32 i;
  191978. for (i = 0; i < row_width; i++)
  191979. {
  191980. *(--dp) = (png_byte)(255 - *(--sp));
  191981. *(--dp) = (png_byte)(255 - *(--sp));
  191982. /* This does nothing:
  191983. *(--dp) = *(--sp);
  191984. *(--dp) = *(--sp);
  191985. *(--dp) = *(--sp);
  191986. *(--dp) = *(--sp);
  191987. *(--dp) = *(--sp);
  191988. *(--dp) = *(--sp);
  191989. We can replace it with:
  191990. */
  191991. sp-=6;
  191992. dp=sp;
  191993. }
  191994. }
  191995. }
  191996. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191997. {
  191998. /* This inverts the alpha channel in GA */
  191999. if (row_info->bit_depth == 8)
  192000. {
  192001. png_bytep sp = row + row_info->rowbytes;
  192002. png_bytep dp = sp;
  192003. png_uint_32 i;
  192004. for (i = 0; i < row_width; i++)
  192005. {
  192006. *(--dp) = (png_byte)(255 - *(--sp));
  192007. *(--dp) = *(--sp);
  192008. }
  192009. }
  192010. /* This inverts the alpha channel in GGAA */
  192011. else
  192012. {
  192013. png_bytep sp = row + row_info->rowbytes;
  192014. png_bytep dp = sp;
  192015. png_uint_32 i;
  192016. for (i = 0; i < row_width; i++)
  192017. {
  192018. *(--dp) = (png_byte)(255 - *(--sp));
  192019. *(--dp) = (png_byte)(255 - *(--sp));
  192020. /*
  192021. *(--dp) = *(--sp);
  192022. *(--dp) = *(--sp);
  192023. */
  192024. sp-=2;
  192025. dp=sp;
  192026. }
  192027. }
  192028. }
  192029. }
  192030. }
  192031. #endif
  192032. #if defined(PNG_READ_FILLER_SUPPORTED)
  192033. /* Add filler channel if we have RGB color */
  192034. void /* PRIVATE */
  192035. png_do_read_filler(png_row_infop row_info, png_bytep row,
  192036. png_uint_32 filler, png_uint_32 flags)
  192037. {
  192038. png_uint_32 i;
  192039. png_uint_32 row_width = row_info->width;
  192040. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  192041. png_byte lo_filler = (png_byte)(filler & 0xff);
  192042. png_debug(1, "in png_do_read_filler\n");
  192043. if (
  192044. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192045. row != NULL && row_info != NULL &&
  192046. #endif
  192047. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192048. {
  192049. if(row_info->bit_depth == 8)
  192050. {
  192051. /* This changes the data from G to GX */
  192052. if (flags & PNG_FLAG_FILLER_AFTER)
  192053. {
  192054. png_bytep sp = row + (png_size_t)row_width;
  192055. png_bytep dp = sp + (png_size_t)row_width;
  192056. for (i = 1; i < row_width; i++)
  192057. {
  192058. *(--dp) = lo_filler;
  192059. *(--dp) = *(--sp);
  192060. }
  192061. *(--dp) = lo_filler;
  192062. row_info->channels = 2;
  192063. row_info->pixel_depth = 16;
  192064. row_info->rowbytes = row_width * 2;
  192065. }
  192066. /* This changes the data from G to XG */
  192067. else
  192068. {
  192069. png_bytep sp = row + (png_size_t)row_width;
  192070. png_bytep dp = sp + (png_size_t)row_width;
  192071. for (i = 0; i < row_width; i++)
  192072. {
  192073. *(--dp) = *(--sp);
  192074. *(--dp) = lo_filler;
  192075. }
  192076. row_info->channels = 2;
  192077. row_info->pixel_depth = 16;
  192078. row_info->rowbytes = row_width * 2;
  192079. }
  192080. }
  192081. else if(row_info->bit_depth == 16)
  192082. {
  192083. /* This changes the data from GG to GGXX */
  192084. if (flags & PNG_FLAG_FILLER_AFTER)
  192085. {
  192086. png_bytep sp = row + (png_size_t)row_width * 2;
  192087. png_bytep dp = sp + (png_size_t)row_width * 2;
  192088. for (i = 1; i < row_width; i++)
  192089. {
  192090. *(--dp) = hi_filler;
  192091. *(--dp) = lo_filler;
  192092. *(--dp) = *(--sp);
  192093. *(--dp) = *(--sp);
  192094. }
  192095. *(--dp) = hi_filler;
  192096. *(--dp) = lo_filler;
  192097. row_info->channels = 2;
  192098. row_info->pixel_depth = 32;
  192099. row_info->rowbytes = row_width * 4;
  192100. }
  192101. /* This changes the data from GG to XXGG */
  192102. else
  192103. {
  192104. png_bytep sp = row + (png_size_t)row_width * 2;
  192105. png_bytep dp = sp + (png_size_t)row_width * 2;
  192106. for (i = 0; i < row_width; i++)
  192107. {
  192108. *(--dp) = *(--sp);
  192109. *(--dp) = *(--sp);
  192110. *(--dp) = hi_filler;
  192111. *(--dp) = lo_filler;
  192112. }
  192113. row_info->channels = 2;
  192114. row_info->pixel_depth = 32;
  192115. row_info->rowbytes = row_width * 4;
  192116. }
  192117. }
  192118. } /* COLOR_TYPE == GRAY */
  192119. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192120. {
  192121. if(row_info->bit_depth == 8)
  192122. {
  192123. /* This changes the data from RGB to RGBX */
  192124. if (flags & PNG_FLAG_FILLER_AFTER)
  192125. {
  192126. png_bytep sp = row + (png_size_t)row_width * 3;
  192127. png_bytep dp = sp + (png_size_t)row_width;
  192128. for (i = 1; i < row_width; i++)
  192129. {
  192130. *(--dp) = lo_filler;
  192131. *(--dp) = *(--sp);
  192132. *(--dp) = *(--sp);
  192133. *(--dp) = *(--sp);
  192134. }
  192135. *(--dp) = lo_filler;
  192136. row_info->channels = 4;
  192137. row_info->pixel_depth = 32;
  192138. row_info->rowbytes = row_width * 4;
  192139. }
  192140. /* This changes the data from RGB to XRGB */
  192141. else
  192142. {
  192143. png_bytep sp = row + (png_size_t)row_width * 3;
  192144. png_bytep dp = sp + (png_size_t)row_width;
  192145. for (i = 0; i < row_width; i++)
  192146. {
  192147. *(--dp) = *(--sp);
  192148. *(--dp) = *(--sp);
  192149. *(--dp) = *(--sp);
  192150. *(--dp) = lo_filler;
  192151. }
  192152. row_info->channels = 4;
  192153. row_info->pixel_depth = 32;
  192154. row_info->rowbytes = row_width * 4;
  192155. }
  192156. }
  192157. else if(row_info->bit_depth == 16)
  192158. {
  192159. /* This changes the data from RRGGBB to RRGGBBXX */
  192160. if (flags & PNG_FLAG_FILLER_AFTER)
  192161. {
  192162. png_bytep sp = row + (png_size_t)row_width * 6;
  192163. png_bytep dp = sp + (png_size_t)row_width * 2;
  192164. for (i = 1; i < row_width; i++)
  192165. {
  192166. *(--dp) = hi_filler;
  192167. *(--dp) = lo_filler;
  192168. *(--dp) = *(--sp);
  192169. *(--dp) = *(--sp);
  192170. *(--dp) = *(--sp);
  192171. *(--dp) = *(--sp);
  192172. *(--dp) = *(--sp);
  192173. *(--dp) = *(--sp);
  192174. }
  192175. *(--dp) = hi_filler;
  192176. *(--dp) = lo_filler;
  192177. row_info->channels = 4;
  192178. row_info->pixel_depth = 64;
  192179. row_info->rowbytes = row_width * 8;
  192180. }
  192181. /* This changes the data from RRGGBB to XXRRGGBB */
  192182. else
  192183. {
  192184. png_bytep sp = row + (png_size_t)row_width * 6;
  192185. png_bytep dp = sp + (png_size_t)row_width * 2;
  192186. for (i = 0; i < row_width; i++)
  192187. {
  192188. *(--dp) = *(--sp);
  192189. *(--dp) = *(--sp);
  192190. *(--dp) = *(--sp);
  192191. *(--dp) = *(--sp);
  192192. *(--dp) = *(--sp);
  192193. *(--dp) = *(--sp);
  192194. *(--dp) = hi_filler;
  192195. *(--dp) = lo_filler;
  192196. }
  192197. row_info->channels = 4;
  192198. row_info->pixel_depth = 64;
  192199. row_info->rowbytes = row_width * 8;
  192200. }
  192201. }
  192202. } /* COLOR_TYPE == RGB */
  192203. }
  192204. #endif
  192205. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192206. /* expand grayscale files to RGB, with or without alpha */
  192207. void /* PRIVATE */
  192208. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192209. {
  192210. png_uint_32 i;
  192211. png_uint_32 row_width = row_info->width;
  192212. png_debug(1, "in png_do_gray_to_rgb\n");
  192213. if (row_info->bit_depth >= 8 &&
  192214. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192215. row != NULL && row_info != NULL &&
  192216. #endif
  192217. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192218. {
  192219. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192220. {
  192221. if (row_info->bit_depth == 8)
  192222. {
  192223. png_bytep sp = row + (png_size_t)row_width - 1;
  192224. png_bytep dp = sp + (png_size_t)row_width * 2;
  192225. for (i = 0; i < row_width; i++)
  192226. {
  192227. *(dp--) = *sp;
  192228. *(dp--) = *sp;
  192229. *(dp--) = *(sp--);
  192230. }
  192231. }
  192232. else
  192233. {
  192234. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192235. png_bytep dp = sp + (png_size_t)row_width * 4;
  192236. for (i = 0; i < row_width; i++)
  192237. {
  192238. *(dp--) = *sp;
  192239. *(dp--) = *(sp - 1);
  192240. *(dp--) = *sp;
  192241. *(dp--) = *(sp - 1);
  192242. *(dp--) = *(sp--);
  192243. *(dp--) = *(sp--);
  192244. }
  192245. }
  192246. }
  192247. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192248. {
  192249. if (row_info->bit_depth == 8)
  192250. {
  192251. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192252. png_bytep dp = sp + (png_size_t)row_width * 2;
  192253. for (i = 0; i < row_width; i++)
  192254. {
  192255. *(dp--) = *(sp--);
  192256. *(dp--) = *sp;
  192257. *(dp--) = *sp;
  192258. *(dp--) = *(sp--);
  192259. }
  192260. }
  192261. else
  192262. {
  192263. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192264. png_bytep dp = sp + (png_size_t)row_width * 4;
  192265. for (i = 0; i < row_width; i++)
  192266. {
  192267. *(dp--) = *(sp--);
  192268. *(dp--) = *(sp--);
  192269. *(dp--) = *sp;
  192270. *(dp--) = *(sp - 1);
  192271. *(dp--) = *sp;
  192272. *(dp--) = *(sp - 1);
  192273. *(dp--) = *(sp--);
  192274. *(dp--) = *(sp--);
  192275. }
  192276. }
  192277. }
  192278. row_info->channels += (png_byte)2;
  192279. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192280. row_info->pixel_depth = (png_byte)(row_info->channels *
  192281. row_info->bit_depth);
  192282. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192283. }
  192284. }
  192285. #endif
  192286. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192287. /* reduce RGB files to grayscale, with or without alpha
  192288. * using the equation given in Poynton's ColorFAQ at
  192289. * <http://www.inforamp.net/~poynton/>
  192290. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192291. *
  192292. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192293. *
  192294. * We approximate this with
  192295. *
  192296. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192297. *
  192298. * which can be expressed with integers as
  192299. *
  192300. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192301. *
  192302. * The calculation is to be done in a linear colorspace.
  192303. *
  192304. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192305. */
  192306. int /* PRIVATE */
  192307. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192308. {
  192309. png_uint_32 i;
  192310. png_uint_32 row_width = row_info->width;
  192311. int rgb_error = 0;
  192312. png_debug(1, "in png_do_rgb_to_gray\n");
  192313. if (
  192314. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192315. row != NULL && row_info != NULL &&
  192316. #endif
  192317. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192318. {
  192319. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192320. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192321. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192322. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192323. {
  192324. if (row_info->bit_depth == 8)
  192325. {
  192326. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192327. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192328. {
  192329. png_bytep sp = row;
  192330. png_bytep dp = row;
  192331. for (i = 0; i < row_width; i++)
  192332. {
  192333. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192334. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192335. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192336. if(red != green || red != blue)
  192337. {
  192338. rgb_error |= 1;
  192339. *(dp++) = png_ptr->gamma_from_1[
  192340. (rc*red+gc*green+bc*blue)>>15];
  192341. }
  192342. else
  192343. *(dp++) = *(sp-1);
  192344. }
  192345. }
  192346. else
  192347. #endif
  192348. {
  192349. png_bytep sp = row;
  192350. png_bytep dp = row;
  192351. for (i = 0; i < row_width; i++)
  192352. {
  192353. png_byte red = *(sp++);
  192354. png_byte green = *(sp++);
  192355. png_byte blue = *(sp++);
  192356. if(red != green || red != blue)
  192357. {
  192358. rgb_error |= 1;
  192359. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192360. }
  192361. else
  192362. *(dp++) = *(sp-1);
  192363. }
  192364. }
  192365. }
  192366. else /* RGB bit_depth == 16 */
  192367. {
  192368. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192369. if (png_ptr->gamma_16_to_1 != NULL &&
  192370. png_ptr->gamma_16_from_1 != NULL)
  192371. {
  192372. png_bytep sp = row;
  192373. png_bytep dp = row;
  192374. for (i = 0; i < row_width; i++)
  192375. {
  192376. png_uint_16 red, green, blue, w;
  192377. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192378. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192379. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192380. if(red == green && red == blue)
  192381. w = red;
  192382. else
  192383. {
  192384. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192385. png_ptr->gamma_shift][red>>8];
  192386. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192387. png_ptr->gamma_shift][green>>8];
  192388. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192389. png_ptr->gamma_shift][blue>>8];
  192390. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192391. + bc*blue_1)>>15);
  192392. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192393. png_ptr->gamma_shift][gray16 >> 8];
  192394. rgb_error |= 1;
  192395. }
  192396. *(dp++) = (png_byte)((w>>8) & 0xff);
  192397. *(dp++) = (png_byte)(w & 0xff);
  192398. }
  192399. }
  192400. else
  192401. #endif
  192402. {
  192403. png_bytep sp = row;
  192404. png_bytep dp = row;
  192405. for (i = 0; i < row_width; i++)
  192406. {
  192407. png_uint_16 red, green, blue, gray16;
  192408. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192409. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192410. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192411. if(red != green || red != blue)
  192412. rgb_error |= 1;
  192413. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192414. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192415. *(dp++) = (png_byte)(gray16 & 0xff);
  192416. }
  192417. }
  192418. }
  192419. }
  192420. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192421. {
  192422. if (row_info->bit_depth == 8)
  192423. {
  192424. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192425. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192426. {
  192427. png_bytep sp = row;
  192428. png_bytep dp = row;
  192429. for (i = 0; i < row_width; i++)
  192430. {
  192431. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192432. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192433. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192434. if(red != green || red != blue)
  192435. rgb_error |= 1;
  192436. *(dp++) = png_ptr->gamma_from_1
  192437. [(rc*red + gc*green + bc*blue)>>15];
  192438. *(dp++) = *(sp++); /* alpha */
  192439. }
  192440. }
  192441. else
  192442. #endif
  192443. {
  192444. png_bytep sp = row;
  192445. png_bytep dp = row;
  192446. for (i = 0; i < row_width; i++)
  192447. {
  192448. png_byte red = *(sp++);
  192449. png_byte green = *(sp++);
  192450. png_byte blue = *(sp++);
  192451. if(red != green || red != blue)
  192452. rgb_error |= 1;
  192453. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192454. *(dp++) = *(sp++); /* alpha */
  192455. }
  192456. }
  192457. }
  192458. else /* RGBA bit_depth == 16 */
  192459. {
  192460. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192461. if (png_ptr->gamma_16_to_1 != NULL &&
  192462. png_ptr->gamma_16_from_1 != NULL)
  192463. {
  192464. png_bytep sp = row;
  192465. png_bytep dp = row;
  192466. for (i = 0; i < row_width; i++)
  192467. {
  192468. png_uint_16 red, green, blue, w;
  192469. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192470. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192471. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192472. if(red == green && red == blue)
  192473. w = red;
  192474. else
  192475. {
  192476. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192477. png_ptr->gamma_shift][red>>8];
  192478. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192479. png_ptr->gamma_shift][green>>8];
  192480. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192481. png_ptr->gamma_shift][blue>>8];
  192482. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192483. + gc * green_1 + bc * blue_1)>>15);
  192484. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192485. png_ptr->gamma_shift][gray16 >> 8];
  192486. rgb_error |= 1;
  192487. }
  192488. *(dp++) = (png_byte)((w>>8) & 0xff);
  192489. *(dp++) = (png_byte)(w & 0xff);
  192490. *(dp++) = *(sp++); /* alpha */
  192491. *(dp++) = *(sp++);
  192492. }
  192493. }
  192494. else
  192495. #endif
  192496. {
  192497. png_bytep sp = row;
  192498. png_bytep dp = row;
  192499. for (i = 0; i < row_width; i++)
  192500. {
  192501. png_uint_16 red, green, blue, gray16;
  192502. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192503. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192504. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192505. if(red != green || red != blue)
  192506. rgb_error |= 1;
  192507. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192508. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192509. *(dp++) = (png_byte)(gray16 & 0xff);
  192510. *(dp++) = *(sp++); /* alpha */
  192511. *(dp++) = *(sp++);
  192512. }
  192513. }
  192514. }
  192515. }
  192516. row_info->channels -= (png_byte)2;
  192517. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192518. row_info->pixel_depth = (png_byte)(row_info->channels *
  192519. row_info->bit_depth);
  192520. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192521. }
  192522. return rgb_error;
  192523. }
  192524. #endif
  192525. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192526. * large of png_color. This lets grayscale images be treated as
  192527. * paletted. Most useful for gamma correction and simplification
  192528. * of code.
  192529. */
  192530. void PNGAPI
  192531. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192532. {
  192533. int num_palette;
  192534. int color_inc;
  192535. int i;
  192536. int v;
  192537. png_debug(1, "in png_do_build_grayscale_palette\n");
  192538. if (palette == NULL)
  192539. return;
  192540. switch (bit_depth)
  192541. {
  192542. case 1:
  192543. num_palette = 2;
  192544. color_inc = 0xff;
  192545. break;
  192546. case 2:
  192547. num_palette = 4;
  192548. color_inc = 0x55;
  192549. break;
  192550. case 4:
  192551. num_palette = 16;
  192552. color_inc = 0x11;
  192553. break;
  192554. case 8:
  192555. num_palette = 256;
  192556. color_inc = 1;
  192557. break;
  192558. default:
  192559. num_palette = 0;
  192560. color_inc = 0;
  192561. break;
  192562. }
  192563. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192564. {
  192565. palette[i].red = (png_byte)v;
  192566. palette[i].green = (png_byte)v;
  192567. palette[i].blue = (png_byte)v;
  192568. }
  192569. }
  192570. /* This function is currently unused. Do we really need it? */
  192571. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192572. void /* PRIVATE */
  192573. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192574. int num_palette)
  192575. {
  192576. png_debug(1, "in png_correct_palette\n");
  192577. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192578. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192579. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192580. {
  192581. png_color back, back_1;
  192582. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192583. {
  192584. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192585. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192586. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192587. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192588. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192589. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192590. }
  192591. else
  192592. {
  192593. double g;
  192594. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192595. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192596. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192597. {
  192598. back.red = png_ptr->background.red;
  192599. back.green = png_ptr->background.green;
  192600. back.blue = png_ptr->background.blue;
  192601. }
  192602. else
  192603. {
  192604. back.red =
  192605. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192606. 255.0 + 0.5);
  192607. back.green =
  192608. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192609. 255.0 + 0.5);
  192610. back.blue =
  192611. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192612. 255.0 + 0.5);
  192613. }
  192614. g = 1.0 / png_ptr->background_gamma;
  192615. back_1.red =
  192616. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192617. 255.0 + 0.5);
  192618. back_1.green =
  192619. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192620. 255.0 + 0.5);
  192621. back_1.blue =
  192622. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192623. 255.0 + 0.5);
  192624. }
  192625. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192626. {
  192627. png_uint_32 i;
  192628. for (i = 0; i < (png_uint_32)num_palette; i++)
  192629. {
  192630. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192631. {
  192632. palette[i] = back;
  192633. }
  192634. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192635. {
  192636. png_byte v, w;
  192637. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192638. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192639. palette[i].red = png_ptr->gamma_from_1[w];
  192640. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192641. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192642. palette[i].green = png_ptr->gamma_from_1[w];
  192643. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192644. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192645. palette[i].blue = png_ptr->gamma_from_1[w];
  192646. }
  192647. else
  192648. {
  192649. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192650. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192651. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192652. }
  192653. }
  192654. }
  192655. else
  192656. {
  192657. int i;
  192658. for (i = 0; i < num_palette; i++)
  192659. {
  192660. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192661. {
  192662. palette[i] = back;
  192663. }
  192664. else
  192665. {
  192666. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192667. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192668. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192669. }
  192670. }
  192671. }
  192672. }
  192673. else
  192674. #endif
  192675. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192676. if (png_ptr->transformations & PNG_GAMMA)
  192677. {
  192678. int i;
  192679. for (i = 0; i < num_palette; i++)
  192680. {
  192681. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192682. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192683. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192684. }
  192685. }
  192686. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192687. else
  192688. #endif
  192689. #endif
  192690. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192691. if (png_ptr->transformations & PNG_BACKGROUND)
  192692. {
  192693. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192694. {
  192695. png_color back;
  192696. back.red = (png_byte)png_ptr->background.red;
  192697. back.green = (png_byte)png_ptr->background.green;
  192698. back.blue = (png_byte)png_ptr->background.blue;
  192699. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192700. {
  192701. if (png_ptr->trans[i] == 0)
  192702. {
  192703. palette[i].red = back.red;
  192704. palette[i].green = back.green;
  192705. palette[i].blue = back.blue;
  192706. }
  192707. else if (png_ptr->trans[i] != 0xff)
  192708. {
  192709. png_composite(palette[i].red, png_ptr->palette[i].red,
  192710. png_ptr->trans[i], back.red);
  192711. png_composite(palette[i].green, png_ptr->palette[i].green,
  192712. png_ptr->trans[i], back.green);
  192713. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192714. png_ptr->trans[i], back.blue);
  192715. }
  192716. }
  192717. }
  192718. else /* assume grayscale palette (what else could it be?) */
  192719. {
  192720. int i;
  192721. for (i = 0; i < num_palette; i++)
  192722. {
  192723. if (i == (png_byte)png_ptr->trans_values.gray)
  192724. {
  192725. palette[i].red = (png_byte)png_ptr->background.red;
  192726. palette[i].green = (png_byte)png_ptr->background.green;
  192727. palette[i].blue = (png_byte)png_ptr->background.blue;
  192728. }
  192729. }
  192730. }
  192731. }
  192732. #endif
  192733. }
  192734. #endif
  192735. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192736. /* Replace any alpha or transparency with the supplied background color.
  192737. * "background" is already in the screen gamma, while "background_1" is
  192738. * at a gamma of 1.0. Paletted files have already been taken care of.
  192739. */
  192740. void /* PRIVATE */
  192741. png_do_background(png_row_infop row_info, png_bytep row,
  192742. png_color_16p trans_values, png_color_16p background
  192743. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192744. , png_color_16p background_1,
  192745. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192746. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192747. png_uint_16pp gamma_16_to_1, int gamma_shift
  192748. #endif
  192749. )
  192750. {
  192751. png_bytep sp, dp;
  192752. png_uint_32 i;
  192753. png_uint_32 row_width=row_info->width;
  192754. int shift;
  192755. png_debug(1, "in png_do_background\n");
  192756. if (background != NULL &&
  192757. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192758. row != NULL && row_info != NULL &&
  192759. #endif
  192760. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192761. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192762. {
  192763. switch (row_info->color_type)
  192764. {
  192765. case PNG_COLOR_TYPE_GRAY:
  192766. {
  192767. switch (row_info->bit_depth)
  192768. {
  192769. case 1:
  192770. {
  192771. sp = row;
  192772. shift = 7;
  192773. for (i = 0; i < row_width; i++)
  192774. {
  192775. if ((png_uint_16)((*sp >> shift) & 0x01)
  192776. == trans_values->gray)
  192777. {
  192778. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192779. *sp |= (png_byte)(background->gray << shift);
  192780. }
  192781. if (!shift)
  192782. {
  192783. shift = 7;
  192784. sp++;
  192785. }
  192786. else
  192787. shift--;
  192788. }
  192789. break;
  192790. }
  192791. case 2:
  192792. {
  192793. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192794. if (gamma_table != NULL)
  192795. {
  192796. sp = row;
  192797. shift = 6;
  192798. for (i = 0; i < row_width; i++)
  192799. {
  192800. if ((png_uint_16)((*sp >> shift) & 0x03)
  192801. == trans_values->gray)
  192802. {
  192803. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192804. *sp |= (png_byte)(background->gray << shift);
  192805. }
  192806. else
  192807. {
  192808. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192809. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192810. (p << 4) | (p << 6)] >> 6) & 0x03);
  192811. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192812. *sp |= (png_byte)(g << shift);
  192813. }
  192814. if (!shift)
  192815. {
  192816. shift = 6;
  192817. sp++;
  192818. }
  192819. else
  192820. shift -= 2;
  192821. }
  192822. }
  192823. else
  192824. #endif
  192825. {
  192826. sp = row;
  192827. shift = 6;
  192828. for (i = 0; i < row_width; i++)
  192829. {
  192830. if ((png_uint_16)((*sp >> shift) & 0x03)
  192831. == trans_values->gray)
  192832. {
  192833. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192834. *sp |= (png_byte)(background->gray << shift);
  192835. }
  192836. if (!shift)
  192837. {
  192838. shift = 6;
  192839. sp++;
  192840. }
  192841. else
  192842. shift -= 2;
  192843. }
  192844. }
  192845. break;
  192846. }
  192847. case 4:
  192848. {
  192849. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192850. if (gamma_table != NULL)
  192851. {
  192852. sp = row;
  192853. shift = 4;
  192854. for (i = 0; i < row_width; i++)
  192855. {
  192856. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192857. == trans_values->gray)
  192858. {
  192859. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192860. *sp |= (png_byte)(background->gray << shift);
  192861. }
  192862. else
  192863. {
  192864. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192865. png_byte g = (png_byte)((gamma_table[p |
  192866. (p << 4)] >> 4) & 0x0f);
  192867. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192868. *sp |= (png_byte)(g << shift);
  192869. }
  192870. if (!shift)
  192871. {
  192872. shift = 4;
  192873. sp++;
  192874. }
  192875. else
  192876. shift -= 4;
  192877. }
  192878. }
  192879. else
  192880. #endif
  192881. {
  192882. sp = row;
  192883. shift = 4;
  192884. for (i = 0; i < row_width; i++)
  192885. {
  192886. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192887. == trans_values->gray)
  192888. {
  192889. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192890. *sp |= (png_byte)(background->gray << shift);
  192891. }
  192892. if (!shift)
  192893. {
  192894. shift = 4;
  192895. sp++;
  192896. }
  192897. else
  192898. shift -= 4;
  192899. }
  192900. }
  192901. break;
  192902. }
  192903. case 8:
  192904. {
  192905. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192906. if (gamma_table != NULL)
  192907. {
  192908. sp = row;
  192909. for (i = 0; i < row_width; i++, sp++)
  192910. {
  192911. if (*sp == trans_values->gray)
  192912. {
  192913. *sp = (png_byte)background->gray;
  192914. }
  192915. else
  192916. {
  192917. *sp = gamma_table[*sp];
  192918. }
  192919. }
  192920. }
  192921. else
  192922. #endif
  192923. {
  192924. sp = row;
  192925. for (i = 0; i < row_width; i++, sp++)
  192926. {
  192927. if (*sp == trans_values->gray)
  192928. {
  192929. *sp = (png_byte)background->gray;
  192930. }
  192931. }
  192932. }
  192933. break;
  192934. }
  192935. case 16:
  192936. {
  192937. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192938. if (gamma_16 != NULL)
  192939. {
  192940. sp = row;
  192941. for (i = 0; i < row_width; i++, sp += 2)
  192942. {
  192943. png_uint_16 v;
  192944. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192945. if (v == trans_values->gray)
  192946. {
  192947. /* background is already in screen gamma */
  192948. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192949. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192950. }
  192951. else
  192952. {
  192953. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192954. *sp = (png_byte)((v >> 8) & 0xff);
  192955. *(sp + 1) = (png_byte)(v & 0xff);
  192956. }
  192957. }
  192958. }
  192959. else
  192960. #endif
  192961. {
  192962. sp = row;
  192963. for (i = 0; i < row_width; i++, sp += 2)
  192964. {
  192965. png_uint_16 v;
  192966. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192967. if (v == trans_values->gray)
  192968. {
  192969. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192970. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192971. }
  192972. }
  192973. }
  192974. break;
  192975. }
  192976. }
  192977. break;
  192978. }
  192979. case PNG_COLOR_TYPE_RGB:
  192980. {
  192981. if (row_info->bit_depth == 8)
  192982. {
  192983. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192984. if (gamma_table != NULL)
  192985. {
  192986. sp = row;
  192987. for (i = 0; i < row_width; i++, sp += 3)
  192988. {
  192989. if (*sp == trans_values->red &&
  192990. *(sp + 1) == trans_values->green &&
  192991. *(sp + 2) == trans_values->blue)
  192992. {
  192993. *sp = (png_byte)background->red;
  192994. *(sp + 1) = (png_byte)background->green;
  192995. *(sp + 2) = (png_byte)background->blue;
  192996. }
  192997. else
  192998. {
  192999. *sp = gamma_table[*sp];
  193000. *(sp + 1) = gamma_table[*(sp + 1)];
  193001. *(sp + 2) = gamma_table[*(sp + 2)];
  193002. }
  193003. }
  193004. }
  193005. else
  193006. #endif
  193007. {
  193008. sp = row;
  193009. for (i = 0; i < row_width; i++, sp += 3)
  193010. {
  193011. if (*sp == trans_values->red &&
  193012. *(sp + 1) == trans_values->green &&
  193013. *(sp + 2) == trans_values->blue)
  193014. {
  193015. *sp = (png_byte)background->red;
  193016. *(sp + 1) = (png_byte)background->green;
  193017. *(sp + 2) = (png_byte)background->blue;
  193018. }
  193019. }
  193020. }
  193021. }
  193022. else /* if (row_info->bit_depth == 16) */
  193023. {
  193024. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193025. if (gamma_16 != NULL)
  193026. {
  193027. sp = row;
  193028. for (i = 0; i < row_width; i++, sp += 6)
  193029. {
  193030. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193031. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193032. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  193033. if (r == trans_values->red && g == trans_values->green &&
  193034. b == trans_values->blue)
  193035. {
  193036. /* background is already in screen gamma */
  193037. *sp = (png_byte)((background->red >> 8) & 0xff);
  193038. *(sp + 1) = (png_byte)(background->red & 0xff);
  193039. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193040. *(sp + 3) = (png_byte)(background->green & 0xff);
  193041. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193042. *(sp + 5) = (png_byte)(background->blue & 0xff);
  193043. }
  193044. else
  193045. {
  193046. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193047. *sp = (png_byte)((v >> 8) & 0xff);
  193048. *(sp + 1) = (png_byte)(v & 0xff);
  193049. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193050. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  193051. *(sp + 3) = (png_byte)(v & 0xff);
  193052. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193053. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  193054. *(sp + 5) = (png_byte)(v & 0xff);
  193055. }
  193056. }
  193057. }
  193058. else
  193059. #endif
  193060. {
  193061. sp = row;
  193062. for (i = 0; i < row_width; i++, sp += 6)
  193063. {
  193064. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  193065. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193066. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  193067. if (r == trans_values->red && g == trans_values->green &&
  193068. b == trans_values->blue)
  193069. {
  193070. *sp = (png_byte)((background->red >> 8) & 0xff);
  193071. *(sp + 1) = (png_byte)(background->red & 0xff);
  193072. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193073. *(sp + 3) = (png_byte)(background->green & 0xff);
  193074. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193075. *(sp + 5) = (png_byte)(background->blue & 0xff);
  193076. }
  193077. }
  193078. }
  193079. }
  193080. break;
  193081. }
  193082. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193083. {
  193084. if (row_info->bit_depth == 8)
  193085. {
  193086. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193087. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193088. gamma_table != NULL)
  193089. {
  193090. sp = row;
  193091. dp = row;
  193092. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193093. {
  193094. png_uint_16 a = *(sp + 1);
  193095. if (a == 0xff)
  193096. {
  193097. *dp = gamma_table[*sp];
  193098. }
  193099. else if (a == 0)
  193100. {
  193101. /* background is already in screen gamma */
  193102. *dp = (png_byte)background->gray;
  193103. }
  193104. else
  193105. {
  193106. png_byte v, w;
  193107. v = gamma_to_1[*sp];
  193108. png_composite(w, v, a, background_1->gray);
  193109. *dp = gamma_from_1[w];
  193110. }
  193111. }
  193112. }
  193113. else
  193114. #endif
  193115. {
  193116. sp = row;
  193117. dp = row;
  193118. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193119. {
  193120. png_byte a = *(sp + 1);
  193121. if (a == 0xff)
  193122. {
  193123. *dp = *sp;
  193124. }
  193125. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193126. else if (a == 0)
  193127. {
  193128. *dp = (png_byte)background->gray;
  193129. }
  193130. else
  193131. {
  193132. png_composite(*dp, *sp, a, background_1->gray);
  193133. }
  193134. #else
  193135. *dp = (png_byte)background->gray;
  193136. #endif
  193137. }
  193138. }
  193139. }
  193140. else /* if (png_ptr->bit_depth == 16) */
  193141. {
  193142. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193143. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193144. gamma_16_to_1 != NULL)
  193145. {
  193146. sp = row;
  193147. dp = row;
  193148. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193149. {
  193150. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193151. if (a == (png_uint_16)0xffff)
  193152. {
  193153. png_uint_16 v;
  193154. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193155. *dp = (png_byte)((v >> 8) & 0xff);
  193156. *(dp + 1) = (png_byte)(v & 0xff);
  193157. }
  193158. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193159. else if (a == 0)
  193160. #else
  193161. else
  193162. #endif
  193163. {
  193164. /* background is already in screen gamma */
  193165. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193166. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193167. }
  193168. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193169. else
  193170. {
  193171. png_uint_16 g, v, w;
  193172. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193173. png_composite_16(v, g, a, background_1->gray);
  193174. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193175. *dp = (png_byte)((w >> 8) & 0xff);
  193176. *(dp + 1) = (png_byte)(w & 0xff);
  193177. }
  193178. #endif
  193179. }
  193180. }
  193181. else
  193182. #endif
  193183. {
  193184. sp = row;
  193185. dp = row;
  193186. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193187. {
  193188. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193189. if (a == (png_uint_16)0xffff)
  193190. {
  193191. png_memcpy(dp, sp, 2);
  193192. }
  193193. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193194. else if (a == 0)
  193195. #else
  193196. else
  193197. #endif
  193198. {
  193199. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193200. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193201. }
  193202. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193203. else
  193204. {
  193205. png_uint_16 g, v;
  193206. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193207. png_composite_16(v, g, a, background_1->gray);
  193208. *dp = (png_byte)((v >> 8) & 0xff);
  193209. *(dp + 1) = (png_byte)(v & 0xff);
  193210. }
  193211. #endif
  193212. }
  193213. }
  193214. }
  193215. break;
  193216. }
  193217. case PNG_COLOR_TYPE_RGB_ALPHA:
  193218. {
  193219. if (row_info->bit_depth == 8)
  193220. {
  193221. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193222. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193223. gamma_table != NULL)
  193224. {
  193225. sp = row;
  193226. dp = row;
  193227. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193228. {
  193229. png_byte a = *(sp + 3);
  193230. if (a == 0xff)
  193231. {
  193232. *dp = gamma_table[*sp];
  193233. *(dp + 1) = gamma_table[*(sp + 1)];
  193234. *(dp + 2) = gamma_table[*(sp + 2)];
  193235. }
  193236. else if (a == 0)
  193237. {
  193238. /* background is already in screen gamma */
  193239. *dp = (png_byte)background->red;
  193240. *(dp + 1) = (png_byte)background->green;
  193241. *(dp + 2) = (png_byte)background->blue;
  193242. }
  193243. else
  193244. {
  193245. png_byte v, w;
  193246. v = gamma_to_1[*sp];
  193247. png_composite(w, v, a, background_1->red);
  193248. *dp = gamma_from_1[w];
  193249. v = gamma_to_1[*(sp + 1)];
  193250. png_composite(w, v, a, background_1->green);
  193251. *(dp + 1) = gamma_from_1[w];
  193252. v = gamma_to_1[*(sp + 2)];
  193253. png_composite(w, v, a, background_1->blue);
  193254. *(dp + 2) = gamma_from_1[w];
  193255. }
  193256. }
  193257. }
  193258. else
  193259. #endif
  193260. {
  193261. sp = row;
  193262. dp = row;
  193263. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193264. {
  193265. png_byte a = *(sp + 3);
  193266. if (a == 0xff)
  193267. {
  193268. *dp = *sp;
  193269. *(dp + 1) = *(sp + 1);
  193270. *(dp + 2) = *(sp + 2);
  193271. }
  193272. else if (a == 0)
  193273. {
  193274. *dp = (png_byte)background->red;
  193275. *(dp + 1) = (png_byte)background->green;
  193276. *(dp + 2) = (png_byte)background->blue;
  193277. }
  193278. else
  193279. {
  193280. png_composite(*dp, *sp, a, background->red);
  193281. png_composite(*(dp + 1), *(sp + 1), a,
  193282. background->green);
  193283. png_composite(*(dp + 2), *(sp + 2), a,
  193284. background->blue);
  193285. }
  193286. }
  193287. }
  193288. }
  193289. else /* if (row_info->bit_depth == 16) */
  193290. {
  193291. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193292. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193293. gamma_16_to_1 != NULL)
  193294. {
  193295. sp = row;
  193296. dp = row;
  193297. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193298. {
  193299. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193300. << 8) + (png_uint_16)(*(sp + 7)));
  193301. if (a == (png_uint_16)0xffff)
  193302. {
  193303. png_uint_16 v;
  193304. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193305. *dp = (png_byte)((v >> 8) & 0xff);
  193306. *(dp + 1) = (png_byte)(v & 0xff);
  193307. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193308. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193309. *(dp + 3) = (png_byte)(v & 0xff);
  193310. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193311. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193312. *(dp + 5) = (png_byte)(v & 0xff);
  193313. }
  193314. else if (a == 0)
  193315. {
  193316. /* background is already in screen gamma */
  193317. *dp = (png_byte)((background->red >> 8) & 0xff);
  193318. *(dp + 1) = (png_byte)(background->red & 0xff);
  193319. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193320. *(dp + 3) = (png_byte)(background->green & 0xff);
  193321. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193322. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193323. }
  193324. else
  193325. {
  193326. png_uint_16 v, w, x;
  193327. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193328. png_composite_16(w, v, a, background_1->red);
  193329. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193330. *dp = (png_byte)((x >> 8) & 0xff);
  193331. *(dp + 1) = (png_byte)(x & 0xff);
  193332. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193333. png_composite_16(w, v, a, background_1->green);
  193334. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193335. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193336. *(dp + 3) = (png_byte)(x & 0xff);
  193337. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193338. png_composite_16(w, v, a, background_1->blue);
  193339. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193340. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193341. *(dp + 5) = (png_byte)(x & 0xff);
  193342. }
  193343. }
  193344. }
  193345. else
  193346. #endif
  193347. {
  193348. sp = row;
  193349. dp = row;
  193350. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193351. {
  193352. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193353. << 8) + (png_uint_16)(*(sp + 7)));
  193354. if (a == (png_uint_16)0xffff)
  193355. {
  193356. png_memcpy(dp, sp, 6);
  193357. }
  193358. else if (a == 0)
  193359. {
  193360. *dp = (png_byte)((background->red >> 8) & 0xff);
  193361. *(dp + 1) = (png_byte)(background->red & 0xff);
  193362. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193363. *(dp + 3) = (png_byte)(background->green & 0xff);
  193364. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193365. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193366. }
  193367. else
  193368. {
  193369. png_uint_16 v;
  193370. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193371. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193372. + *(sp + 3));
  193373. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193374. + *(sp + 5));
  193375. png_composite_16(v, r, a, background->red);
  193376. *dp = (png_byte)((v >> 8) & 0xff);
  193377. *(dp + 1) = (png_byte)(v & 0xff);
  193378. png_composite_16(v, g, a, background->green);
  193379. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193380. *(dp + 3) = (png_byte)(v & 0xff);
  193381. png_composite_16(v, b, a, background->blue);
  193382. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193383. *(dp + 5) = (png_byte)(v & 0xff);
  193384. }
  193385. }
  193386. }
  193387. }
  193388. break;
  193389. }
  193390. }
  193391. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193392. {
  193393. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193394. row_info->channels--;
  193395. row_info->pixel_depth = (png_byte)(row_info->channels *
  193396. row_info->bit_depth);
  193397. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193398. }
  193399. }
  193400. }
  193401. #endif
  193402. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193403. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193404. * you do this after you deal with the transparency issue on grayscale
  193405. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193406. * is 16, use gamma_16_table and gamma_shift. Build these with
  193407. * build_gamma_table().
  193408. */
  193409. void /* PRIVATE */
  193410. png_do_gamma(png_row_infop row_info, png_bytep row,
  193411. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193412. int gamma_shift)
  193413. {
  193414. png_bytep sp;
  193415. png_uint_32 i;
  193416. png_uint_32 row_width=row_info->width;
  193417. png_debug(1, "in png_do_gamma\n");
  193418. if (
  193419. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193420. row != NULL && row_info != NULL &&
  193421. #endif
  193422. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193423. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193424. {
  193425. switch (row_info->color_type)
  193426. {
  193427. case PNG_COLOR_TYPE_RGB:
  193428. {
  193429. if (row_info->bit_depth == 8)
  193430. {
  193431. sp = row;
  193432. for (i = 0; i < row_width; i++)
  193433. {
  193434. *sp = gamma_table[*sp];
  193435. sp++;
  193436. *sp = gamma_table[*sp];
  193437. sp++;
  193438. *sp = gamma_table[*sp];
  193439. sp++;
  193440. }
  193441. }
  193442. else /* if (row_info->bit_depth == 16) */
  193443. {
  193444. sp = row;
  193445. for (i = 0; i < row_width; i++)
  193446. {
  193447. png_uint_16 v;
  193448. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193449. *sp = (png_byte)((v >> 8) & 0xff);
  193450. *(sp + 1) = (png_byte)(v & 0xff);
  193451. sp += 2;
  193452. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193453. *sp = (png_byte)((v >> 8) & 0xff);
  193454. *(sp + 1) = (png_byte)(v & 0xff);
  193455. sp += 2;
  193456. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193457. *sp = (png_byte)((v >> 8) & 0xff);
  193458. *(sp + 1) = (png_byte)(v & 0xff);
  193459. sp += 2;
  193460. }
  193461. }
  193462. break;
  193463. }
  193464. case PNG_COLOR_TYPE_RGB_ALPHA:
  193465. {
  193466. if (row_info->bit_depth == 8)
  193467. {
  193468. sp = row;
  193469. for (i = 0; i < row_width; i++)
  193470. {
  193471. *sp = gamma_table[*sp];
  193472. sp++;
  193473. *sp = gamma_table[*sp];
  193474. sp++;
  193475. *sp = gamma_table[*sp];
  193476. sp++;
  193477. sp++;
  193478. }
  193479. }
  193480. else /* if (row_info->bit_depth == 16) */
  193481. {
  193482. sp = row;
  193483. for (i = 0; i < row_width; i++)
  193484. {
  193485. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193486. *sp = (png_byte)((v >> 8) & 0xff);
  193487. *(sp + 1) = (png_byte)(v & 0xff);
  193488. sp += 2;
  193489. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193490. *sp = (png_byte)((v >> 8) & 0xff);
  193491. *(sp + 1) = (png_byte)(v & 0xff);
  193492. sp += 2;
  193493. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193494. *sp = (png_byte)((v >> 8) & 0xff);
  193495. *(sp + 1) = (png_byte)(v & 0xff);
  193496. sp += 4;
  193497. }
  193498. }
  193499. break;
  193500. }
  193501. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193502. {
  193503. if (row_info->bit_depth == 8)
  193504. {
  193505. sp = row;
  193506. for (i = 0; i < row_width; i++)
  193507. {
  193508. *sp = gamma_table[*sp];
  193509. sp += 2;
  193510. }
  193511. }
  193512. else /* if (row_info->bit_depth == 16) */
  193513. {
  193514. sp = row;
  193515. for (i = 0; i < row_width; i++)
  193516. {
  193517. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193518. *sp = (png_byte)((v >> 8) & 0xff);
  193519. *(sp + 1) = (png_byte)(v & 0xff);
  193520. sp += 4;
  193521. }
  193522. }
  193523. break;
  193524. }
  193525. case PNG_COLOR_TYPE_GRAY:
  193526. {
  193527. if (row_info->bit_depth == 2)
  193528. {
  193529. sp = row;
  193530. for (i = 0; i < row_width; i += 4)
  193531. {
  193532. int a = *sp & 0xc0;
  193533. int b = *sp & 0x30;
  193534. int c = *sp & 0x0c;
  193535. int d = *sp & 0x03;
  193536. *sp = (png_byte)(
  193537. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193538. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193539. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193540. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193541. sp++;
  193542. }
  193543. }
  193544. if (row_info->bit_depth == 4)
  193545. {
  193546. sp = row;
  193547. for (i = 0; i < row_width; i += 2)
  193548. {
  193549. int msb = *sp & 0xf0;
  193550. int lsb = *sp & 0x0f;
  193551. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193552. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193553. sp++;
  193554. }
  193555. }
  193556. else if (row_info->bit_depth == 8)
  193557. {
  193558. sp = row;
  193559. for (i = 0; i < row_width; i++)
  193560. {
  193561. *sp = gamma_table[*sp];
  193562. sp++;
  193563. }
  193564. }
  193565. else if (row_info->bit_depth == 16)
  193566. {
  193567. sp = row;
  193568. for (i = 0; i < row_width; i++)
  193569. {
  193570. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193571. *sp = (png_byte)((v >> 8) & 0xff);
  193572. *(sp + 1) = (png_byte)(v & 0xff);
  193573. sp += 2;
  193574. }
  193575. }
  193576. break;
  193577. }
  193578. }
  193579. }
  193580. }
  193581. #endif
  193582. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193583. /* Expands a palette row to an RGB or RGBA row depending
  193584. * upon whether you supply trans and num_trans.
  193585. */
  193586. void /* PRIVATE */
  193587. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193588. png_colorp palette, png_bytep trans, int num_trans)
  193589. {
  193590. int shift, value;
  193591. png_bytep sp, dp;
  193592. png_uint_32 i;
  193593. png_uint_32 row_width=row_info->width;
  193594. png_debug(1, "in png_do_expand_palette\n");
  193595. if (
  193596. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193597. row != NULL && row_info != NULL &&
  193598. #endif
  193599. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193600. {
  193601. if (row_info->bit_depth < 8)
  193602. {
  193603. switch (row_info->bit_depth)
  193604. {
  193605. case 1:
  193606. {
  193607. sp = row + (png_size_t)((row_width - 1) >> 3);
  193608. dp = row + (png_size_t)row_width - 1;
  193609. shift = 7 - (int)((row_width + 7) & 0x07);
  193610. for (i = 0; i < row_width; i++)
  193611. {
  193612. if ((*sp >> shift) & 0x01)
  193613. *dp = 1;
  193614. else
  193615. *dp = 0;
  193616. if (shift == 7)
  193617. {
  193618. shift = 0;
  193619. sp--;
  193620. }
  193621. else
  193622. shift++;
  193623. dp--;
  193624. }
  193625. break;
  193626. }
  193627. case 2:
  193628. {
  193629. sp = row + (png_size_t)((row_width - 1) >> 2);
  193630. dp = row + (png_size_t)row_width - 1;
  193631. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193632. for (i = 0; i < row_width; i++)
  193633. {
  193634. value = (*sp >> shift) & 0x03;
  193635. *dp = (png_byte)value;
  193636. if (shift == 6)
  193637. {
  193638. shift = 0;
  193639. sp--;
  193640. }
  193641. else
  193642. shift += 2;
  193643. dp--;
  193644. }
  193645. break;
  193646. }
  193647. case 4:
  193648. {
  193649. sp = row + (png_size_t)((row_width - 1) >> 1);
  193650. dp = row + (png_size_t)row_width - 1;
  193651. shift = (int)((row_width & 0x01) << 2);
  193652. for (i = 0; i < row_width; i++)
  193653. {
  193654. value = (*sp >> shift) & 0x0f;
  193655. *dp = (png_byte)value;
  193656. if (shift == 4)
  193657. {
  193658. shift = 0;
  193659. sp--;
  193660. }
  193661. else
  193662. shift += 4;
  193663. dp--;
  193664. }
  193665. break;
  193666. }
  193667. }
  193668. row_info->bit_depth = 8;
  193669. row_info->pixel_depth = 8;
  193670. row_info->rowbytes = row_width;
  193671. }
  193672. switch (row_info->bit_depth)
  193673. {
  193674. case 8:
  193675. {
  193676. if (trans != NULL)
  193677. {
  193678. sp = row + (png_size_t)row_width - 1;
  193679. dp = row + (png_size_t)(row_width << 2) - 1;
  193680. for (i = 0; i < row_width; i++)
  193681. {
  193682. if ((int)(*sp) >= num_trans)
  193683. *dp-- = 0xff;
  193684. else
  193685. *dp-- = trans[*sp];
  193686. *dp-- = palette[*sp].blue;
  193687. *dp-- = palette[*sp].green;
  193688. *dp-- = palette[*sp].red;
  193689. sp--;
  193690. }
  193691. row_info->bit_depth = 8;
  193692. row_info->pixel_depth = 32;
  193693. row_info->rowbytes = row_width * 4;
  193694. row_info->color_type = 6;
  193695. row_info->channels = 4;
  193696. }
  193697. else
  193698. {
  193699. sp = row + (png_size_t)row_width - 1;
  193700. dp = row + (png_size_t)(row_width * 3) - 1;
  193701. for (i = 0; i < row_width; i++)
  193702. {
  193703. *dp-- = palette[*sp].blue;
  193704. *dp-- = palette[*sp].green;
  193705. *dp-- = palette[*sp].red;
  193706. sp--;
  193707. }
  193708. row_info->bit_depth = 8;
  193709. row_info->pixel_depth = 24;
  193710. row_info->rowbytes = row_width * 3;
  193711. row_info->color_type = 2;
  193712. row_info->channels = 3;
  193713. }
  193714. break;
  193715. }
  193716. }
  193717. }
  193718. }
  193719. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193720. * expanded transparency value is supplied, an alpha channel is built.
  193721. */
  193722. void /* PRIVATE */
  193723. png_do_expand(png_row_infop row_info, png_bytep row,
  193724. png_color_16p trans_value)
  193725. {
  193726. int shift, value;
  193727. png_bytep sp, dp;
  193728. png_uint_32 i;
  193729. png_uint_32 row_width=row_info->width;
  193730. png_debug(1, "in png_do_expand\n");
  193731. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193732. if (row != NULL && row_info != NULL)
  193733. #endif
  193734. {
  193735. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193736. {
  193737. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193738. if (row_info->bit_depth < 8)
  193739. {
  193740. switch (row_info->bit_depth)
  193741. {
  193742. case 1:
  193743. {
  193744. gray = (png_uint_16)((gray&0x01)*0xff);
  193745. sp = row + (png_size_t)((row_width - 1) >> 3);
  193746. dp = row + (png_size_t)row_width - 1;
  193747. shift = 7 - (int)((row_width + 7) & 0x07);
  193748. for (i = 0; i < row_width; i++)
  193749. {
  193750. if ((*sp >> shift) & 0x01)
  193751. *dp = 0xff;
  193752. else
  193753. *dp = 0;
  193754. if (shift == 7)
  193755. {
  193756. shift = 0;
  193757. sp--;
  193758. }
  193759. else
  193760. shift++;
  193761. dp--;
  193762. }
  193763. break;
  193764. }
  193765. case 2:
  193766. {
  193767. gray = (png_uint_16)((gray&0x03)*0x55);
  193768. sp = row + (png_size_t)((row_width - 1) >> 2);
  193769. dp = row + (png_size_t)row_width - 1;
  193770. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193771. for (i = 0; i < row_width; i++)
  193772. {
  193773. value = (*sp >> shift) & 0x03;
  193774. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193775. (value << 6));
  193776. if (shift == 6)
  193777. {
  193778. shift = 0;
  193779. sp--;
  193780. }
  193781. else
  193782. shift += 2;
  193783. dp--;
  193784. }
  193785. break;
  193786. }
  193787. case 4:
  193788. {
  193789. gray = (png_uint_16)((gray&0x0f)*0x11);
  193790. sp = row + (png_size_t)((row_width - 1) >> 1);
  193791. dp = row + (png_size_t)row_width - 1;
  193792. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193793. for (i = 0; i < row_width; i++)
  193794. {
  193795. value = (*sp >> shift) & 0x0f;
  193796. *dp = (png_byte)(value | (value << 4));
  193797. if (shift == 4)
  193798. {
  193799. shift = 0;
  193800. sp--;
  193801. }
  193802. else
  193803. shift = 4;
  193804. dp--;
  193805. }
  193806. break;
  193807. }
  193808. }
  193809. row_info->bit_depth = 8;
  193810. row_info->pixel_depth = 8;
  193811. row_info->rowbytes = row_width;
  193812. }
  193813. if (trans_value != NULL)
  193814. {
  193815. if (row_info->bit_depth == 8)
  193816. {
  193817. gray = gray & 0xff;
  193818. sp = row + (png_size_t)row_width - 1;
  193819. dp = row + (png_size_t)(row_width << 1) - 1;
  193820. for (i = 0; i < row_width; i++)
  193821. {
  193822. if (*sp == gray)
  193823. *dp-- = 0;
  193824. else
  193825. *dp-- = 0xff;
  193826. *dp-- = *sp--;
  193827. }
  193828. }
  193829. else if (row_info->bit_depth == 16)
  193830. {
  193831. png_byte gray_high = (gray >> 8) & 0xff;
  193832. png_byte gray_low = gray & 0xff;
  193833. sp = row + row_info->rowbytes - 1;
  193834. dp = row + (row_info->rowbytes << 1) - 1;
  193835. for (i = 0; i < row_width; i++)
  193836. {
  193837. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193838. {
  193839. *dp-- = 0;
  193840. *dp-- = 0;
  193841. }
  193842. else
  193843. {
  193844. *dp-- = 0xff;
  193845. *dp-- = 0xff;
  193846. }
  193847. *dp-- = *sp--;
  193848. *dp-- = *sp--;
  193849. }
  193850. }
  193851. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193852. row_info->channels = 2;
  193853. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193854. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193855. row_width);
  193856. }
  193857. }
  193858. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193859. {
  193860. if (row_info->bit_depth == 8)
  193861. {
  193862. png_byte red = trans_value->red & 0xff;
  193863. png_byte green = trans_value->green & 0xff;
  193864. png_byte blue = trans_value->blue & 0xff;
  193865. sp = row + (png_size_t)row_info->rowbytes - 1;
  193866. dp = row + (png_size_t)(row_width << 2) - 1;
  193867. for (i = 0; i < row_width; i++)
  193868. {
  193869. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193870. *dp-- = 0;
  193871. else
  193872. *dp-- = 0xff;
  193873. *dp-- = *sp--;
  193874. *dp-- = *sp--;
  193875. *dp-- = *sp--;
  193876. }
  193877. }
  193878. else if (row_info->bit_depth == 16)
  193879. {
  193880. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193881. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193882. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193883. png_byte red_low = trans_value->red & 0xff;
  193884. png_byte green_low = trans_value->green & 0xff;
  193885. png_byte blue_low = trans_value->blue & 0xff;
  193886. sp = row + row_info->rowbytes - 1;
  193887. dp = row + (png_size_t)(row_width << 3) - 1;
  193888. for (i = 0; i < row_width; i++)
  193889. {
  193890. if (*(sp - 5) == red_high &&
  193891. *(sp - 4) == red_low &&
  193892. *(sp - 3) == green_high &&
  193893. *(sp - 2) == green_low &&
  193894. *(sp - 1) == blue_high &&
  193895. *(sp ) == blue_low)
  193896. {
  193897. *dp-- = 0;
  193898. *dp-- = 0;
  193899. }
  193900. else
  193901. {
  193902. *dp-- = 0xff;
  193903. *dp-- = 0xff;
  193904. }
  193905. *dp-- = *sp--;
  193906. *dp-- = *sp--;
  193907. *dp-- = *sp--;
  193908. *dp-- = *sp--;
  193909. *dp-- = *sp--;
  193910. *dp-- = *sp--;
  193911. }
  193912. }
  193913. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193914. row_info->channels = 4;
  193915. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193916. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193917. }
  193918. }
  193919. }
  193920. #endif
  193921. #if defined(PNG_READ_DITHER_SUPPORTED)
  193922. void /* PRIVATE */
  193923. png_do_dither(png_row_infop row_info, png_bytep row,
  193924. png_bytep palette_lookup, png_bytep dither_lookup)
  193925. {
  193926. png_bytep sp, dp;
  193927. png_uint_32 i;
  193928. png_uint_32 row_width=row_info->width;
  193929. png_debug(1, "in png_do_dither\n");
  193930. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193931. if (row != NULL && row_info != NULL)
  193932. #endif
  193933. {
  193934. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193935. palette_lookup && row_info->bit_depth == 8)
  193936. {
  193937. int r, g, b, p;
  193938. sp = row;
  193939. dp = row;
  193940. for (i = 0; i < row_width; i++)
  193941. {
  193942. r = *sp++;
  193943. g = *sp++;
  193944. b = *sp++;
  193945. /* this looks real messy, but the compiler will reduce
  193946. it down to a reasonable formula. For example, with
  193947. 5 bits per color, we get:
  193948. p = (((r >> 3) & 0x1f) << 10) |
  193949. (((g >> 3) & 0x1f) << 5) |
  193950. ((b >> 3) & 0x1f);
  193951. */
  193952. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193953. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193954. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193955. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193956. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193957. (PNG_DITHER_BLUE_BITS)) |
  193958. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193959. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193960. *dp++ = palette_lookup[p];
  193961. }
  193962. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193963. row_info->channels = 1;
  193964. row_info->pixel_depth = row_info->bit_depth;
  193965. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193966. }
  193967. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193968. palette_lookup != NULL && row_info->bit_depth == 8)
  193969. {
  193970. int r, g, b, p;
  193971. sp = row;
  193972. dp = row;
  193973. for (i = 0; i < row_width; i++)
  193974. {
  193975. r = *sp++;
  193976. g = *sp++;
  193977. b = *sp++;
  193978. sp++;
  193979. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193980. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193981. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193982. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193983. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193984. (PNG_DITHER_BLUE_BITS)) |
  193985. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193986. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193987. *dp++ = palette_lookup[p];
  193988. }
  193989. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193990. row_info->channels = 1;
  193991. row_info->pixel_depth = row_info->bit_depth;
  193992. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193993. }
  193994. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193995. dither_lookup && row_info->bit_depth == 8)
  193996. {
  193997. sp = row;
  193998. for (i = 0; i < row_width; i++, sp++)
  193999. {
  194000. *sp = dither_lookup[*sp];
  194001. }
  194002. }
  194003. }
  194004. }
  194005. #endif
  194006. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194007. #if defined(PNG_READ_GAMMA_SUPPORTED)
  194008. static PNG_CONST int png_gamma_shift[] =
  194009. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  194010. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  194011. * tables, we don't make a full table if we are reducing to 8-bit in
  194012. * the future. Note also how the gamma_16 tables are segmented so that
  194013. * we don't need to allocate > 64K chunks for a full 16-bit table.
  194014. */
  194015. void /* PRIVATE */
  194016. png_build_gamma_table(png_structp png_ptr)
  194017. {
  194018. png_debug(1, "in png_build_gamma_table\n");
  194019. if (png_ptr->bit_depth <= 8)
  194020. {
  194021. int i;
  194022. double g;
  194023. if (png_ptr->screen_gamma > .000001)
  194024. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194025. else
  194026. g = 1.0;
  194027. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  194028. (png_uint_32)256);
  194029. for (i = 0; i < 256; i++)
  194030. {
  194031. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  194032. g) * 255.0 + .5);
  194033. }
  194034. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194035. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194036. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  194037. {
  194038. g = 1.0 / (png_ptr->gamma);
  194039. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  194040. (png_uint_32)256);
  194041. for (i = 0; i < 256; i++)
  194042. {
  194043. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  194044. g) * 255.0 + .5);
  194045. }
  194046. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  194047. (png_uint_32)256);
  194048. if(png_ptr->screen_gamma > 0.000001)
  194049. g = 1.0 / png_ptr->screen_gamma;
  194050. else
  194051. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194052. for (i = 0; i < 256; i++)
  194053. {
  194054. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  194055. g) * 255.0 + .5);
  194056. }
  194057. }
  194058. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194059. }
  194060. else
  194061. {
  194062. double g;
  194063. int i, j, shift, num;
  194064. int sig_bit;
  194065. png_uint_32 ig;
  194066. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194067. {
  194068. sig_bit = (int)png_ptr->sig_bit.red;
  194069. if ((int)png_ptr->sig_bit.green > sig_bit)
  194070. sig_bit = png_ptr->sig_bit.green;
  194071. if ((int)png_ptr->sig_bit.blue > sig_bit)
  194072. sig_bit = png_ptr->sig_bit.blue;
  194073. }
  194074. else
  194075. {
  194076. sig_bit = (int)png_ptr->sig_bit.gray;
  194077. }
  194078. if (sig_bit > 0)
  194079. shift = 16 - sig_bit;
  194080. else
  194081. shift = 0;
  194082. if (png_ptr->transformations & PNG_16_TO_8)
  194083. {
  194084. if (shift < (16 - PNG_MAX_GAMMA_8))
  194085. shift = (16 - PNG_MAX_GAMMA_8);
  194086. }
  194087. if (shift > 8)
  194088. shift = 8;
  194089. if (shift < 0)
  194090. shift = 0;
  194091. png_ptr->gamma_shift = (png_byte)shift;
  194092. num = (1 << (8 - shift));
  194093. if (png_ptr->screen_gamma > .000001)
  194094. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194095. else
  194096. g = 1.0;
  194097. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  194098. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194099. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  194100. {
  194101. double fin, fout;
  194102. png_uint_32 last, max;
  194103. for (i = 0; i < num; i++)
  194104. {
  194105. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194106. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194107. }
  194108. g = 1.0 / g;
  194109. last = 0;
  194110. for (i = 0; i < 256; i++)
  194111. {
  194112. fout = ((double)i + 0.5) / 256.0;
  194113. fin = pow(fout, g);
  194114. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  194115. while (last <= max)
  194116. {
  194117. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194118. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194119. (png_uint_16)i | ((png_uint_16)i << 8));
  194120. last++;
  194121. }
  194122. }
  194123. while (last < ((png_uint_32)num << 8))
  194124. {
  194125. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194126. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194127. last++;
  194128. }
  194129. }
  194130. else
  194131. {
  194132. for (i = 0; i < num; i++)
  194133. {
  194134. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194135. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194136. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194137. for (j = 0; j < 256; j++)
  194138. {
  194139. png_ptr->gamma_16_table[i][j] =
  194140. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194141. 65535.0, g) * 65535.0 + .5);
  194142. }
  194143. }
  194144. }
  194145. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194146. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194147. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194148. {
  194149. g = 1.0 / (png_ptr->gamma);
  194150. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194151. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194152. for (i = 0; i < num; i++)
  194153. {
  194154. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194155. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194156. ig = (((png_uint_32)i *
  194157. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194158. for (j = 0; j < 256; j++)
  194159. {
  194160. png_ptr->gamma_16_to_1[i][j] =
  194161. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194162. 65535.0, g) * 65535.0 + .5);
  194163. }
  194164. }
  194165. if(png_ptr->screen_gamma > 0.000001)
  194166. g = 1.0 / png_ptr->screen_gamma;
  194167. else
  194168. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194169. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194170. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194171. for (i = 0; i < num; i++)
  194172. {
  194173. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194174. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194175. ig = (((png_uint_32)i *
  194176. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194177. for (j = 0; j < 256; j++)
  194178. {
  194179. png_ptr->gamma_16_from_1[i][j] =
  194180. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194181. 65535.0, g) * 65535.0 + .5);
  194182. }
  194183. }
  194184. }
  194185. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194186. }
  194187. }
  194188. #endif
  194189. /* To do: install integer version of png_build_gamma_table here */
  194190. #endif
  194191. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194192. /* undoes intrapixel differencing */
  194193. void /* PRIVATE */
  194194. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194195. {
  194196. png_debug(1, "in png_do_read_intrapixel\n");
  194197. if (
  194198. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194199. row != NULL && row_info != NULL &&
  194200. #endif
  194201. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194202. {
  194203. int bytes_per_pixel;
  194204. png_uint_32 row_width = row_info->width;
  194205. if (row_info->bit_depth == 8)
  194206. {
  194207. png_bytep rp;
  194208. png_uint_32 i;
  194209. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194210. bytes_per_pixel = 3;
  194211. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194212. bytes_per_pixel = 4;
  194213. else
  194214. return;
  194215. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194216. {
  194217. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194218. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194219. }
  194220. }
  194221. else if (row_info->bit_depth == 16)
  194222. {
  194223. png_bytep rp;
  194224. png_uint_32 i;
  194225. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194226. bytes_per_pixel = 6;
  194227. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194228. bytes_per_pixel = 8;
  194229. else
  194230. return;
  194231. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194232. {
  194233. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194234. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194235. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194236. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194237. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194238. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194239. *(rp+1) = (png_byte)(red & 0xff);
  194240. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194241. *(rp+5) = (png_byte)(blue & 0xff);
  194242. }
  194243. }
  194244. }
  194245. }
  194246. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194247. #endif /* PNG_READ_SUPPORTED */
  194248. /*** End of inlined file: pngrtran.c ***/
  194249. /*** Start of inlined file: pngrutil.c ***/
  194250. /* pngrutil.c - utilities to read a PNG file
  194251. *
  194252. * Last changed in libpng 1.2.21 [October 4, 2007]
  194253. * For conditions of distribution and use, see copyright notice in png.h
  194254. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194255. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194256. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194257. *
  194258. * This file contains routines that are only called from within
  194259. * libpng itself during the course of reading an image.
  194260. */
  194261. #define PNG_INTERNAL
  194262. #if defined(PNG_READ_SUPPORTED)
  194263. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194264. # define WIN32_WCE_OLD
  194265. #endif
  194266. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194267. # if defined(WIN32_WCE_OLD)
  194268. /* strtod() function is not supported on WindowsCE */
  194269. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194270. {
  194271. double result = 0;
  194272. int len;
  194273. wchar_t *str, *end;
  194274. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194275. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194276. if ( NULL != str )
  194277. {
  194278. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194279. result = wcstod(str, &end);
  194280. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194281. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194282. png_free(png_ptr, str);
  194283. }
  194284. return result;
  194285. }
  194286. # else
  194287. # define png_strtod(p,a,b) strtod(a,b)
  194288. # endif
  194289. #endif
  194290. png_uint_32 PNGAPI
  194291. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194292. {
  194293. png_uint_32 i = png_get_uint_32(buf);
  194294. if (i > PNG_UINT_31_MAX)
  194295. png_error(png_ptr, "PNG unsigned integer out of range.");
  194296. return (i);
  194297. }
  194298. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194299. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194300. png_uint_32 PNGAPI
  194301. png_get_uint_32(png_bytep buf)
  194302. {
  194303. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194304. ((png_uint_32)(*(buf + 1)) << 16) +
  194305. ((png_uint_32)(*(buf + 2)) << 8) +
  194306. (png_uint_32)(*(buf + 3));
  194307. return (i);
  194308. }
  194309. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194310. * data is stored in the PNG file in two's complement format, and it is
  194311. * assumed that the machine format for signed integers is the same. */
  194312. png_int_32 PNGAPI
  194313. png_get_int_32(png_bytep buf)
  194314. {
  194315. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194316. ((png_int_32)(*(buf + 1)) << 16) +
  194317. ((png_int_32)(*(buf + 2)) << 8) +
  194318. (png_int_32)(*(buf + 3));
  194319. return (i);
  194320. }
  194321. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194322. png_uint_16 PNGAPI
  194323. png_get_uint_16(png_bytep buf)
  194324. {
  194325. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194326. (png_uint_16)(*(buf + 1)));
  194327. return (i);
  194328. }
  194329. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194330. /* Read data, and (optionally) run it through the CRC. */
  194331. void /* PRIVATE */
  194332. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194333. {
  194334. if(png_ptr == NULL) return;
  194335. png_read_data(png_ptr, buf, length);
  194336. png_calculate_crc(png_ptr, buf, length);
  194337. }
  194338. /* Optionally skip data and then check the CRC. Depending on whether we
  194339. are reading a ancillary or critical chunk, and how the program has set
  194340. things up, we may calculate the CRC on the data and print a message.
  194341. Returns '1' if there was a CRC error, '0' otherwise. */
  194342. int /* PRIVATE */
  194343. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194344. {
  194345. png_size_t i;
  194346. png_size_t istop = png_ptr->zbuf_size;
  194347. for (i = (png_size_t)skip; i > istop; i -= istop)
  194348. {
  194349. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194350. }
  194351. if (i)
  194352. {
  194353. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194354. }
  194355. if (png_crc_error(png_ptr))
  194356. {
  194357. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194358. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194359. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194360. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194361. {
  194362. png_chunk_warning(png_ptr, "CRC error");
  194363. }
  194364. else
  194365. {
  194366. png_chunk_error(png_ptr, "CRC error");
  194367. }
  194368. return (1);
  194369. }
  194370. return (0);
  194371. }
  194372. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194373. the data it has read thus far. */
  194374. int /* PRIVATE */
  194375. png_crc_error(png_structp png_ptr)
  194376. {
  194377. png_byte crc_bytes[4];
  194378. png_uint_32 crc;
  194379. int need_crc = 1;
  194380. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194381. {
  194382. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194383. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194384. need_crc = 0;
  194385. }
  194386. else /* critical */
  194387. {
  194388. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194389. need_crc = 0;
  194390. }
  194391. png_read_data(png_ptr, crc_bytes, 4);
  194392. if (need_crc)
  194393. {
  194394. crc = png_get_uint_32(crc_bytes);
  194395. return ((int)(crc != png_ptr->crc));
  194396. }
  194397. else
  194398. return (0);
  194399. }
  194400. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194401. defined(PNG_READ_iCCP_SUPPORTED)
  194402. /*
  194403. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194404. * points at an allocated area holding the contents of a chunk with a
  194405. * trailing compressed part. What we get back is an allocated area
  194406. * holding the original prefix part and an uncompressed version of the
  194407. * trailing part (the malloc area passed in is freed).
  194408. */
  194409. png_charp /* PRIVATE */
  194410. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194411. png_charp chunkdata, png_size_t chunklength,
  194412. png_size_t prefix_size, png_size_t *newlength)
  194413. {
  194414. static PNG_CONST char msg[] = "Error decoding compressed text";
  194415. png_charp text;
  194416. png_size_t text_size;
  194417. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194418. {
  194419. int ret = Z_OK;
  194420. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194421. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194422. png_ptr->zstream.next_out = png_ptr->zbuf;
  194423. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194424. text_size = 0;
  194425. text = NULL;
  194426. while (png_ptr->zstream.avail_in)
  194427. {
  194428. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194429. if (ret != Z_OK && ret != Z_STREAM_END)
  194430. {
  194431. if (png_ptr->zstream.msg != NULL)
  194432. png_warning(png_ptr, png_ptr->zstream.msg);
  194433. else
  194434. png_warning(png_ptr, msg);
  194435. inflateReset(&png_ptr->zstream);
  194436. png_ptr->zstream.avail_in = 0;
  194437. if (text == NULL)
  194438. {
  194439. text_size = prefix_size + png_sizeof(msg) + 1;
  194440. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194441. if (text == NULL)
  194442. {
  194443. png_free(png_ptr,chunkdata);
  194444. png_error(png_ptr,"Not enough memory to decompress chunk");
  194445. }
  194446. png_memcpy(text, chunkdata, prefix_size);
  194447. }
  194448. text[text_size - 1] = 0x00;
  194449. /* Copy what we can of the error message into the text chunk */
  194450. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194451. text_size = png_sizeof(msg) > text_size ? text_size :
  194452. png_sizeof(msg);
  194453. png_memcpy(text + prefix_size, msg, text_size + 1);
  194454. break;
  194455. }
  194456. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194457. {
  194458. if (text == NULL)
  194459. {
  194460. text_size = prefix_size +
  194461. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194462. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194463. if (text == NULL)
  194464. {
  194465. png_free(png_ptr,chunkdata);
  194466. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194467. }
  194468. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194469. text_size - prefix_size);
  194470. png_memcpy(text, chunkdata, prefix_size);
  194471. *(text + text_size) = 0x00;
  194472. }
  194473. else
  194474. {
  194475. png_charp tmp;
  194476. tmp = text;
  194477. text = (png_charp)png_malloc_warn(png_ptr,
  194478. (png_uint_32)(text_size +
  194479. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194480. if (text == NULL)
  194481. {
  194482. png_free(png_ptr, tmp);
  194483. png_free(png_ptr, chunkdata);
  194484. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194485. }
  194486. png_memcpy(text, tmp, text_size);
  194487. png_free(png_ptr, tmp);
  194488. png_memcpy(text + text_size, png_ptr->zbuf,
  194489. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194490. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194491. *(text + text_size) = 0x00;
  194492. }
  194493. if (ret == Z_STREAM_END)
  194494. break;
  194495. else
  194496. {
  194497. png_ptr->zstream.next_out = png_ptr->zbuf;
  194498. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194499. }
  194500. }
  194501. }
  194502. if (ret != Z_STREAM_END)
  194503. {
  194504. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194505. char umsg[52];
  194506. if (ret == Z_BUF_ERROR)
  194507. png_snprintf(umsg, 52,
  194508. "Buffer error in compressed datastream in %s chunk",
  194509. png_ptr->chunk_name);
  194510. else if (ret == Z_DATA_ERROR)
  194511. png_snprintf(umsg, 52,
  194512. "Data error in compressed datastream in %s chunk",
  194513. png_ptr->chunk_name);
  194514. else
  194515. png_snprintf(umsg, 52,
  194516. "Incomplete compressed datastream in %s chunk",
  194517. png_ptr->chunk_name);
  194518. png_warning(png_ptr, umsg);
  194519. #else
  194520. png_warning(png_ptr,
  194521. "Incomplete compressed datastream in chunk other than IDAT");
  194522. #endif
  194523. text_size=prefix_size;
  194524. if (text == NULL)
  194525. {
  194526. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194527. if (text == NULL)
  194528. {
  194529. png_free(png_ptr, chunkdata);
  194530. png_error(png_ptr,"Not enough memory for text.");
  194531. }
  194532. png_memcpy(text, chunkdata, prefix_size);
  194533. }
  194534. *(text + text_size) = 0x00;
  194535. }
  194536. inflateReset(&png_ptr->zstream);
  194537. png_ptr->zstream.avail_in = 0;
  194538. png_free(png_ptr, chunkdata);
  194539. chunkdata = text;
  194540. *newlength=text_size;
  194541. }
  194542. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194543. {
  194544. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194545. char umsg[50];
  194546. png_snprintf(umsg, 50,
  194547. "Unknown zTXt compression type %d", comp_type);
  194548. png_warning(png_ptr, umsg);
  194549. #else
  194550. png_warning(png_ptr, "Unknown zTXt compression type");
  194551. #endif
  194552. *(chunkdata + prefix_size) = 0x00;
  194553. *newlength=prefix_size;
  194554. }
  194555. return chunkdata;
  194556. }
  194557. #endif
  194558. /* read and check the IDHR chunk */
  194559. void /* PRIVATE */
  194560. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194561. {
  194562. png_byte buf[13];
  194563. png_uint_32 width, height;
  194564. int bit_depth, color_type, compression_type, filter_type;
  194565. int interlace_type;
  194566. png_debug(1, "in png_handle_IHDR\n");
  194567. if (png_ptr->mode & PNG_HAVE_IHDR)
  194568. png_error(png_ptr, "Out of place IHDR");
  194569. /* check the length */
  194570. if (length != 13)
  194571. png_error(png_ptr, "Invalid IHDR chunk");
  194572. png_ptr->mode |= PNG_HAVE_IHDR;
  194573. png_crc_read(png_ptr, buf, 13);
  194574. png_crc_finish(png_ptr, 0);
  194575. width = png_get_uint_31(png_ptr, buf);
  194576. height = png_get_uint_31(png_ptr, buf + 4);
  194577. bit_depth = buf[8];
  194578. color_type = buf[9];
  194579. compression_type = buf[10];
  194580. filter_type = buf[11];
  194581. interlace_type = buf[12];
  194582. /* set internal variables */
  194583. png_ptr->width = width;
  194584. png_ptr->height = height;
  194585. png_ptr->bit_depth = (png_byte)bit_depth;
  194586. png_ptr->interlaced = (png_byte)interlace_type;
  194587. png_ptr->color_type = (png_byte)color_type;
  194588. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194589. png_ptr->filter_type = (png_byte)filter_type;
  194590. #endif
  194591. png_ptr->compression_type = (png_byte)compression_type;
  194592. /* find number of channels */
  194593. switch (png_ptr->color_type)
  194594. {
  194595. case PNG_COLOR_TYPE_GRAY:
  194596. case PNG_COLOR_TYPE_PALETTE:
  194597. png_ptr->channels = 1;
  194598. break;
  194599. case PNG_COLOR_TYPE_RGB:
  194600. png_ptr->channels = 3;
  194601. break;
  194602. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194603. png_ptr->channels = 2;
  194604. break;
  194605. case PNG_COLOR_TYPE_RGB_ALPHA:
  194606. png_ptr->channels = 4;
  194607. break;
  194608. }
  194609. /* set up other useful info */
  194610. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194611. png_ptr->channels);
  194612. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194613. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194614. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194615. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194616. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194617. color_type, interlace_type, compression_type, filter_type);
  194618. }
  194619. /* read and check the palette */
  194620. void /* PRIVATE */
  194621. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194622. {
  194623. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194624. int num, i;
  194625. #ifndef PNG_NO_POINTER_INDEXING
  194626. png_colorp pal_ptr;
  194627. #endif
  194628. png_debug(1, "in png_handle_PLTE\n");
  194629. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194630. png_error(png_ptr, "Missing IHDR before PLTE");
  194631. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194632. {
  194633. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194634. png_crc_finish(png_ptr, length);
  194635. return;
  194636. }
  194637. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194638. png_error(png_ptr, "Duplicate PLTE chunk");
  194639. png_ptr->mode |= PNG_HAVE_PLTE;
  194640. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194641. {
  194642. png_warning(png_ptr,
  194643. "Ignoring PLTE chunk in grayscale PNG");
  194644. png_crc_finish(png_ptr, length);
  194645. return;
  194646. }
  194647. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194648. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194649. {
  194650. png_crc_finish(png_ptr, length);
  194651. return;
  194652. }
  194653. #endif
  194654. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194655. {
  194656. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194657. {
  194658. png_warning(png_ptr, "Invalid palette chunk");
  194659. png_crc_finish(png_ptr, length);
  194660. return;
  194661. }
  194662. else
  194663. {
  194664. png_error(png_ptr, "Invalid palette chunk");
  194665. }
  194666. }
  194667. num = (int)length / 3;
  194668. #ifndef PNG_NO_POINTER_INDEXING
  194669. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194670. {
  194671. png_byte buf[3];
  194672. png_crc_read(png_ptr, buf, 3);
  194673. pal_ptr->red = buf[0];
  194674. pal_ptr->green = buf[1];
  194675. pal_ptr->blue = buf[2];
  194676. }
  194677. #else
  194678. for (i = 0; i < num; i++)
  194679. {
  194680. png_byte buf[3];
  194681. png_crc_read(png_ptr, buf, 3);
  194682. /* don't depend upon png_color being any order */
  194683. palette[i].red = buf[0];
  194684. palette[i].green = buf[1];
  194685. palette[i].blue = buf[2];
  194686. }
  194687. #endif
  194688. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194689. whatever the normal CRC configuration tells us. However, if we
  194690. have an RGB image, the PLTE can be considered ancillary, so
  194691. we will act as though it is. */
  194692. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194693. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194694. #endif
  194695. {
  194696. png_crc_finish(png_ptr, 0);
  194697. }
  194698. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194699. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194700. {
  194701. /* If we don't want to use the data from an ancillary chunk,
  194702. we have two options: an error abort, or a warning and we
  194703. ignore the data in this chunk (which should be OK, since
  194704. it's considered ancillary for a RGB or RGBA image). */
  194705. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194706. {
  194707. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194708. {
  194709. png_chunk_error(png_ptr, "CRC error");
  194710. }
  194711. else
  194712. {
  194713. png_chunk_warning(png_ptr, "CRC error");
  194714. return;
  194715. }
  194716. }
  194717. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194718. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194719. {
  194720. png_chunk_warning(png_ptr, "CRC error");
  194721. }
  194722. }
  194723. #endif
  194724. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194725. #if defined(PNG_READ_tRNS_SUPPORTED)
  194726. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194727. {
  194728. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194729. {
  194730. if (png_ptr->num_trans > (png_uint_16)num)
  194731. {
  194732. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194733. png_ptr->num_trans = (png_uint_16)num;
  194734. }
  194735. if (info_ptr->num_trans > (png_uint_16)num)
  194736. {
  194737. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194738. info_ptr->num_trans = (png_uint_16)num;
  194739. }
  194740. }
  194741. }
  194742. #endif
  194743. }
  194744. void /* PRIVATE */
  194745. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194746. {
  194747. png_debug(1, "in png_handle_IEND\n");
  194748. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194749. {
  194750. png_error(png_ptr, "No image in file");
  194751. }
  194752. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194753. if (length != 0)
  194754. {
  194755. png_warning(png_ptr, "Incorrect IEND chunk length");
  194756. }
  194757. png_crc_finish(png_ptr, length);
  194758. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194759. }
  194760. #if defined(PNG_READ_gAMA_SUPPORTED)
  194761. void /* PRIVATE */
  194762. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194763. {
  194764. png_fixed_point igamma;
  194765. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194766. float file_gamma;
  194767. #endif
  194768. png_byte buf[4];
  194769. png_debug(1, "in png_handle_gAMA\n");
  194770. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194771. png_error(png_ptr, "Missing IHDR before gAMA");
  194772. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194773. {
  194774. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194775. png_crc_finish(png_ptr, length);
  194776. return;
  194777. }
  194778. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194779. /* Should be an error, but we can cope with it */
  194780. png_warning(png_ptr, "Out of place gAMA chunk");
  194781. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194782. #if defined(PNG_READ_sRGB_SUPPORTED)
  194783. && !(info_ptr->valid & PNG_INFO_sRGB)
  194784. #endif
  194785. )
  194786. {
  194787. png_warning(png_ptr, "Duplicate gAMA chunk");
  194788. png_crc_finish(png_ptr, length);
  194789. return;
  194790. }
  194791. if (length != 4)
  194792. {
  194793. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194794. png_crc_finish(png_ptr, length);
  194795. return;
  194796. }
  194797. png_crc_read(png_ptr, buf, 4);
  194798. if (png_crc_finish(png_ptr, 0))
  194799. return;
  194800. igamma = (png_fixed_point)png_get_uint_32(buf);
  194801. /* check for zero gamma */
  194802. if (igamma == 0)
  194803. {
  194804. png_warning(png_ptr,
  194805. "Ignoring gAMA chunk with gamma=0");
  194806. return;
  194807. }
  194808. #if defined(PNG_READ_sRGB_SUPPORTED)
  194809. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194810. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194811. {
  194812. png_warning(png_ptr,
  194813. "Ignoring incorrect gAMA value when sRGB is also present");
  194814. #ifndef PNG_NO_CONSOLE_IO
  194815. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194816. #endif
  194817. return;
  194818. }
  194819. #endif /* PNG_READ_sRGB_SUPPORTED */
  194820. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194821. file_gamma = (float)igamma / (float)100000.0;
  194822. # ifdef PNG_READ_GAMMA_SUPPORTED
  194823. png_ptr->gamma = file_gamma;
  194824. # endif
  194825. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194826. #endif
  194827. #ifdef PNG_FIXED_POINT_SUPPORTED
  194828. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194829. #endif
  194830. }
  194831. #endif
  194832. #if defined(PNG_READ_sBIT_SUPPORTED)
  194833. void /* PRIVATE */
  194834. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194835. {
  194836. png_size_t truelen;
  194837. png_byte buf[4];
  194838. png_debug(1, "in png_handle_sBIT\n");
  194839. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194840. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194841. png_error(png_ptr, "Missing IHDR before sBIT");
  194842. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194843. {
  194844. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194845. png_crc_finish(png_ptr, length);
  194846. return;
  194847. }
  194848. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194849. {
  194850. /* Should be an error, but we can cope with it */
  194851. png_warning(png_ptr, "Out of place sBIT chunk");
  194852. }
  194853. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194854. {
  194855. png_warning(png_ptr, "Duplicate sBIT chunk");
  194856. png_crc_finish(png_ptr, length);
  194857. return;
  194858. }
  194859. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194860. truelen = 3;
  194861. else
  194862. truelen = (png_size_t)png_ptr->channels;
  194863. if (length != truelen || length > 4)
  194864. {
  194865. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194866. png_crc_finish(png_ptr, length);
  194867. return;
  194868. }
  194869. png_crc_read(png_ptr, buf, truelen);
  194870. if (png_crc_finish(png_ptr, 0))
  194871. return;
  194872. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194873. {
  194874. png_ptr->sig_bit.red = buf[0];
  194875. png_ptr->sig_bit.green = buf[1];
  194876. png_ptr->sig_bit.blue = buf[2];
  194877. png_ptr->sig_bit.alpha = buf[3];
  194878. }
  194879. else
  194880. {
  194881. png_ptr->sig_bit.gray = buf[0];
  194882. png_ptr->sig_bit.red = buf[0];
  194883. png_ptr->sig_bit.green = buf[0];
  194884. png_ptr->sig_bit.blue = buf[0];
  194885. png_ptr->sig_bit.alpha = buf[1];
  194886. }
  194887. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194888. }
  194889. #endif
  194890. #if defined(PNG_READ_cHRM_SUPPORTED)
  194891. void /* PRIVATE */
  194892. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194893. {
  194894. png_byte buf[4];
  194895. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194896. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194897. #endif
  194898. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194899. int_y_green, int_x_blue, int_y_blue;
  194900. png_uint_32 uint_x, uint_y;
  194901. png_debug(1, "in png_handle_cHRM\n");
  194902. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194903. png_error(png_ptr, "Missing IHDR before cHRM");
  194904. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194905. {
  194906. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194907. png_crc_finish(png_ptr, length);
  194908. return;
  194909. }
  194910. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194911. /* Should be an error, but we can cope with it */
  194912. png_warning(png_ptr, "Missing PLTE before cHRM");
  194913. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194914. #if defined(PNG_READ_sRGB_SUPPORTED)
  194915. && !(info_ptr->valid & PNG_INFO_sRGB)
  194916. #endif
  194917. )
  194918. {
  194919. png_warning(png_ptr, "Duplicate cHRM chunk");
  194920. png_crc_finish(png_ptr, length);
  194921. return;
  194922. }
  194923. if (length != 32)
  194924. {
  194925. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194926. png_crc_finish(png_ptr, length);
  194927. return;
  194928. }
  194929. png_crc_read(png_ptr, buf, 4);
  194930. uint_x = png_get_uint_32(buf);
  194931. png_crc_read(png_ptr, buf, 4);
  194932. uint_y = png_get_uint_32(buf);
  194933. if (uint_x > 80000L || uint_y > 80000L ||
  194934. uint_x + uint_y > 100000L)
  194935. {
  194936. png_warning(png_ptr, "Invalid cHRM white point");
  194937. png_crc_finish(png_ptr, 24);
  194938. return;
  194939. }
  194940. int_x_white = (png_fixed_point)uint_x;
  194941. int_y_white = (png_fixed_point)uint_y;
  194942. png_crc_read(png_ptr, buf, 4);
  194943. uint_x = png_get_uint_32(buf);
  194944. png_crc_read(png_ptr, buf, 4);
  194945. uint_y = png_get_uint_32(buf);
  194946. if (uint_x + uint_y > 100000L)
  194947. {
  194948. png_warning(png_ptr, "Invalid cHRM red point");
  194949. png_crc_finish(png_ptr, 16);
  194950. return;
  194951. }
  194952. int_x_red = (png_fixed_point)uint_x;
  194953. int_y_red = (png_fixed_point)uint_y;
  194954. png_crc_read(png_ptr, buf, 4);
  194955. uint_x = png_get_uint_32(buf);
  194956. png_crc_read(png_ptr, buf, 4);
  194957. uint_y = png_get_uint_32(buf);
  194958. if (uint_x + uint_y > 100000L)
  194959. {
  194960. png_warning(png_ptr, "Invalid cHRM green point");
  194961. png_crc_finish(png_ptr, 8);
  194962. return;
  194963. }
  194964. int_x_green = (png_fixed_point)uint_x;
  194965. int_y_green = (png_fixed_point)uint_y;
  194966. png_crc_read(png_ptr, buf, 4);
  194967. uint_x = png_get_uint_32(buf);
  194968. png_crc_read(png_ptr, buf, 4);
  194969. uint_y = png_get_uint_32(buf);
  194970. if (uint_x + uint_y > 100000L)
  194971. {
  194972. png_warning(png_ptr, "Invalid cHRM blue point");
  194973. png_crc_finish(png_ptr, 0);
  194974. return;
  194975. }
  194976. int_x_blue = (png_fixed_point)uint_x;
  194977. int_y_blue = (png_fixed_point)uint_y;
  194978. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194979. white_x = (float)int_x_white / (float)100000.0;
  194980. white_y = (float)int_y_white / (float)100000.0;
  194981. red_x = (float)int_x_red / (float)100000.0;
  194982. red_y = (float)int_y_red / (float)100000.0;
  194983. green_x = (float)int_x_green / (float)100000.0;
  194984. green_y = (float)int_y_green / (float)100000.0;
  194985. blue_x = (float)int_x_blue / (float)100000.0;
  194986. blue_y = (float)int_y_blue / (float)100000.0;
  194987. #endif
  194988. #if defined(PNG_READ_sRGB_SUPPORTED)
  194989. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194990. {
  194991. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194992. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194993. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194994. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194995. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194996. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194997. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194998. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194999. {
  195000. png_warning(png_ptr,
  195001. "Ignoring incorrect cHRM value when sRGB is also present");
  195002. #ifndef PNG_NO_CONSOLE_IO
  195003. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195004. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  195005. white_x, white_y, red_x, red_y);
  195006. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  195007. green_x, green_y, blue_x, blue_y);
  195008. #else
  195009. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  195010. int_x_white, int_y_white, int_x_red, int_y_red);
  195011. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  195012. int_x_green, int_y_green, int_x_blue, int_y_blue);
  195013. #endif
  195014. #endif /* PNG_NO_CONSOLE_IO */
  195015. }
  195016. png_crc_finish(png_ptr, 0);
  195017. return;
  195018. }
  195019. #endif /* PNG_READ_sRGB_SUPPORTED */
  195020. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195021. png_set_cHRM(png_ptr, info_ptr,
  195022. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  195023. #endif
  195024. #ifdef PNG_FIXED_POINT_SUPPORTED
  195025. png_set_cHRM_fixed(png_ptr, info_ptr,
  195026. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  195027. int_y_green, int_x_blue, int_y_blue);
  195028. #endif
  195029. if (png_crc_finish(png_ptr, 0))
  195030. return;
  195031. }
  195032. #endif
  195033. #if defined(PNG_READ_sRGB_SUPPORTED)
  195034. void /* PRIVATE */
  195035. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195036. {
  195037. int intent;
  195038. png_byte buf[1];
  195039. png_debug(1, "in png_handle_sRGB\n");
  195040. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195041. png_error(png_ptr, "Missing IHDR before sRGB");
  195042. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195043. {
  195044. png_warning(png_ptr, "Invalid sRGB after IDAT");
  195045. png_crc_finish(png_ptr, length);
  195046. return;
  195047. }
  195048. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195049. /* Should be an error, but we can cope with it */
  195050. png_warning(png_ptr, "Out of place sRGB chunk");
  195051. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  195052. {
  195053. png_warning(png_ptr, "Duplicate sRGB chunk");
  195054. png_crc_finish(png_ptr, length);
  195055. return;
  195056. }
  195057. if (length != 1)
  195058. {
  195059. png_warning(png_ptr, "Incorrect sRGB chunk length");
  195060. png_crc_finish(png_ptr, length);
  195061. return;
  195062. }
  195063. png_crc_read(png_ptr, buf, 1);
  195064. if (png_crc_finish(png_ptr, 0))
  195065. return;
  195066. intent = buf[0];
  195067. /* check for bad intent */
  195068. if (intent >= PNG_sRGB_INTENT_LAST)
  195069. {
  195070. png_warning(png_ptr, "Unknown sRGB intent");
  195071. return;
  195072. }
  195073. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  195074. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  195075. {
  195076. png_fixed_point igamma;
  195077. #ifdef PNG_FIXED_POINT_SUPPORTED
  195078. igamma=info_ptr->int_gamma;
  195079. #else
  195080. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195081. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  195082. # endif
  195083. #endif
  195084. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  195085. {
  195086. png_warning(png_ptr,
  195087. "Ignoring incorrect gAMA value when sRGB is also present");
  195088. #ifndef PNG_NO_CONSOLE_IO
  195089. # ifdef PNG_FIXED_POINT_SUPPORTED
  195090. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  195091. # else
  195092. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195093. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  195094. # endif
  195095. # endif
  195096. #endif
  195097. }
  195098. }
  195099. #endif /* PNG_READ_gAMA_SUPPORTED */
  195100. #ifdef PNG_READ_cHRM_SUPPORTED
  195101. #ifdef PNG_FIXED_POINT_SUPPORTED
  195102. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  195103. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  195104. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  195105. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  195106. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  195107. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  195108. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  195109. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  195110. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  195111. {
  195112. png_warning(png_ptr,
  195113. "Ignoring incorrect cHRM value when sRGB is also present");
  195114. }
  195115. #endif /* PNG_FIXED_POINT_SUPPORTED */
  195116. #endif /* PNG_READ_cHRM_SUPPORTED */
  195117. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  195118. }
  195119. #endif /* PNG_READ_sRGB_SUPPORTED */
  195120. #if defined(PNG_READ_iCCP_SUPPORTED)
  195121. void /* PRIVATE */
  195122. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195123. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195124. {
  195125. png_charp chunkdata;
  195126. png_byte compression_type;
  195127. png_bytep pC;
  195128. png_charp profile;
  195129. png_uint_32 skip = 0;
  195130. png_uint_32 profile_size, profile_length;
  195131. png_size_t slength, prefix_length, data_length;
  195132. png_debug(1, "in png_handle_iCCP\n");
  195133. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195134. png_error(png_ptr, "Missing IHDR before iCCP");
  195135. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195136. {
  195137. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195138. png_crc_finish(png_ptr, length);
  195139. return;
  195140. }
  195141. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195142. /* Should be an error, but we can cope with it */
  195143. png_warning(png_ptr, "Out of place iCCP chunk");
  195144. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195145. {
  195146. png_warning(png_ptr, "Duplicate iCCP chunk");
  195147. png_crc_finish(png_ptr, length);
  195148. return;
  195149. }
  195150. #ifdef PNG_MAX_MALLOC_64K
  195151. if (length > (png_uint_32)65535L)
  195152. {
  195153. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195154. skip = length - (png_uint_32)65535L;
  195155. length = (png_uint_32)65535L;
  195156. }
  195157. #endif
  195158. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195159. slength = (png_size_t)length;
  195160. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195161. if (png_crc_finish(png_ptr, skip))
  195162. {
  195163. png_free(png_ptr, chunkdata);
  195164. return;
  195165. }
  195166. chunkdata[slength] = 0x00;
  195167. for (profile = chunkdata; *profile; profile++)
  195168. /* empty loop to find end of name */ ;
  195169. ++profile;
  195170. /* there should be at least one zero (the compression type byte)
  195171. following the separator, and we should be on it */
  195172. if ( profile >= chunkdata + slength - 1)
  195173. {
  195174. png_free(png_ptr, chunkdata);
  195175. png_warning(png_ptr, "Malformed iCCP chunk");
  195176. return;
  195177. }
  195178. /* compression_type should always be zero */
  195179. compression_type = *profile++;
  195180. if (compression_type)
  195181. {
  195182. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195183. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195184. wrote nonzero) */
  195185. }
  195186. prefix_length = profile - chunkdata;
  195187. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195188. slength, prefix_length, &data_length);
  195189. profile_length = data_length - prefix_length;
  195190. if ( prefix_length > data_length || profile_length < 4)
  195191. {
  195192. png_free(png_ptr, chunkdata);
  195193. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195194. return;
  195195. }
  195196. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195197. pC = (png_bytep)(chunkdata+prefix_length);
  195198. profile_size = ((*(pC ))<<24) |
  195199. ((*(pC+1))<<16) |
  195200. ((*(pC+2))<< 8) |
  195201. ((*(pC+3)) );
  195202. if(profile_size < profile_length)
  195203. profile_length = profile_size;
  195204. if(profile_size > profile_length)
  195205. {
  195206. png_free(png_ptr, chunkdata);
  195207. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195208. return;
  195209. }
  195210. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195211. chunkdata + prefix_length, profile_length);
  195212. png_free(png_ptr, chunkdata);
  195213. }
  195214. #endif /* PNG_READ_iCCP_SUPPORTED */
  195215. #if defined(PNG_READ_sPLT_SUPPORTED)
  195216. void /* PRIVATE */
  195217. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195218. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195219. {
  195220. png_bytep chunkdata;
  195221. png_bytep entry_start;
  195222. png_sPLT_t new_palette;
  195223. #ifdef PNG_NO_POINTER_INDEXING
  195224. png_sPLT_entryp pp;
  195225. #endif
  195226. int data_length, entry_size, i;
  195227. png_uint_32 skip = 0;
  195228. png_size_t slength;
  195229. png_debug(1, "in png_handle_sPLT\n");
  195230. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195231. png_error(png_ptr, "Missing IHDR before sPLT");
  195232. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195233. {
  195234. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195235. png_crc_finish(png_ptr, length);
  195236. return;
  195237. }
  195238. #ifdef PNG_MAX_MALLOC_64K
  195239. if (length > (png_uint_32)65535L)
  195240. {
  195241. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195242. skip = length - (png_uint_32)65535L;
  195243. length = (png_uint_32)65535L;
  195244. }
  195245. #endif
  195246. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195247. slength = (png_size_t)length;
  195248. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195249. if (png_crc_finish(png_ptr, skip))
  195250. {
  195251. png_free(png_ptr, chunkdata);
  195252. return;
  195253. }
  195254. chunkdata[slength] = 0x00;
  195255. for (entry_start = chunkdata; *entry_start; entry_start++)
  195256. /* empty loop to find end of name */ ;
  195257. ++entry_start;
  195258. /* a sample depth should follow the separator, and we should be on it */
  195259. if (entry_start > chunkdata + slength - 2)
  195260. {
  195261. png_free(png_ptr, chunkdata);
  195262. png_warning(png_ptr, "malformed sPLT chunk");
  195263. return;
  195264. }
  195265. new_palette.depth = *entry_start++;
  195266. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195267. data_length = (slength - (entry_start - chunkdata));
  195268. /* integrity-check the data length */
  195269. if (data_length % entry_size)
  195270. {
  195271. png_free(png_ptr, chunkdata);
  195272. png_warning(png_ptr, "sPLT chunk has bad length");
  195273. return;
  195274. }
  195275. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195276. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195277. png_sizeof(png_sPLT_entry)))
  195278. {
  195279. png_warning(png_ptr, "sPLT chunk too long");
  195280. return;
  195281. }
  195282. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195283. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195284. if (new_palette.entries == NULL)
  195285. {
  195286. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195287. return;
  195288. }
  195289. #ifndef PNG_NO_POINTER_INDEXING
  195290. for (i = 0; i < new_palette.nentries; i++)
  195291. {
  195292. png_sPLT_entryp pp = new_palette.entries + i;
  195293. if (new_palette.depth == 8)
  195294. {
  195295. pp->red = *entry_start++;
  195296. pp->green = *entry_start++;
  195297. pp->blue = *entry_start++;
  195298. pp->alpha = *entry_start++;
  195299. }
  195300. else
  195301. {
  195302. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195303. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195304. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195305. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195306. }
  195307. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195308. }
  195309. #else
  195310. pp = new_palette.entries;
  195311. for (i = 0; i < new_palette.nentries; i++)
  195312. {
  195313. if (new_palette.depth == 8)
  195314. {
  195315. pp[i].red = *entry_start++;
  195316. pp[i].green = *entry_start++;
  195317. pp[i].blue = *entry_start++;
  195318. pp[i].alpha = *entry_start++;
  195319. }
  195320. else
  195321. {
  195322. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195323. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195324. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195325. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195326. }
  195327. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195328. }
  195329. #endif
  195330. /* discard all chunk data except the name and stash that */
  195331. new_palette.name = (png_charp)chunkdata;
  195332. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195333. png_free(png_ptr, chunkdata);
  195334. png_free(png_ptr, new_palette.entries);
  195335. }
  195336. #endif /* PNG_READ_sPLT_SUPPORTED */
  195337. #if defined(PNG_READ_tRNS_SUPPORTED)
  195338. void /* PRIVATE */
  195339. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195340. {
  195341. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195342. int bit_mask;
  195343. png_debug(1, "in png_handle_tRNS\n");
  195344. /* For non-indexed color, mask off any bits in the tRNS value that
  195345. * exceed the bit depth. Some creators were writing extra bits there.
  195346. * This is not needed for indexed color. */
  195347. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195348. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195349. png_error(png_ptr, "Missing IHDR before tRNS");
  195350. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195351. {
  195352. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195353. png_crc_finish(png_ptr, length);
  195354. return;
  195355. }
  195356. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195357. {
  195358. png_warning(png_ptr, "Duplicate tRNS chunk");
  195359. png_crc_finish(png_ptr, length);
  195360. return;
  195361. }
  195362. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195363. {
  195364. png_byte buf[2];
  195365. if (length != 2)
  195366. {
  195367. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195368. png_crc_finish(png_ptr, length);
  195369. return;
  195370. }
  195371. png_crc_read(png_ptr, buf, 2);
  195372. png_ptr->num_trans = 1;
  195373. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195374. }
  195375. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195376. {
  195377. png_byte buf[6];
  195378. if (length != 6)
  195379. {
  195380. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195381. png_crc_finish(png_ptr, length);
  195382. return;
  195383. }
  195384. png_crc_read(png_ptr, buf, (png_size_t)length);
  195385. png_ptr->num_trans = 1;
  195386. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195387. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195388. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195389. }
  195390. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195391. {
  195392. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195393. {
  195394. /* Should be an error, but we can cope with it. */
  195395. png_warning(png_ptr, "Missing PLTE before tRNS");
  195396. }
  195397. if (length > (png_uint_32)png_ptr->num_palette ||
  195398. length > PNG_MAX_PALETTE_LENGTH)
  195399. {
  195400. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195401. png_crc_finish(png_ptr, length);
  195402. return;
  195403. }
  195404. if (length == 0)
  195405. {
  195406. png_warning(png_ptr, "Zero length tRNS chunk");
  195407. png_crc_finish(png_ptr, length);
  195408. return;
  195409. }
  195410. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195411. png_ptr->num_trans = (png_uint_16)length;
  195412. }
  195413. else
  195414. {
  195415. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195416. png_crc_finish(png_ptr, length);
  195417. return;
  195418. }
  195419. if (png_crc_finish(png_ptr, 0))
  195420. {
  195421. png_ptr->num_trans = 0;
  195422. return;
  195423. }
  195424. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195425. &(png_ptr->trans_values));
  195426. }
  195427. #endif
  195428. #if defined(PNG_READ_bKGD_SUPPORTED)
  195429. void /* PRIVATE */
  195430. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195431. {
  195432. png_size_t truelen;
  195433. png_byte buf[6];
  195434. png_debug(1, "in png_handle_bKGD\n");
  195435. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195436. png_error(png_ptr, "Missing IHDR before bKGD");
  195437. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195438. {
  195439. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195440. png_crc_finish(png_ptr, length);
  195441. return;
  195442. }
  195443. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195444. !(png_ptr->mode & PNG_HAVE_PLTE))
  195445. {
  195446. png_warning(png_ptr, "Missing PLTE before bKGD");
  195447. png_crc_finish(png_ptr, length);
  195448. return;
  195449. }
  195450. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195451. {
  195452. png_warning(png_ptr, "Duplicate bKGD chunk");
  195453. png_crc_finish(png_ptr, length);
  195454. return;
  195455. }
  195456. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195457. truelen = 1;
  195458. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195459. truelen = 6;
  195460. else
  195461. truelen = 2;
  195462. if (length != truelen)
  195463. {
  195464. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195465. png_crc_finish(png_ptr, length);
  195466. return;
  195467. }
  195468. png_crc_read(png_ptr, buf, truelen);
  195469. if (png_crc_finish(png_ptr, 0))
  195470. return;
  195471. /* We convert the index value into RGB components so that we can allow
  195472. * arbitrary RGB values for background when we have transparency, and
  195473. * so it is easy to determine the RGB values of the background color
  195474. * from the info_ptr struct. */
  195475. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195476. {
  195477. png_ptr->background.index = buf[0];
  195478. if(info_ptr->num_palette)
  195479. {
  195480. if(buf[0] > info_ptr->num_palette)
  195481. {
  195482. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195483. return;
  195484. }
  195485. png_ptr->background.red =
  195486. (png_uint_16)png_ptr->palette[buf[0]].red;
  195487. png_ptr->background.green =
  195488. (png_uint_16)png_ptr->palette[buf[0]].green;
  195489. png_ptr->background.blue =
  195490. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195491. }
  195492. }
  195493. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195494. {
  195495. png_ptr->background.red =
  195496. png_ptr->background.green =
  195497. png_ptr->background.blue =
  195498. png_ptr->background.gray = png_get_uint_16(buf);
  195499. }
  195500. else
  195501. {
  195502. png_ptr->background.red = png_get_uint_16(buf);
  195503. png_ptr->background.green = png_get_uint_16(buf + 2);
  195504. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195505. }
  195506. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195507. }
  195508. #endif
  195509. #if defined(PNG_READ_hIST_SUPPORTED)
  195510. void /* PRIVATE */
  195511. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195512. {
  195513. unsigned int num, i;
  195514. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195515. png_debug(1, "in png_handle_hIST\n");
  195516. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195517. png_error(png_ptr, "Missing IHDR before hIST");
  195518. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195519. {
  195520. png_warning(png_ptr, "Invalid hIST after IDAT");
  195521. png_crc_finish(png_ptr, length);
  195522. return;
  195523. }
  195524. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195525. {
  195526. png_warning(png_ptr, "Missing PLTE before hIST");
  195527. png_crc_finish(png_ptr, length);
  195528. return;
  195529. }
  195530. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195531. {
  195532. png_warning(png_ptr, "Duplicate hIST chunk");
  195533. png_crc_finish(png_ptr, length);
  195534. return;
  195535. }
  195536. num = length / 2 ;
  195537. if (num != (unsigned int) png_ptr->num_palette || num >
  195538. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195539. {
  195540. png_warning(png_ptr, "Incorrect hIST chunk length");
  195541. png_crc_finish(png_ptr, length);
  195542. return;
  195543. }
  195544. for (i = 0; i < num; i++)
  195545. {
  195546. png_byte buf[2];
  195547. png_crc_read(png_ptr, buf, 2);
  195548. readbuf[i] = png_get_uint_16(buf);
  195549. }
  195550. if (png_crc_finish(png_ptr, 0))
  195551. return;
  195552. png_set_hIST(png_ptr, info_ptr, readbuf);
  195553. }
  195554. #endif
  195555. #if defined(PNG_READ_pHYs_SUPPORTED)
  195556. void /* PRIVATE */
  195557. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195558. {
  195559. png_byte buf[9];
  195560. png_uint_32 res_x, res_y;
  195561. int unit_type;
  195562. png_debug(1, "in png_handle_pHYs\n");
  195563. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195564. png_error(png_ptr, "Missing IHDR before pHYs");
  195565. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195566. {
  195567. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195568. png_crc_finish(png_ptr, length);
  195569. return;
  195570. }
  195571. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195572. {
  195573. png_warning(png_ptr, "Duplicate pHYs chunk");
  195574. png_crc_finish(png_ptr, length);
  195575. return;
  195576. }
  195577. if (length != 9)
  195578. {
  195579. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195580. png_crc_finish(png_ptr, length);
  195581. return;
  195582. }
  195583. png_crc_read(png_ptr, buf, 9);
  195584. if (png_crc_finish(png_ptr, 0))
  195585. return;
  195586. res_x = png_get_uint_32(buf);
  195587. res_y = png_get_uint_32(buf + 4);
  195588. unit_type = buf[8];
  195589. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195590. }
  195591. #endif
  195592. #if defined(PNG_READ_oFFs_SUPPORTED)
  195593. void /* PRIVATE */
  195594. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195595. {
  195596. png_byte buf[9];
  195597. png_int_32 offset_x, offset_y;
  195598. int unit_type;
  195599. png_debug(1, "in png_handle_oFFs\n");
  195600. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195601. png_error(png_ptr, "Missing IHDR before oFFs");
  195602. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195603. {
  195604. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195605. png_crc_finish(png_ptr, length);
  195606. return;
  195607. }
  195608. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195609. {
  195610. png_warning(png_ptr, "Duplicate oFFs chunk");
  195611. png_crc_finish(png_ptr, length);
  195612. return;
  195613. }
  195614. if (length != 9)
  195615. {
  195616. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195617. png_crc_finish(png_ptr, length);
  195618. return;
  195619. }
  195620. png_crc_read(png_ptr, buf, 9);
  195621. if (png_crc_finish(png_ptr, 0))
  195622. return;
  195623. offset_x = png_get_int_32(buf);
  195624. offset_y = png_get_int_32(buf + 4);
  195625. unit_type = buf[8];
  195626. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195627. }
  195628. #endif
  195629. #if defined(PNG_READ_pCAL_SUPPORTED)
  195630. /* read the pCAL chunk (described in the PNG Extensions document) */
  195631. void /* PRIVATE */
  195632. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195633. {
  195634. png_charp purpose;
  195635. png_int_32 X0, X1;
  195636. png_byte type, nparams;
  195637. png_charp buf, units, endptr;
  195638. png_charpp params;
  195639. png_size_t slength;
  195640. int i;
  195641. png_debug(1, "in png_handle_pCAL\n");
  195642. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195643. png_error(png_ptr, "Missing IHDR before pCAL");
  195644. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195645. {
  195646. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195647. png_crc_finish(png_ptr, length);
  195648. return;
  195649. }
  195650. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195651. {
  195652. png_warning(png_ptr, "Duplicate pCAL chunk");
  195653. png_crc_finish(png_ptr, length);
  195654. return;
  195655. }
  195656. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195657. length + 1);
  195658. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195659. if (purpose == NULL)
  195660. {
  195661. png_warning(png_ptr, "No memory for pCAL purpose.");
  195662. return;
  195663. }
  195664. slength = (png_size_t)length;
  195665. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195666. if (png_crc_finish(png_ptr, 0))
  195667. {
  195668. png_free(png_ptr, purpose);
  195669. return;
  195670. }
  195671. purpose[slength] = 0x00; /* null terminate the last string */
  195672. png_debug(3, "Finding end of pCAL purpose string\n");
  195673. for (buf = purpose; *buf; buf++)
  195674. /* empty loop */ ;
  195675. endptr = purpose + slength;
  195676. /* We need to have at least 12 bytes after the purpose string
  195677. in order to get the parameter information. */
  195678. if (endptr <= buf + 12)
  195679. {
  195680. png_warning(png_ptr, "Invalid pCAL data");
  195681. png_free(png_ptr, purpose);
  195682. return;
  195683. }
  195684. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195685. X0 = png_get_int_32((png_bytep)buf+1);
  195686. X1 = png_get_int_32((png_bytep)buf+5);
  195687. type = buf[9];
  195688. nparams = buf[10];
  195689. units = buf + 11;
  195690. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195691. /* Check that we have the right number of parameters for known
  195692. equation types. */
  195693. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195694. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195695. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195696. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195697. {
  195698. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195699. png_free(png_ptr, purpose);
  195700. return;
  195701. }
  195702. else if (type >= PNG_EQUATION_LAST)
  195703. {
  195704. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195705. }
  195706. for (buf = units; *buf; buf++)
  195707. /* Empty loop to move past the units string. */ ;
  195708. png_debug(3, "Allocating pCAL parameters array\n");
  195709. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195710. *png_sizeof(png_charp))) ;
  195711. if (params == NULL)
  195712. {
  195713. png_free(png_ptr, purpose);
  195714. png_warning(png_ptr, "No memory for pCAL params.");
  195715. return;
  195716. }
  195717. /* Get pointers to the start of each parameter string. */
  195718. for (i = 0; i < (int)nparams; i++)
  195719. {
  195720. buf++; /* Skip the null string terminator from previous parameter. */
  195721. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195722. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195723. /* Empty loop to move past each parameter string */ ;
  195724. /* Make sure we haven't run out of data yet */
  195725. if (buf > endptr)
  195726. {
  195727. png_warning(png_ptr, "Invalid pCAL data");
  195728. png_free(png_ptr, purpose);
  195729. png_free(png_ptr, params);
  195730. return;
  195731. }
  195732. }
  195733. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195734. units, params);
  195735. png_free(png_ptr, purpose);
  195736. png_free(png_ptr, params);
  195737. }
  195738. #endif
  195739. #if defined(PNG_READ_sCAL_SUPPORTED)
  195740. /* read the sCAL chunk */
  195741. void /* PRIVATE */
  195742. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195743. {
  195744. png_charp buffer, ep;
  195745. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195746. double width, height;
  195747. png_charp vp;
  195748. #else
  195749. #ifdef PNG_FIXED_POINT_SUPPORTED
  195750. png_charp swidth, sheight;
  195751. #endif
  195752. #endif
  195753. png_size_t slength;
  195754. png_debug(1, "in png_handle_sCAL\n");
  195755. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195756. png_error(png_ptr, "Missing IHDR before sCAL");
  195757. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195758. {
  195759. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195760. png_crc_finish(png_ptr, length);
  195761. return;
  195762. }
  195763. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195764. {
  195765. png_warning(png_ptr, "Duplicate sCAL chunk");
  195766. png_crc_finish(png_ptr, length);
  195767. return;
  195768. }
  195769. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195770. length + 1);
  195771. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195772. if (buffer == NULL)
  195773. {
  195774. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195775. return;
  195776. }
  195777. slength = (png_size_t)length;
  195778. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195779. if (png_crc_finish(png_ptr, 0))
  195780. {
  195781. png_free(png_ptr, buffer);
  195782. return;
  195783. }
  195784. buffer[slength] = 0x00; /* null terminate the last string */
  195785. ep = buffer + 1; /* skip unit byte */
  195786. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195787. width = png_strtod(png_ptr, ep, &vp);
  195788. if (*vp)
  195789. {
  195790. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195791. return;
  195792. }
  195793. #else
  195794. #ifdef PNG_FIXED_POINT_SUPPORTED
  195795. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195796. if (swidth == NULL)
  195797. {
  195798. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195799. return;
  195800. }
  195801. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195802. #endif
  195803. #endif
  195804. for (ep = buffer; *ep; ep++)
  195805. /* empty loop */ ;
  195806. ep++;
  195807. if (buffer + slength < ep)
  195808. {
  195809. png_warning(png_ptr, "Truncated sCAL chunk");
  195810. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195811. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195812. png_free(png_ptr, swidth);
  195813. #endif
  195814. png_free(png_ptr, buffer);
  195815. return;
  195816. }
  195817. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195818. height = png_strtod(png_ptr, ep, &vp);
  195819. if (*vp)
  195820. {
  195821. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195822. return;
  195823. }
  195824. #else
  195825. #ifdef PNG_FIXED_POINT_SUPPORTED
  195826. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195827. if (swidth == NULL)
  195828. {
  195829. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195830. return;
  195831. }
  195832. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195833. #endif
  195834. #endif
  195835. if (buffer + slength < ep
  195836. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195837. || width <= 0. || height <= 0.
  195838. #endif
  195839. )
  195840. {
  195841. png_warning(png_ptr, "Invalid sCAL data");
  195842. png_free(png_ptr, buffer);
  195843. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195844. png_free(png_ptr, swidth);
  195845. png_free(png_ptr, sheight);
  195846. #endif
  195847. return;
  195848. }
  195849. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195850. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195851. #else
  195852. #ifdef PNG_FIXED_POINT_SUPPORTED
  195853. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195854. #endif
  195855. #endif
  195856. png_free(png_ptr, buffer);
  195857. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195858. png_free(png_ptr, swidth);
  195859. png_free(png_ptr, sheight);
  195860. #endif
  195861. }
  195862. #endif
  195863. #if defined(PNG_READ_tIME_SUPPORTED)
  195864. void /* PRIVATE */
  195865. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195866. {
  195867. png_byte buf[7];
  195868. png_time mod_time;
  195869. png_debug(1, "in png_handle_tIME\n");
  195870. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195871. png_error(png_ptr, "Out of place tIME chunk");
  195872. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195873. {
  195874. png_warning(png_ptr, "Duplicate tIME chunk");
  195875. png_crc_finish(png_ptr, length);
  195876. return;
  195877. }
  195878. if (png_ptr->mode & PNG_HAVE_IDAT)
  195879. png_ptr->mode |= PNG_AFTER_IDAT;
  195880. if (length != 7)
  195881. {
  195882. png_warning(png_ptr, "Incorrect tIME chunk length");
  195883. png_crc_finish(png_ptr, length);
  195884. return;
  195885. }
  195886. png_crc_read(png_ptr, buf, 7);
  195887. if (png_crc_finish(png_ptr, 0))
  195888. return;
  195889. mod_time.second = buf[6];
  195890. mod_time.minute = buf[5];
  195891. mod_time.hour = buf[4];
  195892. mod_time.day = buf[3];
  195893. mod_time.month = buf[2];
  195894. mod_time.year = png_get_uint_16(buf);
  195895. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195896. }
  195897. #endif
  195898. #if defined(PNG_READ_tEXt_SUPPORTED)
  195899. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195900. void /* PRIVATE */
  195901. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195902. {
  195903. png_textp text_ptr;
  195904. png_charp key;
  195905. png_charp text;
  195906. png_uint_32 skip = 0;
  195907. png_size_t slength;
  195908. int ret;
  195909. png_debug(1, "in png_handle_tEXt\n");
  195910. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195911. png_error(png_ptr, "Missing IHDR before tEXt");
  195912. if (png_ptr->mode & PNG_HAVE_IDAT)
  195913. png_ptr->mode |= PNG_AFTER_IDAT;
  195914. #ifdef PNG_MAX_MALLOC_64K
  195915. if (length > (png_uint_32)65535L)
  195916. {
  195917. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195918. skip = length - (png_uint_32)65535L;
  195919. length = (png_uint_32)65535L;
  195920. }
  195921. #endif
  195922. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195923. if (key == NULL)
  195924. {
  195925. png_warning(png_ptr, "No memory to process text chunk.");
  195926. return;
  195927. }
  195928. slength = (png_size_t)length;
  195929. png_crc_read(png_ptr, (png_bytep)key, slength);
  195930. if (png_crc_finish(png_ptr, skip))
  195931. {
  195932. png_free(png_ptr, key);
  195933. return;
  195934. }
  195935. key[slength] = 0x00;
  195936. for (text = key; *text; text++)
  195937. /* empty loop to find end of key */ ;
  195938. if (text != key + slength)
  195939. text++;
  195940. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195941. (png_uint_32)png_sizeof(png_text));
  195942. if (text_ptr == NULL)
  195943. {
  195944. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195945. png_free(png_ptr, key);
  195946. return;
  195947. }
  195948. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195949. text_ptr->key = key;
  195950. #ifdef PNG_iTXt_SUPPORTED
  195951. text_ptr->lang = NULL;
  195952. text_ptr->lang_key = NULL;
  195953. text_ptr->itxt_length = 0;
  195954. #endif
  195955. text_ptr->text = text;
  195956. text_ptr->text_length = png_strlen(text);
  195957. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195958. png_free(png_ptr, key);
  195959. png_free(png_ptr, text_ptr);
  195960. if (ret)
  195961. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195962. }
  195963. #endif
  195964. #if defined(PNG_READ_zTXt_SUPPORTED)
  195965. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195966. void /* PRIVATE */
  195967. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195968. {
  195969. png_textp text_ptr;
  195970. png_charp chunkdata;
  195971. png_charp text;
  195972. int comp_type;
  195973. int ret;
  195974. png_size_t slength, prefix_len, data_len;
  195975. png_debug(1, "in png_handle_zTXt\n");
  195976. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195977. png_error(png_ptr, "Missing IHDR before zTXt");
  195978. if (png_ptr->mode & PNG_HAVE_IDAT)
  195979. png_ptr->mode |= PNG_AFTER_IDAT;
  195980. #ifdef PNG_MAX_MALLOC_64K
  195981. /* We will no doubt have problems with chunks even half this size, but
  195982. there is no hard and fast rule to tell us where to stop. */
  195983. if (length > (png_uint_32)65535L)
  195984. {
  195985. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195986. png_crc_finish(png_ptr, length);
  195987. return;
  195988. }
  195989. #endif
  195990. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195991. if (chunkdata == NULL)
  195992. {
  195993. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195994. return;
  195995. }
  195996. slength = (png_size_t)length;
  195997. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195998. if (png_crc_finish(png_ptr, 0))
  195999. {
  196000. png_free(png_ptr, chunkdata);
  196001. return;
  196002. }
  196003. chunkdata[slength] = 0x00;
  196004. for (text = chunkdata; *text; text++)
  196005. /* empty loop */ ;
  196006. /* zTXt must have some text after the chunkdataword */
  196007. if (text >= chunkdata + slength - 2)
  196008. {
  196009. png_warning(png_ptr, "Truncated zTXt chunk");
  196010. png_free(png_ptr, chunkdata);
  196011. return;
  196012. }
  196013. else
  196014. {
  196015. comp_type = *(++text);
  196016. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  196017. {
  196018. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  196019. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  196020. }
  196021. text++; /* skip the compression_method byte */
  196022. }
  196023. prefix_len = text - chunkdata;
  196024. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196025. (png_size_t)length, prefix_len, &data_len);
  196026. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196027. (png_uint_32)png_sizeof(png_text));
  196028. if (text_ptr == NULL)
  196029. {
  196030. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  196031. png_free(png_ptr, chunkdata);
  196032. return;
  196033. }
  196034. text_ptr->compression = comp_type;
  196035. text_ptr->key = chunkdata;
  196036. #ifdef PNG_iTXt_SUPPORTED
  196037. text_ptr->lang = NULL;
  196038. text_ptr->lang_key = NULL;
  196039. text_ptr->itxt_length = 0;
  196040. #endif
  196041. text_ptr->text = chunkdata + prefix_len;
  196042. text_ptr->text_length = data_len;
  196043. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196044. png_free(png_ptr, text_ptr);
  196045. png_free(png_ptr, chunkdata);
  196046. if (ret)
  196047. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  196048. }
  196049. #endif
  196050. #if defined(PNG_READ_iTXt_SUPPORTED)
  196051. /* note: this does not correctly handle chunks that are > 64K under DOS */
  196052. void /* PRIVATE */
  196053. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196054. {
  196055. png_textp text_ptr;
  196056. png_charp chunkdata;
  196057. png_charp key, lang, text, lang_key;
  196058. int comp_flag;
  196059. int comp_type = 0;
  196060. int ret;
  196061. png_size_t slength, prefix_len, data_len;
  196062. png_debug(1, "in png_handle_iTXt\n");
  196063. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196064. png_error(png_ptr, "Missing IHDR before iTXt");
  196065. if (png_ptr->mode & PNG_HAVE_IDAT)
  196066. png_ptr->mode |= PNG_AFTER_IDAT;
  196067. #ifdef PNG_MAX_MALLOC_64K
  196068. /* We will no doubt have problems with chunks even half this size, but
  196069. there is no hard and fast rule to tell us where to stop. */
  196070. if (length > (png_uint_32)65535L)
  196071. {
  196072. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  196073. png_crc_finish(png_ptr, length);
  196074. return;
  196075. }
  196076. #endif
  196077. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  196078. if (chunkdata == NULL)
  196079. {
  196080. png_warning(png_ptr, "No memory to process iTXt chunk.");
  196081. return;
  196082. }
  196083. slength = (png_size_t)length;
  196084. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  196085. if (png_crc_finish(png_ptr, 0))
  196086. {
  196087. png_free(png_ptr, chunkdata);
  196088. return;
  196089. }
  196090. chunkdata[slength] = 0x00;
  196091. for (lang = chunkdata; *lang; lang++)
  196092. /* empty loop */ ;
  196093. lang++; /* skip NUL separator */
  196094. /* iTXt must have a language tag (possibly empty), two compression bytes,
  196095. translated keyword (possibly empty), and possibly some text after the
  196096. keyword */
  196097. if (lang >= chunkdata + slength - 3)
  196098. {
  196099. png_warning(png_ptr, "Truncated iTXt chunk");
  196100. png_free(png_ptr, chunkdata);
  196101. return;
  196102. }
  196103. else
  196104. {
  196105. comp_flag = *lang++;
  196106. comp_type = *lang++;
  196107. }
  196108. for (lang_key = lang; *lang_key; lang_key++)
  196109. /* empty loop */ ;
  196110. lang_key++; /* skip NUL separator */
  196111. if (lang_key >= chunkdata + slength)
  196112. {
  196113. png_warning(png_ptr, "Truncated iTXt chunk");
  196114. png_free(png_ptr, chunkdata);
  196115. return;
  196116. }
  196117. for (text = lang_key; *text; text++)
  196118. /* empty loop */ ;
  196119. text++; /* skip NUL separator */
  196120. if (text >= chunkdata + slength)
  196121. {
  196122. png_warning(png_ptr, "Malformed iTXt chunk");
  196123. png_free(png_ptr, chunkdata);
  196124. return;
  196125. }
  196126. prefix_len = text - chunkdata;
  196127. key=chunkdata;
  196128. if (comp_flag)
  196129. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196130. (size_t)length, prefix_len, &data_len);
  196131. else
  196132. data_len=png_strlen(chunkdata + prefix_len);
  196133. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196134. (png_uint_32)png_sizeof(png_text));
  196135. if (text_ptr == NULL)
  196136. {
  196137. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196138. png_free(png_ptr, chunkdata);
  196139. return;
  196140. }
  196141. text_ptr->compression = (int)comp_flag + 1;
  196142. text_ptr->lang_key = chunkdata+(lang_key-key);
  196143. text_ptr->lang = chunkdata+(lang-key);
  196144. text_ptr->itxt_length = data_len;
  196145. text_ptr->text_length = 0;
  196146. text_ptr->key = chunkdata;
  196147. text_ptr->text = chunkdata + prefix_len;
  196148. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196149. png_free(png_ptr, text_ptr);
  196150. png_free(png_ptr, chunkdata);
  196151. if (ret)
  196152. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196153. }
  196154. #endif
  196155. /* This function is called when we haven't found a handler for a
  196156. chunk. If there isn't a problem with the chunk itself (ie bad
  196157. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196158. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196159. case it will be saved away to be written out later. */
  196160. void /* PRIVATE */
  196161. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196162. {
  196163. png_uint_32 skip = 0;
  196164. png_debug(1, "in png_handle_unknown\n");
  196165. if (png_ptr->mode & PNG_HAVE_IDAT)
  196166. {
  196167. #ifdef PNG_USE_LOCAL_ARRAYS
  196168. PNG_CONST PNG_IDAT;
  196169. #endif
  196170. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196171. png_ptr->mode |= PNG_AFTER_IDAT;
  196172. }
  196173. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196174. if (!(png_ptr->chunk_name[0] & 0x20))
  196175. {
  196176. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196177. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196178. PNG_HANDLE_CHUNK_ALWAYS
  196179. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196180. && png_ptr->read_user_chunk_fn == NULL
  196181. #endif
  196182. )
  196183. #endif
  196184. png_chunk_error(png_ptr, "unknown critical chunk");
  196185. }
  196186. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196187. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196188. (png_ptr->read_user_chunk_fn != NULL))
  196189. {
  196190. #ifdef PNG_MAX_MALLOC_64K
  196191. if (length > (png_uint_32)65535L)
  196192. {
  196193. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196194. skip = length - (png_uint_32)65535L;
  196195. length = (png_uint_32)65535L;
  196196. }
  196197. #endif
  196198. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196199. (png_charp)png_ptr->chunk_name, 5);
  196200. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196201. png_ptr->unknown_chunk.size = (png_size_t)length;
  196202. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196203. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196204. if(png_ptr->read_user_chunk_fn != NULL)
  196205. {
  196206. /* callback to user unknown chunk handler */
  196207. int ret;
  196208. ret = (*(png_ptr->read_user_chunk_fn))
  196209. (png_ptr, &png_ptr->unknown_chunk);
  196210. if (ret < 0)
  196211. png_chunk_error(png_ptr, "error in user chunk");
  196212. if (ret == 0)
  196213. {
  196214. if (!(png_ptr->chunk_name[0] & 0x20))
  196215. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196216. PNG_HANDLE_CHUNK_ALWAYS)
  196217. png_chunk_error(png_ptr, "unknown critical chunk");
  196218. png_set_unknown_chunks(png_ptr, info_ptr,
  196219. &png_ptr->unknown_chunk, 1);
  196220. }
  196221. }
  196222. #else
  196223. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196224. #endif
  196225. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196226. png_ptr->unknown_chunk.data = NULL;
  196227. }
  196228. else
  196229. #endif
  196230. skip = length;
  196231. png_crc_finish(png_ptr, skip);
  196232. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196233. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196234. #endif
  196235. }
  196236. /* This function is called to verify that a chunk name is valid.
  196237. This function can't have the "critical chunk check" incorporated
  196238. into it, since in the future we will need to be able to call user
  196239. functions to handle unknown critical chunks after we check that
  196240. the chunk name itself is valid. */
  196241. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196242. void /* PRIVATE */
  196243. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196244. {
  196245. png_debug(1, "in png_check_chunk_name\n");
  196246. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196247. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196248. {
  196249. png_chunk_error(png_ptr, "invalid chunk type");
  196250. }
  196251. }
  196252. /* Combines the row recently read in with the existing pixels in the
  196253. row. This routine takes care of alpha and transparency if requested.
  196254. This routine also handles the two methods of progressive display
  196255. of interlaced images, depending on the mask value.
  196256. The mask value describes which pixels are to be combined with
  196257. the row. The pattern always repeats every 8 pixels, so just 8
  196258. bits are needed. A one indicates the pixel is to be combined,
  196259. a zero indicates the pixel is to be skipped. This is in addition
  196260. to any alpha or transparency value associated with the pixel. If
  196261. you want all pixels to be combined, pass 0xff (255) in mask. */
  196262. void /* PRIVATE */
  196263. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196264. {
  196265. png_debug(1,"in png_combine_row\n");
  196266. if (mask == 0xff)
  196267. {
  196268. png_memcpy(row, png_ptr->row_buf + 1,
  196269. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196270. }
  196271. else
  196272. {
  196273. switch (png_ptr->row_info.pixel_depth)
  196274. {
  196275. case 1:
  196276. {
  196277. png_bytep sp = png_ptr->row_buf + 1;
  196278. png_bytep dp = row;
  196279. int s_inc, s_start, s_end;
  196280. int m = 0x80;
  196281. int shift;
  196282. png_uint_32 i;
  196283. png_uint_32 row_width = png_ptr->width;
  196284. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196285. if (png_ptr->transformations & PNG_PACKSWAP)
  196286. {
  196287. s_start = 0;
  196288. s_end = 7;
  196289. s_inc = 1;
  196290. }
  196291. else
  196292. #endif
  196293. {
  196294. s_start = 7;
  196295. s_end = 0;
  196296. s_inc = -1;
  196297. }
  196298. shift = s_start;
  196299. for (i = 0; i < row_width; i++)
  196300. {
  196301. if (m & mask)
  196302. {
  196303. int value;
  196304. value = (*sp >> shift) & 0x01;
  196305. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196306. *dp |= (png_byte)(value << shift);
  196307. }
  196308. if (shift == s_end)
  196309. {
  196310. shift = s_start;
  196311. sp++;
  196312. dp++;
  196313. }
  196314. else
  196315. shift += s_inc;
  196316. if (m == 1)
  196317. m = 0x80;
  196318. else
  196319. m >>= 1;
  196320. }
  196321. break;
  196322. }
  196323. case 2:
  196324. {
  196325. png_bytep sp = png_ptr->row_buf + 1;
  196326. png_bytep dp = row;
  196327. int s_start, s_end, s_inc;
  196328. int m = 0x80;
  196329. int shift;
  196330. png_uint_32 i;
  196331. png_uint_32 row_width = png_ptr->width;
  196332. int value;
  196333. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196334. if (png_ptr->transformations & PNG_PACKSWAP)
  196335. {
  196336. s_start = 0;
  196337. s_end = 6;
  196338. s_inc = 2;
  196339. }
  196340. else
  196341. #endif
  196342. {
  196343. s_start = 6;
  196344. s_end = 0;
  196345. s_inc = -2;
  196346. }
  196347. shift = s_start;
  196348. for (i = 0; i < row_width; i++)
  196349. {
  196350. if (m & mask)
  196351. {
  196352. value = (*sp >> shift) & 0x03;
  196353. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196354. *dp |= (png_byte)(value << shift);
  196355. }
  196356. if (shift == s_end)
  196357. {
  196358. shift = s_start;
  196359. sp++;
  196360. dp++;
  196361. }
  196362. else
  196363. shift += s_inc;
  196364. if (m == 1)
  196365. m = 0x80;
  196366. else
  196367. m >>= 1;
  196368. }
  196369. break;
  196370. }
  196371. case 4:
  196372. {
  196373. png_bytep sp = png_ptr->row_buf + 1;
  196374. png_bytep dp = row;
  196375. int s_start, s_end, s_inc;
  196376. int m = 0x80;
  196377. int shift;
  196378. png_uint_32 i;
  196379. png_uint_32 row_width = png_ptr->width;
  196380. int value;
  196381. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196382. if (png_ptr->transformations & PNG_PACKSWAP)
  196383. {
  196384. s_start = 0;
  196385. s_end = 4;
  196386. s_inc = 4;
  196387. }
  196388. else
  196389. #endif
  196390. {
  196391. s_start = 4;
  196392. s_end = 0;
  196393. s_inc = -4;
  196394. }
  196395. shift = s_start;
  196396. for (i = 0; i < row_width; i++)
  196397. {
  196398. if (m & mask)
  196399. {
  196400. value = (*sp >> shift) & 0xf;
  196401. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196402. *dp |= (png_byte)(value << shift);
  196403. }
  196404. if (shift == s_end)
  196405. {
  196406. shift = s_start;
  196407. sp++;
  196408. dp++;
  196409. }
  196410. else
  196411. shift += s_inc;
  196412. if (m == 1)
  196413. m = 0x80;
  196414. else
  196415. m >>= 1;
  196416. }
  196417. break;
  196418. }
  196419. default:
  196420. {
  196421. png_bytep sp = png_ptr->row_buf + 1;
  196422. png_bytep dp = row;
  196423. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196424. png_uint_32 i;
  196425. png_uint_32 row_width = png_ptr->width;
  196426. png_byte m = 0x80;
  196427. for (i = 0; i < row_width; i++)
  196428. {
  196429. if (m & mask)
  196430. {
  196431. png_memcpy(dp, sp, pixel_bytes);
  196432. }
  196433. sp += pixel_bytes;
  196434. dp += pixel_bytes;
  196435. if (m == 1)
  196436. m = 0x80;
  196437. else
  196438. m >>= 1;
  196439. }
  196440. break;
  196441. }
  196442. }
  196443. }
  196444. }
  196445. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196446. /* OLD pre-1.0.9 interface:
  196447. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196448. png_uint_32 transformations)
  196449. */
  196450. void /* PRIVATE */
  196451. png_do_read_interlace(png_structp png_ptr)
  196452. {
  196453. png_row_infop row_info = &(png_ptr->row_info);
  196454. png_bytep row = png_ptr->row_buf + 1;
  196455. int pass = png_ptr->pass;
  196456. png_uint_32 transformations = png_ptr->transformations;
  196457. #ifdef PNG_USE_LOCAL_ARRAYS
  196458. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196459. /* offset to next interlace block */
  196460. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196461. #endif
  196462. png_debug(1,"in png_do_read_interlace\n");
  196463. if (row != NULL && row_info != NULL)
  196464. {
  196465. png_uint_32 final_width;
  196466. final_width = row_info->width * png_pass_inc[pass];
  196467. switch (row_info->pixel_depth)
  196468. {
  196469. case 1:
  196470. {
  196471. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196472. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196473. int sshift, dshift;
  196474. int s_start, s_end, s_inc;
  196475. int jstop = png_pass_inc[pass];
  196476. png_byte v;
  196477. png_uint_32 i;
  196478. int j;
  196479. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196480. if (transformations & PNG_PACKSWAP)
  196481. {
  196482. sshift = (int)((row_info->width + 7) & 0x07);
  196483. dshift = (int)((final_width + 7) & 0x07);
  196484. s_start = 7;
  196485. s_end = 0;
  196486. s_inc = -1;
  196487. }
  196488. else
  196489. #endif
  196490. {
  196491. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196492. dshift = 7 - (int)((final_width + 7) & 0x07);
  196493. s_start = 0;
  196494. s_end = 7;
  196495. s_inc = 1;
  196496. }
  196497. for (i = 0; i < row_info->width; i++)
  196498. {
  196499. v = (png_byte)((*sp >> sshift) & 0x01);
  196500. for (j = 0; j < jstop; j++)
  196501. {
  196502. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196503. *dp |= (png_byte)(v << dshift);
  196504. if (dshift == s_end)
  196505. {
  196506. dshift = s_start;
  196507. dp--;
  196508. }
  196509. else
  196510. dshift += s_inc;
  196511. }
  196512. if (sshift == s_end)
  196513. {
  196514. sshift = s_start;
  196515. sp--;
  196516. }
  196517. else
  196518. sshift += s_inc;
  196519. }
  196520. break;
  196521. }
  196522. case 2:
  196523. {
  196524. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196525. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196526. int sshift, dshift;
  196527. int s_start, s_end, s_inc;
  196528. int jstop = png_pass_inc[pass];
  196529. png_uint_32 i;
  196530. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196531. if (transformations & PNG_PACKSWAP)
  196532. {
  196533. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196534. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196535. s_start = 6;
  196536. s_end = 0;
  196537. s_inc = -2;
  196538. }
  196539. else
  196540. #endif
  196541. {
  196542. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196543. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196544. s_start = 0;
  196545. s_end = 6;
  196546. s_inc = 2;
  196547. }
  196548. for (i = 0; i < row_info->width; i++)
  196549. {
  196550. png_byte v;
  196551. int j;
  196552. v = (png_byte)((*sp >> sshift) & 0x03);
  196553. for (j = 0; j < jstop; j++)
  196554. {
  196555. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196556. *dp |= (png_byte)(v << dshift);
  196557. if (dshift == s_end)
  196558. {
  196559. dshift = s_start;
  196560. dp--;
  196561. }
  196562. else
  196563. dshift += s_inc;
  196564. }
  196565. if (sshift == s_end)
  196566. {
  196567. sshift = s_start;
  196568. sp--;
  196569. }
  196570. else
  196571. sshift += s_inc;
  196572. }
  196573. break;
  196574. }
  196575. case 4:
  196576. {
  196577. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196578. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196579. int sshift, dshift;
  196580. int s_start, s_end, s_inc;
  196581. png_uint_32 i;
  196582. int jstop = png_pass_inc[pass];
  196583. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196584. if (transformations & PNG_PACKSWAP)
  196585. {
  196586. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196587. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196588. s_start = 4;
  196589. s_end = 0;
  196590. s_inc = -4;
  196591. }
  196592. else
  196593. #endif
  196594. {
  196595. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196596. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196597. s_start = 0;
  196598. s_end = 4;
  196599. s_inc = 4;
  196600. }
  196601. for (i = 0; i < row_info->width; i++)
  196602. {
  196603. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196604. int j;
  196605. for (j = 0; j < jstop; j++)
  196606. {
  196607. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196608. *dp |= (png_byte)(v << dshift);
  196609. if (dshift == s_end)
  196610. {
  196611. dshift = s_start;
  196612. dp--;
  196613. }
  196614. else
  196615. dshift += s_inc;
  196616. }
  196617. if (sshift == s_end)
  196618. {
  196619. sshift = s_start;
  196620. sp--;
  196621. }
  196622. else
  196623. sshift += s_inc;
  196624. }
  196625. break;
  196626. }
  196627. default:
  196628. {
  196629. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196630. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196631. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196632. int jstop = png_pass_inc[pass];
  196633. png_uint_32 i;
  196634. for (i = 0; i < row_info->width; i++)
  196635. {
  196636. png_byte v[8];
  196637. int j;
  196638. png_memcpy(v, sp, pixel_bytes);
  196639. for (j = 0; j < jstop; j++)
  196640. {
  196641. png_memcpy(dp, v, pixel_bytes);
  196642. dp -= pixel_bytes;
  196643. }
  196644. sp -= pixel_bytes;
  196645. }
  196646. break;
  196647. }
  196648. }
  196649. row_info->width = final_width;
  196650. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196651. }
  196652. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196653. transformations = transformations; /* silence compiler warning */
  196654. #endif
  196655. }
  196656. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196657. void /* PRIVATE */
  196658. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196659. png_bytep prev_row, int filter)
  196660. {
  196661. png_debug(1, "in png_read_filter_row\n");
  196662. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196663. switch (filter)
  196664. {
  196665. case PNG_FILTER_VALUE_NONE:
  196666. break;
  196667. case PNG_FILTER_VALUE_SUB:
  196668. {
  196669. png_uint_32 i;
  196670. png_uint_32 istop = row_info->rowbytes;
  196671. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196672. png_bytep rp = row + bpp;
  196673. png_bytep lp = row;
  196674. for (i = bpp; i < istop; i++)
  196675. {
  196676. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196677. rp++;
  196678. }
  196679. break;
  196680. }
  196681. case PNG_FILTER_VALUE_UP:
  196682. {
  196683. png_uint_32 i;
  196684. png_uint_32 istop = row_info->rowbytes;
  196685. png_bytep rp = row;
  196686. png_bytep pp = prev_row;
  196687. for (i = 0; i < istop; i++)
  196688. {
  196689. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196690. rp++;
  196691. }
  196692. break;
  196693. }
  196694. case PNG_FILTER_VALUE_AVG:
  196695. {
  196696. png_uint_32 i;
  196697. png_bytep rp = row;
  196698. png_bytep pp = prev_row;
  196699. png_bytep lp = row;
  196700. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196701. png_uint_32 istop = row_info->rowbytes - bpp;
  196702. for (i = 0; i < bpp; i++)
  196703. {
  196704. *rp = (png_byte)(((int)(*rp) +
  196705. ((int)(*pp++) / 2 )) & 0xff);
  196706. rp++;
  196707. }
  196708. for (i = 0; i < istop; i++)
  196709. {
  196710. *rp = (png_byte)(((int)(*rp) +
  196711. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196712. rp++;
  196713. }
  196714. break;
  196715. }
  196716. case PNG_FILTER_VALUE_PAETH:
  196717. {
  196718. png_uint_32 i;
  196719. png_bytep rp = row;
  196720. png_bytep pp = prev_row;
  196721. png_bytep lp = row;
  196722. png_bytep cp = prev_row;
  196723. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196724. png_uint_32 istop=row_info->rowbytes - bpp;
  196725. for (i = 0; i < bpp; i++)
  196726. {
  196727. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196728. rp++;
  196729. }
  196730. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196731. {
  196732. int a, b, c, pa, pb, pc, p;
  196733. a = *lp++;
  196734. b = *pp++;
  196735. c = *cp++;
  196736. p = b - c;
  196737. pc = a - c;
  196738. #ifdef PNG_USE_ABS
  196739. pa = abs(p);
  196740. pb = abs(pc);
  196741. pc = abs(p + pc);
  196742. #else
  196743. pa = p < 0 ? -p : p;
  196744. pb = pc < 0 ? -pc : pc;
  196745. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196746. #endif
  196747. /*
  196748. if (pa <= pb && pa <= pc)
  196749. p = a;
  196750. else if (pb <= pc)
  196751. p = b;
  196752. else
  196753. p = c;
  196754. */
  196755. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196756. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196757. rp++;
  196758. }
  196759. break;
  196760. }
  196761. default:
  196762. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196763. *row=0;
  196764. break;
  196765. }
  196766. }
  196767. void /* PRIVATE */
  196768. png_read_finish_row(png_structp png_ptr)
  196769. {
  196770. #ifdef PNG_USE_LOCAL_ARRAYS
  196771. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196772. /* start of interlace block */
  196773. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196774. /* offset to next interlace block */
  196775. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196776. /* start of interlace block in the y direction */
  196777. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196778. /* offset to next interlace block in the y direction */
  196779. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196780. #endif
  196781. png_debug(1, "in png_read_finish_row\n");
  196782. png_ptr->row_number++;
  196783. if (png_ptr->row_number < png_ptr->num_rows)
  196784. return;
  196785. if (png_ptr->interlaced)
  196786. {
  196787. png_ptr->row_number = 0;
  196788. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196789. png_ptr->rowbytes + 1);
  196790. do
  196791. {
  196792. png_ptr->pass++;
  196793. if (png_ptr->pass >= 7)
  196794. break;
  196795. png_ptr->iwidth = (png_ptr->width +
  196796. png_pass_inc[png_ptr->pass] - 1 -
  196797. png_pass_start[png_ptr->pass]) /
  196798. png_pass_inc[png_ptr->pass];
  196799. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196800. png_ptr->iwidth) + 1;
  196801. if (!(png_ptr->transformations & PNG_INTERLACE))
  196802. {
  196803. png_ptr->num_rows = (png_ptr->height +
  196804. png_pass_yinc[png_ptr->pass] - 1 -
  196805. png_pass_ystart[png_ptr->pass]) /
  196806. png_pass_yinc[png_ptr->pass];
  196807. if (!(png_ptr->num_rows))
  196808. continue;
  196809. }
  196810. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196811. break;
  196812. } while (png_ptr->iwidth == 0);
  196813. if (png_ptr->pass < 7)
  196814. return;
  196815. }
  196816. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196817. {
  196818. #ifdef PNG_USE_LOCAL_ARRAYS
  196819. PNG_CONST PNG_IDAT;
  196820. #endif
  196821. char extra;
  196822. int ret;
  196823. png_ptr->zstream.next_out = (Bytef *)&extra;
  196824. png_ptr->zstream.avail_out = (uInt)1;
  196825. for(;;)
  196826. {
  196827. if (!(png_ptr->zstream.avail_in))
  196828. {
  196829. while (!png_ptr->idat_size)
  196830. {
  196831. png_byte chunk_length[4];
  196832. png_crc_finish(png_ptr, 0);
  196833. png_read_data(png_ptr, chunk_length, 4);
  196834. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196835. png_reset_crc(png_ptr);
  196836. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196837. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196838. png_error(png_ptr, "Not enough image data");
  196839. }
  196840. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196841. png_ptr->zstream.next_in = png_ptr->zbuf;
  196842. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196843. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196844. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196845. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196846. }
  196847. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196848. if (ret == Z_STREAM_END)
  196849. {
  196850. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196851. png_ptr->idat_size)
  196852. png_warning(png_ptr, "Extra compressed data");
  196853. png_ptr->mode |= PNG_AFTER_IDAT;
  196854. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196855. break;
  196856. }
  196857. if (ret != Z_OK)
  196858. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196859. "Decompression Error");
  196860. if (!(png_ptr->zstream.avail_out))
  196861. {
  196862. png_warning(png_ptr, "Extra compressed data.");
  196863. png_ptr->mode |= PNG_AFTER_IDAT;
  196864. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196865. break;
  196866. }
  196867. }
  196868. png_ptr->zstream.avail_out = 0;
  196869. }
  196870. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196871. png_warning(png_ptr, "Extra compression data");
  196872. inflateReset(&png_ptr->zstream);
  196873. png_ptr->mode |= PNG_AFTER_IDAT;
  196874. }
  196875. void /* PRIVATE */
  196876. png_read_start_row(png_structp png_ptr)
  196877. {
  196878. #ifdef PNG_USE_LOCAL_ARRAYS
  196879. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196880. /* start of interlace block */
  196881. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196882. /* offset to next interlace block */
  196883. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196884. /* start of interlace block in the y direction */
  196885. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196886. /* offset to next interlace block in the y direction */
  196887. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196888. #endif
  196889. int max_pixel_depth;
  196890. png_uint_32 row_bytes;
  196891. png_debug(1, "in png_read_start_row\n");
  196892. png_ptr->zstream.avail_in = 0;
  196893. png_init_read_transformations(png_ptr);
  196894. if (png_ptr->interlaced)
  196895. {
  196896. if (!(png_ptr->transformations & PNG_INTERLACE))
  196897. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196898. png_pass_ystart[0]) / png_pass_yinc[0];
  196899. else
  196900. png_ptr->num_rows = png_ptr->height;
  196901. png_ptr->iwidth = (png_ptr->width +
  196902. png_pass_inc[png_ptr->pass] - 1 -
  196903. png_pass_start[png_ptr->pass]) /
  196904. png_pass_inc[png_ptr->pass];
  196905. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196906. png_ptr->irowbytes = (png_size_t)row_bytes;
  196907. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196908. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196909. }
  196910. else
  196911. {
  196912. png_ptr->num_rows = png_ptr->height;
  196913. png_ptr->iwidth = png_ptr->width;
  196914. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196915. }
  196916. max_pixel_depth = png_ptr->pixel_depth;
  196917. #if defined(PNG_READ_PACK_SUPPORTED)
  196918. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196919. max_pixel_depth = 8;
  196920. #endif
  196921. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196922. if (png_ptr->transformations & PNG_EXPAND)
  196923. {
  196924. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196925. {
  196926. if (png_ptr->num_trans)
  196927. max_pixel_depth = 32;
  196928. else
  196929. max_pixel_depth = 24;
  196930. }
  196931. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196932. {
  196933. if (max_pixel_depth < 8)
  196934. max_pixel_depth = 8;
  196935. if (png_ptr->num_trans)
  196936. max_pixel_depth *= 2;
  196937. }
  196938. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196939. {
  196940. if (png_ptr->num_trans)
  196941. {
  196942. max_pixel_depth *= 4;
  196943. max_pixel_depth /= 3;
  196944. }
  196945. }
  196946. }
  196947. #endif
  196948. #if defined(PNG_READ_FILLER_SUPPORTED)
  196949. if (png_ptr->transformations & (PNG_FILLER))
  196950. {
  196951. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196952. max_pixel_depth = 32;
  196953. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196954. {
  196955. if (max_pixel_depth <= 8)
  196956. max_pixel_depth = 16;
  196957. else
  196958. max_pixel_depth = 32;
  196959. }
  196960. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196961. {
  196962. if (max_pixel_depth <= 32)
  196963. max_pixel_depth = 32;
  196964. else
  196965. max_pixel_depth = 64;
  196966. }
  196967. }
  196968. #endif
  196969. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196970. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196971. {
  196972. if (
  196973. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196974. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196975. #endif
  196976. #if defined(PNG_READ_FILLER_SUPPORTED)
  196977. (png_ptr->transformations & (PNG_FILLER)) ||
  196978. #endif
  196979. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196980. {
  196981. if (max_pixel_depth <= 16)
  196982. max_pixel_depth = 32;
  196983. else
  196984. max_pixel_depth = 64;
  196985. }
  196986. else
  196987. {
  196988. if (max_pixel_depth <= 8)
  196989. {
  196990. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196991. max_pixel_depth = 32;
  196992. else
  196993. max_pixel_depth = 24;
  196994. }
  196995. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196996. max_pixel_depth = 64;
  196997. else
  196998. max_pixel_depth = 48;
  196999. }
  197000. }
  197001. #endif
  197002. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  197003. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197004. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  197005. {
  197006. int user_pixel_depth=png_ptr->user_transform_depth*
  197007. png_ptr->user_transform_channels;
  197008. if(user_pixel_depth > max_pixel_depth)
  197009. max_pixel_depth=user_pixel_depth;
  197010. }
  197011. #endif
  197012. /* align the width on the next larger 8 pixels. Mainly used
  197013. for interlacing */
  197014. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  197015. /* calculate the maximum bytes needed, adding a byte and a pixel
  197016. for safety's sake */
  197017. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  197018. 1 + ((max_pixel_depth + 7) >> 3);
  197019. #ifdef PNG_MAX_MALLOC_64K
  197020. if (row_bytes > (png_uint_32)65536L)
  197021. png_error(png_ptr, "This image requires a row greater than 64KB");
  197022. #endif
  197023. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  197024. png_ptr->row_buf = png_ptr->big_row_buf+32;
  197025. #ifdef PNG_MAX_MALLOC_64K
  197026. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  197027. png_error(png_ptr, "This image requires a row greater than 64KB");
  197028. #endif
  197029. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  197030. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  197031. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  197032. png_ptr->rowbytes + 1));
  197033. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  197034. png_debug1(3, "width = %lu,\n", png_ptr->width);
  197035. png_debug1(3, "height = %lu,\n", png_ptr->height);
  197036. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  197037. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  197038. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  197039. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  197040. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  197041. }
  197042. #endif /* PNG_READ_SUPPORTED */
  197043. /*** End of inlined file: pngrutil.c ***/
  197044. /*** Start of inlined file: pngset.c ***/
  197045. /* pngset.c - storage of image information into info struct
  197046. *
  197047. * Last changed in libpng 1.2.21 [October 4, 2007]
  197048. * For conditions of distribution and use, see copyright notice in png.h
  197049. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197050. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197051. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197052. *
  197053. * The functions here are used during reads to store data from the file
  197054. * into the info struct, and during writes to store application data
  197055. * into the info struct for writing into the file. This abstracts the
  197056. * info struct and allows us to change the structure in the future.
  197057. */
  197058. #define PNG_INTERNAL
  197059. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197060. #if defined(PNG_bKGD_SUPPORTED)
  197061. void PNGAPI
  197062. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  197063. {
  197064. png_debug1(1, "in %s storage function\n", "bKGD");
  197065. if (png_ptr == NULL || info_ptr == NULL)
  197066. return;
  197067. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  197068. info_ptr->valid |= PNG_INFO_bKGD;
  197069. }
  197070. #endif
  197071. #if defined(PNG_cHRM_SUPPORTED)
  197072. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197073. void PNGAPI
  197074. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  197075. double white_x, double white_y, double red_x, double red_y,
  197076. double green_x, double green_y, double blue_x, double blue_y)
  197077. {
  197078. png_debug1(1, "in %s storage function\n", "cHRM");
  197079. if (png_ptr == NULL || info_ptr == NULL)
  197080. return;
  197081. if (white_x < 0.0 || white_y < 0.0 ||
  197082. red_x < 0.0 || red_y < 0.0 ||
  197083. green_x < 0.0 || green_y < 0.0 ||
  197084. blue_x < 0.0 || blue_y < 0.0)
  197085. {
  197086. png_warning(png_ptr,
  197087. "Ignoring attempt to set negative chromaticity value");
  197088. return;
  197089. }
  197090. if (white_x > 21474.83 || white_y > 21474.83 ||
  197091. red_x > 21474.83 || red_y > 21474.83 ||
  197092. green_x > 21474.83 || green_y > 21474.83 ||
  197093. blue_x > 21474.83 || blue_y > 21474.83)
  197094. {
  197095. png_warning(png_ptr,
  197096. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197097. return;
  197098. }
  197099. info_ptr->x_white = (float)white_x;
  197100. info_ptr->y_white = (float)white_y;
  197101. info_ptr->x_red = (float)red_x;
  197102. info_ptr->y_red = (float)red_y;
  197103. info_ptr->x_green = (float)green_x;
  197104. info_ptr->y_green = (float)green_y;
  197105. info_ptr->x_blue = (float)blue_x;
  197106. info_ptr->y_blue = (float)blue_y;
  197107. #ifdef PNG_FIXED_POINT_SUPPORTED
  197108. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  197109. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  197110. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  197111. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  197112. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  197113. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  197114. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  197115. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  197116. #endif
  197117. info_ptr->valid |= PNG_INFO_cHRM;
  197118. }
  197119. #endif
  197120. #ifdef PNG_FIXED_POINT_SUPPORTED
  197121. void PNGAPI
  197122. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197123. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197124. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197125. png_fixed_point blue_x, png_fixed_point blue_y)
  197126. {
  197127. png_debug1(1, "in %s storage function\n", "cHRM");
  197128. if (png_ptr == NULL || info_ptr == NULL)
  197129. return;
  197130. if (white_x < 0 || white_y < 0 ||
  197131. red_x < 0 || red_y < 0 ||
  197132. green_x < 0 || green_y < 0 ||
  197133. blue_x < 0 || blue_y < 0)
  197134. {
  197135. png_warning(png_ptr,
  197136. "Ignoring attempt to set negative chromaticity value");
  197137. return;
  197138. }
  197139. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197140. if (white_x > (double) PNG_UINT_31_MAX ||
  197141. white_y > (double) PNG_UINT_31_MAX ||
  197142. red_x > (double) PNG_UINT_31_MAX ||
  197143. red_y > (double) PNG_UINT_31_MAX ||
  197144. green_x > (double) PNG_UINT_31_MAX ||
  197145. green_y > (double) PNG_UINT_31_MAX ||
  197146. blue_x > (double) PNG_UINT_31_MAX ||
  197147. blue_y > (double) PNG_UINT_31_MAX)
  197148. #else
  197149. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197150. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197151. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197152. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197153. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197154. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197155. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197156. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197157. #endif
  197158. {
  197159. png_warning(png_ptr,
  197160. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197161. return;
  197162. }
  197163. info_ptr->int_x_white = white_x;
  197164. info_ptr->int_y_white = white_y;
  197165. info_ptr->int_x_red = red_x;
  197166. info_ptr->int_y_red = red_y;
  197167. info_ptr->int_x_green = green_x;
  197168. info_ptr->int_y_green = green_y;
  197169. info_ptr->int_x_blue = blue_x;
  197170. info_ptr->int_y_blue = blue_y;
  197171. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197172. info_ptr->x_white = (float)(white_x/100000.);
  197173. info_ptr->y_white = (float)(white_y/100000.);
  197174. info_ptr->x_red = (float)( red_x/100000.);
  197175. info_ptr->y_red = (float)( red_y/100000.);
  197176. info_ptr->x_green = (float)(green_x/100000.);
  197177. info_ptr->y_green = (float)(green_y/100000.);
  197178. info_ptr->x_blue = (float)( blue_x/100000.);
  197179. info_ptr->y_blue = (float)( blue_y/100000.);
  197180. #endif
  197181. info_ptr->valid |= PNG_INFO_cHRM;
  197182. }
  197183. #endif
  197184. #endif
  197185. #if defined(PNG_gAMA_SUPPORTED)
  197186. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197187. void PNGAPI
  197188. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197189. {
  197190. double gamma;
  197191. png_debug1(1, "in %s storage function\n", "gAMA");
  197192. if (png_ptr == NULL || info_ptr == NULL)
  197193. return;
  197194. /* Check for overflow */
  197195. if (file_gamma > 21474.83)
  197196. {
  197197. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197198. gamma=21474.83;
  197199. }
  197200. else
  197201. gamma=file_gamma;
  197202. info_ptr->gamma = (float)gamma;
  197203. #ifdef PNG_FIXED_POINT_SUPPORTED
  197204. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197205. #endif
  197206. info_ptr->valid |= PNG_INFO_gAMA;
  197207. if(gamma == 0.0)
  197208. png_warning(png_ptr, "Setting gamma=0");
  197209. }
  197210. #endif
  197211. void PNGAPI
  197212. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197213. int_gamma)
  197214. {
  197215. png_fixed_point gamma;
  197216. png_debug1(1, "in %s storage function\n", "gAMA");
  197217. if (png_ptr == NULL || info_ptr == NULL)
  197218. return;
  197219. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197220. {
  197221. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197222. gamma=PNG_UINT_31_MAX;
  197223. }
  197224. else
  197225. {
  197226. if (int_gamma < 0)
  197227. {
  197228. png_warning(png_ptr, "Setting negative gamma to zero");
  197229. gamma=0;
  197230. }
  197231. else
  197232. gamma=int_gamma;
  197233. }
  197234. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197235. info_ptr->gamma = (float)(gamma/100000.);
  197236. #endif
  197237. #ifdef PNG_FIXED_POINT_SUPPORTED
  197238. info_ptr->int_gamma = gamma;
  197239. #endif
  197240. info_ptr->valid |= PNG_INFO_gAMA;
  197241. if(gamma == 0)
  197242. png_warning(png_ptr, "Setting gamma=0");
  197243. }
  197244. #endif
  197245. #if defined(PNG_hIST_SUPPORTED)
  197246. void PNGAPI
  197247. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197248. {
  197249. int i;
  197250. png_debug1(1, "in %s storage function\n", "hIST");
  197251. if (png_ptr == NULL || info_ptr == NULL)
  197252. return;
  197253. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197254. > PNG_MAX_PALETTE_LENGTH)
  197255. {
  197256. png_warning(png_ptr,
  197257. "Invalid palette size, hIST allocation skipped.");
  197258. return;
  197259. }
  197260. #ifdef PNG_FREE_ME_SUPPORTED
  197261. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197262. #endif
  197263. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197264. 1.2.1 */
  197265. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197266. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197267. if (png_ptr->hist == NULL)
  197268. {
  197269. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197270. return;
  197271. }
  197272. for (i = 0; i < info_ptr->num_palette; i++)
  197273. png_ptr->hist[i] = hist[i];
  197274. info_ptr->hist = png_ptr->hist;
  197275. info_ptr->valid |= PNG_INFO_hIST;
  197276. #ifdef PNG_FREE_ME_SUPPORTED
  197277. info_ptr->free_me |= PNG_FREE_HIST;
  197278. #else
  197279. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197280. #endif
  197281. }
  197282. #endif
  197283. void PNGAPI
  197284. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197285. png_uint_32 width, png_uint_32 height, int bit_depth,
  197286. int color_type, int interlace_type, int compression_type,
  197287. int filter_type)
  197288. {
  197289. png_debug1(1, "in %s storage function\n", "IHDR");
  197290. if (png_ptr == NULL || info_ptr == NULL)
  197291. return;
  197292. /* check for width and height valid values */
  197293. if (width == 0 || height == 0)
  197294. png_error(png_ptr, "Image width or height is zero in IHDR");
  197295. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197296. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197297. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197298. #else
  197299. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197300. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197301. #endif
  197302. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197303. png_error(png_ptr, "Invalid image size in IHDR");
  197304. if ( width > (PNG_UINT_32_MAX
  197305. >> 3) /* 8-byte RGBA pixels */
  197306. - 64 /* bigrowbuf hack */
  197307. - 1 /* filter byte */
  197308. - 7*8 /* rounding of width to multiple of 8 pixels */
  197309. - 8) /* extra max_pixel_depth pad */
  197310. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197311. /* check other values */
  197312. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197313. bit_depth != 8 && bit_depth != 16)
  197314. png_error(png_ptr, "Invalid bit depth in IHDR");
  197315. if (color_type < 0 || color_type == 1 ||
  197316. color_type == 5 || color_type > 6)
  197317. png_error(png_ptr, "Invalid color type in IHDR");
  197318. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197319. ((color_type == PNG_COLOR_TYPE_RGB ||
  197320. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197321. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197322. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197323. if (interlace_type >= PNG_INTERLACE_LAST)
  197324. png_error(png_ptr, "Unknown interlace method in IHDR");
  197325. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197326. png_error(png_ptr, "Unknown compression method in IHDR");
  197327. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197328. /* Accept filter_method 64 (intrapixel differencing) only if
  197329. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197330. * 2. Libpng did not read a PNG signature (this filter_method is only
  197331. * used in PNG datastreams that are embedded in MNG datastreams) and
  197332. * 3. The application called png_permit_mng_features with a mask that
  197333. * included PNG_FLAG_MNG_FILTER_64 and
  197334. * 4. The filter_method is 64 and
  197335. * 5. The color_type is RGB or RGBA
  197336. */
  197337. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197338. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197339. if(filter_type != PNG_FILTER_TYPE_BASE)
  197340. {
  197341. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197342. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197343. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197344. (color_type == PNG_COLOR_TYPE_RGB ||
  197345. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197346. png_error(png_ptr, "Unknown filter method in IHDR");
  197347. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197348. png_warning(png_ptr, "Invalid filter method in IHDR");
  197349. }
  197350. #else
  197351. if(filter_type != PNG_FILTER_TYPE_BASE)
  197352. png_error(png_ptr, "Unknown filter method in IHDR");
  197353. #endif
  197354. info_ptr->width = width;
  197355. info_ptr->height = height;
  197356. info_ptr->bit_depth = (png_byte)bit_depth;
  197357. info_ptr->color_type =(png_byte) color_type;
  197358. info_ptr->compression_type = (png_byte)compression_type;
  197359. info_ptr->filter_type = (png_byte)filter_type;
  197360. info_ptr->interlace_type = (png_byte)interlace_type;
  197361. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197362. info_ptr->channels = 1;
  197363. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197364. info_ptr->channels = 3;
  197365. else
  197366. info_ptr->channels = 1;
  197367. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197368. info_ptr->channels++;
  197369. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197370. /* check for potential overflow */
  197371. if (width > (PNG_UINT_32_MAX
  197372. >> 3) /* 8-byte RGBA pixels */
  197373. - 64 /* bigrowbuf hack */
  197374. - 1 /* filter byte */
  197375. - 7*8 /* rounding of width to multiple of 8 pixels */
  197376. - 8) /* extra max_pixel_depth pad */
  197377. info_ptr->rowbytes = (png_size_t)0;
  197378. else
  197379. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197380. }
  197381. #if defined(PNG_oFFs_SUPPORTED)
  197382. void PNGAPI
  197383. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197384. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197385. {
  197386. png_debug1(1, "in %s storage function\n", "oFFs");
  197387. if (png_ptr == NULL || info_ptr == NULL)
  197388. return;
  197389. info_ptr->x_offset = offset_x;
  197390. info_ptr->y_offset = offset_y;
  197391. info_ptr->offset_unit_type = (png_byte)unit_type;
  197392. info_ptr->valid |= PNG_INFO_oFFs;
  197393. }
  197394. #endif
  197395. #if defined(PNG_pCAL_SUPPORTED)
  197396. void PNGAPI
  197397. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197398. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197399. png_charp units, png_charpp params)
  197400. {
  197401. png_uint_32 length;
  197402. int i;
  197403. png_debug1(1, "in %s storage function\n", "pCAL");
  197404. if (png_ptr == NULL || info_ptr == NULL)
  197405. return;
  197406. length = png_strlen(purpose) + 1;
  197407. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197408. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197409. if (info_ptr->pcal_purpose == NULL)
  197410. {
  197411. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197412. return;
  197413. }
  197414. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197415. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197416. info_ptr->pcal_X0 = X0;
  197417. info_ptr->pcal_X1 = X1;
  197418. info_ptr->pcal_type = (png_byte)type;
  197419. info_ptr->pcal_nparams = (png_byte)nparams;
  197420. length = png_strlen(units) + 1;
  197421. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197422. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197423. if (info_ptr->pcal_units == NULL)
  197424. {
  197425. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197426. return;
  197427. }
  197428. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197429. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197430. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197431. if (info_ptr->pcal_params == NULL)
  197432. {
  197433. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197434. return;
  197435. }
  197436. info_ptr->pcal_params[nparams] = NULL;
  197437. for (i = 0; i < nparams; i++)
  197438. {
  197439. length = png_strlen(params[i]) + 1;
  197440. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197441. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197442. if (info_ptr->pcal_params[i] == NULL)
  197443. {
  197444. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197445. return;
  197446. }
  197447. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197448. }
  197449. info_ptr->valid |= PNG_INFO_pCAL;
  197450. #ifdef PNG_FREE_ME_SUPPORTED
  197451. info_ptr->free_me |= PNG_FREE_PCAL;
  197452. #endif
  197453. }
  197454. #endif
  197455. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197456. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197457. void PNGAPI
  197458. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197459. int unit, double width, double height)
  197460. {
  197461. png_debug1(1, "in %s storage function\n", "sCAL");
  197462. if (png_ptr == NULL || info_ptr == NULL)
  197463. return;
  197464. info_ptr->scal_unit = (png_byte)unit;
  197465. info_ptr->scal_pixel_width = width;
  197466. info_ptr->scal_pixel_height = height;
  197467. info_ptr->valid |= PNG_INFO_sCAL;
  197468. }
  197469. #else
  197470. #ifdef PNG_FIXED_POINT_SUPPORTED
  197471. void PNGAPI
  197472. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197473. int unit, png_charp swidth, png_charp sheight)
  197474. {
  197475. png_uint_32 length;
  197476. png_debug1(1, "in %s storage function\n", "sCAL");
  197477. if (png_ptr == NULL || info_ptr == NULL)
  197478. return;
  197479. info_ptr->scal_unit = (png_byte)unit;
  197480. length = png_strlen(swidth) + 1;
  197481. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197482. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197483. if (info_ptr->scal_s_width == NULL)
  197484. {
  197485. png_warning(png_ptr,
  197486. "Memory allocation failed while processing sCAL.");
  197487. }
  197488. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197489. length = png_strlen(sheight) + 1;
  197490. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197491. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197492. if (info_ptr->scal_s_height == NULL)
  197493. {
  197494. png_free (png_ptr, info_ptr->scal_s_width);
  197495. png_warning(png_ptr,
  197496. "Memory allocation failed while processing sCAL.");
  197497. }
  197498. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197499. info_ptr->valid |= PNG_INFO_sCAL;
  197500. #ifdef PNG_FREE_ME_SUPPORTED
  197501. info_ptr->free_me |= PNG_FREE_SCAL;
  197502. #endif
  197503. }
  197504. #endif
  197505. #endif
  197506. #endif
  197507. #if defined(PNG_pHYs_SUPPORTED)
  197508. void PNGAPI
  197509. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197510. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197511. {
  197512. png_debug1(1, "in %s storage function\n", "pHYs");
  197513. if (png_ptr == NULL || info_ptr == NULL)
  197514. return;
  197515. info_ptr->x_pixels_per_unit = res_x;
  197516. info_ptr->y_pixels_per_unit = res_y;
  197517. info_ptr->phys_unit_type = (png_byte)unit_type;
  197518. info_ptr->valid |= PNG_INFO_pHYs;
  197519. }
  197520. #endif
  197521. void PNGAPI
  197522. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197523. png_colorp palette, int num_palette)
  197524. {
  197525. png_debug1(1, "in %s storage function\n", "PLTE");
  197526. if (png_ptr == NULL || info_ptr == NULL)
  197527. return;
  197528. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197529. {
  197530. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197531. png_error(png_ptr, "Invalid palette length");
  197532. else
  197533. {
  197534. png_warning(png_ptr, "Invalid palette length");
  197535. return;
  197536. }
  197537. }
  197538. /*
  197539. * It may not actually be necessary to set png_ptr->palette here;
  197540. * we do it for backward compatibility with the way the png_handle_tRNS
  197541. * function used to do the allocation.
  197542. */
  197543. #ifdef PNG_FREE_ME_SUPPORTED
  197544. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197545. #endif
  197546. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197547. of num_palette entries,
  197548. in case of an invalid PNG file that has too-large sample values. */
  197549. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197550. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197551. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197552. png_sizeof(png_color));
  197553. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197554. info_ptr->palette = png_ptr->palette;
  197555. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197556. #ifdef PNG_FREE_ME_SUPPORTED
  197557. info_ptr->free_me |= PNG_FREE_PLTE;
  197558. #else
  197559. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197560. #endif
  197561. info_ptr->valid |= PNG_INFO_PLTE;
  197562. }
  197563. #if defined(PNG_sBIT_SUPPORTED)
  197564. void PNGAPI
  197565. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197566. png_color_8p sig_bit)
  197567. {
  197568. png_debug1(1, "in %s storage function\n", "sBIT");
  197569. if (png_ptr == NULL || info_ptr == NULL)
  197570. return;
  197571. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197572. info_ptr->valid |= PNG_INFO_sBIT;
  197573. }
  197574. #endif
  197575. #if defined(PNG_sRGB_SUPPORTED)
  197576. void PNGAPI
  197577. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197578. {
  197579. png_debug1(1, "in %s storage function\n", "sRGB");
  197580. if (png_ptr == NULL || info_ptr == NULL)
  197581. return;
  197582. info_ptr->srgb_intent = (png_byte)intent;
  197583. info_ptr->valid |= PNG_INFO_sRGB;
  197584. }
  197585. void PNGAPI
  197586. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197587. int intent)
  197588. {
  197589. #if defined(PNG_gAMA_SUPPORTED)
  197590. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197591. float file_gamma;
  197592. #endif
  197593. #ifdef PNG_FIXED_POINT_SUPPORTED
  197594. png_fixed_point int_file_gamma;
  197595. #endif
  197596. #endif
  197597. #if defined(PNG_cHRM_SUPPORTED)
  197598. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197599. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197600. #endif
  197601. #ifdef PNG_FIXED_POINT_SUPPORTED
  197602. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197603. int_green_y, int_blue_x, int_blue_y;
  197604. #endif
  197605. #endif
  197606. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197607. if (png_ptr == NULL || info_ptr == NULL)
  197608. return;
  197609. png_set_sRGB(png_ptr, info_ptr, intent);
  197610. #if defined(PNG_gAMA_SUPPORTED)
  197611. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197612. file_gamma = (float).45455;
  197613. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197614. #endif
  197615. #ifdef PNG_FIXED_POINT_SUPPORTED
  197616. int_file_gamma = 45455L;
  197617. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197618. #endif
  197619. #endif
  197620. #if defined(PNG_cHRM_SUPPORTED)
  197621. #ifdef PNG_FIXED_POINT_SUPPORTED
  197622. int_white_x = 31270L;
  197623. int_white_y = 32900L;
  197624. int_red_x = 64000L;
  197625. int_red_y = 33000L;
  197626. int_green_x = 30000L;
  197627. int_green_y = 60000L;
  197628. int_blue_x = 15000L;
  197629. int_blue_y = 6000L;
  197630. png_set_cHRM_fixed(png_ptr, info_ptr,
  197631. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197632. int_blue_x, int_blue_y);
  197633. #endif
  197634. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197635. white_x = (float).3127;
  197636. white_y = (float).3290;
  197637. red_x = (float).64;
  197638. red_y = (float).33;
  197639. green_x = (float).30;
  197640. green_y = (float).60;
  197641. blue_x = (float).15;
  197642. blue_y = (float).06;
  197643. png_set_cHRM(png_ptr, info_ptr,
  197644. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197645. #endif
  197646. #endif
  197647. }
  197648. #endif
  197649. #if defined(PNG_iCCP_SUPPORTED)
  197650. void PNGAPI
  197651. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197652. png_charp name, int compression_type,
  197653. png_charp profile, png_uint_32 proflen)
  197654. {
  197655. png_charp new_iccp_name;
  197656. png_charp new_iccp_profile;
  197657. png_debug1(1, "in %s storage function\n", "iCCP");
  197658. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197659. return;
  197660. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197661. if (new_iccp_name == NULL)
  197662. {
  197663. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197664. return;
  197665. }
  197666. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197667. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197668. if (new_iccp_profile == NULL)
  197669. {
  197670. png_free (png_ptr, new_iccp_name);
  197671. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197672. return;
  197673. }
  197674. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197675. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197676. info_ptr->iccp_proflen = proflen;
  197677. info_ptr->iccp_name = new_iccp_name;
  197678. info_ptr->iccp_profile = new_iccp_profile;
  197679. /* Compression is always zero but is here so the API and info structure
  197680. * does not have to change if we introduce multiple compression types */
  197681. info_ptr->iccp_compression = (png_byte)compression_type;
  197682. #ifdef PNG_FREE_ME_SUPPORTED
  197683. info_ptr->free_me |= PNG_FREE_ICCP;
  197684. #endif
  197685. info_ptr->valid |= PNG_INFO_iCCP;
  197686. }
  197687. #endif
  197688. #if defined(PNG_TEXT_SUPPORTED)
  197689. void PNGAPI
  197690. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197691. int num_text)
  197692. {
  197693. int ret;
  197694. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197695. if (ret)
  197696. png_error(png_ptr, "Insufficient memory to store text");
  197697. }
  197698. int /* PRIVATE */
  197699. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197700. int num_text)
  197701. {
  197702. int i;
  197703. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197704. "text" : (png_const_charp)png_ptr->chunk_name));
  197705. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197706. return(0);
  197707. /* Make sure we have enough space in the "text" array in info_struct
  197708. * to hold all of the incoming text_ptr objects.
  197709. */
  197710. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197711. {
  197712. if (info_ptr->text != NULL)
  197713. {
  197714. png_textp old_text;
  197715. int old_max;
  197716. old_max = info_ptr->max_text;
  197717. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197718. old_text = info_ptr->text;
  197719. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197720. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197721. if (info_ptr->text == NULL)
  197722. {
  197723. png_free(png_ptr, old_text);
  197724. return(1);
  197725. }
  197726. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197727. png_sizeof(png_text)));
  197728. png_free(png_ptr, old_text);
  197729. }
  197730. else
  197731. {
  197732. info_ptr->max_text = num_text + 8;
  197733. info_ptr->num_text = 0;
  197734. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197735. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197736. if (info_ptr->text == NULL)
  197737. return(1);
  197738. #ifdef PNG_FREE_ME_SUPPORTED
  197739. info_ptr->free_me |= PNG_FREE_TEXT;
  197740. #endif
  197741. }
  197742. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197743. info_ptr->max_text);
  197744. }
  197745. for (i = 0; i < num_text; i++)
  197746. {
  197747. png_size_t text_length,key_len;
  197748. png_size_t lang_len,lang_key_len;
  197749. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197750. if (text_ptr[i].key == NULL)
  197751. continue;
  197752. key_len = png_strlen(text_ptr[i].key);
  197753. if(text_ptr[i].compression <= 0)
  197754. {
  197755. lang_len = 0;
  197756. lang_key_len = 0;
  197757. }
  197758. else
  197759. #ifdef PNG_iTXt_SUPPORTED
  197760. {
  197761. /* set iTXt data */
  197762. if (text_ptr[i].lang != NULL)
  197763. lang_len = png_strlen(text_ptr[i].lang);
  197764. else
  197765. lang_len = 0;
  197766. if (text_ptr[i].lang_key != NULL)
  197767. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197768. else
  197769. lang_key_len = 0;
  197770. }
  197771. #else
  197772. {
  197773. png_warning(png_ptr, "iTXt chunk not supported.");
  197774. continue;
  197775. }
  197776. #endif
  197777. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197778. {
  197779. text_length = 0;
  197780. #ifdef PNG_iTXt_SUPPORTED
  197781. if(text_ptr[i].compression > 0)
  197782. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197783. else
  197784. #endif
  197785. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197786. }
  197787. else
  197788. {
  197789. text_length = png_strlen(text_ptr[i].text);
  197790. textp->compression = text_ptr[i].compression;
  197791. }
  197792. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197793. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197794. if (textp->key == NULL)
  197795. return(1);
  197796. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197797. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197798. (int)textp->key);
  197799. png_memcpy(textp->key, text_ptr[i].key,
  197800. (png_size_t)(key_len));
  197801. *(textp->key+key_len) = '\0';
  197802. #ifdef PNG_iTXt_SUPPORTED
  197803. if (text_ptr[i].compression > 0)
  197804. {
  197805. textp->lang=textp->key + key_len + 1;
  197806. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197807. *(textp->lang+lang_len) = '\0';
  197808. textp->lang_key=textp->lang + lang_len + 1;
  197809. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197810. *(textp->lang_key+lang_key_len) = '\0';
  197811. textp->text=textp->lang_key + lang_key_len + 1;
  197812. }
  197813. else
  197814. #endif
  197815. {
  197816. #ifdef PNG_iTXt_SUPPORTED
  197817. textp->lang=NULL;
  197818. textp->lang_key=NULL;
  197819. #endif
  197820. textp->text=textp->key + key_len + 1;
  197821. }
  197822. if(text_length)
  197823. png_memcpy(textp->text, text_ptr[i].text,
  197824. (png_size_t)(text_length));
  197825. *(textp->text+text_length) = '\0';
  197826. #ifdef PNG_iTXt_SUPPORTED
  197827. if(textp->compression > 0)
  197828. {
  197829. textp->text_length = 0;
  197830. textp->itxt_length = text_length;
  197831. }
  197832. else
  197833. #endif
  197834. {
  197835. textp->text_length = text_length;
  197836. #ifdef PNG_iTXt_SUPPORTED
  197837. textp->itxt_length = 0;
  197838. #endif
  197839. }
  197840. info_ptr->num_text++;
  197841. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197842. }
  197843. return(0);
  197844. }
  197845. #endif
  197846. #if defined(PNG_tIME_SUPPORTED)
  197847. void PNGAPI
  197848. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197849. {
  197850. png_debug1(1, "in %s storage function\n", "tIME");
  197851. if (png_ptr == NULL || info_ptr == NULL ||
  197852. (png_ptr->mode & PNG_WROTE_tIME))
  197853. return;
  197854. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197855. info_ptr->valid |= PNG_INFO_tIME;
  197856. }
  197857. #endif
  197858. #if defined(PNG_tRNS_SUPPORTED)
  197859. void PNGAPI
  197860. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197861. png_bytep trans, int num_trans, png_color_16p trans_values)
  197862. {
  197863. png_debug1(1, "in %s storage function\n", "tRNS");
  197864. if (png_ptr == NULL || info_ptr == NULL)
  197865. return;
  197866. if (trans != NULL)
  197867. {
  197868. /*
  197869. * It may not actually be necessary to set png_ptr->trans here;
  197870. * we do it for backward compatibility with the way the png_handle_tRNS
  197871. * function used to do the allocation.
  197872. */
  197873. #ifdef PNG_FREE_ME_SUPPORTED
  197874. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197875. #endif
  197876. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197877. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197878. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197879. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197880. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197881. #ifdef PNG_FREE_ME_SUPPORTED
  197882. info_ptr->free_me |= PNG_FREE_TRNS;
  197883. #else
  197884. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197885. #endif
  197886. }
  197887. if (trans_values != NULL)
  197888. {
  197889. png_memcpy(&(info_ptr->trans_values), trans_values,
  197890. png_sizeof(png_color_16));
  197891. if (num_trans == 0)
  197892. num_trans = 1;
  197893. }
  197894. info_ptr->num_trans = (png_uint_16)num_trans;
  197895. info_ptr->valid |= PNG_INFO_tRNS;
  197896. }
  197897. #endif
  197898. #if defined(PNG_sPLT_SUPPORTED)
  197899. void PNGAPI
  197900. png_set_sPLT(png_structp png_ptr,
  197901. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197902. {
  197903. png_sPLT_tp np;
  197904. int i;
  197905. if (png_ptr == NULL || info_ptr == NULL)
  197906. return;
  197907. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197908. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197909. if (np == NULL)
  197910. {
  197911. png_warning(png_ptr, "No memory for sPLT palettes.");
  197912. return;
  197913. }
  197914. png_memcpy(np, info_ptr->splt_palettes,
  197915. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197916. png_free(png_ptr, info_ptr->splt_palettes);
  197917. info_ptr->splt_palettes=NULL;
  197918. for (i = 0; i < nentries; i++)
  197919. {
  197920. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197921. png_sPLT_tp from = entries + i;
  197922. to->name = (png_charp)png_malloc_warn(png_ptr,
  197923. png_strlen(from->name) + 1);
  197924. if (to->name == NULL)
  197925. {
  197926. png_warning(png_ptr,
  197927. "Out of memory while processing sPLT chunk");
  197928. }
  197929. /* TODO: use png_malloc_warn */
  197930. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197931. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197932. from->nentries * png_sizeof(png_sPLT_entry));
  197933. /* TODO: use png_malloc_warn */
  197934. png_memcpy(to->entries, from->entries,
  197935. from->nentries * png_sizeof(png_sPLT_entry));
  197936. if (to->entries == NULL)
  197937. {
  197938. png_warning(png_ptr,
  197939. "Out of memory while processing sPLT chunk");
  197940. png_free(png_ptr,to->name);
  197941. to->name = NULL;
  197942. }
  197943. to->nentries = from->nentries;
  197944. to->depth = from->depth;
  197945. }
  197946. info_ptr->splt_palettes = np;
  197947. info_ptr->splt_palettes_num += nentries;
  197948. info_ptr->valid |= PNG_INFO_sPLT;
  197949. #ifdef PNG_FREE_ME_SUPPORTED
  197950. info_ptr->free_me |= PNG_FREE_SPLT;
  197951. #endif
  197952. }
  197953. #endif /* PNG_sPLT_SUPPORTED */
  197954. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197955. void PNGAPI
  197956. png_set_unknown_chunks(png_structp png_ptr,
  197957. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197958. {
  197959. png_unknown_chunkp np;
  197960. int i;
  197961. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197962. return;
  197963. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197964. (info_ptr->unknown_chunks_num + num_unknowns) *
  197965. png_sizeof(png_unknown_chunk));
  197966. if (np == NULL)
  197967. {
  197968. png_warning(png_ptr,
  197969. "Out of memory while processing unknown chunk.");
  197970. return;
  197971. }
  197972. png_memcpy(np, info_ptr->unknown_chunks,
  197973. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197974. png_free(png_ptr, info_ptr->unknown_chunks);
  197975. info_ptr->unknown_chunks=NULL;
  197976. for (i = 0; i < num_unknowns; i++)
  197977. {
  197978. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197979. png_unknown_chunkp from = unknowns + i;
  197980. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197981. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197982. if (to->data == NULL)
  197983. {
  197984. png_warning(png_ptr,
  197985. "Out of memory while processing unknown chunk.");
  197986. }
  197987. else
  197988. {
  197989. png_memcpy(to->data, from->data, from->size);
  197990. to->size = from->size;
  197991. /* note our location in the read or write sequence */
  197992. to->location = (png_byte)(png_ptr->mode & 0xff);
  197993. }
  197994. }
  197995. info_ptr->unknown_chunks = np;
  197996. info_ptr->unknown_chunks_num += num_unknowns;
  197997. #ifdef PNG_FREE_ME_SUPPORTED
  197998. info_ptr->free_me |= PNG_FREE_UNKN;
  197999. #endif
  198000. }
  198001. void PNGAPI
  198002. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  198003. int chunk, int location)
  198004. {
  198005. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  198006. (int)info_ptr->unknown_chunks_num)
  198007. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  198008. }
  198009. #endif
  198010. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198011. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  198012. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  198013. void PNGAPI
  198014. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  198015. {
  198016. /* This function is deprecated in favor of png_permit_mng_features()
  198017. and will be removed from libpng-1.3.0 */
  198018. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  198019. if (png_ptr == NULL)
  198020. return;
  198021. png_ptr->mng_features_permitted = (png_byte)
  198022. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  198023. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  198024. }
  198025. #endif
  198026. #endif
  198027. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198028. png_uint_32 PNGAPI
  198029. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  198030. {
  198031. png_debug(1, "in png_permit_mng_features\n");
  198032. if (png_ptr == NULL)
  198033. return (png_uint_32)0;
  198034. png_ptr->mng_features_permitted =
  198035. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  198036. return (png_uint_32)png_ptr->mng_features_permitted;
  198037. }
  198038. #endif
  198039. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  198040. void PNGAPI
  198041. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  198042. chunk_list, int num_chunks)
  198043. {
  198044. png_bytep new_list, p;
  198045. int i, old_num_chunks;
  198046. if (png_ptr == NULL)
  198047. return;
  198048. if (num_chunks == 0)
  198049. {
  198050. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  198051. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  198052. else
  198053. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  198054. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  198055. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  198056. else
  198057. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  198058. return;
  198059. }
  198060. if (chunk_list == NULL)
  198061. return;
  198062. old_num_chunks=png_ptr->num_chunk_list;
  198063. new_list=(png_bytep)png_malloc(png_ptr,
  198064. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  198065. if(png_ptr->chunk_list != NULL)
  198066. {
  198067. png_memcpy(new_list, png_ptr->chunk_list,
  198068. (png_size_t)(5*old_num_chunks));
  198069. png_free(png_ptr, png_ptr->chunk_list);
  198070. png_ptr->chunk_list=NULL;
  198071. }
  198072. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  198073. (png_size_t)(5*num_chunks));
  198074. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  198075. *p=(png_byte)keep;
  198076. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  198077. png_ptr->chunk_list=new_list;
  198078. #ifdef PNG_FREE_ME_SUPPORTED
  198079. png_ptr->free_me |= PNG_FREE_LIST;
  198080. #endif
  198081. }
  198082. #endif
  198083. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  198084. void PNGAPI
  198085. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  198086. png_user_chunk_ptr read_user_chunk_fn)
  198087. {
  198088. png_debug(1, "in png_set_read_user_chunk_fn\n");
  198089. if (png_ptr == NULL)
  198090. return;
  198091. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  198092. png_ptr->user_chunk_ptr = user_chunk_ptr;
  198093. }
  198094. #endif
  198095. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198096. void PNGAPI
  198097. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  198098. {
  198099. png_debug1(1, "in %s storage function\n", "rows");
  198100. if (png_ptr == NULL || info_ptr == NULL)
  198101. return;
  198102. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  198103. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  198104. info_ptr->row_pointers = row_pointers;
  198105. if(row_pointers)
  198106. info_ptr->valid |= PNG_INFO_IDAT;
  198107. }
  198108. #endif
  198109. #ifdef PNG_WRITE_SUPPORTED
  198110. void PNGAPI
  198111. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  198112. {
  198113. if (png_ptr == NULL)
  198114. return;
  198115. if(png_ptr->zbuf)
  198116. png_free(png_ptr, png_ptr->zbuf);
  198117. png_ptr->zbuf_size = (png_size_t)size;
  198118. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198119. png_ptr->zstream.next_out = png_ptr->zbuf;
  198120. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198121. }
  198122. #endif
  198123. void PNGAPI
  198124. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198125. {
  198126. if (png_ptr && info_ptr)
  198127. info_ptr->valid &= ~(mask);
  198128. }
  198129. #ifndef PNG_1_0_X
  198130. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198131. /* function was added to libpng 1.2.0 and should always exist by default */
  198132. void PNGAPI
  198133. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  198134. {
  198135. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198136. if (png_ptr != NULL)
  198137. png_ptr->asm_flags = 0;
  198138. }
  198139. /* this function was added to libpng 1.2.0 */
  198140. void PNGAPI
  198141. png_set_mmx_thresholds (png_structp png_ptr,
  198142. png_byte,
  198143. png_uint_32)
  198144. {
  198145. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198146. if (png_ptr == NULL)
  198147. return;
  198148. }
  198149. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198150. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198151. /* this function was added to libpng 1.2.6 */
  198152. void PNGAPI
  198153. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198154. png_uint_32 user_height_max)
  198155. {
  198156. /* Images with dimensions larger than these limits will be
  198157. * rejected by png_set_IHDR(). To accept any PNG datastream
  198158. * regardless of dimensions, set both limits to 0x7ffffffL.
  198159. */
  198160. if(png_ptr == NULL) return;
  198161. png_ptr->user_width_max = user_width_max;
  198162. png_ptr->user_height_max = user_height_max;
  198163. }
  198164. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198165. #endif /* ?PNG_1_0_X */
  198166. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198167. /*** End of inlined file: pngset.c ***/
  198168. /*** Start of inlined file: pngtrans.c ***/
  198169. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198170. *
  198171. * Last changed in libpng 1.2.17 May 15, 2007
  198172. * For conditions of distribution and use, see copyright notice in png.h
  198173. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198174. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198175. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198176. */
  198177. #define PNG_INTERNAL
  198178. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198179. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198180. /* turn on BGR-to-RGB mapping */
  198181. void PNGAPI
  198182. png_set_bgr(png_structp png_ptr)
  198183. {
  198184. png_debug(1, "in png_set_bgr\n");
  198185. if(png_ptr == NULL) return;
  198186. png_ptr->transformations |= PNG_BGR;
  198187. }
  198188. #endif
  198189. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198190. /* turn on 16 bit byte swapping */
  198191. void PNGAPI
  198192. png_set_swap(png_structp png_ptr)
  198193. {
  198194. png_debug(1, "in png_set_swap\n");
  198195. if(png_ptr == NULL) return;
  198196. if (png_ptr->bit_depth == 16)
  198197. png_ptr->transformations |= PNG_SWAP_BYTES;
  198198. }
  198199. #endif
  198200. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198201. /* turn on pixel packing */
  198202. void PNGAPI
  198203. png_set_packing(png_structp png_ptr)
  198204. {
  198205. png_debug(1, "in png_set_packing\n");
  198206. if(png_ptr == NULL) return;
  198207. if (png_ptr->bit_depth < 8)
  198208. {
  198209. png_ptr->transformations |= PNG_PACK;
  198210. png_ptr->usr_bit_depth = 8;
  198211. }
  198212. }
  198213. #endif
  198214. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198215. /* turn on packed pixel swapping */
  198216. void PNGAPI
  198217. png_set_packswap(png_structp png_ptr)
  198218. {
  198219. png_debug(1, "in png_set_packswap\n");
  198220. if(png_ptr == NULL) return;
  198221. if (png_ptr->bit_depth < 8)
  198222. png_ptr->transformations |= PNG_PACKSWAP;
  198223. }
  198224. #endif
  198225. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198226. void PNGAPI
  198227. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198228. {
  198229. png_debug(1, "in png_set_shift\n");
  198230. if(png_ptr == NULL) return;
  198231. png_ptr->transformations |= PNG_SHIFT;
  198232. png_ptr->shift = *true_bits;
  198233. }
  198234. #endif
  198235. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198236. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198237. int PNGAPI
  198238. png_set_interlace_handling(png_structp png_ptr)
  198239. {
  198240. png_debug(1, "in png_set_interlace handling\n");
  198241. if (png_ptr && png_ptr->interlaced)
  198242. {
  198243. png_ptr->transformations |= PNG_INTERLACE;
  198244. return (7);
  198245. }
  198246. return (1);
  198247. }
  198248. #endif
  198249. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198250. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198251. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198252. * for 48-bit input data, as well as to avoid problems with some compilers
  198253. * that don't like bytes as parameters.
  198254. */
  198255. void PNGAPI
  198256. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198257. {
  198258. png_debug(1, "in png_set_filler\n");
  198259. if(png_ptr == NULL) return;
  198260. png_ptr->transformations |= PNG_FILLER;
  198261. png_ptr->filler = (png_byte)filler;
  198262. if (filler_loc == PNG_FILLER_AFTER)
  198263. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198264. else
  198265. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198266. /* This should probably go in the "do_read_filler" routine.
  198267. * I attempted to do that in libpng-1.0.1a but that caused problems
  198268. * so I restored it in libpng-1.0.2a
  198269. */
  198270. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198271. {
  198272. png_ptr->usr_channels = 4;
  198273. }
  198274. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198275. * a less-than-8-bit grayscale to GA? */
  198276. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198277. {
  198278. png_ptr->usr_channels = 2;
  198279. }
  198280. }
  198281. #if !defined(PNG_1_0_X)
  198282. /* Added to libpng-1.2.7 */
  198283. void PNGAPI
  198284. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198285. {
  198286. png_debug(1, "in png_set_add_alpha\n");
  198287. if(png_ptr == NULL) return;
  198288. png_set_filler(png_ptr, filler, filler_loc);
  198289. png_ptr->transformations |= PNG_ADD_ALPHA;
  198290. }
  198291. #endif
  198292. #endif
  198293. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198294. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198295. void PNGAPI
  198296. png_set_swap_alpha(png_structp png_ptr)
  198297. {
  198298. png_debug(1, "in png_set_swap_alpha\n");
  198299. if(png_ptr == NULL) return;
  198300. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198301. }
  198302. #endif
  198303. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198304. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198305. void PNGAPI
  198306. png_set_invert_alpha(png_structp png_ptr)
  198307. {
  198308. png_debug(1, "in png_set_invert_alpha\n");
  198309. if(png_ptr == NULL) return;
  198310. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198311. }
  198312. #endif
  198313. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198314. void PNGAPI
  198315. png_set_invert_mono(png_structp png_ptr)
  198316. {
  198317. png_debug(1, "in png_set_invert_mono\n");
  198318. if(png_ptr == NULL) return;
  198319. png_ptr->transformations |= PNG_INVERT_MONO;
  198320. }
  198321. /* invert monochrome grayscale data */
  198322. void /* PRIVATE */
  198323. png_do_invert(png_row_infop row_info, png_bytep row)
  198324. {
  198325. png_debug(1, "in png_do_invert\n");
  198326. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198327. * if (row_info->bit_depth == 1 &&
  198328. */
  198329. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198330. if (row == NULL || row_info == NULL)
  198331. return;
  198332. #endif
  198333. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198334. {
  198335. png_bytep rp = row;
  198336. png_uint_32 i;
  198337. png_uint_32 istop = row_info->rowbytes;
  198338. for (i = 0; i < istop; i++)
  198339. {
  198340. *rp = (png_byte)(~(*rp));
  198341. rp++;
  198342. }
  198343. }
  198344. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198345. row_info->bit_depth == 8)
  198346. {
  198347. png_bytep rp = row;
  198348. png_uint_32 i;
  198349. png_uint_32 istop = row_info->rowbytes;
  198350. for (i = 0; i < istop; i+=2)
  198351. {
  198352. *rp = (png_byte)(~(*rp));
  198353. rp+=2;
  198354. }
  198355. }
  198356. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198357. row_info->bit_depth == 16)
  198358. {
  198359. png_bytep rp = row;
  198360. png_uint_32 i;
  198361. png_uint_32 istop = row_info->rowbytes;
  198362. for (i = 0; i < istop; i+=4)
  198363. {
  198364. *rp = (png_byte)(~(*rp));
  198365. *(rp+1) = (png_byte)(~(*(rp+1)));
  198366. rp+=4;
  198367. }
  198368. }
  198369. }
  198370. #endif
  198371. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198372. /* swaps byte order on 16 bit depth images */
  198373. void /* PRIVATE */
  198374. png_do_swap(png_row_infop row_info, png_bytep row)
  198375. {
  198376. png_debug(1, "in png_do_swap\n");
  198377. if (
  198378. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198379. row != NULL && row_info != NULL &&
  198380. #endif
  198381. row_info->bit_depth == 16)
  198382. {
  198383. png_bytep rp = row;
  198384. png_uint_32 i;
  198385. png_uint_32 istop= row_info->width * row_info->channels;
  198386. for (i = 0; i < istop; i++, rp += 2)
  198387. {
  198388. png_byte t = *rp;
  198389. *rp = *(rp + 1);
  198390. *(rp + 1) = t;
  198391. }
  198392. }
  198393. }
  198394. #endif
  198395. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198396. static PNG_CONST png_byte onebppswaptable[256] = {
  198397. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198398. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198399. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198400. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198401. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198402. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198403. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198404. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198405. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198406. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198407. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198408. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198409. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198410. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198411. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198412. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198413. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198414. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198415. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198416. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198417. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198418. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198419. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198420. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198421. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198422. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198423. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198424. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198425. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198426. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198427. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198428. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198429. };
  198430. static PNG_CONST png_byte twobppswaptable[256] = {
  198431. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198432. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198433. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198434. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198435. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198436. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198437. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198438. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198439. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198440. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198441. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198442. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198443. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198444. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198445. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198446. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198447. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198448. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198449. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198450. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198451. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198452. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198453. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198454. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198455. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198456. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198457. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198458. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198459. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198460. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198461. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198462. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198463. };
  198464. static PNG_CONST png_byte fourbppswaptable[256] = {
  198465. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198466. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198467. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198468. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198469. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198470. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198471. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198472. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198473. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198474. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198475. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198476. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198477. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198478. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198479. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198480. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198481. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198482. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198483. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198484. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198485. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198486. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198487. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198488. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198489. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198490. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198491. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198492. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198493. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198494. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198495. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198496. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198497. };
  198498. /* swaps pixel packing order within bytes */
  198499. void /* PRIVATE */
  198500. png_do_packswap(png_row_infop row_info, png_bytep row)
  198501. {
  198502. png_debug(1, "in png_do_packswap\n");
  198503. if (
  198504. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198505. row != NULL && row_info != NULL &&
  198506. #endif
  198507. row_info->bit_depth < 8)
  198508. {
  198509. png_bytep rp, end, table;
  198510. end = row + row_info->rowbytes;
  198511. if (row_info->bit_depth == 1)
  198512. table = (png_bytep)onebppswaptable;
  198513. else if (row_info->bit_depth == 2)
  198514. table = (png_bytep)twobppswaptable;
  198515. else if (row_info->bit_depth == 4)
  198516. table = (png_bytep)fourbppswaptable;
  198517. else
  198518. return;
  198519. for (rp = row; rp < end; rp++)
  198520. *rp = table[*rp];
  198521. }
  198522. }
  198523. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198524. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198525. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198526. /* remove filler or alpha byte(s) */
  198527. void /* PRIVATE */
  198528. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198529. {
  198530. png_debug(1, "in png_do_strip_filler\n");
  198531. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198532. if (row != NULL && row_info != NULL)
  198533. #endif
  198534. {
  198535. png_bytep sp=row;
  198536. png_bytep dp=row;
  198537. png_uint_32 row_width=row_info->width;
  198538. png_uint_32 i;
  198539. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198540. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198541. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198542. row_info->channels == 4)
  198543. {
  198544. if (row_info->bit_depth == 8)
  198545. {
  198546. /* This converts from RGBX or RGBA to RGB */
  198547. if (flags & PNG_FLAG_FILLER_AFTER)
  198548. {
  198549. dp+=3; sp+=4;
  198550. for (i = 1; i < row_width; i++)
  198551. {
  198552. *dp++ = *sp++;
  198553. *dp++ = *sp++;
  198554. *dp++ = *sp++;
  198555. sp++;
  198556. }
  198557. }
  198558. /* This converts from XRGB or ARGB to RGB */
  198559. else
  198560. {
  198561. for (i = 0; i < row_width; i++)
  198562. {
  198563. sp++;
  198564. *dp++ = *sp++;
  198565. *dp++ = *sp++;
  198566. *dp++ = *sp++;
  198567. }
  198568. }
  198569. row_info->pixel_depth = 24;
  198570. row_info->rowbytes = row_width * 3;
  198571. }
  198572. else /* if (row_info->bit_depth == 16) */
  198573. {
  198574. if (flags & PNG_FLAG_FILLER_AFTER)
  198575. {
  198576. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198577. sp += 8; dp += 6;
  198578. for (i = 1; i < row_width; i++)
  198579. {
  198580. /* This could be (although png_memcpy is probably slower):
  198581. png_memcpy(dp, sp, 6);
  198582. sp += 8;
  198583. dp += 6;
  198584. */
  198585. *dp++ = *sp++;
  198586. *dp++ = *sp++;
  198587. *dp++ = *sp++;
  198588. *dp++ = *sp++;
  198589. *dp++ = *sp++;
  198590. *dp++ = *sp++;
  198591. sp += 2;
  198592. }
  198593. }
  198594. else
  198595. {
  198596. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198597. for (i = 0; i < row_width; i++)
  198598. {
  198599. /* This could be (although png_memcpy is probably slower):
  198600. png_memcpy(dp, sp, 6);
  198601. sp += 8;
  198602. dp += 6;
  198603. */
  198604. sp+=2;
  198605. *dp++ = *sp++;
  198606. *dp++ = *sp++;
  198607. *dp++ = *sp++;
  198608. *dp++ = *sp++;
  198609. *dp++ = *sp++;
  198610. *dp++ = *sp++;
  198611. }
  198612. }
  198613. row_info->pixel_depth = 48;
  198614. row_info->rowbytes = row_width * 6;
  198615. }
  198616. row_info->channels = 3;
  198617. }
  198618. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198619. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198620. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198621. row_info->channels == 2)
  198622. {
  198623. if (row_info->bit_depth == 8)
  198624. {
  198625. /* This converts from GX or GA to G */
  198626. if (flags & PNG_FLAG_FILLER_AFTER)
  198627. {
  198628. for (i = 0; i < row_width; i++)
  198629. {
  198630. *dp++ = *sp++;
  198631. sp++;
  198632. }
  198633. }
  198634. /* This converts from XG or AG to G */
  198635. else
  198636. {
  198637. for (i = 0; i < row_width; i++)
  198638. {
  198639. sp++;
  198640. *dp++ = *sp++;
  198641. }
  198642. }
  198643. row_info->pixel_depth = 8;
  198644. row_info->rowbytes = row_width;
  198645. }
  198646. else /* if (row_info->bit_depth == 16) */
  198647. {
  198648. if (flags & PNG_FLAG_FILLER_AFTER)
  198649. {
  198650. /* This converts from GGXX or GGAA to GG */
  198651. sp += 4; dp += 2;
  198652. for (i = 1; i < row_width; i++)
  198653. {
  198654. *dp++ = *sp++;
  198655. *dp++ = *sp++;
  198656. sp += 2;
  198657. }
  198658. }
  198659. else
  198660. {
  198661. /* This converts from XXGG or AAGG to GG */
  198662. for (i = 0; i < row_width; i++)
  198663. {
  198664. sp += 2;
  198665. *dp++ = *sp++;
  198666. *dp++ = *sp++;
  198667. }
  198668. }
  198669. row_info->pixel_depth = 16;
  198670. row_info->rowbytes = row_width * 2;
  198671. }
  198672. row_info->channels = 1;
  198673. }
  198674. if (flags & PNG_FLAG_STRIP_ALPHA)
  198675. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198676. }
  198677. }
  198678. #endif
  198679. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198680. /* swaps red and blue bytes within a pixel */
  198681. void /* PRIVATE */
  198682. png_do_bgr(png_row_infop row_info, png_bytep row)
  198683. {
  198684. png_debug(1, "in png_do_bgr\n");
  198685. if (
  198686. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198687. row != NULL && row_info != NULL &&
  198688. #endif
  198689. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198690. {
  198691. png_uint_32 row_width = row_info->width;
  198692. if (row_info->bit_depth == 8)
  198693. {
  198694. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198695. {
  198696. png_bytep rp;
  198697. png_uint_32 i;
  198698. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198699. {
  198700. png_byte save = *rp;
  198701. *rp = *(rp + 2);
  198702. *(rp + 2) = save;
  198703. }
  198704. }
  198705. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198706. {
  198707. png_bytep rp;
  198708. png_uint_32 i;
  198709. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198710. {
  198711. png_byte save = *rp;
  198712. *rp = *(rp + 2);
  198713. *(rp + 2) = save;
  198714. }
  198715. }
  198716. }
  198717. else if (row_info->bit_depth == 16)
  198718. {
  198719. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198720. {
  198721. png_bytep rp;
  198722. png_uint_32 i;
  198723. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198724. {
  198725. png_byte save = *rp;
  198726. *rp = *(rp + 4);
  198727. *(rp + 4) = save;
  198728. save = *(rp + 1);
  198729. *(rp + 1) = *(rp + 5);
  198730. *(rp + 5) = save;
  198731. }
  198732. }
  198733. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198734. {
  198735. png_bytep rp;
  198736. png_uint_32 i;
  198737. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198738. {
  198739. png_byte save = *rp;
  198740. *rp = *(rp + 4);
  198741. *(rp + 4) = save;
  198742. save = *(rp + 1);
  198743. *(rp + 1) = *(rp + 5);
  198744. *(rp + 5) = save;
  198745. }
  198746. }
  198747. }
  198748. }
  198749. }
  198750. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198751. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198752. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198753. defined(PNG_LEGACY_SUPPORTED)
  198754. void PNGAPI
  198755. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198756. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198757. {
  198758. png_debug(1, "in png_set_user_transform_info\n");
  198759. if(png_ptr == NULL) return;
  198760. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198761. png_ptr->user_transform_ptr = user_transform_ptr;
  198762. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198763. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198764. #else
  198765. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198766. png_warning(png_ptr,
  198767. "This version of libpng does not support user transform info");
  198768. #endif
  198769. }
  198770. #endif
  198771. /* This function returns a pointer to the user_transform_ptr associated with
  198772. * the user transform functions. The application should free any memory
  198773. * associated with this pointer before png_write_destroy and png_read_destroy
  198774. * are called.
  198775. */
  198776. png_voidp PNGAPI
  198777. png_get_user_transform_ptr(png_structp png_ptr)
  198778. {
  198779. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198780. if (png_ptr == NULL) return (NULL);
  198781. return ((png_voidp)png_ptr->user_transform_ptr);
  198782. #else
  198783. return (NULL);
  198784. #endif
  198785. }
  198786. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198787. /*** End of inlined file: pngtrans.c ***/
  198788. /*** Start of inlined file: pngwio.c ***/
  198789. /* pngwio.c - functions for data output
  198790. *
  198791. * Last changed in libpng 1.2.13 November 13, 2006
  198792. * For conditions of distribution and use, see copyright notice in png.h
  198793. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198794. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198795. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198796. *
  198797. * This file provides a location for all output. Users who need
  198798. * special handling are expected to write functions that have the same
  198799. * arguments as these and perform similar functions, but that possibly
  198800. * use different output methods. Note that you shouldn't change these
  198801. * functions, but rather write replacement functions and then change
  198802. * them at run time with png_set_write_fn(...).
  198803. */
  198804. #define PNG_INTERNAL
  198805. #ifdef PNG_WRITE_SUPPORTED
  198806. /* Write the data to whatever output you are using. The default routine
  198807. writes to a file pointer. Note that this routine sometimes gets called
  198808. with very small lengths, so you should implement some kind of simple
  198809. buffering if you are using unbuffered writes. This should never be asked
  198810. to write more than 64K on a 16 bit machine. */
  198811. void /* PRIVATE */
  198812. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198813. {
  198814. if (png_ptr->write_data_fn != NULL )
  198815. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198816. else
  198817. png_error(png_ptr, "Call to NULL write function");
  198818. }
  198819. #if !defined(PNG_NO_STDIO)
  198820. /* This is the function that does the actual writing of data. If you are
  198821. not writing to a standard C stream, you should create a replacement
  198822. write_data function and use it at run time with png_set_write_fn(), rather
  198823. than changing the library. */
  198824. #ifndef USE_FAR_KEYWORD
  198825. void PNGAPI
  198826. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198827. {
  198828. png_uint_32 check;
  198829. if(png_ptr == NULL) return;
  198830. #if defined(_WIN32_WCE)
  198831. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198832. check = 0;
  198833. #else
  198834. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198835. #endif
  198836. if (check != length)
  198837. png_error(png_ptr, "Write Error");
  198838. }
  198839. #else
  198840. /* this is the model-independent version. Since the standard I/O library
  198841. can't handle far buffers in the medium and small models, we have to copy
  198842. the data.
  198843. */
  198844. #define NEAR_BUF_SIZE 1024
  198845. #define MIN(a,b) (a <= b ? a : b)
  198846. void PNGAPI
  198847. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198848. {
  198849. png_uint_32 check;
  198850. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198851. png_FILE_p io_ptr;
  198852. if(png_ptr == NULL) return;
  198853. /* Check if data really is near. If so, use usual code. */
  198854. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198855. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198856. if ((png_bytep)near_data == data)
  198857. {
  198858. #if defined(_WIN32_WCE)
  198859. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198860. check = 0;
  198861. #else
  198862. check = fwrite(near_data, 1, length, io_ptr);
  198863. #endif
  198864. }
  198865. else
  198866. {
  198867. png_byte buf[NEAR_BUF_SIZE];
  198868. png_size_t written, remaining, err;
  198869. check = 0;
  198870. remaining = length;
  198871. do
  198872. {
  198873. written = MIN(NEAR_BUF_SIZE, remaining);
  198874. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198875. #if defined(_WIN32_WCE)
  198876. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198877. err = 0;
  198878. #else
  198879. err = fwrite(buf, 1, written, io_ptr);
  198880. #endif
  198881. if (err != written)
  198882. break;
  198883. else
  198884. check += err;
  198885. data += written;
  198886. remaining -= written;
  198887. }
  198888. while (remaining != 0);
  198889. }
  198890. if (check != length)
  198891. png_error(png_ptr, "Write Error");
  198892. }
  198893. #endif
  198894. #endif
  198895. /* This function is called to output any data pending writing (normally
  198896. to disk). After png_flush is called, there should be no data pending
  198897. writing in any buffers. */
  198898. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198899. void /* PRIVATE */
  198900. png_flush(png_structp png_ptr)
  198901. {
  198902. if (png_ptr->output_flush_fn != NULL)
  198903. (*(png_ptr->output_flush_fn))(png_ptr);
  198904. }
  198905. #if !defined(PNG_NO_STDIO)
  198906. void PNGAPI
  198907. png_default_flush(png_structp png_ptr)
  198908. {
  198909. #if !defined(_WIN32_WCE)
  198910. png_FILE_p io_ptr;
  198911. #endif
  198912. if(png_ptr == NULL) return;
  198913. #if !defined(_WIN32_WCE)
  198914. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198915. if (io_ptr != NULL)
  198916. fflush(io_ptr);
  198917. #endif
  198918. }
  198919. #endif
  198920. #endif
  198921. /* This function allows the application to supply new output functions for
  198922. libpng if standard C streams aren't being used.
  198923. This function takes as its arguments:
  198924. png_ptr - pointer to a png output data structure
  198925. io_ptr - pointer to user supplied structure containing info about
  198926. the output functions. May be NULL.
  198927. write_data_fn - pointer to a new output function that takes as its
  198928. arguments a pointer to a png_struct, a pointer to
  198929. data to be written, and a 32-bit unsigned int that is
  198930. the number of bytes to be written. The new write
  198931. function should call png_error(png_ptr, "Error msg")
  198932. to exit and output any fatal error messages.
  198933. flush_data_fn - pointer to a new flush function that takes as its
  198934. arguments a pointer to a png_struct. After a call to
  198935. the flush function, there should be no data in any buffers
  198936. or pending transmission. If the output method doesn't do
  198937. any buffering of ouput, a function prototype must still be
  198938. supplied although it doesn't have to do anything. If
  198939. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198940. time, output_flush_fn will be ignored, although it must be
  198941. supplied for compatibility. */
  198942. void PNGAPI
  198943. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198944. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198945. {
  198946. if(png_ptr == NULL) return;
  198947. png_ptr->io_ptr = io_ptr;
  198948. #if !defined(PNG_NO_STDIO)
  198949. if (write_data_fn != NULL)
  198950. png_ptr->write_data_fn = write_data_fn;
  198951. else
  198952. png_ptr->write_data_fn = png_default_write_data;
  198953. #else
  198954. png_ptr->write_data_fn = write_data_fn;
  198955. #endif
  198956. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198957. #if !defined(PNG_NO_STDIO)
  198958. if (output_flush_fn != NULL)
  198959. png_ptr->output_flush_fn = output_flush_fn;
  198960. else
  198961. png_ptr->output_flush_fn = png_default_flush;
  198962. #else
  198963. png_ptr->output_flush_fn = output_flush_fn;
  198964. #endif
  198965. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198966. /* It is an error to read while writing a png file */
  198967. if (png_ptr->read_data_fn != NULL)
  198968. {
  198969. png_ptr->read_data_fn = NULL;
  198970. png_warning(png_ptr,
  198971. "Attempted to set both read_data_fn and write_data_fn in");
  198972. png_warning(png_ptr,
  198973. "the same structure. Resetting read_data_fn to NULL.");
  198974. }
  198975. }
  198976. #if defined(USE_FAR_KEYWORD)
  198977. #if defined(_MSC_VER)
  198978. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198979. {
  198980. void *near_ptr;
  198981. void FAR *far_ptr;
  198982. FP_OFF(near_ptr) = FP_OFF(ptr);
  198983. far_ptr = (void FAR *)near_ptr;
  198984. if(check != 0)
  198985. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198986. png_error(png_ptr,"segment lost in conversion");
  198987. return(near_ptr);
  198988. }
  198989. # else
  198990. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198991. {
  198992. void *near_ptr;
  198993. void FAR *far_ptr;
  198994. near_ptr = (void FAR *)ptr;
  198995. far_ptr = (void FAR *)near_ptr;
  198996. if(check != 0)
  198997. if(far_ptr != ptr)
  198998. png_error(png_ptr,"segment lost in conversion");
  198999. return(near_ptr);
  199000. }
  199001. # endif
  199002. # endif
  199003. #endif /* PNG_WRITE_SUPPORTED */
  199004. /*** End of inlined file: pngwio.c ***/
  199005. /*** Start of inlined file: pngwrite.c ***/
  199006. /* pngwrite.c - general routines to write a PNG file
  199007. *
  199008. * Last changed in libpng 1.2.15 January 5, 2007
  199009. * For conditions of distribution and use, see copyright notice in png.h
  199010. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  199011. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199012. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199013. */
  199014. /* get internal access to png.h */
  199015. #define PNG_INTERNAL
  199016. #ifdef PNG_WRITE_SUPPORTED
  199017. /* Writes all the PNG information. This is the suggested way to use the
  199018. * library. If you have a new chunk to add, make a function to write it,
  199019. * and put it in the correct location here. If you want the chunk written
  199020. * after the image data, put it in png_write_end(). I strongly encourage
  199021. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  199022. * the chunk, as that will keep the code from breaking if you want to just
  199023. * write a plain PNG file. If you have long comments, I suggest writing
  199024. * them in png_write_end(), and compressing them.
  199025. */
  199026. void PNGAPI
  199027. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  199028. {
  199029. png_debug(1, "in png_write_info_before_PLTE\n");
  199030. if (png_ptr == NULL || info_ptr == NULL)
  199031. return;
  199032. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199033. {
  199034. png_write_sig(png_ptr); /* write PNG signature */
  199035. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199036. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  199037. {
  199038. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  199039. png_ptr->mng_features_permitted=0;
  199040. }
  199041. #endif
  199042. /* write IHDR information. */
  199043. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  199044. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  199045. info_ptr->filter_type,
  199046. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199047. info_ptr->interlace_type);
  199048. #else
  199049. 0);
  199050. #endif
  199051. /* the rest of these check to see if the valid field has the appropriate
  199052. flag set, and if it does, writes the chunk. */
  199053. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  199054. if (info_ptr->valid & PNG_INFO_gAMA)
  199055. {
  199056. # ifdef PNG_FLOATING_POINT_SUPPORTED
  199057. png_write_gAMA(png_ptr, info_ptr->gamma);
  199058. #else
  199059. #ifdef PNG_FIXED_POINT_SUPPORTED
  199060. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  199061. # endif
  199062. #endif
  199063. }
  199064. #endif
  199065. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  199066. if (info_ptr->valid & PNG_INFO_sRGB)
  199067. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  199068. #endif
  199069. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  199070. if (info_ptr->valid & PNG_INFO_iCCP)
  199071. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  199072. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  199073. #endif
  199074. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  199075. if (info_ptr->valid & PNG_INFO_sBIT)
  199076. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  199077. #endif
  199078. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  199079. if (info_ptr->valid & PNG_INFO_cHRM)
  199080. {
  199081. #ifdef PNG_FLOATING_POINT_SUPPORTED
  199082. png_write_cHRM(png_ptr,
  199083. info_ptr->x_white, info_ptr->y_white,
  199084. info_ptr->x_red, info_ptr->y_red,
  199085. info_ptr->x_green, info_ptr->y_green,
  199086. info_ptr->x_blue, info_ptr->y_blue);
  199087. #else
  199088. # ifdef PNG_FIXED_POINT_SUPPORTED
  199089. png_write_cHRM_fixed(png_ptr,
  199090. info_ptr->int_x_white, info_ptr->int_y_white,
  199091. info_ptr->int_x_red, info_ptr->int_y_red,
  199092. info_ptr->int_x_green, info_ptr->int_y_green,
  199093. info_ptr->int_x_blue, info_ptr->int_y_blue);
  199094. # endif
  199095. #endif
  199096. }
  199097. #endif
  199098. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199099. if (info_ptr->unknown_chunks_num)
  199100. {
  199101. png_unknown_chunk *up;
  199102. png_debug(5, "writing extra chunks\n");
  199103. for (up = info_ptr->unknown_chunks;
  199104. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199105. up++)
  199106. {
  199107. int keep=png_handle_as_unknown(png_ptr, up->name);
  199108. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199109. up->location && !(up->location & PNG_HAVE_PLTE) &&
  199110. !(up->location & PNG_HAVE_IDAT) &&
  199111. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199112. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199113. {
  199114. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199115. }
  199116. }
  199117. }
  199118. #endif
  199119. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199120. }
  199121. }
  199122. void PNGAPI
  199123. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199124. {
  199125. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199126. int i;
  199127. #endif
  199128. png_debug(1, "in png_write_info\n");
  199129. if (png_ptr == NULL || info_ptr == NULL)
  199130. return;
  199131. png_write_info_before_PLTE(png_ptr, info_ptr);
  199132. if (info_ptr->valid & PNG_INFO_PLTE)
  199133. png_write_PLTE(png_ptr, info_ptr->palette,
  199134. (png_uint_32)info_ptr->num_palette);
  199135. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199136. png_error(png_ptr, "Valid palette required for paletted images");
  199137. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199138. if (info_ptr->valid & PNG_INFO_tRNS)
  199139. {
  199140. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199141. /* invert the alpha channel (in tRNS) */
  199142. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199143. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199144. {
  199145. int j;
  199146. for (j=0; j<(int)info_ptr->num_trans; j++)
  199147. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199148. }
  199149. #endif
  199150. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199151. info_ptr->num_trans, info_ptr->color_type);
  199152. }
  199153. #endif
  199154. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199155. if (info_ptr->valid & PNG_INFO_bKGD)
  199156. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199157. #endif
  199158. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199159. if (info_ptr->valid & PNG_INFO_hIST)
  199160. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199161. #endif
  199162. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199163. if (info_ptr->valid & PNG_INFO_oFFs)
  199164. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199165. info_ptr->offset_unit_type);
  199166. #endif
  199167. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199168. if (info_ptr->valid & PNG_INFO_pCAL)
  199169. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199170. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199171. info_ptr->pcal_units, info_ptr->pcal_params);
  199172. #endif
  199173. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199174. if (info_ptr->valid & PNG_INFO_sCAL)
  199175. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199176. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199177. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199178. #else
  199179. #ifdef PNG_FIXED_POINT_SUPPORTED
  199180. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199181. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199182. #else
  199183. png_warning(png_ptr,
  199184. "png_write_sCAL not supported; sCAL chunk not written.");
  199185. #endif
  199186. #endif
  199187. #endif
  199188. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199189. if (info_ptr->valid & PNG_INFO_pHYs)
  199190. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199191. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199192. #endif
  199193. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199194. if (info_ptr->valid & PNG_INFO_tIME)
  199195. {
  199196. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199197. png_ptr->mode |= PNG_WROTE_tIME;
  199198. }
  199199. #endif
  199200. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199201. if (info_ptr->valid & PNG_INFO_sPLT)
  199202. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199203. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199204. #endif
  199205. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199206. /* Check to see if we need to write text chunks */
  199207. for (i = 0; i < info_ptr->num_text; i++)
  199208. {
  199209. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199210. info_ptr->text[i].compression);
  199211. /* an internationalized chunk? */
  199212. if (info_ptr->text[i].compression > 0)
  199213. {
  199214. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199215. /* write international chunk */
  199216. png_write_iTXt(png_ptr,
  199217. info_ptr->text[i].compression,
  199218. info_ptr->text[i].key,
  199219. info_ptr->text[i].lang,
  199220. info_ptr->text[i].lang_key,
  199221. info_ptr->text[i].text);
  199222. #else
  199223. png_warning(png_ptr, "Unable to write international text");
  199224. #endif
  199225. /* Mark this chunk as written */
  199226. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199227. }
  199228. /* If we want a compressed text chunk */
  199229. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199230. {
  199231. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199232. /* write compressed chunk */
  199233. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199234. info_ptr->text[i].text, 0,
  199235. info_ptr->text[i].compression);
  199236. #else
  199237. png_warning(png_ptr, "Unable to write compressed text");
  199238. #endif
  199239. /* Mark this chunk as written */
  199240. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199241. }
  199242. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199243. {
  199244. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199245. /* write uncompressed chunk */
  199246. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199247. info_ptr->text[i].text,
  199248. 0);
  199249. #else
  199250. png_warning(png_ptr, "Unable to write uncompressed text");
  199251. #endif
  199252. /* Mark this chunk as written */
  199253. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199254. }
  199255. }
  199256. #endif
  199257. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199258. if (info_ptr->unknown_chunks_num)
  199259. {
  199260. png_unknown_chunk *up;
  199261. png_debug(5, "writing extra chunks\n");
  199262. for (up = info_ptr->unknown_chunks;
  199263. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199264. up++)
  199265. {
  199266. int keep=png_handle_as_unknown(png_ptr, up->name);
  199267. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199268. up->location && (up->location & PNG_HAVE_PLTE) &&
  199269. !(up->location & PNG_HAVE_IDAT) &&
  199270. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199271. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199272. {
  199273. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199274. }
  199275. }
  199276. }
  199277. #endif
  199278. }
  199279. /* Writes the end of the PNG file. If you don't want to write comments or
  199280. * time information, you can pass NULL for info. If you already wrote these
  199281. * in png_write_info(), do not write them again here. If you have long
  199282. * comments, I suggest writing them here, and compressing them.
  199283. */
  199284. void PNGAPI
  199285. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199286. {
  199287. png_debug(1, "in png_write_end\n");
  199288. if (png_ptr == NULL)
  199289. return;
  199290. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199291. png_error(png_ptr, "No IDATs written into file");
  199292. /* see if user wants us to write information chunks */
  199293. if (info_ptr != NULL)
  199294. {
  199295. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199296. int i; /* local index variable */
  199297. #endif
  199298. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199299. /* check to see if user has supplied a time chunk */
  199300. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199301. !(png_ptr->mode & PNG_WROTE_tIME))
  199302. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199303. #endif
  199304. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199305. /* loop through comment chunks */
  199306. for (i = 0; i < info_ptr->num_text; i++)
  199307. {
  199308. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199309. info_ptr->text[i].compression);
  199310. /* an internationalized chunk? */
  199311. if (info_ptr->text[i].compression > 0)
  199312. {
  199313. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199314. /* write international chunk */
  199315. png_write_iTXt(png_ptr,
  199316. info_ptr->text[i].compression,
  199317. info_ptr->text[i].key,
  199318. info_ptr->text[i].lang,
  199319. info_ptr->text[i].lang_key,
  199320. info_ptr->text[i].text);
  199321. #else
  199322. png_warning(png_ptr, "Unable to write international text");
  199323. #endif
  199324. /* Mark this chunk as written */
  199325. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199326. }
  199327. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199328. {
  199329. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199330. /* write compressed chunk */
  199331. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199332. info_ptr->text[i].text, 0,
  199333. info_ptr->text[i].compression);
  199334. #else
  199335. png_warning(png_ptr, "Unable to write compressed text");
  199336. #endif
  199337. /* Mark this chunk as written */
  199338. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199339. }
  199340. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199341. {
  199342. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199343. /* write uncompressed chunk */
  199344. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199345. info_ptr->text[i].text, 0);
  199346. #else
  199347. png_warning(png_ptr, "Unable to write uncompressed text");
  199348. #endif
  199349. /* Mark this chunk as written */
  199350. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199351. }
  199352. }
  199353. #endif
  199354. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199355. if (info_ptr->unknown_chunks_num)
  199356. {
  199357. png_unknown_chunk *up;
  199358. png_debug(5, "writing extra chunks\n");
  199359. for (up = info_ptr->unknown_chunks;
  199360. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199361. up++)
  199362. {
  199363. int keep=png_handle_as_unknown(png_ptr, up->name);
  199364. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199365. up->location && (up->location & PNG_AFTER_IDAT) &&
  199366. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199367. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199368. {
  199369. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199370. }
  199371. }
  199372. }
  199373. #endif
  199374. }
  199375. png_ptr->mode |= PNG_AFTER_IDAT;
  199376. /* write end of PNG file */
  199377. png_write_IEND(png_ptr);
  199378. }
  199379. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199380. #if !defined(_WIN32_WCE)
  199381. /* "time.h" functions are not supported on WindowsCE */
  199382. void PNGAPI
  199383. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199384. {
  199385. png_debug(1, "in png_convert_from_struct_tm\n");
  199386. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199387. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199388. ptime->day = (png_byte)ttime->tm_mday;
  199389. ptime->hour = (png_byte)ttime->tm_hour;
  199390. ptime->minute = (png_byte)ttime->tm_min;
  199391. ptime->second = (png_byte)ttime->tm_sec;
  199392. }
  199393. void PNGAPI
  199394. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199395. {
  199396. struct tm *tbuf;
  199397. png_debug(1, "in png_convert_from_time_t\n");
  199398. tbuf = gmtime(&ttime);
  199399. png_convert_from_struct_tm(ptime, tbuf);
  199400. }
  199401. #endif
  199402. #endif
  199403. /* Initialize png_ptr structure, and allocate any memory needed */
  199404. png_structp PNGAPI
  199405. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199406. png_error_ptr error_fn, png_error_ptr warn_fn)
  199407. {
  199408. #ifdef PNG_USER_MEM_SUPPORTED
  199409. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199410. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199411. }
  199412. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199413. png_structp PNGAPI
  199414. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199415. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199416. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199417. {
  199418. #endif /* PNG_USER_MEM_SUPPORTED */
  199419. png_structp png_ptr;
  199420. #ifdef PNG_SETJMP_SUPPORTED
  199421. #ifdef USE_FAR_KEYWORD
  199422. jmp_buf jmpbuf;
  199423. #endif
  199424. #endif
  199425. int i;
  199426. png_debug(1, "in png_create_write_struct\n");
  199427. #ifdef PNG_USER_MEM_SUPPORTED
  199428. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199429. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199430. #else
  199431. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199432. #endif /* PNG_USER_MEM_SUPPORTED */
  199433. if (png_ptr == NULL)
  199434. return (NULL);
  199435. /* added at libpng-1.2.6 */
  199436. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199437. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199438. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199439. #endif
  199440. #ifdef PNG_SETJMP_SUPPORTED
  199441. #ifdef USE_FAR_KEYWORD
  199442. if (setjmp(jmpbuf))
  199443. #else
  199444. if (setjmp(png_ptr->jmpbuf))
  199445. #endif
  199446. {
  199447. png_free(png_ptr, png_ptr->zbuf);
  199448. png_ptr->zbuf=NULL;
  199449. png_destroy_struct(png_ptr);
  199450. return (NULL);
  199451. }
  199452. #ifdef USE_FAR_KEYWORD
  199453. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199454. #endif
  199455. #endif
  199456. #ifdef PNG_USER_MEM_SUPPORTED
  199457. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199458. #endif /* PNG_USER_MEM_SUPPORTED */
  199459. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199460. i=0;
  199461. do
  199462. {
  199463. if(user_png_ver[i] != png_libpng_ver[i])
  199464. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199465. } while (png_libpng_ver[i++]);
  199466. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199467. {
  199468. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199469. * we must recompile any applications that use any older library version.
  199470. * For versions after libpng 1.0, we will be compatible, so we need
  199471. * only check the first digit.
  199472. */
  199473. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199474. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199475. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199476. {
  199477. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199478. char msg[80];
  199479. if (user_png_ver)
  199480. {
  199481. png_snprintf(msg, 80,
  199482. "Application was compiled with png.h from libpng-%.20s",
  199483. user_png_ver);
  199484. png_warning(png_ptr, msg);
  199485. }
  199486. png_snprintf(msg, 80,
  199487. "Application is running with png.c from libpng-%.20s",
  199488. png_libpng_ver);
  199489. png_warning(png_ptr, msg);
  199490. #endif
  199491. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199492. png_ptr->flags=0;
  199493. #endif
  199494. png_error(png_ptr,
  199495. "Incompatible libpng version in application and library");
  199496. }
  199497. }
  199498. /* initialize zbuf - compression buffer */
  199499. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199500. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199501. (png_uint_32)png_ptr->zbuf_size);
  199502. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199503. png_flush_ptr_NULL);
  199504. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199505. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199506. 1, png_doublep_NULL, png_doublep_NULL);
  199507. #endif
  199508. #ifdef PNG_SETJMP_SUPPORTED
  199509. /* Applications that neglect to set up their own setjmp() and then encounter
  199510. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199511. abort instead of returning. */
  199512. #ifdef USE_FAR_KEYWORD
  199513. if (setjmp(jmpbuf))
  199514. PNG_ABORT();
  199515. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199516. #else
  199517. if (setjmp(png_ptr->jmpbuf))
  199518. PNG_ABORT();
  199519. #endif
  199520. #endif
  199521. return (png_ptr);
  199522. }
  199523. /* Initialize png_ptr structure, and allocate any memory needed */
  199524. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199525. /* Deprecated. */
  199526. #undef png_write_init
  199527. void PNGAPI
  199528. png_write_init(png_structp png_ptr)
  199529. {
  199530. /* We only come here via pre-1.0.7-compiled applications */
  199531. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199532. }
  199533. void PNGAPI
  199534. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199535. png_size_t png_struct_size, png_size_t png_info_size)
  199536. {
  199537. /* We only come here via pre-1.0.12-compiled applications */
  199538. if(png_ptr == NULL) return;
  199539. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199540. if(png_sizeof(png_struct) > png_struct_size ||
  199541. png_sizeof(png_info) > png_info_size)
  199542. {
  199543. char msg[80];
  199544. png_ptr->warning_fn=NULL;
  199545. if (user_png_ver)
  199546. {
  199547. png_snprintf(msg, 80,
  199548. "Application was compiled with png.h from libpng-%.20s",
  199549. user_png_ver);
  199550. png_warning(png_ptr, msg);
  199551. }
  199552. png_snprintf(msg, 80,
  199553. "Application is running with png.c from libpng-%.20s",
  199554. png_libpng_ver);
  199555. png_warning(png_ptr, msg);
  199556. }
  199557. #endif
  199558. if(png_sizeof(png_struct) > png_struct_size)
  199559. {
  199560. png_ptr->error_fn=NULL;
  199561. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199562. png_ptr->flags=0;
  199563. #endif
  199564. png_error(png_ptr,
  199565. "The png struct allocated by the application for writing is too small.");
  199566. }
  199567. if(png_sizeof(png_info) > png_info_size)
  199568. {
  199569. png_ptr->error_fn=NULL;
  199570. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199571. png_ptr->flags=0;
  199572. #endif
  199573. png_error(png_ptr,
  199574. "The info struct allocated by the application for writing is too small.");
  199575. }
  199576. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199577. }
  199578. #endif /* PNG_1_0_X || PNG_1_2_X */
  199579. void PNGAPI
  199580. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199581. png_size_t png_struct_size)
  199582. {
  199583. png_structp png_ptr=*ptr_ptr;
  199584. #ifdef PNG_SETJMP_SUPPORTED
  199585. jmp_buf tmp_jmp; /* to save current jump buffer */
  199586. #endif
  199587. int i = 0;
  199588. if (png_ptr == NULL)
  199589. return;
  199590. do
  199591. {
  199592. if (user_png_ver[i] != png_libpng_ver[i])
  199593. {
  199594. #ifdef PNG_LEGACY_SUPPORTED
  199595. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199596. #else
  199597. png_ptr->warning_fn=NULL;
  199598. png_warning(png_ptr,
  199599. "Application uses deprecated png_write_init() and should be recompiled.");
  199600. break;
  199601. #endif
  199602. }
  199603. } while (png_libpng_ver[i++]);
  199604. png_debug(1, "in png_write_init_3\n");
  199605. #ifdef PNG_SETJMP_SUPPORTED
  199606. /* save jump buffer and error functions */
  199607. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199608. #endif
  199609. if (png_sizeof(png_struct) > png_struct_size)
  199610. {
  199611. png_destroy_struct(png_ptr);
  199612. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199613. *ptr_ptr = png_ptr;
  199614. }
  199615. /* reset all variables to 0 */
  199616. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199617. /* added at libpng-1.2.6 */
  199618. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199619. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199620. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199621. #endif
  199622. #ifdef PNG_SETJMP_SUPPORTED
  199623. /* restore jump buffer */
  199624. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199625. #endif
  199626. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199627. png_flush_ptr_NULL);
  199628. /* initialize zbuf - compression buffer */
  199629. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199630. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199631. (png_uint_32)png_ptr->zbuf_size);
  199632. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199633. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199634. 1, png_doublep_NULL, png_doublep_NULL);
  199635. #endif
  199636. }
  199637. /* Write a few rows of image data. If the image is interlaced,
  199638. * either you will have to write the 7 sub images, or, if you
  199639. * have called png_set_interlace_handling(), you will have to
  199640. * "write" the image seven times.
  199641. */
  199642. void PNGAPI
  199643. png_write_rows(png_structp png_ptr, png_bytepp row,
  199644. png_uint_32 num_rows)
  199645. {
  199646. png_uint_32 i; /* row counter */
  199647. png_bytepp rp; /* row pointer */
  199648. png_debug(1, "in png_write_rows\n");
  199649. if (png_ptr == NULL)
  199650. return;
  199651. /* loop through the rows */
  199652. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199653. {
  199654. png_write_row(png_ptr, *rp);
  199655. }
  199656. }
  199657. /* Write the image. You only need to call this function once, even
  199658. * if you are writing an interlaced image.
  199659. */
  199660. void PNGAPI
  199661. png_write_image(png_structp png_ptr, png_bytepp image)
  199662. {
  199663. png_uint_32 i; /* row index */
  199664. int pass, num_pass; /* pass variables */
  199665. png_bytepp rp; /* points to current row */
  199666. if (png_ptr == NULL)
  199667. return;
  199668. png_debug(1, "in png_write_image\n");
  199669. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199670. /* intialize interlace handling. If image is not interlaced,
  199671. this will set pass to 1 */
  199672. num_pass = png_set_interlace_handling(png_ptr);
  199673. #else
  199674. num_pass = 1;
  199675. #endif
  199676. /* loop through passes */
  199677. for (pass = 0; pass < num_pass; pass++)
  199678. {
  199679. /* loop through image */
  199680. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199681. {
  199682. png_write_row(png_ptr, *rp);
  199683. }
  199684. }
  199685. }
  199686. /* called by user to write a row of image data */
  199687. void PNGAPI
  199688. png_write_row(png_structp png_ptr, png_bytep row)
  199689. {
  199690. if (png_ptr == NULL)
  199691. return;
  199692. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199693. png_ptr->row_number, png_ptr->pass);
  199694. /* initialize transformations and other stuff if first time */
  199695. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199696. {
  199697. /* make sure we wrote the header info */
  199698. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199699. png_error(png_ptr,
  199700. "png_write_info was never called before png_write_row.");
  199701. /* check for transforms that have been set but were defined out */
  199702. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199703. if (png_ptr->transformations & PNG_INVERT_MONO)
  199704. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199705. #endif
  199706. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199707. if (png_ptr->transformations & PNG_FILLER)
  199708. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199709. #endif
  199710. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199711. if (png_ptr->transformations & PNG_PACKSWAP)
  199712. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199713. #endif
  199714. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199715. if (png_ptr->transformations & PNG_PACK)
  199716. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199717. #endif
  199718. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199719. if (png_ptr->transformations & PNG_SHIFT)
  199720. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199721. #endif
  199722. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199723. if (png_ptr->transformations & PNG_BGR)
  199724. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199725. #endif
  199726. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199727. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199728. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199729. #endif
  199730. png_write_start_row(png_ptr);
  199731. }
  199732. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199733. /* if interlaced and not interested in row, return */
  199734. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199735. {
  199736. switch (png_ptr->pass)
  199737. {
  199738. case 0:
  199739. if (png_ptr->row_number & 0x07)
  199740. {
  199741. png_write_finish_row(png_ptr);
  199742. return;
  199743. }
  199744. break;
  199745. case 1:
  199746. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199747. {
  199748. png_write_finish_row(png_ptr);
  199749. return;
  199750. }
  199751. break;
  199752. case 2:
  199753. if ((png_ptr->row_number & 0x07) != 4)
  199754. {
  199755. png_write_finish_row(png_ptr);
  199756. return;
  199757. }
  199758. break;
  199759. case 3:
  199760. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199761. {
  199762. png_write_finish_row(png_ptr);
  199763. return;
  199764. }
  199765. break;
  199766. case 4:
  199767. if ((png_ptr->row_number & 0x03) != 2)
  199768. {
  199769. png_write_finish_row(png_ptr);
  199770. return;
  199771. }
  199772. break;
  199773. case 5:
  199774. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199775. {
  199776. png_write_finish_row(png_ptr);
  199777. return;
  199778. }
  199779. break;
  199780. case 6:
  199781. if (!(png_ptr->row_number & 0x01))
  199782. {
  199783. png_write_finish_row(png_ptr);
  199784. return;
  199785. }
  199786. break;
  199787. }
  199788. }
  199789. #endif
  199790. /* set up row info for transformations */
  199791. png_ptr->row_info.color_type = png_ptr->color_type;
  199792. png_ptr->row_info.width = png_ptr->usr_width;
  199793. png_ptr->row_info.channels = png_ptr->usr_channels;
  199794. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199795. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199796. png_ptr->row_info.channels);
  199797. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199798. png_ptr->row_info.width);
  199799. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199800. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199801. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199802. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199803. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199804. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199805. /* Copy user's row into buffer, leaving room for filter byte. */
  199806. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199807. png_ptr->row_info.rowbytes);
  199808. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199809. /* handle interlacing */
  199810. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199811. (png_ptr->transformations & PNG_INTERLACE))
  199812. {
  199813. png_do_write_interlace(&(png_ptr->row_info),
  199814. png_ptr->row_buf + 1, png_ptr->pass);
  199815. /* this should always get caught above, but still ... */
  199816. if (!(png_ptr->row_info.width))
  199817. {
  199818. png_write_finish_row(png_ptr);
  199819. return;
  199820. }
  199821. }
  199822. #endif
  199823. /* handle other transformations */
  199824. if (png_ptr->transformations)
  199825. png_do_write_transformations(png_ptr);
  199826. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199827. /* Write filter_method 64 (intrapixel differencing) only if
  199828. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199829. * 2. Libpng did not write a PNG signature (this filter_method is only
  199830. * used in PNG datastreams that are embedded in MNG datastreams) and
  199831. * 3. The application called png_permit_mng_features with a mask that
  199832. * included PNG_FLAG_MNG_FILTER_64 and
  199833. * 4. The filter_method is 64 and
  199834. * 5. The color_type is RGB or RGBA
  199835. */
  199836. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199837. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199838. {
  199839. /* Intrapixel differencing */
  199840. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199841. }
  199842. #endif
  199843. /* Find a filter if necessary, filter the row and write it out. */
  199844. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199845. if (png_ptr->write_row_fn != NULL)
  199846. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199847. }
  199848. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199849. /* Set the automatic flush interval or 0 to turn flushing off */
  199850. void PNGAPI
  199851. png_set_flush(png_structp png_ptr, int nrows)
  199852. {
  199853. png_debug(1, "in png_set_flush\n");
  199854. if (png_ptr == NULL)
  199855. return;
  199856. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199857. }
  199858. /* flush the current output buffers now */
  199859. void PNGAPI
  199860. png_write_flush(png_structp png_ptr)
  199861. {
  199862. int wrote_IDAT;
  199863. png_debug(1, "in png_write_flush\n");
  199864. if (png_ptr == NULL)
  199865. return;
  199866. /* We have already written out all of the data */
  199867. if (png_ptr->row_number >= png_ptr->num_rows)
  199868. return;
  199869. do
  199870. {
  199871. int ret;
  199872. /* compress the data */
  199873. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199874. wrote_IDAT = 0;
  199875. /* check for compression errors */
  199876. if (ret != Z_OK)
  199877. {
  199878. if (png_ptr->zstream.msg != NULL)
  199879. png_error(png_ptr, png_ptr->zstream.msg);
  199880. else
  199881. png_error(png_ptr, "zlib error");
  199882. }
  199883. if (!(png_ptr->zstream.avail_out))
  199884. {
  199885. /* write the IDAT and reset the zlib output buffer */
  199886. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199887. png_ptr->zbuf_size);
  199888. png_ptr->zstream.next_out = png_ptr->zbuf;
  199889. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199890. wrote_IDAT = 1;
  199891. }
  199892. } while(wrote_IDAT == 1);
  199893. /* If there is any data left to be output, write it into a new IDAT */
  199894. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199895. {
  199896. /* write the IDAT and reset the zlib output buffer */
  199897. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199898. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199899. png_ptr->zstream.next_out = png_ptr->zbuf;
  199900. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199901. }
  199902. png_ptr->flush_rows = 0;
  199903. png_flush(png_ptr);
  199904. }
  199905. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199906. /* free all memory used by the write */
  199907. void PNGAPI
  199908. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199909. {
  199910. png_structp png_ptr = NULL;
  199911. png_infop info_ptr = NULL;
  199912. #ifdef PNG_USER_MEM_SUPPORTED
  199913. png_free_ptr free_fn = NULL;
  199914. png_voidp mem_ptr = NULL;
  199915. #endif
  199916. png_debug(1, "in png_destroy_write_struct\n");
  199917. if (png_ptr_ptr != NULL)
  199918. {
  199919. png_ptr = *png_ptr_ptr;
  199920. #ifdef PNG_USER_MEM_SUPPORTED
  199921. free_fn = png_ptr->free_fn;
  199922. mem_ptr = png_ptr->mem_ptr;
  199923. #endif
  199924. }
  199925. if (info_ptr_ptr != NULL)
  199926. info_ptr = *info_ptr_ptr;
  199927. if (info_ptr != NULL)
  199928. {
  199929. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199930. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199931. if (png_ptr->num_chunk_list)
  199932. {
  199933. png_free(png_ptr, png_ptr->chunk_list);
  199934. png_ptr->chunk_list=NULL;
  199935. png_ptr->num_chunk_list=0;
  199936. }
  199937. #endif
  199938. #ifdef PNG_USER_MEM_SUPPORTED
  199939. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199940. (png_voidp)mem_ptr);
  199941. #else
  199942. png_destroy_struct((png_voidp)info_ptr);
  199943. #endif
  199944. *info_ptr_ptr = NULL;
  199945. }
  199946. if (png_ptr != NULL)
  199947. {
  199948. png_write_destroy(png_ptr);
  199949. #ifdef PNG_USER_MEM_SUPPORTED
  199950. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199951. (png_voidp)mem_ptr);
  199952. #else
  199953. png_destroy_struct((png_voidp)png_ptr);
  199954. #endif
  199955. *png_ptr_ptr = NULL;
  199956. }
  199957. }
  199958. /* Free any memory used in png_ptr struct (old method) */
  199959. void /* PRIVATE */
  199960. png_write_destroy(png_structp png_ptr)
  199961. {
  199962. #ifdef PNG_SETJMP_SUPPORTED
  199963. jmp_buf tmp_jmp; /* save jump buffer */
  199964. #endif
  199965. png_error_ptr error_fn;
  199966. png_error_ptr warning_fn;
  199967. png_voidp error_ptr;
  199968. #ifdef PNG_USER_MEM_SUPPORTED
  199969. png_free_ptr free_fn;
  199970. #endif
  199971. png_debug(1, "in png_write_destroy\n");
  199972. /* free any memory zlib uses */
  199973. deflateEnd(&png_ptr->zstream);
  199974. /* free our memory. png_free checks NULL for us. */
  199975. png_free(png_ptr, png_ptr->zbuf);
  199976. png_free(png_ptr, png_ptr->row_buf);
  199977. png_free(png_ptr, png_ptr->prev_row);
  199978. png_free(png_ptr, png_ptr->sub_row);
  199979. png_free(png_ptr, png_ptr->up_row);
  199980. png_free(png_ptr, png_ptr->avg_row);
  199981. png_free(png_ptr, png_ptr->paeth_row);
  199982. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199983. png_free(png_ptr, png_ptr->time_buffer);
  199984. #endif
  199985. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199986. png_free(png_ptr, png_ptr->prev_filters);
  199987. png_free(png_ptr, png_ptr->filter_weights);
  199988. png_free(png_ptr, png_ptr->inv_filter_weights);
  199989. png_free(png_ptr, png_ptr->filter_costs);
  199990. png_free(png_ptr, png_ptr->inv_filter_costs);
  199991. #endif
  199992. #ifdef PNG_SETJMP_SUPPORTED
  199993. /* reset structure */
  199994. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199995. #endif
  199996. error_fn = png_ptr->error_fn;
  199997. warning_fn = png_ptr->warning_fn;
  199998. error_ptr = png_ptr->error_ptr;
  199999. #ifdef PNG_USER_MEM_SUPPORTED
  200000. free_fn = png_ptr->free_fn;
  200001. #endif
  200002. png_memset(png_ptr, 0, png_sizeof (png_struct));
  200003. png_ptr->error_fn = error_fn;
  200004. png_ptr->warning_fn = warning_fn;
  200005. png_ptr->error_ptr = error_ptr;
  200006. #ifdef PNG_USER_MEM_SUPPORTED
  200007. png_ptr->free_fn = free_fn;
  200008. #endif
  200009. #ifdef PNG_SETJMP_SUPPORTED
  200010. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  200011. #endif
  200012. }
  200013. /* Allow the application to select one or more row filters to use. */
  200014. void PNGAPI
  200015. png_set_filter(png_structp png_ptr, int method, int filters)
  200016. {
  200017. png_debug(1, "in png_set_filter\n");
  200018. if (png_ptr == NULL)
  200019. return;
  200020. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200021. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200022. (method == PNG_INTRAPIXEL_DIFFERENCING))
  200023. method = PNG_FILTER_TYPE_BASE;
  200024. #endif
  200025. if (method == PNG_FILTER_TYPE_BASE)
  200026. {
  200027. switch (filters & (PNG_ALL_FILTERS | 0x07))
  200028. {
  200029. #ifndef PNG_NO_WRITE_FILTER
  200030. case 5:
  200031. case 6:
  200032. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  200033. #endif /* PNG_NO_WRITE_FILTER */
  200034. case PNG_FILTER_VALUE_NONE:
  200035. png_ptr->do_filter=PNG_FILTER_NONE; break;
  200036. #ifndef PNG_NO_WRITE_FILTER
  200037. case PNG_FILTER_VALUE_SUB:
  200038. png_ptr->do_filter=PNG_FILTER_SUB; break;
  200039. case PNG_FILTER_VALUE_UP:
  200040. png_ptr->do_filter=PNG_FILTER_UP; break;
  200041. case PNG_FILTER_VALUE_AVG:
  200042. png_ptr->do_filter=PNG_FILTER_AVG; break;
  200043. case PNG_FILTER_VALUE_PAETH:
  200044. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  200045. default: png_ptr->do_filter = (png_byte)filters; break;
  200046. #else
  200047. default: png_warning(png_ptr, "Unknown row filter for method 0");
  200048. #endif /* PNG_NO_WRITE_FILTER */
  200049. }
  200050. /* If we have allocated the row_buf, this means we have already started
  200051. * with the image and we should have allocated all of the filter buffers
  200052. * that have been selected. If prev_row isn't already allocated, then
  200053. * it is too late to start using the filters that need it, since we
  200054. * will be missing the data in the previous row. If an application
  200055. * wants to start and stop using particular filters during compression,
  200056. * it should start out with all of the filters, and then add and
  200057. * remove them after the start of compression.
  200058. */
  200059. if (png_ptr->row_buf != NULL)
  200060. {
  200061. #ifndef PNG_NO_WRITE_FILTER
  200062. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  200063. {
  200064. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  200065. (png_ptr->rowbytes + 1));
  200066. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  200067. }
  200068. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  200069. {
  200070. if (png_ptr->prev_row == NULL)
  200071. {
  200072. png_warning(png_ptr, "Can't add Up filter after starting");
  200073. png_ptr->do_filter &= ~PNG_FILTER_UP;
  200074. }
  200075. else
  200076. {
  200077. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  200078. (png_ptr->rowbytes + 1));
  200079. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  200080. }
  200081. }
  200082. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  200083. {
  200084. if (png_ptr->prev_row == NULL)
  200085. {
  200086. png_warning(png_ptr, "Can't add Average filter after starting");
  200087. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  200088. }
  200089. else
  200090. {
  200091. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  200092. (png_ptr->rowbytes + 1));
  200093. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  200094. }
  200095. }
  200096. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  200097. png_ptr->paeth_row == NULL)
  200098. {
  200099. if (png_ptr->prev_row == NULL)
  200100. {
  200101. png_warning(png_ptr, "Can't add Paeth filter after starting");
  200102. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  200103. }
  200104. else
  200105. {
  200106. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  200107. (png_ptr->rowbytes + 1));
  200108. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  200109. }
  200110. }
  200111. if (png_ptr->do_filter == PNG_NO_FILTERS)
  200112. #endif /* PNG_NO_WRITE_FILTER */
  200113. png_ptr->do_filter = PNG_FILTER_NONE;
  200114. }
  200115. }
  200116. else
  200117. png_error(png_ptr, "Unknown custom filter method");
  200118. }
  200119. /* This allows us to influence the way in which libpng chooses the "best"
  200120. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200121. * differences metric is relatively fast and effective, there is some
  200122. * question as to whether it can be improved upon by trying to keep the
  200123. * filtered data going to zlib more consistent, hopefully resulting in
  200124. * better compression.
  200125. */
  200126. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200127. void PNGAPI
  200128. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200129. int num_weights, png_doublep filter_weights,
  200130. png_doublep filter_costs)
  200131. {
  200132. int i;
  200133. png_debug(1, "in png_set_filter_heuristics\n");
  200134. if (png_ptr == NULL)
  200135. return;
  200136. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200137. {
  200138. png_warning(png_ptr, "Unknown filter heuristic method");
  200139. return;
  200140. }
  200141. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200142. {
  200143. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200144. }
  200145. if (num_weights < 0 || filter_weights == NULL ||
  200146. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200147. {
  200148. num_weights = 0;
  200149. }
  200150. png_ptr->num_prev_filters = (png_byte)num_weights;
  200151. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200152. if (num_weights > 0)
  200153. {
  200154. if (png_ptr->prev_filters == NULL)
  200155. {
  200156. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200157. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200158. /* To make sure that the weighting starts out fairly */
  200159. for (i = 0; i < num_weights; i++)
  200160. {
  200161. png_ptr->prev_filters[i] = 255;
  200162. }
  200163. }
  200164. if (png_ptr->filter_weights == NULL)
  200165. {
  200166. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200167. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200168. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200169. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200170. for (i = 0; i < num_weights; i++)
  200171. {
  200172. png_ptr->inv_filter_weights[i] =
  200173. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200174. }
  200175. }
  200176. for (i = 0; i < num_weights; i++)
  200177. {
  200178. if (filter_weights[i] < 0.0)
  200179. {
  200180. png_ptr->inv_filter_weights[i] =
  200181. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200182. }
  200183. else
  200184. {
  200185. png_ptr->inv_filter_weights[i] =
  200186. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200187. png_ptr->filter_weights[i] =
  200188. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200189. }
  200190. }
  200191. }
  200192. /* If, in the future, there are other filter methods, this would
  200193. * need to be based on png_ptr->filter.
  200194. */
  200195. if (png_ptr->filter_costs == NULL)
  200196. {
  200197. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200198. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200199. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200200. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200201. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200202. {
  200203. png_ptr->inv_filter_costs[i] =
  200204. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200205. }
  200206. }
  200207. /* Here is where we set the relative costs of the different filters. We
  200208. * should take the desired compression level into account when setting
  200209. * the costs, so that Paeth, for instance, has a high relative cost at low
  200210. * compression levels, while it has a lower relative cost at higher
  200211. * compression settings. The filter types are in order of increasing
  200212. * relative cost, so it would be possible to do this with an algorithm.
  200213. */
  200214. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200215. {
  200216. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200217. {
  200218. png_ptr->inv_filter_costs[i] =
  200219. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200220. }
  200221. else if (filter_costs[i] >= 1.0)
  200222. {
  200223. png_ptr->inv_filter_costs[i] =
  200224. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200225. png_ptr->filter_costs[i] =
  200226. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200227. }
  200228. }
  200229. }
  200230. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200231. void PNGAPI
  200232. png_set_compression_level(png_structp png_ptr, int level)
  200233. {
  200234. png_debug(1, "in png_set_compression_level\n");
  200235. if (png_ptr == NULL)
  200236. return;
  200237. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200238. png_ptr->zlib_level = level;
  200239. }
  200240. void PNGAPI
  200241. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200242. {
  200243. png_debug(1, "in png_set_compression_mem_level\n");
  200244. if (png_ptr == NULL)
  200245. return;
  200246. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200247. png_ptr->zlib_mem_level = mem_level;
  200248. }
  200249. void PNGAPI
  200250. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200251. {
  200252. png_debug(1, "in png_set_compression_strategy\n");
  200253. if (png_ptr == NULL)
  200254. return;
  200255. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200256. png_ptr->zlib_strategy = strategy;
  200257. }
  200258. void PNGAPI
  200259. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200260. {
  200261. if (png_ptr == NULL)
  200262. return;
  200263. if (window_bits > 15)
  200264. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200265. else if (window_bits < 8)
  200266. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200267. #ifndef WBITS_8_OK
  200268. /* avoid libpng bug with 256-byte windows */
  200269. if (window_bits == 8)
  200270. {
  200271. png_warning(png_ptr, "Compression window is being reset to 512");
  200272. window_bits=9;
  200273. }
  200274. #endif
  200275. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200276. png_ptr->zlib_window_bits = window_bits;
  200277. }
  200278. void PNGAPI
  200279. png_set_compression_method(png_structp png_ptr, int method)
  200280. {
  200281. png_debug(1, "in png_set_compression_method\n");
  200282. if (png_ptr == NULL)
  200283. return;
  200284. if (method != 8)
  200285. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200286. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200287. png_ptr->zlib_method = method;
  200288. }
  200289. void PNGAPI
  200290. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200291. {
  200292. if (png_ptr == NULL)
  200293. return;
  200294. png_ptr->write_row_fn = write_row_fn;
  200295. }
  200296. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200297. void PNGAPI
  200298. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200299. write_user_transform_fn)
  200300. {
  200301. png_debug(1, "in png_set_write_user_transform_fn\n");
  200302. if (png_ptr == NULL)
  200303. return;
  200304. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200305. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200306. }
  200307. #endif
  200308. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200309. void PNGAPI
  200310. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200311. int transforms, voidp params)
  200312. {
  200313. if (png_ptr == NULL || info_ptr == NULL)
  200314. return;
  200315. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200316. /* invert the alpha channel from opacity to transparency */
  200317. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200318. png_set_invert_alpha(png_ptr);
  200319. #endif
  200320. /* Write the file header information. */
  200321. png_write_info(png_ptr, info_ptr);
  200322. /* ------ these transformations don't touch the info structure ------- */
  200323. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200324. /* invert monochrome pixels */
  200325. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200326. png_set_invert_mono(png_ptr);
  200327. #endif
  200328. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200329. /* Shift the pixels up to a legal bit depth and fill in
  200330. * as appropriate to correctly scale the image.
  200331. */
  200332. if ((transforms & PNG_TRANSFORM_SHIFT)
  200333. && (info_ptr->valid & PNG_INFO_sBIT))
  200334. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200335. #endif
  200336. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200337. /* pack pixels into bytes */
  200338. if (transforms & PNG_TRANSFORM_PACKING)
  200339. png_set_packing(png_ptr);
  200340. #endif
  200341. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200342. /* swap location of alpha bytes from ARGB to RGBA */
  200343. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200344. png_set_swap_alpha(png_ptr);
  200345. #endif
  200346. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200347. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200348. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200349. */
  200350. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200351. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200352. #endif
  200353. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200354. /* flip BGR pixels to RGB */
  200355. if (transforms & PNG_TRANSFORM_BGR)
  200356. png_set_bgr(png_ptr);
  200357. #endif
  200358. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200359. /* swap bytes of 16-bit files to most significant byte first */
  200360. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200361. png_set_swap(png_ptr);
  200362. #endif
  200363. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200364. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200365. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200366. png_set_packswap(png_ptr);
  200367. #endif
  200368. /* ----------------------- end of transformations ------------------- */
  200369. /* write the bits */
  200370. if (info_ptr->valid & PNG_INFO_IDAT)
  200371. png_write_image(png_ptr, info_ptr->row_pointers);
  200372. /* It is REQUIRED to call this to finish writing the rest of the file */
  200373. png_write_end(png_ptr, info_ptr);
  200374. transforms = transforms; /* quiet compiler warnings */
  200375. params = params;
  200376. }
  200377. #endif
  200378. #endif /* PNG_WRITE_SUPPORTED */
  200379. /*** End of inlined file: pngwrite.c ***/
  200380. /*** Start of inlined file: pngwtran.c ***/
  200381. /* pngwtran.c - transforms the data in a row for PNG writers
  200382. *
  200383. * Last changed in libpng 1.2.9 April 14, 2006
  200384. * For conditions of distribution and use, see copyright notice in png.h
  200385. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200386. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200387. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200388. */
  200389. #define PNG_INTERNAL
  200390. #ifdef PNG_WRITE_SUPPORTED
  200391. /* Transform the data according to the user's wishes. The order of
  200392. * transformations is significant.
  200393. */
  200394. void /* PRIVATE */
  200395. png_do_write_transformations(png_structp png_ptr)
  200396. {
  200397. png_debug(1, "in png_do_write_transformations\n");
  200398. if (png_ptr == NULL)
  200399. return;
  200400. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200401. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200402. if(png_ptr->write_user_transform_fn != NULL)
  200403. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200404. (png_ptr, /* png_ptr */
  200405. &(png_ptr->row_info), /* row_info: */
  200406. /* png_uint_32 width; width of row */
  200407. /* png_uint_32 rowbytes; number of bytes in row */
  200408. /* png_byte color_type; color type of pixels */
  200409. /* png_byte bit_depth; bit depth of samples */
  200410. /* png_byte channels; number of channels (1-4) */
  200411. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200412. png_ptr->row_buf + 1); /* start of pixel data for row */
  200413. #endif
  200414. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200415. if (png_ptr->transformations & PNG_FILLER)
  200416. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200417. png_ptr->flags);
  200418. #endif
  200419. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200420. if (png_ptr->transformations & PNG_PACKSWAP)
  200421. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200422. #endif
  200423. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200424. if (png_ptr->transformations & PNG_PACK)
  200425. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200426. (png_uint_32)png_ptr->bit_depth);
  200427. #endif
  200428. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200429. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200430. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200431. #endif
  200432. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200433. if (png_ptr->transformations & PNG_SHIFT)
  200434. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200435. &(png_ptr->shift));
  200436. #endif
  200437. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200438. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200439. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200440. #endif
  200441. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200442. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200443. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200444. #endif
  200445. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200446. if (png_ptr->transformations & PNG_BGR)
  200447. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200448. #endif
  200449. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200450. if (png_ptr->transformations & PNG_INVERT_MONO)
  200451. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200452. #endif
  200453. }
  200454. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200455. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200456. * row_info bit depth should be 8 (one pixel per byte). The channels
  200457. * should be 1 (this only happens on grayscale and paletted images).
  200458. */
  200459. void /* PRIVATE */
  200460. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200461. {
  200462. png_debug(1, "in png_do_pack\n");
  200463. if (row_info->bit_depth == 8 &&
  200464. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200465. row != NULL && row_info != NULL &&
  200466. #endif
  200467. row_info->channels == 1)
  200468. {
  200469. switch ((int)bit_depth)
  200470. {
  200471. case 1:
  200472. {
  200473. png_bytep sp, dp;
  200474. int mask, v;
  200475. png_uint_32 i;
  200476. png_uint_32 row_width = row_info->width;
  200477. sp = row;
  200478. dp = row;
  200479. mask = 0x80;
  200480. v = 0;
  200481. for (i = 0; i < row_width; i++)
  200482. {
  200483. if (*sp != 0)
  200484. v |= mask;
  200485. sp++;
  200486. if (mask > 1)
  200487. mask >>= 1;
  200488. else
  200489. {
  200490. mask = 0x80;
  200491. *dp = (png_byte)v;
  200492. dp++;
  200493. v = 0;
  200494. }
  200495. }
  200496. if (mask != 0x80)
  200497. *dp = (png_byte)v;
  200498. break;
  200499. }
  200500. case 2:
  200501. {
  200502. png_bytep sp, dp;
  200503. int shift, v;
  200504. png_uint_32 i;
  200505. png_uint_32 row_width = row_info->width;
  200506. sp = row;
  200507. dp = row;
  200508. shift = 6;
  200509. v = 0;
  200510. for (i = 0; i < row_width; i++)
  200511. {
  200512. png_byte value;
  200513. value = (png_byte)(*sp & 0x03);
  200514. v |= (value << shift);
  200515. if (shift == 0)
  200516. {
  200517. shift = 6;
  200518. *dp = (png_byte)v;
  200519. dp++;
  200520. v = 0;
  200521. }
  200522. else
  200523. shift -= 2;
  200524. sp++;
  200525. }
  200526. if (shift != 6)
  200527. *dp = (png_byte)v;
  200528. break;
  200529. }
  200530. case 4:
  200531. {
  200532. png_bytep sp, dp;
  200533. int shift, v;
  200534. png_uint_32 i;
  200535. png_uint_32 row_width = row_info->width;
  200536. sp = row;
  200537. dp = row;
  200538. shift = 4;
  200539. v = 0;
  200540. for (i = 0; i < row_width; i++)
  200541. {
  200542. png_byte value;
  200543. value = (png_byte)(*sp & 0x0f);
  200544. v |= (value << shift);
  200545. if (shift == 0)
  200546. {
  200547. shift = 4;
  200548. *dp = (png_byte)v;
  200549. dp++;
  200550. v = 0;
  200551. }
  200552. else
  200553. shift -= 4;
  200554. sp++;
  200555. }
  200556. if (shift != 4)
  200557. *dp = (png_byte)v;
  200558. break;
  200559. }
  200560. }
  200561. row_info->bit_depth = (png_byte)bit_depth;
  200562. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200563. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200564. row_info->width);
  200565. }
  200566. }
  200567. #endif
  200568. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200569. /* Shift pixel values to take advantage of whole range. Pass the
  200570. * true number of bits in bit_depth. The row should be packed
  200571. * according to row_info->bit_depth. Thus, if you had a row of
  200572. * bit depth 4, but the pixels only had values from 0 to 7, you
  200573. * would pass 3 as bit_depth, and this routine would translate the
  200574. * data to 0 to 15.
  200575. */
  200576. void /* PRIVATE */
  200577. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200578. {
  200579. png_debug(1, "in png_do_shift\n");
  200580. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200581. if (row != NULL && row_info != NULL &&
  200582. #else
  200583. if (
  200584. #endif
  200585. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200586. {
  200587. int shift_start[4], shift_dec[4];
  200588. int channels = 0;
  200589. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200590. {
  200591. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200592. shift_dec[channels] = bit_depth->red;
  200593. channels++;
  200594. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200595. shift_dec[channels] = bit_depth->green;
  200596. channels++;
  200597. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200598. shift_dec[channels] = bit_depth->blue;
  200599. channels++;
  200600. }
  200601. else
  200602. {
  200603. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200604. shift_dec[channels] = bit_depth->gray;
  200605. channels++;
  200606. }
  200607. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200608. {
  200609. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200610. shift_dec[channels] = bit_depth->alpha;
  200611. channels++;
  200612. }
  200613. /* with low row depths, could only be grayscale, so one channel */
  200614. if (row_info->bit_depth < 8)
  200615. {
  200616. png_bytep bp = row;
  200617. png_uint_32 i;
  200618. png_byte mask;
  200619. png_uint_32 row_bytes = row_info->rowbytes;
  200620. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200621. mask = 0x55;
  200622. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200623. mask = 0x11;
  200624. else
  200625. mask = 0xff;
  200626. for (i = 0; i < row_bytes; i++, bp++)
  200627. {
  200628. png_uint_16 v;
  200629. int j;
  200630. v = *bp;
  200631. *bp = 0;
  200632. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200633. {
  200634. if (j > 0)
  200635. *bp |= (png_byte)((v << j) & 0xff);
  200636. else
  200637. *bp |= (png_byte)((v >> (-j)) & mask);
  200638. }
  200639. }
  200640. }
  200641. else if (row_info->bit_depth == 8)
  200642. {
  200643. png_bytep bp = row;
  200644. png_uint_32 i;
  200645. png_uint_32 istop = channels * row_info->width;
  200646. for (i = 0; i < istop; i++, bp++)
  200647. {
  200648. png_uint_16 v;
  200649. int j;
  200650. int c = (int)(i%channels);
  200651. v = *bp;
  200652. *bp = 0;
  200653. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200654. {
  200655. if (j > 0)
  200656. *bp |= (png_byte)((v << j) & 0xff);
  200657. else
  200658. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200659. }
  200660. }
  200661. }
  200662. else
  200663. {
  200664. png_bytep bp;
  200665. png_uint_32 i;
  200666. png_uint_32 istop = channels * row_info->width;
  200667. for (bp = row, i = 0; i < istop; i++)
  200668. {
  200669. int c = (int)(i%channels);
  200670. png_uint_16 value, v;
  200671. int j;
  200672. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200673. value = 0;
  200674. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200675. {
  200676. if (j > 0)
  200677. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200678. else
  200679. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200680. }
  200681. *bp++ = (png_byte)(value >> 8);
  200682. *bp++ = (png_byte)(value & 0xff);
  200683. }
  200684. }
  200685. }
  200686. }
  200687. #endif
  200688. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200689. void /* PRIVATE */
  200690. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200691. {
  200692. png_debug(1, "in png_do_write_swap_alpha\n");
  200693. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200694. if (row != NULL && row_info != NULL)
  200695. #endif
  200696. {
  200697. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200698. {
  200699. /* This converts from ARGB to RGBA */
  200700. if (row_info->bit_depth == 8)
  200701. {
  200702. png_bytep sp, dp;
  200703. png_uint_32 i;
  200704. png_uint_32 row_width = row_info->width;
  200705. for (i = 0, sp = dp = row; i < row_width; i++)
  200706. {
  200707. png_byte save = *(sp++);
  200708. *(dp++) = *(sp++);
  200709. *(dp++) = *(sp++);
  200710. *(dp++) = *(sp++);
  200711. *(dp++) = save;
  200712. }
  200713. }
  200714. /* This converts from AARRGGBB to RRGGBBAA */
  200715. else
  200716. {
  200717. png_bytep sp, dp;
  200718. png_uint_32 i;
  200719. png_uint_32 row_width = row_info->width;
  200720. for (i = 0, sp = dp = row; i < row_width; i++)
  200721. {
  200722. png_byte save[2];
  200723. save[0] = *(sp++);
  200724. save[1] = *(sp++);
  200725. *(dp++) = *(sp++);
  200726. *(dp++) = *(sp++);
  200727. *(dp++) = *(sp++);
  200728. *(dp++) = *(sp++);
  200729. *(dp++) = *(sp++);
  200730. *(dp++) = *(sp++);
  200731. *(dp++) = save[0];
  200732. *(dp++) = save[1];
  200733. }
  200734. }
  200735. }
  200736. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200737. {
  200738. /* This converts from AG to GA */
  200739. if (row_info->bit_depth == 8)
  200740. {
  200741. png_bytep sp, dp;
  200742. png_uint_32 i;
  200743. png_uint_32 row_width = row_info->width;
  200744. for (i = 0, sp = dp = row; i < row_width; i++)
  200745. {
  200746. png_byte save = *(sp++);
  200747. *(dp++) = *(sp++);
  200748. *(dp++) = save;
  200749. }
  200750. }
  200751. /* This converts from AAGG to GGAA */
  200752. else
  200753. {
  200754. png_bytep sp, dp;
  200755. png_uint_32 i;
  200756. png_uint_32 row_width = row_info->width;
  200757. for (i = 0, sp = dp = row; i < row_width; i++)
  200758. {
  200759. png_byte save[2];
  200760. save[0] = *(sp++);
  200761. save[1] = *(sp++);
  200762. *(dp++) = *(sp++);
  200763. *(dp++) = *(sp++);
  200764. *(dp++) = save[0];
  200765. *(dp++) = save[1];
  200766. }
  200767. }
  200768. }
  200769. }
  200770. }
  200771. #endif
  200772. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200773. void /* PRIVATE */
  200774. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200775. {
  200776. png_debug(1, "in png_do_write_invert_alpha\n");
  200777. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200778. if (row != NULL && row_info != NULL)
  200779. #endif
  200780. {
  200781. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200782. {
  200783. /* This inverts the alpha channel in RGBA */
  200784. if (row_info->bit_depth == 8)
  200785. {
  200786. png_bytep sp, dp;
  200787. png_uint_32 i;
  200788. png_uint_32 row_width = row_info->width;
  200789. for (i = 0, sp = dp = row; i < row_width; i++)
  200790. {
  200791. /* does nothing
  200792. *(dp++) = *(sp++);
  200793. *(dp++) = *(sp++);
  200794. *(dp++) = *(sp++);
  200795. */
  200796. sp+=3; dp = sp;
  200797. *(dp++) = (png_byte)(255 - *(sp++));
  200798. }
  200799. }
  200800. /* This inverts the alpha channel in RRGGBBAA */
  200801. else
  200802. {
  200803. png_bytep sp, dp;
  200804. png_uint_32 i;
  200805. png_uint_32 row_width = row_info->width;
  200806. for (i = 0, sp = dp = row; i < row_width; i++)
  200807. {
  200808. /* does nothing
  200809. *(dp++) = *(sp++);
  200810. *(dp++) = *(sp++);
  200811. *(dp++) = *(sp++);
  200812. *(dp++) = *(sp++);
  200813. *(dp++) = *(sp++);
  200814. *(dp++) = *(sp++);
  200815. */
  200816. sp+=6; dp = sp;
  200817. *(dp++) = (png_byte)(255 - *(sp++));
  200818. *(dp++) = (png_byte)(255 - *(sp++));
  200819. }
  200820. }
  200821. }
  200822. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200823. {
  200824. /* This inverts the alpha channel in GA */
  200825. if (row_info->bit_depth == 8)
  200826. {
  200827. png_bytep sp, dp;
  200828. png_uint_32 i;
  200829. png_uint_32 row_width = row_info->width;
  200830. for (i = 0, sp = dp = row; i < row_width; i++)
  200831. {
  200832. *(dp++) = *(sp++);
  200833. *(dp++) = (png_byte)(255 - *(sp++));
  200834. }
  200835. }
  200836. /* This inverts the alpha channel in GGAA */
  200837. else
  200838. {
  200839. png_bytep sp, dp;
  200840. png_uint_32 i;
  200841. png_uint_32 row_width = row_info->width;
  200842. for (i = 0, sp = dp = row; i < row_width; i++)
  200843. {
  200844. /* does nothing
  200845. *(dp++) = *(sp++);
  200846. *(dp++) = *(sp++);
  200847. */
  200848. sp+=2; dp = sp;
  200849. *(dp++) = (png_byte)(255 - *(sp++));
  200850. *(dp++) = (png_byte)(255 - *(sp++));
  200851. }
  200852. }
  200853. }
  200854. }
  200855. }
  200856. #endif
  200857. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200858. /* undoes intrapixel differencing */
  200859. void /* PRIVATE */
  200860. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200861. {
  200862. png_debug(1, "in png_do_write_intrapixel\n");
  200863. if (
  200864. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200865. row != NULL && row_info != NULL &&
  200866. #endif
  200867. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200868. {
  200869. int bytes_per_pixel;
  200870. png_uint_32 row_width = row_info->width;
  200871. if (row_info->bit_depth == 8)
  200872. {
  200873. png_bytep rp;
  200874. png_uint_32 i;
  200875. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200876. bytes_per_pixel = 3;
  200877. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200878. bytes_per_pixel = 4;
  200879. else
  200880. return;
  200881. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200882. {
  200883. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200884. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200885. }
  200886. }
  200887. else if (row_info->bit_depth == 16)
  200888. {
  200889. png_bytep rp;
  200890. png_uint_32 i;
  200891. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200892. bytes_per_pixel = 6;
  200893. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200894. bytes_per_pixel = 8;
  200895. else
  200896. return;
  200897. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200898. {
  200899. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200900. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200901. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200902. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200903. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200904. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200905. *(rp+1) = (png_byte)(red & 0xff);
  200906. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200907. *(rp+5) = (png_byte)(blue & 0xff);
  200908. }
  200909. }
  200910. }
  200911. }
  200912. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200913. #endif /* PNG_WRITE_SUPPORTED */
  200914. /*** End of inlined file: pngwtran.c ***/
  200915. /*** Start of inlined file: pngwutil.c ***/
  200916. /* pngwutil.c - utilities to write a PNG file
  200917. *
  200918. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200919. * For conditions of distribution and use, see copyright notice in png.h
  200920. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200921. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200922. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200923. */
  200924. #define PNG_INTERNAL
  200925. #ifdef PNG_WRITE_SUPPORTED
  200926. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200927. * with unsigned numbers for convenience, although one supported
  200928. * ancillary chunk uses signed (two's complement) numbers.
  200929. */
  200930. void PNGAPI
  200931. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200932. {
  200933. buf[0] = (png_byte)((i >> 24) & 0xff);
  200934. buf[1] = (png_byte)((i >> 16) & 0xff);
  200935. buf[2] = (png_byte)((i >> 8) & 0xff);
  200936. buf[3] = (png_byte)(i & 0xff);
  200937. }
  200938. /* The png_save_int_32 function assumes integers are stored in two's
  200939. * complement format. If this isn't the case, then this routine needs to
  200940. * be modified to write data in two's complement format.
  200941. */
  200942. void PNGAPI
  200943. png_save_int_32(png_bytep buf, png_int_32 i)
  200944. {
  200945. buf[0] = (png_byte)((i >> 24) & 0xff);
  200946. buf[1] = (png_byte)((i >> 16) & 0xff);
  200947. buf[2] = (png_byte)((i >> 8) & 0xff);
  200948. buf[3] = (png_byte)(i & 0xff);
  200949. }
  200950. /* Place a 16-bit number into a buffer in PNG byte order.
  200951. * The parameter is declared unsigned int, not png_uint_16,
  200952. * just to avoid potential problems on pre-ANSI C compilers.
  200953. */
  200954. void PNGAPI
  200955. png_save_uint_16(png_bytep buf, unsigned int i)
  200956. {
  200957. buf[0] = (png_byte)((i >> 8) & 0xff);
  200958. buf[1] = (png_byte)(i & 0xff);
  200959. }
  200960. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200961. * representing the chunk name. The array must be at least 4 bytes in
  200962. * length, and does not need to be null terminated. To be safe, pass the
  200963. * pre-defined chunk names here, and if you need a new one, define it
  200964. * where the others are defined. The length is the length of the data.
  200965. * All the data must be present. If that is not possible, use the
  200966. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200967. * functions instead.
  200968. */
  200969. void PNGAPI
  200970. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200971. png_bytep data, png_size_t length)
  200972. {
  200973. if(png_ptr == NULL) return;
  200974. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200975. png_write_chunk_data(png_ptr, data, length);
  200976. png_write_chunk_end(png_ptr);
  200977. }
  200978. /* Write the start of a PNG chunk. The type is the chunk type.
  200979. * The total_length is the sum of the lengths of all the data you will be
  200980. * passing in png_write_chunk_data().
  200981. */
  200982. void PNGAPI
  200983. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200984. png_uint_32 length)
  200985. {
  200986. png_byte buf[4];
  200987. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200988. if(png_ptr == NULL) return;
  200989. /* write the length */
  200990. png_save_uint_32(buf, length);
  200991. png_write_data(png_ptr, buf, (png_size_t)4);
  200992. /* write the chunk name */
  200993. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200994. /* reset the crc and run it over the chunk name */
  200995. png_reset_crc(png_ptr);
  200996. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200997. }
  200998. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200999. * Note that multiple calls to this function are allowed, and that the
  201000. * sum of the lengths from these calls *must* add up to the total_length
  201001. * given to png_write_chunk_start().
  201002. */
  201003. void PNGAPI
  201004. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  201005. {
  201006. /* write the data, and run the CRC over it */
  201007. if(png_ptr == NULL) return;
  201008. if (data != NULL && length > 0)
  201009. {
  201010. png_calculate_crc(png_ptr, data, length);
  201011. png_write_data(png_ptr, data, length);
  201012. }
  201013. }
  201014. /* Finish a chunk started with png_write_chunk_start(). */
  201015. void PNGAPI
  201016. png_write_chunk_end(png_structp png_ptr)
  201017. {
  201018. png_byte buf[4];
  201019. if(png_ptr == NULL) return;
  201020. /* write the crc */
  201021. png_save_uint_32(buf, png_ptr->crc);
  201022. png_write_data(png_ptr, buf, (png_size_t)4);
  201023. }
  201024. /* Simple function to write the signature. If we have already written
  201025. * the magic bytes of the signature, or more likely, the PNG stream is
  201026. * being embedded into another stream and doesn't need its own signature,
  201027. * we should call png_set_sig_bytes() to tell libpng how many of the
  201028. * bytes have already been written.
  201029. */
  201030. void /* PRIVATE */
  201031. png_write_sig(png_structp png_ptr)
  201032. {
  201033. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  201034. /* write the rest of the 8 byte signature */
  201035. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  201036. (png_size_t)8 - png_ptr->sig_bytes);
  201037. if(png_ptr->sig_bytes < 3)
  201038. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  201039. }
  201040. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  201041. /*
  201042. * This pair of functions encapsulates the operation of (a) compressing a
  201043. * text string, and (b) issuing it later as a series of chunk data writes.
  201044. * The compression_state structure is shared context for these functions
  201045. * set up by the caller in order to make the whole mess thread-safe.
  201046. */
  201047. typedef struct
  201048. {
  201049. char *input; /* the uncompressed input data */
  201050. int input_len; /* its length */
  201051. int num_output_ptr; /* number of output pointers used */
  201052. int max_output_ptr; /* size of output_ptr */
  201053. png_charpp output_ptr; /* array of pointers to output */
  201054. } compression_state;
  201055. /* compress given text into storage in the png_ptr structure */
  201056. static int /* PRIVATE */
  201057. png_text_compress(png_structp png_ptr,
  201058. png_charp text, png_size_t text_len, int compression,
  201059. compression_state *comp)
  201060. {
  201061. int ret;
  201062. comp->num_output_ptr = 0;
  201063. comp->max_output_ptr = 0;
  201064. comp->output_ptr = NULL;
  201065. comp->input = NULL;
  201066. comp->input_len = 0;
  201067. /* we may just want to pass the text right through */
  201068. if (compression == PNG_TEXT_COMPRESSION_NONE)
  201069. {
  201070. comp->input = text;
  201071. comp->input_len = text_len;
  201072. return((int)text_len);
  201073. }
  201074. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  201075. {
  201076. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201077. char msg[50];
  201078. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  201079. png_warning(png_ptr, msg);
  201080. #else
  201081. png_warning(png_ptr, "Unknown compression type");
  201082. #endif
  201083. }
  201084. /* We can't write the chunk until we find out how much data we have,
  201085. * which means we need to run the compressor first and save the
  201086. * output. This shouldn't be a problem, as the vast majority of
  201087. * comments should be reasonable, but we will set up an array of
  201088. * malloc'd pointers to be sure.
  201089. *
  201090. * If we knew the application was well behaved, we could simplify this
  201091. * greatly by assuming we can always malloc an output buffer large
  201092. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  201093. * and malloc this directly. The only time this would be a bad idea is
  201094. * if we can't malloc more than 64K and we have 64K of random input
  201095. * data, or if the input string is incredibly large (although this
  201096. * wouldn't cause a failure, just a slowdown due to swapping).
  201097. */
  201098. /* set up the compression buffers */
  201099. png_ptr->zstream.avail_in = (uInt)text_len;
  201100. png_ptr->zstream.next_in = (Bytef *)text;
  201101. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201102. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  201103. /* this is the same compression loop as in png_write_row() */
  201104. do
  201105. {
  201106. /* compress the data */
  201107. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201108. if (ret != Z_OK)
  201109. {
  201110. /* error */
  201111. if (png_ptr->zstream.msg != NULL)
  201112. png_error(png_ptr, png_ptr->zstream.msg);
  201113. else
  201114. png_error(png_ptr, "zlib error");
  201115. }
  201116. /* check to see if we need more room */
  201117. if (!(png_ptr->zstream.avail_out))
  201118. {
  201119. /* make sure the output array has room */
  201120. if (comp->num_output_ptr >= comp->max_output_ptr)
  201121. {
  201122. int old_max;
  201123. old_max = comp->max_output_ptr;
  201124. comp->max_output_ptr = comp->num_output_ptr + 4;
  201125. if (comp->output_ptr != NULL)
  201126. {
  201127. png_charpp old_ptr;
  201128. old_ptr = comp->output_ptr;
  201129. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201130. (png_uint_32)(comp->max_output_ptr *
  201131. png_sizeof (png_charpp)));
  201132. png_memcpy(comp->output_ptr, old_ptr, old_max
  201133. * png_sizeof (png_charp));
  201134. png_free(png_ptr, old_ptr);
  201135. }
  201136. else
  201137. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201138. (png_uint_32)(comp->max_output_ptr *
  201139. png_sizeof (png_charp)));
  201140. }
  201141. /* save the data */
  201142. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201143. (png_uint_32)png_ptr->zbuf_size);
  201144. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201145. png_ptr->zbuf_size);
  201146. comp->num_output_ptr++;
  201147. /* and reset the buffer */
  201148. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201149. png_ptr->zstream.next_out = png_ptr->zbuf;
  201150. }
  201151. /* continue until we don't have any more to compress */
  201152. } while (png_ptr->zstream.avail_in);
  201153. /* finish the compression */
  201154. do
  201155. {
  201156. /* tell zlib we are finished */
  201157. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201158. if (ret == Z_OK)
  201159. {
  201160. /* check to see if we need more room */
  201161. if (!(png_ptr->zstream.avail_out))
  201162. {
  201163. /* check to make sure our output array has room */
  201164. if (comp->num_output_ptr >= comp->max_output_ptr)
  201165. {
  201166. int old_max;
  201167. old_max = comp->max_output_ptr;
  201168. comp->max_output_ptr = comp->num_output_ptr + 4;
  201169. if (comp->output_ptr != NULL)
  201170. {
  201171. png_charpp old_ptr;
  201172. old_ptr = comp->output_ptr;
  201173. /* This could be optimized to realloc() */
  201174. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201175. (png_uint_32)(comp->max_output_ptr *
  201176. png_sizeof (png_charpp)));
  201177. png_memcpy(comp->output_ptr, old_ptr,
  201178. old_max * png_sizeof (png_charp));
  201179. png_free(png_ptr, old_ptr);
  201180. }
  201181. else
  201182. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201183. (png_uint_32)(comp->max_output_ptr *
  201184. png_sizeof (png_charp)));
  201185. }
  201186. /* save off the data */
  201187. comp->output_ptr[comp->num_output_ptr] =
  201188. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201189. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201190. png_ptr->zbuf_size);
  201191. comp->num_output_ptr++;
  201192. /* and reset the buffer pointers */
  201193. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201194. png_ptr->zstream.next_out = png_ptr->zbuf;
  201195. }
  201196. }
  201197. else if (ret != Z_STREAM_END)
  201198. {
  201199. /* we got an error */
  201200. if (png_ptr->zstream.msg != NULL)
  201201. png_error(png_ptr, png_ptr->zstream.msg);
  201202. else
  201203. png_error(png_ptr, "zlib error");
  201204. }
  201205. } while (ret != Z_STREAM_END);
  201206. /* text length is number of buffers plus last buffer */
  201207. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201208. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201209. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201210. return((int)text_len);
  201211. }
  201212. /* ship the compressed text out via chunk writes */
  201213. static void /* PRIVATE */
  201214. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201215. {
  201216. int i;
  201217. /* handle the no-compression case */
  201218. if (comp->input)
  201219. {
  201220. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201221. (png_size_t)comp->input_len);
  201222. return;
  201223. }
  201224. /* write saved output buffers, if any */
  201225. for (i = 0; i < comp->num_output_ptr; i++)
  201226. {
  201227. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201228. png_ptr->zbuf_size);
  201229. png_free(png_ptr, comp->output_ptr[i]);
  201230. comp->output_ptr[i]=NULL;
  201231. }
  201232. if (comp->max_output_ptr != 0)
  201233. png_free(png_ptr, comp->output_ptr);
  201234. comp->output_ptr=NULL;
  201235. /* write anything left in zbuf */
  201236. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201237. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201238. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201239. /* reset zlib for another zTXt/iTXt or image data */
  201240. deflateReset(&png_ptr->zstream);
  201241. png_ptr->zstream.data_type = Z_BINARY;
  201242. }
  201243. #endif
  201244. /* Write the IHDR chunk, and update the png_struct with the necessary
  201245. * information. Note that the rest of this code depends upon this
  201246. * information being correct.
  201247. */
  201248. void /* PRIVATE */
  201249. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201250. int bit_depth, int color_type, int compression_type, int filter_type,
  201251. int interlace_type)
  201252. {
  201253. #ifdef PNG_USE_LOCAL_ARRAYS
  201254. PNG_IHDR;
  201255. #endif
  201256. png_byte buf[13]; /* buffer to store the IHDR info */
  201257. png_debug(1, "in png_write_IHDR\n");
  201258. /* Check that we have valid input data from the application info */
  201259. switch (color_type)
  201260. {
  201261. case PNG_COLOR_TYPE_GRAY:
  201262. switch (bit_depth)
  201263. {
  201264. case 1:
  201265. case 2:
  201266. case 4:
  201267. case 8:
  201268. case 16: png_ptr->channels = 1; break;
  201269. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201270. }
  201271. break;
  201272. case PNG_COLOR_TYPE_RGB:
  201273. if (bit_depth != 8 && bit_depth != 16)
  201274. png_error(png_ptr, "Invalid bit depth for RGB image");
  201275. png_ptr->channels = 3;
  201276. break;
  201277. case PNG_COLOR_TYPE_PALETTE:
  201278. switch (bit_depth)
  201279. {
  201280. case 1:
  201281. case 2:
  201282. case 4:
  201283. case 8: png_ptr->channels = 1; break;
  201284. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201285. }
  201286. break;
  201287. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201288. if (bit_depth != 8 && bit_depth != 16)
  201289. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201290. png_ptr->channels = 2;
  201291. break;
  201292. case PNG_COLOR_TYPE_RGB_ALPHA:
  201293. if (bit_depth != 8 && bit_depth != 16)
  201294. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201295. png_ptr->channels = 4;
  201296. break;
  201297. default:
  201298. png_error(png_ptr, "Invalid image color type specified");
  201299. }
  201300. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201301. {
  201302. png_warning(png_ptr, "Invalid compression type specified");
  201303. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201304. }
  201305. /* Write filter_method 64 (intrapixel differencing) only if
  201306. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201307. * 2. Libpng did not write a PNG signature (this filter_method is only
  201308. * used in PNG datastreams that are embedded in MNG datastreams) and
  201309. * 3. The application called png_permit_mng_features with a mask that
  201310. * included PNG_FLAG_MNG_FILTER_64 and
  201311. * 4. The filter_method is 64 and
  201312. * 5. The color_type is RGB or RGBA
  201313. */
  201314. if (
  201315. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201316. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201317. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201318. (color_type == PNG_COLOR_TYPE_RGB ||
  201319. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201320. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201321. #endif
  201322. filter_type != PNG_FILTER_TYPE_BASE)
  201323. {
  201324. png_warning(png_ptr, "Invalid filter type specified");
  201325. filter_type = PNG_FILTER_TYPE_BASE;
  201326. }
  201327. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201328. if (interlace_type != PNG_INTERLACE_NONE &&
  201329. interlace_type != PNG_INTERLACE_ADAM7)
  201330. {
  201331. png_warning(png_ptr, "Invalid interlace type specified");
  201332. interlace_type = PNG_INTERLACE_ADAM7;
  201333. }
  201334. #else
  201335. interlace_type=PNG_INTERLACE_NONE;
  201336. #endif
  201337. /* save off the relevent information */
  201338. png_ptr->bit_depth = (png_byte)bit_depth;
  201339. png_ptr->color_type = (png_byte)color_type;
  201340. png_ptr->interlaced = (png_byte)interlace_type;
  201341. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201342. png_ptr->filter_type = (png_byte)filter_type;
  201343. #endif
  201344. png_ptr->compression_type = (png_byte)compression_type;
  201345. png_ptr->width = width;
  201346. png_ptr->height = height;
  201347. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201348. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201349. /* set the usr info, so any transformations can modify it */
  201350. png_ptr->usr_width = png_ptr->width;
  201351. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201352. png_ptr->usr_channels = png_ptr->channels;
  201353. /* pack the header information into the buffer */
  201354. png_save_uint_32(buf, width);
  201355. png_save_uint_32(buf + 4, height);
  201356. buf[8] = (png_byte)bit_depth;
  201357. buf[9] = (png_byte)color_type;
  201358. buf[10] = (png_byte)compression_type;
  201359. buf[11] = (png_byte)filter_type;
  201360. buf[12] = (png_byte)interlace_type;
  201361. /* write the chunk */
  201362. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201363. /* initialize zlib with PNG info */
  201364. png_ptr->zstream.zalloc = png_zalloc;
  201365. png_ptr->zstream.zfree = png_zfree;
  201366. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201367. if (!(png_ptr->do_filter))
  201368. {
  201369. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201370. png_ptr->bit_depth < 8)
  201371. png_ptr->do_filter = PNG_FILTER_NONE;
  201372. else
  201373. png_ptr->do_filter = PNG_ALL_FILTERS;
  201374. }
  201375. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201376. {
  201377. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201378. png_ptr->zlib_strategy = Z_FILTERED;
  201379. else
  201380. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201381. }
  201382. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201383. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201384. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201385. png_ptr->zlib_mem_level = 8;
  201386. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201387. png_ptr->zlib_window_bits = 15;
  201388. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201389. png_ptr->zlib_method = 8;
  201390. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201391. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201392. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201393. png_error(png_ptr, "zlib failed to initialize compressor");
  201394. png_ptr->zstream.next_out = png_ptr->zbuf;
  201395. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201396. /* libpng is not interested in zstream.data_type */
  201397. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201398. png_ptr->zstream.data_type = Z_BINARY;
  201399. png_ptr->mode = PNG_HAVE_IHDR;
  201400. }
  201401. /* write the palette. We are careful not to trust png_color to be in the
  201402. * correct order for PNG, so people can redefine it to any convenient
  201403. * structure.
  201404. */
  201405. void /* PRIVATE */
  201406. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201407. {
  201408. #ifdef PNG_USE_LOCAL_ARRAYS
  201409. PNG_PLTE;
  201410. #endif
  201411. png_uint_32 i;
  201412. png_colorp pal_ptr;
  201413. png_byte buf[3];
  201414. png_debug(1, "in png_write_PLTE\n");
  201415. if ((
  201416. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201417. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201418. #endif
  201419. num_pal == 0) || num_pal > 256)
  201420. {
  201421. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201422. {
  201423. png_error(png_ptr, "Invalid number of colors in palette");
  201424. }
  201425. else
  201426. {
  201427. png_warning(png_ptr, "Invalid number of colors in palette");
  201428. return;
  201429. }
  201430. }
  201431. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201432. {
  201433. png_warning(png_ptr,
  201434. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201435. return;
  201436. }
  201437. png_ptr->num_palette = (png_uint_16)num_pal;
  201438. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201439. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201440. #ifndef PNG_NO_POINTER_INDEXING
  201441. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201442. {
  201443. buf[0] = pal_ptr->red;
  201444. buf[1] = pal_ptr->green;
  201445. buf[2] = pal_ptr->blue;
  201446. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201447. }
  201448. #else
  201449. /* This is a little slower but some buggy compilers need to do this instead */
  201450. pal_ptr=palette;
  201451. for (i = 0; i < num_pal; i++)
  201452. {
  201453. buf[0] = pal_ptr[i].red;
  201454. buf[1] = pal_ptr[i].green;
  201455. buf[2] = pal_ptr[i].blue;
  201456. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201457. }
  201458. #endif
  201459. png_write_chunk_end(png_ptr);
  201460. png_ptr->mode |= PNG_HAVE_PLTE;
  201461. }
  201462. /* write an IDAT chunk */
  201463. void /* PRIVATE */
  201464. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201465. {
  201466. #ifdef PNG_USE_LOCAL_ARRAYS
  201467. PNG_IDAT;
  201468. #endif
  201469. png_debug(1, "in png_write_IDAT\n");
  201470. /* Optimize the CMF field in the zlib stream. */
  201471. /* This hack of the zlib stream is compliant to the stream specification. */
  201472. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201473. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201474. {
  201475. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201476. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201477. {
  201478. /* Avoid memory underflows and multiplication overflows. */
  201479. /* The conditions below are practically always satisfied;
  201480. however, they still must be checked. */
  201481. if (length >= 2 &&
  201482. png_ptr->height < 16384 && png_ptr->width < 16384)
  201483. {
  201484. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201485. ((png_ptr->width *
  201486. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201487. unsigned int z_cinfo = z_cmf >> 4;
  201488. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201489. while (uncompressed_idat_size <= half_z_window_size &&
  201490. half_z_window_size >= 256)
  201491. {
  201492. z_cinfo--;
  201493. half_z_window_size >>= 1;
  201494. }
  201495. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201496. if (data[0] != (png_byte)z_cmf)
  201497. {
  201498. data[0] = (png_byte)z_cmf;
  201499. data[1] &= 0xe0;
  201500. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201501. }
  201502. }
  201503. }
  201504. else
  201505. png_error(png_ptr,
  201506. "Invalid zlib compression method or flags in IDAT");
  201507. }
  201508. png_write_chunk(png_ptr, png_IDAT, data, length);
  201509. png_ptr->mode |= PNG_HAVE_IDAT;
  201510. }
  201511. /* write an IEND chunk */
  201512. void /* PRIVATE */
  201513. png_write_IEND(png_structp png_ptr)
  201514. {
  201515. #ifdef PNG_USE_LOCAL_ARRAYS
  201516. PNG_IEND;
  201517. #endif
  201518. png_debug(1, "in png_write_IEND\n");
  201519. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201520. (png_size_t)0);
  201521. png_ptr->mode |= PNG_HAVE_IEND;
  201522. }
  201523. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201524. /* write a gAMA chunk */
  201525. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201526. void /* PRIVATE */
  201527. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201528. {
  201529. #ifdef PNG_USE_LOCAL_ARRAYS
  201530. PNG_gAMA;
  201531. #endif
  201532. png_uint_32 igamma;
  201533. png_byte buf[4];
  201534. png_debug(1, "in png_write_gAMA\n");
  201535. /* file_gamma is saved in 1/100,000ths */
  201536. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201537. png_save_uint_32(buf, igamma);
  201538. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201539. }
  201540. #endif
  201541. #ifdef PNG_FIXED_POINT_SUPPORTED
  201542. void /* PRIVATE */
  201543. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201544. {
  201545. #ifdef PNG_USE_LOCAL_ARRAYS
  201546. PNG_gAMA;
  201547. #endif
  201548. png_byte buf[4];
  201549. png_debug(1, "in png_write_gAMA\n");
  201550. /* file_gamma is saved in 1/100,000ths */
  201551. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201552. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201553. }
  201554. #endif
  201555. #endif
  201556. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201557. /* write a sRGB chunk */
  201558. void /* PRIVATE */
  201559. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201560. {
  201561. #ifdef PNG_USE_LOCAL_ARRAYS
  201562. PNG_sRGB;
  201563. #endif
  201564. png_byte buf[1];
  201565. png_debug(1, "in png_write_sRGB\n");
  201566. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201567. png_warning(png_ptr,
  201568. "Invalid sRGB rendering intent specified");
  201569. buf[0]=(png_byte)srgb_intent;
  201570. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201571. }
  201572. #endif
  201573. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201574. /* write an iCCP chunk */
  201575. void /* PRIVATE */
  201576. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201577. png_charp profile, int profile_len)
  201578. {
  201579. #ifdef PNG_USE_LOCAL_ARRAYS
  201580. PNG_iCCP;
  201581. #endif
  201582. png_size_t name_len;
  201583. png_charp new_name;
  201584. compression_state comp;
  201585. int embedded_profile_len = 0;
  201586. png_debug(1, "in png_write_iCCP\n");
  201587. comp.num_output_ptr = 0;
  201588. comp.max_output_ptr = 0;
  201589. comp.output_ptr = NULL;
  201590. comp.input = NULL;
  201591. comp.input_len = 0;
  201592. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201593. &new_name)) == 0)
  201594. {
  201595. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201596. return;
  201597. }
  201598. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201599. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201600. if (profile == NULL)
  201601. profile_len = 0;
  201602. if (profile_len > 3)
  201603. embedded_profile_len =
  201604. ((*( (png_bytep)profile ))<<24) |
  201605. ((*( (png_bytep)profile+1))<<16) |
  201606. ((*( (png_bytep)profile+2))<< 8) |
  201607. ((*( (png_bytep)profile+3)) );
  201608. if (profile_len < embedded_profile_len)
  201609. {
  201610. png_warning(png_ptr,
  201611. "Embedded profile length too large in iCCP chunk");
  201612. return;
  201613. }
  201614. if (profile_len > embedded_profile_len)
  201615. {
  201616. png_warning(png_ptr,
  201617. "Truncating profile to actual length in iCCP chunk");
  201618. profile_len = embedded_profile_len;
  201619. }
  201620. if (profile_len)
  201621. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201622. PNG_COMPRESSION_TYPE_BASE, &comp);
  201623. /* make sure we include the NULL after the name and the compression type */
  201624. png_write_chunk_start(png_ptr, png_iCCP,
  201625. (png_uint_32)name_len+profile_len+2);
  201626. new_name[name_len+1]=0x00;
  201627. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201628. if (profile_len)
  201629. png_write_compressed_data_out(png_ptr, &comp);
  201630. png_write_chunk_end(png_ptr);
  201631. png_free(png_ptr, new_name);
  201632. }
  201633. #endif
  201634. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201635. /* write a sPLT chunk */
  201636. void /* PRIVATE */
  201637. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201638. {
  201639. #ifdef PNG_USE_LOCAL_ARRAYS
  201640. PNG_sPLT;
  201641. #endif
  201642. png_size_t name_len;
  201643. png_charp new_name;
  201644. png_byte entrybuf[10];
  201645. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201646. int palette_size = entry_size * spalette->nentries;
  201647. png_sPLT_entryp ep;
  201648. #ifdef PNG_NO_POINTER_INDEXING
  201649. int i;
  201650. #endif
  201651. png_debug(1, "in png_write_sPLT\n");
  201652. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201653. spalette->name, &new_name))==0)
  201654. {
  201655. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201656. return;
  201657. }
  201658. /* make sure we include the NULL after the name */
  201659. png_write_chunk_start(png_ptr, png_sPLT,
  201660. (png_uint_32)(name_len + 2 + palette_size));
  201661. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201662. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201663. /* loop through each palette entry, writing appropriately */
  201664. #ifndef PNG_NO_POINTER_INDEXING
  201665. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201666. {
  201667. if (spalette->depth == 8)
  201668. {
  201669. entrybuf[0] = (png_byte)ep->red;
  201670. entrybuf[1] = (png_byte)ep->green;
  201671. entrybuf[2] = (png_byte)ep->blue;
  201672. entrybuf[3] = (png_byte)ep->alpha;
  201673. png_save_uint_16(entrybuf + 4, ep->frequency);
  201674. }
  201675. else
  201676. {
  201677. png_save_uint_16(entrybuf + 0, ep->red);
  201678. png_save_uint_16(entrybuf + 2, ep->green);
  201679. png_save_uint_16(entrybuf + 4, ep->blue);
  201680. png_save_uint_16(entrybuf + 6, ep->alpha);
  201681. png_save_uint_16(entrybuf + 8, ep->frequency);
  201682. }
  201683. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201684. }
  201685. #else
  201686. ep=spalette->entries;
  201687. for (i=0; i>spalette->nentries; i++)
  201688. {
  201689. if (spalette->depth == 8)
  201690. {
  201691. entrybuf[0] = (png_byte)ep[i].red;
  201692. entrybuf[1] = (png_byte)ep[i].green;
  201693. entrybuf[2] = (png_byte)ep[i].blue;
  201694. entrybuf[3] = (png_byte)ep[i].alpha;
  201695. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201696. }
  201697. else
  201698. {
  201699. png_save_uint_16(entrybuf + 0, ep[i].red);
  201700. png_save_uint_16(entrybuf + 2, ep[i].green);
  201701. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201702. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201703. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201704. }
  201705. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201706. }
  201707. #endif
  201708. png_write_chunk_end(png_ptr);
  201709. png_free(png_ptr, new_name);
  201710. }
  201711. #endif
  201712. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201713. /* write the sBIT chunk */
  201714. void /* PRIVATE */
  201715. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201716. {
  201717. #ifdef PNG_USE_LOCAL_ARRAYS
  201718. PNG_sBIT;
  201719. #endif
  201720. png_byte buf[4];
  201721. png_size_t size;
  201722. png_debug(1, "in png_write_sBIT\n");
  201723. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201724. if (color_type & PNG_COLOR_MASK_COLOR)
  201725. {
  201726. png_byte maxbits;
  201727. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201728. png_ptr->usr_bit_depth);
  201729. if (sbit->red == 0 || sbit->red > maxbits ||
  201730. sbit->green == 0 || sbit->green > maxbits ||
  201731. sbit->blue == 0 || sbit->blue > maxbits)
  201732. {
  201733. png_warning(png_ptr, "Invalid sBIT depth specified");
  201734. return;
  201735. }
  201736. buf[0] = sbit->red;
  201737. buf[1] = sbit->green;
  201738. buf[2] = sbit->blue;
  201739. size = 3;
  201740. }
  201741. else
  201742. {
  201743. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201744. {
  201745. png_warning(png_ptr, "Invalid sBIT depth specified");
  201746. return;
  201747. }
  201748. buf[0] = sbit->gray;
  201749. size = 1;
  201750. }
  201751. if (color_type & PNG_COLOR_MASK_ALPHA)
  201752. {
  201753. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201754. {
  201755. png_warning(png_ptr, "Invalid sBIT depth specified");
  201756. return;
  201757. }
  201758. buf[size++] = sbit->alpha;
  201759. }
  201760. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201761. }
  201762. #endif
  201763. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201764. /* write the cHRM chunk */
  201765. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201766. void /* PRIVATE */
  201767. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201768. double red_x, double red_y, double green_x, double green_y,
  201769. double blue_x, double blue_y)
  201770. {
  201771. #ifdef PNG_USE_LOCAL_ARRAYS
  201772. PNG_cHRM;
  201773. #endif
  201774. png_byte buf[32];
  201775. png_uint_32 itemp;
  201776. png_debug(1, "in png_write_cHRM\n");
  201777. /* each value is saved in 1/100,000ths */
  201778. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201779. white_x + white_y > 1.0)
  201780. {
  201781. png_warning(png_ptr, "Invalid cHRM white point specified");
  201782. #if !defined(PNG_NO_CONSOLE_IO)
  201783. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201784. #endif
  201785. return;
  201786. }
  201787. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201788. png_save_uint_32(buf, itemp);
  201789. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201790. png_save_uint_32(buf + 4, itemp);
  201791. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201792. {
  201793. png_warning(png_ptr, "Invalid cHRM red point specified");
  201794. return;
  201795. }
  201796. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201797. png_save_uint_32(buf + 8, itemp);
  201798. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201799. png_save_uint_32(buf + 12, itemp);
  201800. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201801. {
  201802. png_warning(png_ptr, "Invalid cHRM green point specified");
  201803. return;
  201804. }
  201805. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201806. png_save_uint_32(buf + 16, itemp);
  201807. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201808. png_save_uint_32(buf + 20, itemp);
  201809. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201810. {
  201811. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201812. return;
  201813. }
  201814. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201815. png_save_uint_32(buf + 24, itemp);
  201816. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201817. png_save_uint_32(buf + 28, itemp);
  201818. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201819. }
  201820. #endif
  201821. #ifdef PNG_FIXED_POINT_SUPPORTED
  201822. void /* PRIVATE */
  201823. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201824. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201825. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201826. png_fixed_point blue_y)
  201827. {
  201828. #ifdef PNG_USE_LOCAL_ARRAYS
  201829. PNG_cHRM;
  201830. #endif
  201831. png_byte buf[32];
  201832. png_debug(1, "in png_write_cHRM\n");
  201833. /* each value is saved in 1/100,000ths */
  201834. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201835. {
  201836. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201837. #if !defined(PNG_NO_CONSOLE_IO)
  201838. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201839. #endif
  201840. return;
  201841. }
  201842. png_save_uint_32(buf, (png_uint_32)white_x);
  201843. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201844. if (red_x + red_y > 100000L)
  201845. {
  201846. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201847. return;
  201848. }
  201849. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201850. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201851. if (green_x + green_y > 100000L)
  201852. {
  201853. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201854. return;
  201855. }
  201856. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201857. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201858. if (blue_x + blue_y > 100000L)
  201859. {
  201860. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201861. return;
  201862. }
  201863. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201864. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201865. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201866. }
  201867. #endif
  201868. #endif
  201869. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201870. /* write the tRNS chunk */
  201871. void /* PRIVATE */
  201872. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201873. int num_trans, int color_type)
  201874. {
  201875. #ifdef PNG_USE_LOCAL_ARRAYS
  201876. PNG_tRNS;
  201877. #endif
  201878. png_byte buf[6];
  201879. png_debug(1, "in png_write_tRNS\n");
  201880. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201881. {
  201882. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201883. {
  201884. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201885. return;
  201886. }
  201887. /* write the chunk out as it is */
  201888. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201889. }
  201890. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201891. {
  201892. /* one 16 bit value */
  201893. if(tran->gray >= (1 << png_ptr->bit_depth))
  201894. {
  201895. png_warning(png_ptr,
  201896. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201897. return;
  201898. }
  201899. png_save_uint_16(buf, tran->gray);
  201900. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201901. }
  201902. else if (color_type == PNG_COLOR_TYPE_RGB)
  201903. {
  201904. /* three 16 bit values */
  201905. png_save_uint_16(buf, tran->red);
  201906. png_save_uint_16(buf + 2, tran->green);
  201907. png_save_uint_16(buf + 4, tran->blue);
  201908. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201909. {
  201910. png_warning(png_ptr,
  201911. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201912. return;
  201913. }
  201914. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201915. }
  201916. else
  201917. {
  201918. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201919. }
  201920. }
  201921. #endif
  201922. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201923. /* write the background chunk */
  201924. void /* PRIVATE */
  201925. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201926. {
  201927. #ifdef PNG_USE_LOCAL_ARRAYS
  201928. PNG_bKGD;
  201929. #endif
  201930. png_byte buf[6];
  201931. png_debug(1, "in png_write_bKGD\n");
  201932. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201933. {
  201934. if (
  201935. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201936. (png_ptr->num_palette ||
  201937. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201938. #endif
  201939. back->index > png_ptr->num_palette)
  201940. {
  201941. png_warning(png_ptr, "Invalid background palette index");
  201942. return;
  201943. }
  201944. buf[0] = back->index;
  201945. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201946. }
  201947. else if (color_type & PNG_COLOR_MASK_COLOR)
  201948. {
  201949. png_save_uint_16(buf, back->red);
  201950. png_save_uint_16(buf + 2, back->green);
  201951. png_save_uint_16(buf + 4, back->blue);
  201952. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201953. {
  201954. png_warning(png_ptr,
  201955. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201956. return;
  201957. }
  201958. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201959. }
  201960. else
  201961. {
  201962. if(back->gray >= (1 << png_ptr->bit_depth))
  201963. {
  201964. png_warning(png_ptr,
  201965. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201966. return;
  201967. }
  201968. png_save_uint_16(buf, back->gray);
  201969. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201970. }
  201971. }
  201972. #endif
  201973. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201974. /* write the histogram */
  201975. void /* PRIVATE */
  201976. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201977. {
  201978. #ifdef PNG_USE_LOCAL_ARRAYS
  201979. PNG_hIST;
  201980. #endif
  201981. int i;
  201982. png_byte buf[3];
  201983. png_debug(1, "in png_write_hIST\n");
  201984. if (num_hist > (int)png_ptr->num_palette)
  201985. {
  201986. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201987. png_ptr->num_palette);
  201988. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201989. return;
  201990. }
  201991. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201992. for (i = 0; i < num_hist; i++)
  201993. {
  201994. png_save_uint_16(buf, hist[i]);
  201995. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201996. }
  201997. png_write_chunk_end(png_ptr);
  201998. }
  201999. #endif
  202000. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  202001. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  202002. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  202003. * and if invalid, correct the keyword rather than discarding the entire
  202004. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  202005. * length, forbids leading or trailing whitespace, multiple internal spaces,
  202006. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  202007. *
  202008. * The new_key is allocated to hold the corrected keyword and must be freed
  202009. * by the calling routine. This avoids problems with trying to write to
  202010. * static keywords without having to have duplicate copies of the strings.
  202011. */
  202012. png_size_t /* PRIVATE */
  202013. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  202014. {
  202015. png_size_t key_len;
  202016. png_charp kp, dp;
  202017. int kflag;
  202018. int kwarn=0;
  202019. png_debug(1, "in png_check_keyword\n");
  202020. *new_key = NULL;
  202021. if (key == NULL || (key_len = png_strlen(key)) == 0)
  202022. {
  202023. png_warning(png_ptr, "zero length keyword");
  202024. return ((png_size_t)0);
  202025. }
  202026. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  202027. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  202028. if (*new_key == NULL)
  202029. {
  202030. png_warning(png_ptr, "Out of memory while procesing keyword");
  202031. return ((png_size_t)0);
  202032. }
  202033. /* Replace non-printing characters with a blank and print a warning */
  202034. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  202035. {
  202036. if ((png_byte)*kp < 0x20 ||
  202037. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  202038. {
  202039. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  202040. char msg[40];
  202041. png_snprintf(msg, 40,
  202042. "invalid keyword character 0x%02X", (png_byte)*kp);
  202043. png_warning(png_ptr, msg);
  202044. #else
  202045. png_warning(png_ptr, "invalid character in keyword");
  202046. #endif
  202047. *dp = ' ';
  202048. }
  202049. else
  202050. {
  202051. *dp = *kp;
  202052. }
  202053. }
  202054. *dp = '\0';
  202055. /* Remove any trailing white space. */
  202056. kp = *new_key + key_len - 1;
  202057. if (*kp == ' ')
  202058. {
  202059. png_warning(png_ptr, "trailing spaces removed from keyword");
  202060. while (*kp == ' ')
  202061. {
  202062. *(kp--) = '\0';
  202063. key_len--;
  202064. }
  202065. }
  202066. /* Remove any leading white space. */
  202067. kp = *new_key;
  202068. if (*kp == ' ')
  202069. {
  202070. png_warning(png_ptr, "leading spaces removed from keyword");
  202071. while (*kp == ' ')
  202072. {
  202073. kp++;
  202074. key_len--;
  202075. }
  202076. }
  202077. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  202078. /* Remove multiple internal spaces. */
  202079. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  202080. {
  202081. if (*kp == ' ' && kflag == 0)
  202082. {
  202083. *(dp++) = *kp;
  202084. kflag = 1;
  202085. }
  202086. else if (*kp == ' ')
  202087. {
  202088. key_len--;
  202089. kwarn=1;
  202090. }
  202091. else
  202092. {
  202093. *(dp++) = *kp;
  202094. kflag = 0;
  202095. }
  202096. }
  202097. *dp = '\0';
  202098. if(kwarn)
  202099. png_warning(png_ptr, "extra interior spaces removed from keyword");
  202100. if (key_len == 0)
  202101. {
  202102. png_free(png_ptr, *new_key);
  202103. *new_key=NULL;
  202104. png_warning(png_ptr, "Zero length keyword");
  202105. }
  202106. if (key_len > 79)
  202107. {
  202108. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  202109. new_key[79] = '\0';
  202110. key_len = 79;
  202111. }
  202112. return (key_len);
  202113. }
  202114. #endif
  202115. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  202116. /* write a tEXt chunk */
  202117. void /* PRIVATE */
  202118. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202119. png_size_t text_len)
  202120. {
  202121. #ifdef PNG_USE_LOCAL_ARRAYS
  202122. PNG_tEXt;
  202123. #endif
  202124. png_size_t key_len;
  202125. png_charp new_key;
  202126. png_debug(1, "in png_write_tEXt\n");
  202127. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202128. {
  202129. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202130. return;
  202131. }
  202132. if (text == NULL || *text == '\0')
  202133. text_len = 0;
  202134. else
  202135. text_len = png_strlen(text);
  202136. /* make sure we include the 0 after the key */
  202137. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202138. /*
  202139. * We leave it to the application to meet PNG-1.0 requirements on the
  202140. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202141. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202142. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202143. */
  202144. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202145. if (text_len)
  202146. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202147. png_write_chunk_end(png_ptr);
  202148. png_free(png_ptr, new_key);
  202149. }
  202150. #endif
  202151. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202152. /* write a compressed text chunk */
  202153. void /* PRIVATE */
  202154. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202155. png_size_t text_len, int compression)
  202156. {
  202157. #ifdef PNG_USE_LOCAL_ARRAYS
  202158. PNG_zTXt;
  202159. #endif
  202160. png_size_t key_len;
  202161. char buf[1];
  202162. png_charp new_key;
  202163. compression_state comp;
  202164. png_debug(1, "in png_write_zTXt\n");
  202165. comp.num_output_ptr = 0;
  202166. comp.max_output_ptr = 0;
  202167. comp.output_ptr = NULL;
  202168. comp.input = NULL;
  202169. comp.input_len = 0;
  202170. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202171. {
  202172. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202173. return;
  202174. }
  202175. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202176. {
  202177. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202178. png_free(png_ptr, new_key);
  202179. return;
  202180. }
  202181. text_len = png_strlen(text);
  202182. /* compute the compressed data; do it now for the length */
  202183. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202184. &comp);
  202185. /* write start of chunk */
  202186. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202187. (key_len+text_len+2));
  202188. /* write key */
  202189. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202190. png_free(png_ptr, new_key);
  202191. buf[0] = (png_byte)compression;
  202192. /* write compression */
  202193. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202194. /* write the compressed data */
  202195. png_write_compressed_data_out(png_ptr, &comp);
  202196. /* close the chunk */
  202197. png_write_chunk_end(png_ptr);
  202198. }
  202199. #endif
  202200. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202201. /* write an iTXt chunk */
  202202. void /* PRIVATE */
  202203. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202204. png_charp lang, png_charp lang_key, png_charp text)
  202205. {
  202206. #ifdef PNG_USE_LOCAL_ARRAYS
  202207. PNG_iTXt;
  202208. #endif
  202209. png_size_t lang_len, key_len, lang_key_len, text_len;
  202210. png_charp new_lang, new_key;
  202211. png_byte cbuf[2];
  202212. compression_state comp;
  202213. png_debug(1, "in png_write_iTXt\n");
  202214. comp.num_output_ptr = 0;
  202215. comp.max_output_ptr = 0;
  202216. comp.output_ptr = NULL;
  202217. comp.input = NULL;
  202218. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202219. {
  202220. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202221. return;
  202222. }
  202223. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202224. {
  202225. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202226. new_lang = NULL;
  202227. lang_len = 0;
  202228. }
  202229. if (lang_key == NULL)
  202230. lang_key_len = 0;
  202231. else
  202232. lang_key_len = png_strlen(lang_key);
  202233. if (text == NULL)
  202234. text_len = 0;
  202235. else
  202236. text_len = png_strlen(text);
  202237. /* compute the compressed data; do it now for the length */
  202238. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202239. &comp);
  202240. /* make sure we include the compression flag, the compression byte,
  202241. * and the NULs after the key, lang, and lang_key parts */
  202242. png_write_chunk_start(png_ptr, png_iTXt,
  202243. (png_uint_32)(
  202244. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202245. + key_len
  202246. + lang_len
  202247. + lang_key_len
  202248. + text_len));
  202249. /*
  202250. * We leave it to the application to meet PNG-1.0 requirements on the
  202251. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202252. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202253. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202254. */
  202255. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202256. /* set the compression flag */
  202257. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202258. compression == PNG_TEXT_COMPRESSION_NONE)
  202259. cbuf[0] = 0;
  202260. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202261. cbuf[0] = 1;
  202262. /* set the compression method */
  202263. cbuf[1] = 0;
  202264. png_write_chunk_data(png_ptr, cbuf, 2);
  202265. cbuf[0] = 0;
  202266. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202267. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202268. png_write_compressed_data_out(png_ptr, &comp);
  202269. png_write_chunk_end(png_ptr);
  202270. png_free(png_ptr, new_key);
  202271. if (new_lang)
  202272. png_free(png_ptr, new_lang);
  202273. }
  202274. #endif
  202275. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202276. /* write the oFFs chunk */
  202277. void /* PRIVATE */
  202278. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202279. int unit_type)
  202280. {
  202281. #ifdef PNG_USE_LOCAL_ARRAYS
  202282. PNG_oFFs;
  202283. #endif
  202284. png_byte buf[9];
  202285. png_debug(1, "in png_write_oFFs\n");
  202286. if (unit_type >= PNG_OFFSET_LAST)
  202287. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202288. png_save_int_32(buf, x_offset);
  202289. png_save_int_32(buf + 4, y_offset);
  202290. buf[8] = (png_byte)unit_type;
  202291. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202292. }
  202293. #endif
  202294. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202295. /* write the pCAL chunk (described in the PNG extensions document) */
  202296. void /* PRIVATE */
  202297. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202298. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202299. {
  202300. #ifdef PNG_USE_LOCAL_ARRAYS
  202301. PNG_pCAL;
  202302. #endif
  202303. png_size_t purpose_len, units_len, total_len;
  202304. png_uint_32p params_len;
  202305. png_byte buf[10];
  202306. png_charp new_purpose;
  202307. int i;
  202308. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202309. if (type >= PNG_EQUATION_LAST)
  202310. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202311. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202312. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202313. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202314. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202315. total_len = purpose_len + units_len + 10;
  202316. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202317. *png_sizeof(png_uint_32)));
  202318. /* Find the length of each parameter, making sure we don't count the
  202319. null terminator for the last parameter. */
  202320. for (i = 0; i < nparams; i++)
  202321. {
  202322. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202323. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202324. total_len += (png_size_t)params_len[i];
  202325. }
  202326. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202327. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202328. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202329. png_save_int_32(buf, X0);
  202330. png_save_int_32(buf + 4, X1);
  202331. buf[8] = (png_byte)type;
  202332. buf[9] = (png_byte)nparams;
  202333. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202334. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202335. png_free(png_ptr, new_purpose);
  202336. for (i = 0; i < nparams; i++)
  202337. {
  202338. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202339. (png_size_t)params_len[i]);
  202340. }
  202341. png_free(png_ptr, params_len);
  202342. png_write_chunk_end(png_ptr);
  202343. }
  202344. #endif
  202345. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202346. /* write the sCAL chunk */
  202347. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202348. void /* PRIVATE */
  202349. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202350. {
  202351. #ifdef PNG_USE_LOCAL_ARRAYS
  202352. PNG_sCAL;
  202353. #endif
  202354. char buf[64];
  202355. png_size_t total_len;
  202356. png_debug(1, "in png_write_sCAL\n");
  202357. buf[0] = (char)unit;
  202358. #if defined(_WIN32_WCE)
  202359. /* sprintf() function is not supported on WindowsCE */
  202360. {
  202361. wchar_t wc_buf[32];
  202362. size_t wc_len;
  202363. swprintf(wc_buf, TEXT("%12.12e"), width);
  202364. wc_len = wcslen(wc_buf);
  202365. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202366. total_len = wc_len + 2;
  202367. swprintf(wc_buf, TEXT("%12.12e"), height);
  202368. wc_len = wcslen(wc_buf);
  202369. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202370. NULL, NULL);
  202371. total_len += wc_len;
  202372. }
  202373. #else
  202374. png_snprintf(buf + 1, 63, "%12.12e", width);
  202375. total_len = 1 + png_strlen(buf + 1) + 1;
  202376. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202377. total_len += png_strlen(buf + total_len);
  202378. #endif
  202379. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202380. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202381. }
  202382. #else
  202383. #ifdef PNG_FIXED_POINT_SUPPORTED
  202384. void /* PRIVATE */
  202385. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202386. png_charp height)
  202387. {
  202388. #ifdef PNG_USE_LOCAL_ARRAYS
  202389. PNG_sCAL;
  202390. #endif
  202391. png_byte buf[64];
  202392. png_size_t wlen, hlen, total_len;
  202393. png_debug(1, "in png_write_sCAL_s\n");
  202394. wlen = png_strlen(width);
  202395. hlen = png_strlen(height);
  202396. total_len = wlen + hlen + 2;
  202397. if (total_len > 64)
  202398. {
  202399. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202400. return;
  202401. }
  202402. buf[0] = (png_byte)unit;
  202403. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202404. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202405. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202406. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202407. }
  202408. #endif
  202409. #endif
  202410. #endif
  202411. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202412. /* write the pHYs chunk */
  202413. void /* PRIVATE */
  202414. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202415. png_uint_32 y_pixels_per_unit,
  202416. int unit_type)
  202417. {
  202418. #ifdef PNG_USE_LOCAL_ARRAYS
  202419. PNG_pHYs;
  202420. #endif
  202421. png_byte buf[9];
  202422. png_debug(1, "in png_write_pHYs\n");
  202423. if (unit_type >= PNG_RESOLUTION_LAST)
  202424. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202425. png_save_uint_32(buf, x_pixels_per_unit);
  202426. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202427. buf[8] = (png_byte)unit_type;
  202428. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202429. }
  202430. #endif
  202431. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202432. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202433. * or png_convert_from_time_t(), or fill in the structure yourself.
  202434. */
  202435. void /* PRIVATE */
  202436. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202437. {
  202438. #ifdef PNG_USE_LOCAL_ARRAYS
  202439. PNG_tIME;
  202440. #endif
  202441. png_byte buf[7];
  202442. png_debug(1, "in png_write_tIME\n");
  202443. if (mod_time->month > 12 || mod_time->month < 1 ||
  202444. mod_time->day > 31 || mod_time->day < 1 ||
  202445. mod_time->hour > 23 || mod_time->second > 60)
  202446. {
  202447. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202448. return;
  202449. }
  202450. png_save_uint_16(buf, mod_time->year);
  202451. buf[2] = mod_time->month;
  202452. buf[3] = mod_time->day;
  202453. buf[4] = mod_time->hour;
  202454. buf[5] = mod_time->minute;
  202455. buf[6] = mod_time->second;
  202456. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202457. }
  202458. #endif
  202459. /* initializes the row writing capability of libpng */
  202460. void /* PRIVATE */
  202461. png_write_start_row(png_structp png_ptr)
  202462. {
  202463. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202464. #ifdef PNG_USE_LOCAL_ARRAYS
  202465. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202466. /* start of interlace block */
  202467. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202468. /* offset to next interlace block */
  202469. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202470. /* start of interlace block in the y direction */
  202471. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202472. /* offset to next interlace block in the y direction */
  202473. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202474. #endif
  202475. #endif
  202476. png_size_t buf_size;
  202477. png_debug(1, "in png_write_start_row\n");
  202478. buf_size = (png_size_t)(PNG_ROWBYTES(
  202479. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202480. /* set up row buffer */
  202481. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202482. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202483. #ifndef PNG_NO_WRITE_FILTERING
  202484. /* set up filtering buffer, if using this filter */
  202485. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202486. {
  202487. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202488. (png_ptr->rowbytes + 1));
  202489. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202490. }
  202491. /* We only need to keep the previous row if we are using one of these. */
  202492. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202493. {
  202494. /* set up previous row buffer */
  202495. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202496. png_memset(png_ptr->prev_row, 0, buf_size);
  202497. if (png_ptr->do_filter & PNG_FILTER_UP)
  202498. {
  202499. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202500. (png_ptr->rowbytes + 1));
  202501. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202502. }
  202503. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202504. {
  202505. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202506. (png_ptr->rowbytes + 1));
  202507. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202508. }
  202509. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202510. {
  202511. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202512. (png_ptr->rowbytes + 1));
  202513. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202514. }
  202515. #endif /* PNG_NO_WRITE_FILTERING */
  202516. }
  202517. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202518. /* if interlaced, we need to set up width and height of pass */
  202519. if (png_ptr->interlaced)
  202520. {
  202521. if (!(png_ptr->transformations & PNG_INTERLACE))
  202522. {
  202523. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202524. png_pass_ystart[0]) / png_pass_yinc[0];
  202525. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202526. png_pass_start[0]) / png_pass_inc[0];
  202527. }
  202528. else
  202529. {
  202530. png_ptr->num_rows = png_ptr->height;
  202531. png_ptr->usr_width = png_ptr->width;
  202532. }
  202533. }
  202534. else
  202535. #endif
  202536. {
  202537. png_ptr->num_rows = png_ptr->height;
  202538. png_ptr->usr_width = png_ptr->width;
  202539. }
  202540. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202541. png_ptr->zstream.next_out = png_ptr->zbuf;
  202542. }
  202543. /* Internal use only. Called when finished processing a row of data. */
  202544. void /* PRIVATE */
  202545. png_write_finish_row(png_structp png_ptr)
  202546. {
  202547. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202548. #ifdef PNG_USE_LOCAL_ARRAYS
  202549. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202550. /* start of interlace block */
  202551. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202552. /* offset to next interlace block */
  202553. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202554. /* start of interlace block in the y direction */
  202555. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202556. /* offset to next interlace block in the y direction */
  202557. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202558. #endif
  202559. #endif
  202560. int ret;
  202561. png_debug(1, "in png_write_finish_row\n");
  202562. /* next row */
  202563. png_ptr->row_number++;
  202564. /* see if we are done */
  202565. if (png_ptr->row_number < png_ptr->num_rows)
  202566. return;
  202567. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202568. /* if interlaced, go to next pass */
  202569. if (png_ptr->interlaced)
  202570. {
  202571. png_ptr->row_number = 0;
  202572. if (png_ptr->transformations & PNG_INTERLACE)
  202573. {
  202574. png_ptr->pass++;
  202575. }
  202576. else
  202577. {
  202578. /* loop until we find a non-zero width or height pass */
  202579. do
  202580. {
  202581. png_ptr->pass++;
  202582. if (png_ptr->pass >= 7)
  202583. break;
  202584. png_ptr->usr_width = (png_ptr->width +
  202585. png_pass_inc[png_ptr->pass] - 1 -
  202586. png_pass_start[png_ptr->pass]) /
  202587. png_pass_inc[png_ptr->pass];
  202588. png_ptr->num_rows = (png_ptr->height +
  202589. png_pass_yinc[png_ptr->pass] - 1 -
  202590. png_pass_ystart[png_ptr->pass]) /
  202591. png_pass_yinc[png_ptr->pass];
  202592. if (png_ptr->transformations & PNG_INTERLACE)
  202593. break;
  202594. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202595. }
  202596. /* reset the row above the image for the next pass */
  202597. if (png_ptr->pass < 7)
  202598. {
  202599. if (png_ptr->prev_row != NULL)
  202600. png_memset(png_ptr->prev_row, 0,
  202601. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202602. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202603. return;
  202604. }
  202605. }
  202606. #endif
  202607. /* if we get here, we've just written the last row, so we need
  202608. to flush the compressor */
  202609. do
  202610. {
  202611. /* tell the compressor we are done */
  202612. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202613. /* check for an error */
  202614. if (ret == Z_OK)
  202615. {
  202616. /* check to see if we need more room */
  202617. if (!(png_ptr->zstream.avail_out))
  202618. {
  202619. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202620. png_ptr->zstream.next_out = png_ptr->zbuf;
  202621. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202622. }
  202623. }
  202624. else if (ret != Z_STREAM_END)
  202625. {
  202626. if (png_ptr->zstream.msg != NULL)
  202627. png_error(png_ptr, png_ptr->zstream.msg);
  202628. else
  202629. png_error(png_ptr, "zlib error");
  202630. }
  202631. } while (ret != Z_STREAM_END);
  202632. /* write any extra space */
  202633. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202634. {
  202635. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202636. png_ptr->zstream.avail_out);
  202637. }
  202638. deflateReset(&png_ptr->zstream);
  202639. png_ptr->zstream.data_type = Z_BINARY;
  202640. }
  202641. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202642. /* Pick out the correct pixels for the interlace pass.
  202643. * The basic idea here is to go through the row with a source
  202644. * pointer and a destination pointer (sp and dp), and copy the
  202645. * correct pixels for the pass. As the row gets compacted,
  202646. * sp will always be >= dp, so we should never overwrite anything.
  202647. * See the default: case for the easiest code to understand.
  202648. */
  202649. void /* PRIVATE */
  202650. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202651. {
  202652. #ifdef PNG_USE_LOCAL_ARRAYS
  202653. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202654. /* start of interlace block */
  202655. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202656. /* offset to next interlace block */
  202657. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202658. #endif
  202659. png_debug(1, "in png_do_write_interlace\n");
  202660. /* we don't have to do anything on the last pass (6) */
  202661. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202662. if (row != NULL && row_info != NULL && pass < 6)
  202663. #else
  202664. if (pass < 6)
  202665. #endif
  202666. {
  202667. /* each pixel depth is handled separately */
  202668. switch (row_info->pixel_depth)
  202669. {
  202670. case 1:
  202671. {
  202672. png_bytep sp;
  202673. png_bytep dp;
  202674. int shift;
  202675. int d;
  202676. int value;
  202677. png_uint_32 i;
  202678. png_uint_32 row_width = row_info->width;
  202679. dp = row;
  202680. d = 0;
  202681. shift = 7;
  202682. for (i = png_pass_start[pass]; i < row_width;
  202683. i += png_pass_inc[pass])
  202684. {
  202685. sp = row + (png_size_t)(i >> 3);
  202686. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202687. d |= (value << shift);
  202688. if (shift == 0)
  202689. {
  202690. shift = 7;
  202691. *dp++ = (png_byte)d;
  202692. d = 0;
  202693. }
  202694. else
  202695. shift--;
  202696. }
  202697. if (shift != 7)
  202698. *dp = (png_byte)d;
  202699. break;
  202700. }
  202701. case 2:
  202702. {
  202703. png_bytep sp;
  202704. png_bytep dp;
  202705. int shift;
  202706. int d;
  202707. int value;
  202708. png_uint_32 i;
  202709. png_uint_32 row_width = row_info->width;
  202710. dp = row;
  202711. shift = 6;
  202712. d = 0;
  202713. for (i = png_pass_start[pass]; i < row_width;
  202714. i += png_pass_inc[pass])
  202715. {
  202716. sp = row + (png_size_t)(i >> 2);
  202717. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202718. d |= (value << shift);
  202719. if (shift == 0)
  202720. {
  202721. shift = 6;
  202722. *dp++ = (png_byte)d;
  202723. d = 0;
  202724. }
  202725. else
  202726. shift -= 2;
  202727. }
  202728. if (shift != 6)
  202729. *dp = (png_byte)d;
  202730. break;
  202731. }
  202732. case 4:
  202733. {
  202734. png_bytep sp;
  202735. png_bytep dp;
  202736. int shift;
  202737. int d;
  202738. int value;
  202739. png_uint_32 i;
  202740. png_uint_32 row_width = row_info->width;
  202741. dp = row;
  202742. shift = 4;
  202743. d = 0;
  202744. for (i = png_pass_start[pass]; i < row_width;
  202745. i += png_pass_inc[pass])
  202746. {
  202747. sp = row + (png_size_t)(i >> 1);
  202748. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202749. d |= (value << shift);
  202750. if (shift == 0)
  202751. {
  202752. shift = 4;
  202753. *dp++ = (png_byte)d;
  202754. d = 0;
  202755. }
  202756. else
  202757. shift -= 4;
  202758. }
  202759. if (shift != 4)
  202760. *dp = (png_byte)d;
  202761. break;
  202762. }
  202763. default:
  202764. {
  202765. png_bytep sp;
  202766. png_bytep dp;
  202767. png_uint_32 i;
  202768. png_uint_32 row_width = row_info->width;
  202769. png_size_t pixel_bytes;
  202770. /* start at the beginning */
  202771. dp = row;
  202772. /* find out how many bytes each pixel takes up */
  202773. pixel_bytes = (row_info->pixel_depth >> 3);
  202774. /* loop through the row, only looking at the pixels that
  202775. matter */
  202776. for (i = png_pass_start[pass]; i < row_width;
  202777. i += png_pass_inc[pass])
  202778. {
  202779. /* find out where the original pixel is */
  202780. sp = row + (png_size_t)i * pixel_bytes;
  202781. /* move the pixel */
  202782. if (dp != sp)
  202783. png_memcpy(dp, sp, pixel_bytes);
  202784. /* next pixel */
  202785. dp += pixel_bytes;
  202786. }
  202787. break;
  202788. }
  202789. }
  202790. /* set new row width */
  202791. row_info->width = (row_info->width +
  202792. png_pass_inc[pass] - 1 -
  202793. png_pass_start[pass]) /
  202794. png_pass_inc[pass];
  202795. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202796. row_info->width);
  202797. }
  202798. }
  202799. #endif
  202800. /* This filters the row, chooses which filter to use, if it has not already
  202801. * been specified by the application, and then writes the row out with the
  202802. * chosen filter.
  202803. */
  202804. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202805. #define PNG_HISHIFT 10
  202806. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202807. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202808. void /* PRIVATE */
  202809. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202810. {
  202811. png_bytep best_row;
  202812. #ifndef PNG_NO_WRITE_FILTER
  202813. png_bytep prev_row, row_buf;
  202814. png_uint_32 mins, bpp;
  202815. png_byte filter_to_do = png_ptr->do_filter;
  202816. png_uint_32 row_bytes = row_info->rowbytes;
  202817. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202818. int num_p_filters = (int)png_ptr->num_prev_filters;
  202819. #endif
  202820. png_debug(1, "in png_write_find_filter\n");
  202821. /* find out how many bytes offset each pixel is */
  202822. bpp = (row_info->pixel_depth + 7) >> 3;
  202823. prev_row = png_ptr->prev_row;
  202824. #endif
  202825. best_row = png_ptr->row_buf;
  202826. #ifndef PNG_NO_WRITE_FILTER
  202827. row_buf = best_row;
  202828. mins = PNG_MAXSUM;
  202829. /* The prediction method we use is to find which method provides the
  202830. * smallest value when summing the absolute values of the distances
  202831. * from zero, using anything >= 128 as negative numbers. This is known
  202832. * as the "minimum sum of absolute differences" heuristic. Other
  202833. * heuristics are the "weighted minimum sum of absolute differences"
  202834. * (experimental and can in theory improve compression), and the "zlib
  202835. * predictive" method (not implemented yet), which does test compressions
  202836. * of lines using different filter methods, and then chooses the
  202837. * (series of) filter(s) that give minimum compressed data size (VERY
  202838. * computationally expensive).
  202839. *
  202840. * GRR 980525: consider also
  202841. * (1) minimum sum of absolute differences from running average (i.e.,
  202842. * keep running sum of non-absolute differences & count of bytes)
  202843. * [track dispersion, too? restart average if dispersion too large?]
  202844. * (1b) minimum sum of absolute differences from sliding average, probably
  202845. * with window size <= deflate window (usually 32K)
  202846. * (2) minimum sum of squared differences from zero or running average
  202847. * (i.e., ~ root-mean-square approach)
  202848. */
  202849. /* We don't need to test the 'no filter' case if this is the only filter
  202850. * that has been chosen, as it doesn't actually do anything to the data.
  202851. */
  202852. if ((filter_to_do & PNG_FILTER_NONE) &&
  202853. filter_to_do != PNG_FILTER_NONE)
  202854. {
  202855. png_bytep rp;
  202856. png_uint_32 sum = 0;
  202857. png_uint_32 i;
  202858. int v;
  202859. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202860. {
  202861. v = *rp;
  202862. sum += (v < 128) ? v : 256 - v;
  202863. }
  202864. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202865. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202866. {
  202867. png_uint_32 sumhi, sumlo;
  202868. int j;
  202869. sumlo = sum & PNG_LOMASK;
  202870. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202871. /* Reduce the sum if we match any of the previous rows */
  202872. for (j = 0; j < num_p_filters; j++)
  202873. {
  202874. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202875. {
  202876. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202877. PNG_WEIGHT_SHIFT;
  202878. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202879. PNG_WEIGHT_SHIFT;
  202880. }
  202881. }
  202882. /* Factor in the cost of this filter (this is here for completeness,
  202883. * but it makes no sense to have a "cost" for the NONE filter, as
  202884. * it has the minimum possible computational cost - none).
  202885. */
  202886. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202887. PNG_COST_SHIFT;
  202888. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202889. PNG_COST_SHIFT;
  202890. if (sumhi > PNG_HIMASK)
  202891. sum = PNG_MAXSUM;
  202892. else
  202893. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202894. }
  202895. #endif
  202896. mins = sum;
  202897. }
  202898. /* sub filter */
  202899. if (filter_to_do == PNG_FILTER_SUB)
  202900. /* it's the only filter so no testing is needed */
  202901. {
  202902. png_bytep rp, lp, dp;
  202903. png_uint_32 i;
  202904. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202905. i++, rp++, dp++)
  202906. {
  202907. *dp = *rp;
  202908. }
  202909. for (lp = row_buf + 1; i < row_bytes;
  202910. i++, rp++, lp++, dp++)
  202911. {
  202912. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202913. }
  202914. best_row = png_ptr->sub_row;
  202915. }
  202916. else if (filter_to_do & PNG_FILTER_SUB)
  202917. {
  202918. png_bytep rp, dp, lp;
  202919. png_uint_32 sum = 0, lmins = mins;
  202920. png_uint_32 i;
  202921. int v;
  202922. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202923. /* We temporarily increase the "minimum sum" by the factor we
  202924. * would reduce the sum of this filter, so that we can do the
  202925. * early exit comparison without scaling the sum each time.
  202926. */
  202927. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202928. {
  202929. int j;
  202930. png_uint_32 lmhi, lmlo;
  202931. lmlo = lmins & PNG_LOMASK;
  202932. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202933. for (j = 0; j < num_p_filters; j++)
  202934. {
  202935. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202936. {
  202937. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202938. PNG_WEIGHT_SHIFT;
  202939. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202940. PNG_WEIGHT_SHIFT;
  202941. }
  202942. }
  202943. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202944. PNG_COST_SHIFT;
  202945. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202946. PNG_COST_SHIFT;
  202947. if (lmhi > PNG_HIMASK)
  202948. lmins = PNG_MAXSUM;
  202949. else
  202950. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202951. }
  202952. #endif
  202953. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202954. i++, rp++, dp++)
  202955. {
  202956. v = *dp = *rp;
  202957. sum += (v < 128) ? v : 256 - v;
  202958. }
  202959. for (lp = row_buf + 1; i < row_bytes;
  202960. i++, rp++, lp++, dp++)
  202961. {
  202962. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202963. sum += (v < 128) ? v : 256 - v;
  202964. if (sum > lmins) /* We are already worse, don't continue. */
  202965. break;
  202966. }
  202967. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202968. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202969. {
  202970. int j;
  202971. png_uint_32 sumhi, sumlo;
  202972. sumlo = sum & PNG_LOMASK;
  202973. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202974. for (j = 0; j < num_p_filters; j++)
  202975. {
  202976. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202977. {
  202978. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202979. PNG_WEIGHT_SHIFT;
  202980. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202981. PNG_WEIGHT_SHIFT;
  202982. }
  202983. }
  202984. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202985. PNG_COST_SHIFT;
  202986. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202987. PNG_COST_SHIFT;
  202988. if (sumhi > PNG_HIMASK)
  202989. sum = PNG_MAXSUM;
  202990. else
  202991. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202992. }
  202993. #endif
  202994. if (sum < mins)
  202995. {
  202996. mins = sum;
  202997. best_row = png_ptr->sub_row;
  202998. }
  202999. }
  203000. /* up filter */
  203001. if (filter_to_do == PNG_FILTER_UP)
  203002. {
  203003. png_bytep rp, dp, pp;
  203004. png_uint_32 i;
  203005. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  203006. pp = prev_row + 1; i < row_bytes;
  203007. i++, rp++, pp++, dp++)
  203008. {
  203009. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  203010. }
  203011. best_row = png_ptr->up_row;
  203012. }
  203013. else if (filter_to_do & PNG_FILTER_UP)
  203014. {
  203015. png_bytep rp, dp, pp;
  203016. png_uint_32 sum = 0, lmins = mins;
  203017. png_uint_32 i;
  203018. int v;
  203019. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203020. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203021. {
  203022. int j;
  203023. png_uint_32 lmhi, lmlo;
  203024. lmlo = lmins & PNG_LOMASK;
  203025. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203026. for (j = 0; j < num_p_filters; j++)
  203027. {
  203028. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  203029. {
  203030. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203031. PNG_WEIGHT_SHIFT;
  203032. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203033. PNG_WEIGHT_SHIFT;
  203034. }
  203035. }
  203036. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  203037. PNG_COST_SHIFT;
  203038. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  203039. PNG_COST_SHIFT;
  203040. if (lmhi > PNG_HIMASK)
  203041. lmins = PNG_MAXSUM;
  203042. else
  203043. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203044. }
  203045. #endif
  203046. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  203047. pp = prev_row + 1; i < row_bytes; i++)
  203048. {
  203049. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203050. sum += (v < 128) ? v : 256 - v;
  203051. if (sum > lmins) /* We are already worse, don't continue. */
  203052. break;
  203053. }
  203054. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203055. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203056. {
  203057. int j;
  203058. png_uint_32 sumhi, sumlo;
  203059. sumlo = sum & PNG_LOMASK;
  203060. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203061. for (j = 0; j < num_p_filters; j++)
  203062. {
  203063. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  203064. {
  203065. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203066. PNG_WEIGHT_SHIFT;
  203067. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203068. PNG_WEIGHT_SHIFT;
  203069. }
  203070. }
  203071. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  203072. PNG_COST_SHIFT;
  203073. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  203074. PNG_COST_SHIFT;
  203075. if (sumhi > PNG_HIMASK)
  203076. sum = PNG_MAXSUM;
  203077. else
  203078. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203079. }
  203080. #endif
  203081. if (sum < mins)
  203082. {
  203083. mins = sum;
  203084. best_row = png_ptr->up_row;
  203085. }
  203086. }
  203087. /* avg filter */
  203088. if (filter_to_do == PNG_FILTER_AVG)
  203089. {
  203090. png_bytep rp, dp, pp, lp;
  203091. png_uint_32 i;
  203092. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203093. pp = prev_row + 1; i < bpp; i++)
  203094. {
  203095. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203096. }
  203097. for (lp = row_buf + 1; i < row_bytes; i++)
  203098. {
  203099. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  203100. & 0xff);
  203101. }
  203102. best_row = png_ptr->avg_row;
  203103. }
  203104. else if (filter_to_do & PNG_FILTER_AVG)
  203105. {
  203106. png_bytep rp, dp, pp, lp;
  203107. png_uint_32 sum = 0, lmins = mins;
  203108. png_uint_32 i;
  203109. int v;
  203110. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203111. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203112. {
  203113. int j;
  203114. png_uint_32 lmhi, lmlo;
  203115. lmlo = lmins & PNG_LOMASK;
  203116. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203117. for (j = 0; j < num_p_filters; j++)
  203118. {
  203119. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203120. {
  203121. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203122. PNG_WEIGHT_SHIFT;
  203123. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203124. PNG_WEIGHT_SHIFT;
  203125. }
  203126. }
  203127. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203128. PNG_COST_SHIFT;
  203129. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203130. PNG_COST_SHIFT;
  203131. if (lmhi > PNG_HIMASK)
  203132. lmins = PNG_MAXSUM;
  203133. else
  203134. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203135. }
  203136. #endif
  203137. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203138. pp = prev_row + 1; i < bpp; i++)
  203139. {
  203140. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203141. sum += (v < 128) ? v : 256 - v;
  203142. }
  203143. for (lp = row_buf + 1; i < row_bytes; i++)
  203144. {
  203145. v = *dp++ =
  203146. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203147. sum += (v < 128) ? v : 256 - v;
  203148. if (sum > lmins) /* We are already worse, don't continue. */
  203149. break;
  203150. }
  203151. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203152. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203153. {
  203154. int j;
  203155. png_uint_32 sumhi, sumlo;
  203156. sumlo = sum & PNG_LOMASK;
  203157. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203158. for (j = 0; j < num_p_filters; j++)
  203159. {
  203160. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203161. {
  203162. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203163. PNG_WEIGHT_SHIFT;
  203164. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203165. PNG_WEIGHT_SHIFT;
  203166. }
  203167. }
  203168. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203169. PNG_COST_SHIFT;
  203170. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203171. PNG_COST_SHIFT;
  203172. if (sumhi > PNG_HIMASK)
  203173. sum = PNG_MAXSUM;
  203174. else
  203175. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203176. }
  203177. #endif
  203178. if (sum < mins)
  203179. {
  203180. mins = sum;
  203181. best_row = png_ptr->avg_row;
  203182. }
  203183. }
  203184. /* Paeth filter */
  203185. if (filter_to_do == PNG_FILTER_PAETH)
  203186. {
  203187. png_bytep rp, dp, pp, cp, lp;
  203188. png_uint_32 i;
  203189. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203190. pp = prev_row + 1; i < bpp; i++)
  203191. {
  203192. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203193. }
  203194. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203195. {
  203196. int a, b, c, pa, pb, pc, p;
  203197. b = *pp++;
  203198. c = *cp++;
  203199. a = *lp++;
  203200. p = b - c;
  203201. pc = a - c;
  203202. #ifdef PNG_USE_ABS
  203203. pa = abs(p);
  203204. pb = abs(pc);
  203205. pc = abs(p + pc);
  203206. #else
  203207. pa = p < 0 ? -p : p;
  203208. pb = pc < 0 ? -pc : pc;
  203209. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203210. #endif
  203211. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203212. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203213. }
  203214. best_row = png_ptr->paeth_row;
  203215. }
  203216. else if (filter_to_do & PNG_FILTER_PAETH)
  203217. {
  203218. png_bytep rp, dp, pp, cp, lp;
  203219. png_uint_32 sum = 0, lmins = mins;
  203220. png_uint_32 i;
  203221. int v;
  203222. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203223. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203224. {
  203225. int j;
  203226. png_uint_32 lmhi, lmlo;
  203227. lmlo = lmins & PNG_LOMASK;
  203228. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203229. for (j = 0; j < num_p_filters; j++)
  203230. {
  203231. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203232. {
  203233. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203234. PNG_WEIGHT_SHIFT;
  203235. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203236. PNG_WEIGHT_SHIFT;
  203237. }
  203238. }
  203239. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203240. PNG_COST_SHIFT;
  203241. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203242. PNG_COST_SHIFT;
  203243. if (lmhi > PNG_HIMASK)
  203244. lmins = PNG_MAXSUM;
  203245. else
  203246. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203247. }
  203248. #endif
  203249. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203250. pp = prev_row + 1; i < bpp; i++)
  203251. {
  203252. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203253. sum += (v < 128) ? v : 256 - v;
  203254. }
  203255. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203256. {
  203257. int a, b, c, pa, pb, pc, p;
  203258. b = *pp++;
  203259. c = *cp++;
  203260. a = *lp++;
  203261. #ifndef PNG_SLOW_PAETH
  203262. p = b - c;
  203263. pc = a - c;
  203264. #ifdef PNG_USE_ABS
  203265. pa = abs(p);
  203266. pb = abs(pc);
  203267. pc = abs(p + pc);
  203268. #else
  203269. pa = p < 0 ? -p : p;
  203270. pb = pc < 0 ? -pc : pc;
  203271. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203272. #endif
  203273. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203274. #else /* PNG_SLOW_PAETH */
  203275. p = a + b - c;
  203276. pa = abs(p - a);
  203277. pb = abs(p - b);
  203278. pc = abs(p - c);
  203279. if (pa <= pb && pa <= pc)
  203280. p = a;
  203281. else if (pb <= pc)
  203282. p = b;
  203283. else
  203284. p = c;
  203285. #endif /* PNG_SLOW_PAETH */
  203286. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203287. sum += (v < 128) ? v : 256 - v;
  203288. if (sum > lmins) /* We are already worse, don't continue. */
  203289. break;
  203290. }
  203291. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203292. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203293. {
  203294. int j;
  203295. png_uint_32 sumhi, sumlo;
  203296. sumlo = sum & PNG_LOMASK;
  203297. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203298. for (j = 0; j < num_p_filters; j++)
  203299. {
  203300. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203301. {
  203302. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203303. PNG_WEIGHT_SHIFT;
  203304. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203305. PNG_WEIGHT_SHIFT;
  203306. }
  203307. }
  203308. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203309. PNG_COST_SHIFT;
  203310. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203311. PNG_COST_SHIFT;
  203312. if (sumhi > PNG_HIMASK)
  203313. sum = PNG_MAXSUM;
  203314. else
  203315. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203316. }
  203317. #endif
  203318. if (sum < mins)
  203319. {
  203320. best_row = png_ptr->paeth_row;
  203321. }
  203322. }
  203323. #endif /* PNG_NO_WRITE_FILTER */
  203324. /* Do the actual writing of the filtered row data from the chosen filter. */
  203325. png_write_filtered_row(png_ptr, best_row);
  203326. #ifndef PNG_NO_WRITE_FILTER
  203327. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203328. /* Save the type of filter we picked this time for future calculations */
  203329. if (png_ptr->num_prev_filters > 0)
  203330. {
  203331. int j;
  203332. for (j = 1; j < num_p_filters; j++)
  203333. {
  203334. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203335. }
  203336. png_ptr->prev_filters[j] = best_row[0];
  203337. }
  203338. #endif
  203339. #endif /* PNG_NO_WRITE_FILTER */
  203340. }
  203341. /* Do the actual writing of a previously filtered row. */
  203342. void /* PRIVATE */
  203343. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203344. {
  203345. png_debug(1, "in png_write_filtered_row\n");
  203346. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203347. /* set up the zlib input buffer */
  203348. png_ptr->zstream.next_in = filtered_row;
  203349. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203350. /* repeat until we have compressed all the data */
  203351. do
  203352. {
  203353. int ret; /* return of zlib */
  203354. /* compress the data */
  203355. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203356. /* check for compression errors */
  203357. if (ret != Z_OK)
  203358. {
  203359. if (png_ptr->zstream.msg != NULL)
  203360. png_error(png_ptr, png_ptr->zstream.msg);
  203361. else
  203362. png_error(png_ptr, "zlib error");
  203363. }
  203364. /* see if it is time to write another IDAT */
  203365. if (!(png_ptr->zstream.avail_out))
  203366. {
  203367. /* write the IDAT and reset the zlib output buffer */
  203368. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203369. png_ptr->zstream.next_out = png_ptr->zbuf;
  203370. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203371. }
  203372. /* repeat until all data has been compressed */
  203373. } while (png_ptr->zstream.avail_in);
  203374. /* swap the current and previous rows */
  203375. if (png_ptr->prev_row != NULL)
  203376. {
  203377. png_bytep tptr;
  203378. tptr = png_ptr->prev_row;
  203379. png_ptr->prev_row = png_ptr->row_buf;
  203380. png_ptr->row_buf = tptr;
  203381. }
  203382. /* finish row - updates counters and flushes zlib if last row */
  203383. png_write_finish_row(png_ptr);
  203384. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203385. png_ptr->flush_rows++;
  203386. if (png_ptr->flush_dist > 0 &&
  203387. png_ptr->flush_rows >= png_ptr->flush_dist)
  203388. {
  203389. png_write_flush(png_ptr);
  203390. }
  203391. #endif
  203392. }
  203393. #endif /* PNG_WRITE_SUPPORTED */
  203394. /*** End of inlined file: pngwutil.c ***/
  203395. #else
  203396. extern "C"
  203397. {
  203398. #include <png.h>
  203399. #include <pngconf.h>
  203400. }
  203401. #endif
  203402. }
  203403. #undef max
  203404. #undef min
  203405. #if JUCE_MSVC
  203406. #pragma warning (pop)
  203407. #endif
  203408. BEGIN_JUCE_NAMESPACE
  203409. using ::calloc;
  203410. using ::malloc;
  203411. using ::free;
  203412. namespace PNGHelpers
  203413. {
  203414. using namespace pnglibNamespace;
  203415. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  203416. {
  203417. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203418. }
  203419. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203420. {
  203421. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203422. }
  203423. struct PNGErrorStruct {};
  203424. static void errorCallback (png_structp, png_const_charp)
  203425. {
  203426. throw PNGErrorStruct();
  203427. }
  203428. }
  203429. PNGImageFormat::PNGImageFormat() {}
  203430. PNGImageFormat::~PNGImageFormat() {}
  203431. const String PNGImageFormat::getFormatName()
  203432. {
  203433. return "PNG";
  203434. }
  203435. bool PNGImageFormat::canUnderstand (InputStream& in)
  203436. {
  203437. const int bytesNeeded = 4;
  203438. char header [bytesNeeded];
  203439. return in.read (header, bytesNeeded) == bytesNeeded
  203440. && header[1] == 'P'
  203441. && header[2] == 'N'
  203442. && header[3] == 'G';
  203443. }
  203444. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203445. const Image juce_loadWithCoreImage (InputStream& input);
  203446. #endif
  203447. const Image PNGImageFormat::decodeImage (InputStream& in)
  203448. {
  203449. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203450. return juce_loadWithCoreImage (in);
  203451. #else
  203452. using namespace pnglibNamespace;
  203453. Image image;
  203454. png_structp pngReadStruct;
  203455. png_infop pngInfoStruct;
  203456. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203457. if (pngReadStruct != 0)
  203458. {
  203459. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203460. if (pngInfoStruct == 0)
  203461. {
  203462. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203463. return Image::null;
  203464. }
  203465. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203466. // read the header..
  203467. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203468. png_uint_32 width, height;
  203469. int bitDepth, colorType, interlaceType;
  203470. png_read_info (pngReadStruct, pngInfoStruct);
  203471. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203472. &width, &height,
  203473. &bitDepth, &colorType,
  203474. &interlaceType, 0, 0);
  203475. if (bitDepth == 16)
  203476. png_set_strip_16 (pngReadStruct);
  203477. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203478. png_set_expand (pngReadStruct);
  203479. if (bitDepth < 8)
  203480. png_set_expand (pngReadStruct);
  203481. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203482. png_set_expand (pngReadStruct);
  203483. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203484. png_set_gray_to_rgb (pngReadStruct);
  203485. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203486. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203487. || pngInfoStruct->num_trans > 0;
  203488. // Load the image into a temp buffer in the pnglib format..
  203489. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203490. {
  203491. HeapBlock <png_bytep> rows (height);
  203492. for (int y = (int) height; --y >= 0;)
  203493. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203494. png_read_image (pngReadStruct, rows);
  203495. png_read_end (pngReadStruct, pngInfoStruct);
  203496. }
  203497. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203498. // now convert the data to a juce image format..
  203499. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203500. (int) width, (int) height, hasAlphaChan);
  203501. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203502. const Image::BitmapData destData (image, true);
  203503. uint8* srcRow = tempBuffer;
  203504. uint8* destRow = destData.data;
  203505. for (int y = 0; y < (int) height; ++y)
  203506. {
  203507. const uint8* src = srcRow;
  203508. srcRow += (width << 2);
  203509. uint8* dest = destRow;
  203510. destRow += destData.lineStride;
  203511. if (hasAlphaChan)
  203512. {
  203513. for (int i = (int) width; --i >= 0;)
  203514. {
  203515. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203516. ((PixelARGB*) dest)->premultiply();
  203517. dest += destData.pixelStride;
  203518. src += 4;
  203519. }
  203520. }
  203521. else
  203522. {
  203523. for (int i = (int) width; --i >= 0;)
  203524. {
  203525. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203526. dest += destData.pixelStride;
  203527. src += 4;
  203528. }
  203529. }
  203530. }
  203531. }
  203532. return image;
  203533. #endif
  203534. }
  203535. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203536. {
  203537. using namespace pnglibNamespace;
  203538. const int width = image.getWidth();
  203539. const int height = image.getHeight();
  203540. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203541. if (pngWriteStruct == 0)
  203542. return false;
  203543. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203544. if (pngInfoStruct == 0)
  203545. {
  203546. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203547. return false;
  203548. }
  203549. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203550. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203551. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203552. : PNG_COLOR_TYPE_RGB,
  203553. PNG_INTERLACE_NONE,
  203554. PNG_COMPRESSION_TYPE_BASE,
  203555. PNG_FILTER_TYPE_BASE);
  203556. HeapBlock <uint8> rowData (width * 4);
  203557. png_color_8 sig_bit;
  203558. sig_bit.red = 8;
  203559. sig_bit.green = 8;
  203560. sig_bit.blue = 8;
  203561. sig_bit.alpha = 8;
  203562. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203563. png_write_info (pngWriteStruct, pngInfoStruct);
  203564. png_set_shift (pngWriteStruct, &sig_bit);
  203565. png_set_packing (pngWriteStruct);
  203566. const Image::BitmapData srcData (image, false);
  203567. for (int y = 0; y < height; ++y)
  203568. {
  203569. uint8* dst = rowData;
  203570. const uint8* src = srcData.getLinePointer (y);
  203571. if (image.hasAlphaChannel())
  203572. {
  203573. for (int i = width; --i >= 0;)
  203574. {
  203575. PixelARGB p (*(const PixelARGB*) src);
  203576. p.unpremultiply();
  203577. *dst++ = p.getRed();
  203578. *dst++ = p.getGreen();
  203579. *dst++ = p.getBlue();
  203580. *dst++ = p.getAlpha();
  203581. src += srcData.pixelStride;
  203582. }
  203583. }
  203584. else
  203585. {
  203586. for (int i = width; --i >= 0;)
  203587. {
  203588. *dst++ = ((const PixelRGB*) src)->getRed();
  203589. *dst++ = ((const PixelRGB*) src)->getGreen();
  203590. *dst++ = ((const PixelRGB*) src)->getBlue();
  203591. src += srcData.pixelStride;
  203592. }
  203593. }
  203594. png_write_rows (pngWriteStruct, &rowData, 1);
  203595. }
  203596. png_write_end (pngWriteStruct, pngInfoStruct);
  203597. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203598. out.flush();
  203599. return true;
  203600. }
  203601. END_JUCE_NAMESPACE
  203602. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203603. #endif
  203604. //==============================================================================
  203605. #if JUCE_BUILD_NATIVE
  203606. #if JUCE_WINDOWS
  203607. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203608. /*
  203609. This file wraps together all the win32-specific code, so that
  203610. we can include all the native headers just once, and compile all our
  203611. platform-specific stuff in one big lump, keeping it out of the way of
  203612. the rest of the codebase.
  203613. */
  203614. #if JUCE_WINDOWS
  203615. BEGIN_JUCE_NAMESPACE
  203616. #define JUCE_INCLUDED_FILE 1
  203617. // Now include the actual code files..
  203618. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203619. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203620. // compiled on its own).
  203621. #if JUCE_INCLUDED_FILE
  203622. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203623. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203624. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203625. #ifndef DOXYGEN
  203626. // use with DynamicLibraryLoader to simplify importing functions
  203627. //
  203628. // functionName: function to import
  203629. // localFunctionName: name you want to use to actually call it (must be different)
  203630. // returnType: the return type
  203631. // object: the DynamicLibraryLoader to use
  203632. // params: list of params (bracketed)
  203633. //
  203634. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203635. typedef returnType (WINAPI *type##localFunctionName) params; \
  203636. type##localFunctionName localFunctionName \
  203637. = (type##localFunctionName)object.findProcAddress (#functionName);
  203638. // loads and unloads a DLL automatically
  203639. class JUCE_API DynamicLibraryLoader
  203640. {
  203641. public:
  203642. DynamicLibraryLoader (const String& name);
  203643. ~DynamicLibraryLoader();
  203644. void* findProcAddress (const String& functionName);
  203645. private:
  203646. void* libHandle;
  203647. };
  203648. #endif
  203649. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203650. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203651. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203652. {
  203653. libHandle = LoadLibrary (name);
  203654. }
  203655. DynamicLibraryLoader::~DynamicLibraryLoader()
  203656. {
  203657. FreeLibrary ((HMODULE) libHandle);
  203658. }
  203659. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203660. {
  203661. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  203662. }
  203663. #endif
  203664. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203665. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203666. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203667. // compiled on its own).
  203668. #if JUCE_INCLUDED_FILE
  203669. extern void juce_initialiseThreadEvents();
  203670. void Logger::outputDebugString (const String& text)
  203671. {
  203672. OutputDebugString (text + "\n");
  203673. }
  203674. static int64 hiResTicksPerSecond;
  203675. static double hiResTicksScaleFactor;
  203676. #if JUCE_USE_INTRINSICS
  203677. // CPU info functions using intrinsics...
  203678. #pragma intrinsic (__cpuid)
  203679. #pragma intrinsic (__rdtsc)
  203680. const String SystemStats::getCpuVendor()
  203681. {
  203682. int info [4];
  203683. __cpuid (info, 0);
  203684. char v [12];
  203685. memcpy (v, info + 1, 4);
  203686. memcpy (v + 4, info + 3, 4);
  203687. memcpy (v + 8, info + 2, 4);
  203688. return String (v, 12);
  203689. }
  203690. #else
  203691. // CPU info functions using old fashioned inline asm...
  203692. static void juce_getCpuVendor (char* const v)
  203693. {
  203694. int vendor[4];
  203695. zeromem (vendor, 16);
  203696. #ifdef JUCE_64BIT
  203697. #else
  203698. #ifndef __MINGW32__
  203699. __try
  203700. #endif
  203701. {
  203702. #if JUCE_GCC
  203703. unsigned int dummy = 0;
  203704. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203705. #else
  203706. __asm
  203707. {
  203708. mov eax, 0
  203709. cpuid
  203710. mov [vendor], ebx
  203711. mov [vendor + 4], edx
  203712. mov [vendor + 8], ecx
  203713. }
  203714. #endif
  203715. }
  203716. #ifndef __MINGW32__
  203717. __except (EXCEPTION_EXECUTE_HANDLER)
  203718. {
  203719. *v = 0;
  203720. }
  203721. #endif
  203722. #endif
  203723. memcpy (v, vendor, 16);
  203724. }
  203725. const String SystemStats::getCpuVendor()
  203726. {
  203727. char v [16];
  203728. juce_getCpuVendor (v);
  203729. return String (v, 16);
  203730. }
  203731. #endif
  203732. void SystemStats::initialiseStats()
  203733. {
  203734. juce_initialiseThreadEvents();
  203735. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203736. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203737. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203738. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203739. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203740. #else
  203741. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203742. #endif
  203743. {
  203744. SYSTEM_INFO systemInfo;
  203745. GetSystemInfo (&systemInfo);
  203746. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203747. }
  203748. LARGE_INTEGER f;
  203749. QueryPerformanceFrequency (&f);
  203750. hiResTicksPerSecond = f.QuadPart;
  203751. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203752. String s (SystemStats::getJUCEVersion());
  203753. const MMRESULT res = timeBeginPeriod (1);
  203754. (void) res;
  203755. jassert (res == TIMERR_NOERROR);
  203756. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203757. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203758. #endif
  203759. }
  203760. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203761. {
  203762. OSVERSIONINFO info;
  203763. info.dwOSVersionInfoSize = sizeof (info);
  203764. GetVersionEx (&info);
  203765. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203766. {
  203767. switch (info.dwMajorVersion)
  203768. {
  203769. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203770. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203771. default: jassertfalse; break; // !! not a supported OS!
  203772. }
  203773. }
  203774. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203775. {
  203776. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203777. return Win98;
  203778. }
  203779. return UnknownOS;
  203780. }
  203781. const String SystemStats::getOperatingSystemName()
  203782. {
  203783. const char* name = "Unknown OS";
  203784. switch (getOperatingSystemType())
  203785. {
  203786. case Windows7: name = "Windows 7"; break;
  203787. case WinVista: name = "Windows Vista"; break;
  203788. case WinXP: name = "Windows XP"; break;
  203789. case Win2000: name = "Windows 2000"; break;
  203790. case Win98: name = "Windows 98"; break;
  203791. default: jassertfalse; break; // !! new type of OS?
  203792. }
  203793. return name;
  203794. }
  203795. bool SystemStats::isOperatingSystem64Bit()
  203796. {
  203797. #ifdef _WIN64
  203798. return true;
  203799. #else
  203800. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203801. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203802. BOOL isWow64 = FALSE;
  203803. return (fnIsWow64Process != 0)
  203804. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203805. && (isWow64 != FALSE);
  203806. #endif
  203807. }
  203808. int SystemStats::getMemorySizeInMegabytes()
  203809. {
  203810. MEMORYSTATUSEX mem;
  203811. mem.dwLength = sizeof (mem);
  203812. GlobalMemoryStatusEx (&mem);
  203813. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203814. }
  203815. uint32 juce_millisecondsSinceStartup() throw()
  203816. {
  203817. return (uint32) timeGetTime();
  203818. }
  203819. int64 Time::getHighResolutionTicks() throw()
  203820. {
  203821. LARGE_INTEGER ticks;
  203822. QueryPerformanceCounter (&ticks);
  203823. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203824. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203825. // fix for a very obscure PCI hardware bug that can make the counter
  203826. // sometimes jump forwards by a few seconds..
  203827. static int64 hiResTicksOffset = 0;
  203828. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203829. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203830. hiResTicksOffset = newOffset;
  203831. return ticks.QuadPart + hiResTicksOffset;
  203832. }
  203833. double Time::getMillisecondCounterHiRes() throw()
  203834. {
  203835. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203836. }
  203837. int64 Time::getHighResolutionTicksPerSecond() throw()
  203838. {
  203839. return hiResTicksPerSecond;
  203840. }
  203841. static int64 juce_getClockCycleCounter() throw()
  203842. {
  203843. #if JUCE_USE_INTRINSICS
  203844. // MS intrinsics version...
  203845. return __rdtsc();
  203846. #elif JUCE_GCC
  203847. // GNU inline asm version...
  203848. unsigned int hi = 0, lo = 0;
  203849. __asm__ __volatile__ (
  203850. "xor %%eax, %%eax \n\
  203851. xor %%edx, %%edx \n\
  203852. rdtsc \n\
  203853. movl %%eax, %[lo] \n\
  203854. movl %%edx, %[hi]"
  203855. :
  203856. : [hi] "m" (hi),
  203857. [lo] "m" (lo)
  203858. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203859. return (int64) ((((uint64) hi) << 32) | lo);
  203860. #else
  203861. // MSVC inline asm version...
  203862. unsigned int hi = 0, lo = 0;
  203863. __asm
  203864. {
  203865. xor eax, eax
  203866. xor edx, edx
  203867. rdtsc
  203868. mov lo, eax
  203869. mov hi, edx
  203870. }
  203871. return (int64) ((((uint64) hi) << 32) | lo);
  203872. #endif
  203873. }
  203874. int SystemStats::getCpuSpeedInMegaherz()
  203875. {
  203876. const int64 cycles = juce_getClockCycleCounter();
  203877. const uint32 millis = Time::getMillisecondCounter();
  203878. int lastResult = 0;
  203879. for (;;)
  203880. {
  203881. int n = 1000000;
  203882. while (--n > 0) {}
  203883. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203884. const int64 cyclesNow = juce_getClockCycleCounter();
  203885. if (millisElapsed > 80)
  203886. {
  203887. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203888. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203889. return newResult;
  203890. lastResult = newResult;
  203891. }
  203892. }
  203893. }
  203894. bool Time::setSystemTimeToThisTime() const
  203895. {
  203896. SYSTEMTIME st;
  203897. st.wDayOfWeek = 0;
  203898. st.wYear = (WORD) getYear();
  203899. st.wMonth = (WORD) (getMonth() + 1);
  203900. st.wDay = (WORD) getDayOfMonth();
  203901. st.wHour = (WORD) getHours();
  203902. st.wMinute = (WORD) getMinutes();
  203903. st.wSecond = (WORD) getSeconds();
  203904. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203905. // do this twice because of daylight saving conversion problems - the
  203906. // first one sets it up, the second one kicks it in.
  203907. return SetLocalTime (&st) != 0
  203908. && SetLocalTime (&st) != 0;
  203909. }
  203910. int SystemStats::getPageSize()
  203911. {
  203912. SYSTEM_INFO systemInfo;
  203913. GetSystemInfo (&systemInfo);
  203914. return systemInfo.dwPageSize;
  203915. }
  203916. const String SystemStats::getLogonName()
  203917. {
  203918. TCHAR text [256];
  203919. DWORD len = numElementsInArray (text) - 2;
  203920. zerostruct (text);
  203921. GetUserName (text, &len);
  203922. return String (text, len);
  203923. }
  203924. const String SystemStats::getFullUserName()
  203925. {
  203926. return getLogonName();
  203927. }
  203928. #endif
  203929. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203930. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203931. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203932. // compiled on its own).
  203933. #if JUCE_INCLUDED_FILE
  203934. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203935. extern HWND juce_messageWindowHandle;
  203936. #endif
  203937. #if ! JUCE_USE_INTRINSICS
  203938. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203939. // older ones we have to actually call the ops as win32 functions..
  203940. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203941. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203942. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203943. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203944. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203945. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203946. {
  203947. jassertfalse; // This operation isn't available in old MS compiler versions!
  203948. __int64 oldValue = *value;
  203949. if (oldValue == valueToCompare)
  203950. *value = newValue;
  203951. return oldValue;
  203952. }
  203953. #endif
  203954. CriticalSection::CriticalSection() throw()
  203955. {
  203956. // (just to check the MS haven't changed this structure and broken things...)
  203957. #if _MSC_VER >= 1400
  203958. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203959. #else
  203960. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203961. #endif
  203962. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203963. }
  203964. CriticalSection::~CriticalSection() throw()
  203965. {
  203966. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203967. }
  203968. void CriticalSection::enter() const throw()
  203969. {
  203970. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203971. }
  203972. bool CriticalSection::tryEnter() const throw()
  203973. {
  203974. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203975. }
  203976. void CriticalSection::exit() const throw()
  203977. {
  203978. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203979. }
  203980. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203981. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203982. {
  203983. }
  203984. WaitableEvent::~WaitableEvent() throw()
  203985. {
  203986. CloseHandle (internal);
  203987. }
  203988. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203989. {
  203990. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203991. }
  203992. void WaitableEvent::signal() const throw()
  203993. {
  203994. SetEvent (internal);
  203995. }
  203996. void WaitableEvent::reset() const throw()
  203997. {
  203998. ResetEvent (internal);
  203999. }
  204000. void JUCE_API juce_threadEntryPoint (void*);
  204001. static unsigned int __stdcall threadEntryProc (void* userData)
  204002. {
  204003. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204004. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  204005. GetCurrentThreadId(), TRUE);
  204006. #endif
  204007. juce_threadEntryPoint (userData);
  204008. _endthreadex (0);
  204009. return 0;
  204010. }
  204011. void juce_CloseThreadHandle (void* handle)
  204012. {
  204013. CloseHandle ((HANDLE) handle);
  204014. }
  204015. void* juce_createThread (void* userData)
  204016. {
  204017. unsigned int threadId;
  204018. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  204019. }
  204020. void juce_killThread (void* handle)
  204021. {
  204022. if (handle != 0)
  204023. {
  204024. #if JUCE_DEBUG
  204025. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  204026. #endif
  204027. TerminateThread (handle, 0);
  204028. }
  204029. }
  204030. void juce_setCurrentThreadName (const String& name)
  204031. {
  204032. #if JUCE_DEBUG && JUCE_MSVC
  204033. struct
  204034. {
  204035. DWORD dwType;
  204036. LPCSTR szName;
  204037. DWORD dwThreadID;
  204038. DWORD dwFlags;
  204039. } info;
  204040. info.dwType = 0x1000;
  204041. info.szName = name.toCString();
  204042. info.dwThreadID = GetCurrentThreadId();
  204043. info.dwFlags = 0;
  204044. __try
  204045. {
  204046. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  204047. }
  204048. __except (EXCEPTION_CONTINUE_EXECUTION)
  204049. {}
  204050. #else
  204051. (void) name;
  204052. #endif
  204053. }
  204054. Thread::ThreadID Thread::getCurrentThreadId()
  204055. {
  204056. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  204057. }
  204058. // priority 1 to 10 where 5=normal, 1=low
  204059. bool juce_setThreadPriority (void* threadHandle, int priority)
  204060. {
  204061. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  204062. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  204063. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  204064. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  204065. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  204066. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  204067. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  204068. if (threadHandle == 0)
  204069. threadHandle = GetCurrentThread();
  204070. return SetThreadPriority (threadHandle, pri) != FALSE;
  204071. }
  204072. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  204073. {
  204074. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  204075. }
  204076. static HANDLE sleepEvent = 0;
  204077. void juce_initialiseThreadEvents()
  204078. {
  204079. if (sleepEvent == 0)
  204080. #if JUCE_DEBUG
  204081. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  204082. #else
  204083. sleepEvent = CreateEvent (0, 0, 0, 0);
  204084. #endif
  204085. }
  204086. void Thread::yield()
  204087. {
  204088. Sleep (0);
  204089. }
  204090. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204091. {
  204092. if (millisecs >= 10)
  204093. {
  204094. Sleep (millisecs);
  204095. }
  204096. else
  204097. {
  204098. jassert (sleepEvent != 0);
  204099. // unlike Sleep() this is guaranteed to return to the current thread after
  204100. // the time expires, so we'll use this for short waits, which are more likely
  204101. // to need to be accurate
  204102. WaitForSingleObject (sleepEvent, millisecs);
  204103. }
  204104. }
  204105. static int lastProcessPriority = -1;
  204106. // called by WindowDriver because Windows does wierd things to process priority
  204107. // when you swap apps, and this forces an update when the app is brought to the front.
  204108. void juce_repeatLastProcessPriority()
  204109. {
  204110. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204111. {
  204112. DWORD p;
  204113. switch (lastProcessPriority)
  204114. {
  204115. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204116. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204117. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204118. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204119. default: jassertfalse; return; // bad priority value
  204120. }
  204121. SetPriorityClass (GetCurrentProcess(), p);
  204122. }
  204123. }
  204124. void Process::setPriority (ProcessPriority prior)
  204125. {
  204126. if (lastProcessPriority != (int) prior)
  204127. {
  204128. lastProcessPriority = (int) prior;
  204129. juce_repeatLastProcessPriority();
  204130. }
  204131. }
  204132. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  204133. {
  204134. return IsDebuggerPresent() != FALSE;
  204135. }
  204136. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204137. {
  204138. return juce_isRunningUnderDebugger();
  204139. }
  204140. void Process::raisePrivilege()
  204141. {
  204142. jassertfalse; // xxx not implemented
  204143. }
  204144. void Process::lowerPrivilege()
  204145. {
  204146. jassertfalse; // xxx not implemented
  204147. }
  204148. void Process::terminate()
  204149. {
  204150. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204151. _CrtDumpMemoryLeaks();
  204152. #endif
  204153. // bullet in the head in case there's a problem shutting down..
  204154. ExitProcess (0);
  204155. }
  204156. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204157. {
  204158. void* result = 0;
  204159. JUCE_TRY
  204160. {
  204161. result = LoadLibrary (name);
  204162. }
  204163. JUCE_CATCH_ALL
  204164. return result;
  204165. }
  204166. void PlatformUtilities::freeDynamicLibrary (void* h)
  204167. {
  204168. JUCE_TRY
  204169. {
  204170. if (h != 0)
  204171. FreeLibrary ((HMODULE) h);
  204172. }
  204173. JUCE_CATCH_ALL
  204174. }
  204175. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204176. {
  204177. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  204178. }
  204179. class InterProcessLock::Pimpl
  204180. {
  204181. public:
  204182. Pimpl (const String& name, const int timeOutMillisecs)
  204183. : handle (0), refCount (1)
  204184. {
  204185. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204186. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204187. {
  204188. if (timeOutMillisecs == 0)
  204189. {
  204190. close();
  204191. return;
  204192. }
  204193. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204194. {
  204195. case WAIT_OBJECT_0:
  204196. case WAIT_ABANDONED:
  204197. break;
  204198. case WAIT_TIMEOUT:
  204199. default:
  204200. close();
  204201. break;
  204202. }
  204203. }
  204204. }
  204205. ~Pimpl()
  204206. {
  204207. close();
  204208. }
  204209. void close()
  204210. {
  204211. if (handle != 0)
  204212. {
  204213. ReleaseMutex (handle);
  204214. CloseHandle (handle);
  204215. handle = 0;
  204216. }
  204217. }
  204218. HANDLE handle;
  204219. int refCount;
  204220. };
  204221. InterProcessLock::InterProcessLock (const String& name_)
  204222. : name (name_)
  204223. {
  204224. }
  204225. InterProcessLock::~InterProcessLock()
  204226. {
  204227. }
  204228. bool InterProcessLock::enter (const int timeOutMillisecs)
  204229. {
  204230. const ScopedLock sl (lock);
  204231. if (pimpl == 0)
  204232. {
  204233. pimpl = new Pimpl (name, timeOutMillisecs);
  204234. if (pimpl->handle == 0)
  204235. pimpl = 0;
  204236. }
  204237. else
  204238. {
  204239. pimpl->refCount++;
  204240. }
  204241. return pimpl != 0;
  204242. }
  204243. void InterProcessLock::exit()
  204244. {
  204245. const ScopedLock sl (lock);
  204246. // Trying to release the lock too many times!
  204247. jassert (pimpl != 0);
  204248. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204249. pimpl = 0;
  204250. }
  204251. #endif
  204252. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204253. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204254. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204255. // compiled on its own).
  204256. #if JUCE_INCLUDED_FILE
  204257. #ifndef CSIDL_MYMUSIC
  204258. #define CSIDL_MYMUSIC 0x000d
  204259. #endif
  204260. #ifndef CSIDL_MYVIDEO
  204261. #define CSIDL_MYVIDEO 0x000e
  204262. #endif
  204263. #ifndef INVALID_FILE_ATTRIBUTES
  204264. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204265. #endif
  204266. const juce_wchar File::separator = '\\';
  204267. const String File::separatorString ("\\");
  204268. bool File::exists() const
  204269. {
  204270. return fullPath.isNotEmpty()
  204271. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204272. }
  204273. bool File::existsAsFile() const
  204274. {
  204275. return fullPath.isNotEmpty()
  204276. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204277. }
  204278. bool File::isDirectory() const
  204279. {
  204280. const DWORD attr = GetFileAttributes (fullPath);
  204281. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204282. }
  204283. bool File::hasWriteAccess() const
  204284. {
  204285. if (exists())
  204286. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204287. // on windows, it seems that even read-only directories can still be written into,
  204288. // so checking the parent directory's permissions would return the wrong result..
  204289. return true;
  204290. }
  204291. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204292. {
  204293. DWORD attr = GetFileAttributes (fullPath);
  204294. if (attr == INVALID_FILE_ATTRIBUTES)
  204295. return false;
  204296. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204297. return true;
  204298. if (shouldBeReadOnly)
  204299. attr |= FILE_ATTRIBUTE_READONLY;
  204300. else
  204301. attr &= ~FILE_ATTRIBUTE_READONLY;
  204302. return SetFileAttributes (fullPath, attr) != FALSE;
  204303. }
  204304. bool File::isHidden() const
  204305. {
  204306. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204307. }
  204308. bool File::deleteFile() const
  204309. {
  204310. if (! exists())
  204311. return true;
  204312. else if (isDirectory())
  204313. return RemoveDirectory (fullPath) != 0;
  204314. else
  204315. return DeleteFile (fullPath) != 0;
  204316. }
  204317. bool File::moveToTrash() const
  204318. {
  204319. if (! exists())
  204320. return true;
  204321. SHFILEOPSTRUCT fos;
  204322. zerostruct (fos);
  204323. // The string we pass in must be double null terminated..
  204324. String doubleNullTermPath (getFullPathName() + " ");
  204325. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204326. p [getFullPathName().length()] = 0;
  204327. fos.wFunc = FO_DELETE;
  204328. fos.pFrom = p;
  204329. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204330. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204331. return SHFileOperation (&fos) == 0;
  204332. }
  204333. bool File::copyInternal (const File& dest) const
  204334. {
  204335. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204336. }
  204337. bool File::moveInternal (const File& dest) const
  204338. {
  204339. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204340. }
  204341. void File::createDirectoryInternal (const String& fileName) const
  204342. {
  204343. CreateDirectory (fileName, 0);
  204344. }
  204345. int64 juce_fileSetPosition (void* handle, int64 pos)
  204346. {
  204347. LARGE_INTEGER li;
  204348. li.QuadPart = pos;
  204349. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204350. return li.QuadPart;
  204351. }
  204352. void FileInputStream::openHandle()
  204353. {
  204354. totalSize = file.getSize();
  204355. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204356. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204357. if (h != INVALID_HANDLE_VALUE)
  204358. fileHandle = (void*) h;
  204359. }
  204360. void FileInputStream::closeHandle()
  204361. {
  204362. CloseHandle ((HANDLE) fileHandle);
  204363. }
  204364. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204365. {
  204366. if (fileHandle != 0)
  204367. {
  204368. DWORD actualNum = 0;
  204369. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204370. return (size_t) actualNum;
  204371. }
  204372. return 0;
  204373. }
  204374. void FileOutputStream::openHandle()
  204375. {
  204376. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204377. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204378. if (h != INVALID_HANDLE_VALUE)
  204379. {
  204380. LARGE_INTEGER li;
  204381. li.QuadPart = 0;
  204382. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204383. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204384. {
  204385. fileHandle = (void*) h;
  204386. currentPosition = li.QuadPart;
  204387. }
  204388. }
  204389. }
  204390. void FileOutputStream::closeHandle()
  204391. {
  204392. CloseHandle ((HANDLE) fileHandle);
  204393. }
  204394. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204395. {
  204396. if (fileHandle != 0)
  204397. {
  204398. DWORD actualNum = 0;
  204399. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204400. return (int) actualNum;
  204401. }
  204402. return 0;
  204403. }
  204404. void FileOutputStream::flushInternal()
  204405. {
  204406. if (fileHandle != 0)
  204407. FlushFileBuffers ((HANDLE) fileHandle);
  204408. }
  204409. int64 File::getSize() const
  204410. {
  204411. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204412. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204413. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204414. return 0;
  204415. }
  204416. static int64 fileTimeToTime (const FILETIME* const ft)
  204417. {
  204418. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204419. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204420. }
  204421. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204422. {
  204423. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204424. }
  204425. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204426. {
  204427. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204428. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204429. {
  204430. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204431. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204432. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204433. }
  204434. else
  204435. {
  204436. creationTime = accessTime = modificationTime = 0;
  204437. }
  204438. }
  204439. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204440. {
  204441. bool ok = false;
  204442. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204443. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204444. if (h != INVALID_HANDLE_VALUE)
  204445. {
  204446. FILETIME m, a, c;
  204447. timeToFileTime (modificationTime, &m);
  204448. timeToFileTime (accessTime, &a);
  204449. timeToFileTime (creationTime, &c);
  204450. ok = SetFileTime (h,
  204451. creationTime > 0 ? &c : 0,
  204452. accessTime > 0 ? &a : 0,
  204453. modificationTime > 0 ? &m : 0) != 0;
  204454. CloseHandle (h);
  204455. }
  204456. return ok;
  204457. }
  204458. void File::findFileSystemRoots (Array<File>& destArray)
  204459. {
  204460. TCHAR buffer [2048];
  204461. buffer[0] = 0;
  204462. buffer[1] = 0;
  204463. GetLogicalDriveStrings (2048, buffer);
  204464. const TCHAR* n = buffer;
  204465. StringArray roots;
  204466. while (*n != 0)
  204467. {
  204468. roots.add (String (n));
  204469. while (*n++ != 0)
  204470. {}
  204471. }
  204472. roots.sort (true);
  204473. for (int i = 0; i < roots.size(); ++i)
  204474. destArray.add (roots [i]);
  204475. }
  204476. static const String getDriveFromPath (const String& path)
  204477. {
  204478. if (path.isNotEmpty() && path[1] == ':')
  204479. return path.substring (0, 2) + '\\';
  204480. return path;
  204481. }
  204482. const String File::getVolumeLabel() const
  204483. {
  204484. TCHAR dest[64];
  204485. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204486. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204487. dest[0] = 0;
  204488. return dest;
  204489. }
  204490. int File::getVolumeSerialNumber() const
  204491. {
  204492. TCHAR dest[64];
  204493. DWORD serialNum;
  204494. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204495. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204496. return 0;
  204497. return (int) serialNum;
  204498. }
  204499. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204500. {
  204501. ULARGE_INTEGER spc, tot, totFree;
  204502. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204503. return total ? (int64) tot.QuadPart
  204504. : (int64) spc.QuadPart;
  204505. return 0;
  204506. }
  204507. int64 File::getBytesFreeOnVolume() const
  204508. {
  204509. return getDiskSpaceInfo (getFullPathName(), false);
  204510. }
  204511. int64 File::getVolumeTotalSize() const
  204512. {
  204513. return getDiskSpaceInfo (getFullPathName(), true);
  204514. }
  204515. static unsigned int getWindowsDriveType (const String& path)
  204516. {
  204517. return GetDriveType (getDriveFromPath (path));
  204518. }
  204519. bool File::isOnCDRomDrive() const
  204520. {
  204521. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204522. }
  204523. bool File::isOnHardDisk() const
  204524. {
  204525. if (fullPath.isEmpty())
  204526. return false;
  204527. const unsigned int n = getWindowsDriveType (getFullPathName());
  204528. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204529. return n != DRIVE_REMOVABLE;
  204530. else
  204531. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204532. }
  204533. bool File::isOnRemovableDrive() const
  204534. {
  204535. if (fullPath.isEmpty())
  204536. return false;
  204537. const unsigned int n = getWindowsDriveType (getFullPathName());
  204538. return n == DRIVE_CDROM
  204539. || n == DRIVE_REMOTE
  204540. || n == DRIVE_REMOVABLE
  204541. || n == DRIVE_RAMDISK;
  204542. }
  204543. static const File juce_getSpecialFolderPath (int type)
  204544. {
  204545. WCHAR path [MAX_PATH + 256];
  204546. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204547. return File (String (path));
  204548. return File::nonexistent;
  204549. }
  204550. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204551. {
  204552. int csidlType = 0;
  204553. switch (type)
  204554. {
  204555. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204556. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204557. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204558. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204559. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204560. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204561. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204562. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204563. case tempDirectory:
  204564. {
  204565. WCHAR dest [2048];
  204566. dest[0] = 0;
  204567. GetTempPath (numElementsInArray (dest), dest);
  204568. return File (String (dest));
  204569. }
  204570. case invokedExecutableFile:
  204571. case currentExecutableFile:
  204572. case currentApplicationFile:
  204573. {
  204574. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204575. WCHAR dest [MAX_PATH + 256];
  204576. dest[0] = 0;
  204577. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204578. return File (String (dest));
  204579. }
  204580. case hostApplicationPath:
  204581. {
  204582. WCHAR dest [MAX_PATH + 256];
  204583. dest[0] = 0;
  204584. GetModuleFileName (0, dest, numElementsInArray (dest));
  204585. return File (String (dest));
  204586. }
  204587. default:
  204588. jassertfalse; // unknown type?
  204589. return File::nonexistent;
  204590. }
  204591. return juce_getSpecialFolderPath (csidlType);
  204592. }
  204593. const File File::getCurrentWorkingDirectory()
  204594. {
  204595. WCHAR dest [MAX_PATH + 256];
  204596. dest[0] = 0;
  204597. GetCurrentDirectory (numElementsInArray (dest), dest);
  204598. return File (String (dest));
  204599. }
  204600. bool File::setAsCurrentWorkingDirectory() const
  204601. {
  204602. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204603. }
  204604. const String File::getVersion() const
  204605. {
  204606. String result;
  204607. DWORD handle = 0;
  204608. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204609. HeapBlock<char> buffer;
  204610. buffer.calloc (bufferSize);
  204611. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204612. {
  204613. VS_FIXEDFILEINFO* vffi;
  204614. UINT len = 0;
  204615. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204616. {
  204617. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204618. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204619. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204620. << (int) LOWORD (vffi->dwFileVersionLS);
  204621. }
  204622. }
  204623. return result;
  204624. }
  204625. const File File::getLinkedTarget() const
  204626. {
  204627. File result (*this);
  204628. String p (getFullPathName());
  204629. if (! exists())
  204630. p += ".lnk";
  204631. else if (getFileExtension() != ".lnk")
  204632. return result;
  204633. ComSmartPtr <IShellLink> shellLink;
  204634. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204635. {
  204636. ComSmartPtr <IPersistFile> persistFile;
  204637. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  204638. {
  204639. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204640. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204641. {
  204642. WIN32_FIND_DATA winFindData;
  204643. WCHAR resolvedPath [MAX_PATH];
  204644. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204645. result = File (resolvedPath);
  204646. }
  204647. }
  204648. }
  204649. return result;
  204650. }
  204651. class DirectoryIterator::NativeIterator::Pimpl
  204652. {
  204653. public:
  204654. Pimpl (const File& directory, const String& wildCard)
  204655. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204656. handle (INVALID_HANDLE_VALUE)
  204657. {
  204658. }
  204659. ~Pimpl()
  204660. {
  204661. if (handle != INVALID_HANDLE_VALUE)
  204662. FindClose (handle);
  204663. }
  204664. bool next (String& filenameFound,
  204665. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204666. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204667. {
  204668. WIN32_FIND_DATA findData;
  204669. if (handle == INVALID_HANDLE_VALUE)
  204670. {
  204671. handle = FindFirstFile (directoryWithWildCard, &findData);
  204672. if (handle == INVALID_HANDLE_VALUE)
  204673. return false;
  204674. }
  204675. else
  204676. {
  204677. if (FindNextFile (handle, &findData) == 0)
  204678. return false;
  204679. }
  204680. filenameFound = findData.cFileName;
  204681. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204682. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204683. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204684. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204685. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204686. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204687. return true;
  204688. }
  204689. juce_UseDebuggingNewOperator
  204690. private:
  204691. const String directoryWithWildCard;
  204692. HANDLE handle;
  204693. Pimpl (const Pimpl&);
  204694. Pimpl& operator= (const Pimpl&);
  204695. };
  204696. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204697. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204698. {
  204699. }
  204700. DirectoryIterator::NativeIterator::~NativeIterator()
  204701. {
  204702. }
  204703. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204704. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204705. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204706. {
  204707. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204708. }
  204709. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204710. {
  204711. HINSTANCE hInstance = 0;
  204712. JUCE_TRY
  204713. {
  204714. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204715. }
  204716. JUCE_CATCH_ALL
  204717. return hInstance > (HINSTANCE) 32;
  204718. }
  204719. void File::revealToUser() const
  204720. {
  204721. if (isDirectory())
  204722. startAsProcess();
  204723. else if (getParentDirectory().exists())
  204724. getParentDirectory().startAsProcess();
  204725. }
  204726. class NamedPipeInternal
  204727. {
  204728. public:
  204729. NamedPipeInternal (const String& file, const bool isPipe_)
  204730. : pipeH (0),
  204731. cancelEvent (0),
  204732. connected (false),
  204733. isPipe (isPipe_)
  204734. {
  204735. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204736. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204737. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204738. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204739. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204740. }
  204741. ~NamedPipeInternal()
  204742. {
  204743. disconnectPipe();
  204744. if (pipeH != 0)
  204745. CloseHandle (pipeH);
  204746. CloseHandle (cancelEvent);
  204747. }
  204748. bool connect (const int timeOutMs)
  204749. {
  204750. if (! isPipe)
  204751. return true;
  204752. if (! connected)
  204753. {
  204754. OVERLAPPED over;
  204755. zerostruct (over);
  204756. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204757. if (ConnectNamedPipe (pipeH, &over))
  204758. {
  204759. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204760. }
  204761. else
  204762. {
  204763. const int err = GetLastError();
  204764. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204765. {
  204766. HANDLE handles[] = { over.hEvent, cancelEvent };
  204767. if (WaitForMultipleObjects (2, handles, FALSE,
  204768. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204769. connected = true;
  204770. }
  204771. else if (err == ERROR_PIPE_CONNECTED)
  204772. {
  204773. connected = true;
  204774. }
  204775. }
  204776. CloseHandle (over.hEvent);
  204777. }
  204778. return connected;
  204779. }
  204780. void disconnectPipe()
  204781. {
  204782. if (connected)
  204783. {
  204784. DisconnectNamedPipe (pipeH);
  204785. connected = false;
  204786. }
  204787. }
  204788. HANDLE pipeH;
  204789. HANDLE cancelEvent;
  204790. bool connected, isPipe;
  204791. };
  204792. void NamedPipe::close()
  204793. {
  204794. cancelPendingReads();
  204795. const ScopedLock sl (lock);
  204796. delete static_cast<NamedPipeInternal*> (internal);
  204797. internal = 0;
  204798. }
  204799. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204800. {
  204801. close();
  204802. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204803. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204804. {
  204805. internal = intern.release();
  204806. return true;
  204807. }
  204808. return false;
  204809. }
  204810. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204811. {
  204812. const ScopedLock sl (lock);
  204813. int bytesRead = -1;
  204814. bool waitAgain = true;
  204815. while (waitAgain && internal != 0)
  204816. {
  204817. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204818. waitAgain = false;
  204819. if (! intern->connect (timeOutMilliseconds))
  204820. break;
  204821. if (maxBytesToRead <= 0)
  204822. return 0;
  204823. OVERLAPPED over;
  204824. zerostruct (over);
  204825. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204826. unsigned long numRead;
  204827. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204828. {
  204829. bytesRead = (int) numRead;
  204830. }
  204831. else if (GetLastError() == ERROR_IO_PENDING)
  204832. {
  204833. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204834. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204835. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204836. : INFINITE);
  204837. if (waitResult != WAIT_OBJECT_0)
  204838. {
  204839. // if the operation timed out, let's cancel it...
  204840. CancelIo (intern->pipeH);
  204841. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204842. }
  204843. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204844. {
  204845. bytesRead = (int) numRead;
  204846. }
  204847. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204848. {
  204849. intern->disconnectPipe();
  204850. waitAgain = true;
  204851. }
  204852. }
  204853. else
  204854. {
  204855. waitAgain = internal != 0;
  204856. Sleep (5);
  204857. }
  204858. CloseHandle (over.hEvent);
  204859. }
  204860. return bytesRead;
  204861. }
  204862. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204863. {
  204864. int bytesWritten = -1;
  204865. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204866. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204867. {
  204868. if (numBytesToWrite <= 0)
  204869. return 0;
  204870. OVERLAPPED over;
  204871. zerostruct (over);
  204872. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204873. unsigned long numWritten;
  204874. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204875. {
  204876. bytesWritten = (int) numWritten;
  204877. }
  204878. else if (GetLastError() == ERROR_IO_PENDING)
  204879. {
  204880. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204881. DWORD waitResult;
  204882. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204883. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204884. : INFINITE);
  204885. if (waitResult != WAIT_OBJECT_0)
  204886. {
  204887. CancelIo (intern->pipeH);
  204888. WaitForSingleObject (over.hEvent, INFINITE);
  204889. }
  204890. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204891. {
  204892. bytesWritten = (int) numWritten;
  204893. }
  204894. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204895. {
  204896. intern->disconnectPipe();
  204897. }
  204898. }
  204899. CloseHandle (over.hEvent);
  204900. }
  204901. return bytesWritten;
  204902. }
  204903. void NamedPipe::cancelPendingReads()
  204904. {
  204905. if (internal != 0)
  204906. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204907. }
  204908. #endif
  204909. /*** End of inlined file: juce_win32_Files.cpp ***/
  204910. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204911. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204912. // compiled on its own).
  204913. #if JUCE_INCLUDED_FILE
  204914. #ifndef INTERNET_FLAG_NEED_FILE
  204915. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204916. #endif
  204917. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204918. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204919. #endif
  204920. struct ConnectionAndRequestStruct
  204921. {
  204922. HINTERNET connection, request;
  204923. };
  204924. static HINTERNET sessionHandle = 0;
  204925. #ifndef WORKAROUND_TIMEOUT_BUG
  204926. //#define WORKAROUND_TIMEOUT_BUG 1
  204927. #endif
  204928. #if WORKAROUND_TIMEOUT_BUG
  204929. // Required because of a Microsoft bug in setting a timeout
  204930. class InternetConnectThread : public Thread
  204931. {
  204932. public:
  204933. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204934. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204935. {
  204936. startThread();
  204937. }
  204938. ~InternetConnectThread()
  204939. {
  204940. stopThread (60000);
  204941. }
  204942. void run()
  204943. {
  204944. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204945. uc.nPort, _T(""), _T(""),
  204946. isFtp ? INTERNET_SERVICE_FTP
  204947. : INTERNET_SERVICE_HTTP,
  204948. 0, 0);
  204949. notify();
  204950. }
  204951. juce_UseDebuggingNewOperator
  204952. private:
  204953. URL_COMPONENTS& uc;
  204954. HINTERNET& connection;
  204955. const bool isFtp;
  204956. InternetConnectThread (const InternetConnectThread&);
  204957. InternetConnectThread& operator= (const InternetConnectThread&);
  204958. };
  204959. #endif
  204960. void* juce_openInternetFile (const String& url,
  204961. const String& headers,
  204962. const MemoryBlock& postData,
  204963. const bool isPost,
  204964. URL::OpenStreamProgressCallback* callback,
  204965. void* callbackContext,
  204966. int timeOutMs)
  204967. {
  204968. if (sessionHandle == 0)
  204969. sessionHandle = InternetOpen (_T("juce"),
  204970. INTERNET_OPEN_TYPE_PRECONFIG,
  204971. 0, 0, 0);
  204972. if (sessionHandle != 0)
  204973. {
  204974. // break up the url..
  204975. TCHAR file[1024], server[1024];
  204976. URL_COMPONENTS uc;
  204977. zerostruct (uc);
  204978. uc.dwStructSize = sizeof (uc);
  204979. uc.dwUrlPathLength = sizeof (file);
  204980. uc.dwHostNameLength = sizeof (server);
  204981. uc.lpszUrlPath = file;
  204982. uc.lpszHostName = server;
  204983. if (InternetCrackUrl (url, 0, 0, &uc))
  204984. {
  204985. int disable = 1;
  204986. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204987. if (timeOutMs == 0)
  204988. timeOutMs = 30000;
  204989. else if (timeOutMs < 0)
  204990. timeOutMs = -1;
  204991. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204992. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204993. #if WORKAROUND_TIMEOUT_BUG
  204994. HINTERNET connection = 0;
  204995. {
  204996. InternetConnectThread connectThread (uc, connection, isFtp);
  204997. connectThread.wait (timeOutMs);
  204998. if (connection == 0)
  204999. {
  205000. InternetCloseHandle (sessionHandle);
  205001. sessionHandle = 0;
  205002. }
  205003. }
  205004. #else
  205005. HINTERNET connection = InternetConnect (sessionHandle,
  205006. uc.lpszHostName,
  205007. uc.nPort,
  205008. _T(""), _T(""),
  205009. isFtp ? INTERNET_SERVICE_FTP
  205010. : INTERNET_SERVICE_HTTP,
  205011. 0, 0);
  205012. #endif
  205013. if (connection != 0)
  205014. {
  205015. if (isFtp)
  205016. {
  205017. HINTERNET request = FtpOpenFile (connection,
  205018. uc.lpszUrlPath,
  205019. GENERIC_READ,
  205020. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  205021. 0);
  205022. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  205023. result->connection = connection;
  205024. result->request = request;
  205025. return result;
  205026. }
  205027. else
  205028. {
  205029. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  205030. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  205031. if (url.startsWithIgnoreCase ("https:"))
  205032. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  205033. // IE7 seems to automatically work out when it's https)
  205034. HINTERNET request = HttpOpenRequest (connection,
  205035. isPost ? _T("POST")
  205036. : _T("GET"),
  205037. uc.lpszUrlPath,
  205038. 0, 0, mimeTypes, flags, 0);
  205039. if (request != 0)
  205040. {
  205041. INTERNET_BUFFERS buffers;
  205042. zerostruct (buffers);
  205043. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  205044. buffers.lpcszHeader = (LPCTSTR) headers;
  205045. buffers.dwHeadersLength = headers.length();
  205046. buffers.dwBufferTotal = (DWORD) postData.getSize();
  205047. ConnectionAndRequestStruct* result = 0;
  205048. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  205049. {
  205050. int bytesSent = 0;
  205051. for (;;)
  205052. {
  205053. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  205054. DWORD bytesDone = 0;
  205055. if (bytesToDo > 0
  205056. && ! InternetWriteFile (request,
  205057. static_cast <const char*> (postData.getData()) + bytesSent,
  205058. bytesToDo, &bytesDone))
  205059. {
  205060. break;
  205061. }
  205062. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  205063. {
  205064. result = new ConnectionAndRequestStruct();
  205065. result->connection = connection;
  205066. result->request = request;
  205067. if (! HttpEndRequest (request, 0, 0, 0))
  205068. break;
  205069. return result;
  205070. }
  205071. bytesSent += bytesDone;
  205072. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  205073. break;
  205074. }
  205075. }
  205076. InternetCloseHandle (request);
  205077. }
  205078. InternetCloseHandle (connection);
  205079. }
  205080. }
  205081. }
  205082. }
  205083. return 0;
  205084. }
  205085. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  205086. {
  205087. DWORD bytesRead = 0;
  205088. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205089. if (crs != 0)
  205090. InternetReadFile (crs->request,
  205091. buffer, bytesToRead,
  205092. &bytesRead);
  205093. return bytesRead;
  205094. }
  205095. int juce_seekInInternetFile (void* handle, int newPosition)
  205096. {
  205097. if (handle != 0)
  205098. {
  205099. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205100. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  205101. }
  205102. return -1;
  205103. }
  205104. int64 juce_getInternetFileContentLength (void* handle)
  205105. {
  205106. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205107. if (crs != 0)
  205108. {
  205109. DWORD index = 0, result = 0, size = sizeof (result);
  205110. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205111. return (int64) result;
  205112. }
  205113. return -1;
  205114. }
  205115. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  205116. {
  205117. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205118. if (crs != 0)
  205119. {
  205120. DWORD bufferSizeBytes = 4096;
  205121. for (;;)
  205122. {
  205123. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205124. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205125. {
  205126. StringArray headersArray;
  205127. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205128. for (int i = 0; i < headersArray.size(); ++i)
  205129. {
  205130. const String& header = headersArray[i];
  205131. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205132. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205133. const String previousValue (headers [key]);
  205134. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205135. }
  205136. break;
  205137. }
  205138. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205139. break;
  205140. }
  205141. }
  205142. }
  205143. void juce_closeInternetFile (void* handle)
  205144. {
  205145. if (handle != 0)
  205146. {
  205147. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  205148. InternetCloseHandle (crs->request);
  205149. InternetCloseHandle (crs->connection);
  205150. }
  205151. }
  205152. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  205153. {
  205154. int numFound = 0;
  205155. DynamicLibraryLoader dll ("iphlpapi.dll");
  205156. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205157. if (getAdaptersInfo != 0)
  205158. {
  205159. ULONG len = sizeof (IP_ADAPTER_INFO);
  205160. MemoryBlock mb;
  205161. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205162. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205163. {
  205164. mb.setSize (len);
  205165. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205166. }
  205167. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205168. {
  205169. PIP_ADAPTER_INFO adapter = adapterInfo;
  205170. while (adapter != 0)
  205171. {
  205172. int64 mac = 0;
  205173. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  205174. mac = (mac << 8) | adapter->Address[i];
  205175. if (littleEndian)
  205176. mac = (int64) ByteOrder::swap ((uint64) mac);
  205177. if (numFound < maxNum && mac != 0)
  205178. addresses [numFound++] = mac;
  205179. adapter = adapter->Next;
  205180. }
  205181. }
  205182. }
  205183. return numFound;
  205184. }
  205185. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  205186. {
  205187. int numFound = 0;
  205188. DynamicLibraryLoader dll ("netapi32.dll");
  205189. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205190. if (NetbiosCall != 0)
  205191. {
  205192. NCB ncb;
  205193. zerostruct (ncb);
  205194. struct ASTAT
  205195. {
  205196. ADAPTER_STATUS adapt;
  205197. NAME_BUFFER NameBuff [30];
  205198. };
  205199. ASTAT astat;
  205200. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205201. LANA_ENUM enums;
  205202. zerostruct (enums);
  205203. ncb.ncb_command = NCBENUM;
  205204. ncb.ncb_buffer = (unsigned char*) &enums;
  205205. ncb.ncb_length = sizeof (LANA_ENUM);
  205206. NetbiosCall (&ncb);
  205207. for (int i = 0; i < enums.length; ++i)
  205208. {
  205209. zerostruct (ncb);
  205210. ncb.ncb_command = NCBRESET;
  205211. ncb.ncb_lana_num = enums.lana[i];
  205212. if (NetbiosCall (&ncb) == 0)
  205213. {
  205214. zerostruct (ncb);
  205215. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205216. ncb.ncb_command = NCBASTAT;
  205217. ncb.ncb_lana_num = enums.lana[i];
  205218. ncb.ncb_buffer = (unsigned char*) &astat;
  205219. ncb.ncb_length = sizeof (ASTAT);
  205220. if (NetbiosCall (&ncb) == 0)
  205221. {
  205222. if (astat.adapt.adapter_type == 0xfe)
  205223. {
  205224. uint64 mac = 0;
  205225. for (int i = 6; --i >= 0;)
  205226. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  205227. if (numFound < maxNum && mac != 0)
  205228. addresses [numFound++] = mac;
  205229. }
  205230. }
  205231. }
  205232. }
  205233. }
  205234. return numFound;
  205235. }
  205236. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  205237. {
  205238. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205239. if (numFound == 0)
  205240. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205241. return numFound;
  205242. }
  205243. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205244. const String& emailSubject,
  205245. const String& bodyText,
  205246. const StringArray& filesToAttach)
  205247. {
  205248. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205249. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205250. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205251. bool ok = false;
  205252. if (mapiSendMail != 0)
  205253. {
  205254. MapiMessage message;
  205255. zerostruct (message);
  205256. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205257. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205258. MapiRecipDesc recip;
  205259. zerostruct (recip);
  205260. recip.ulRecipClass = MAPI_TO;
  205261. String targetEmailAddress_ (targetEmailAddress);
  205262. if (targetEmailAddress_.isEmpty())
  205263. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205264. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205265. message.nRecipCount = 1;
  205266. message.lpRecips = &recip;
  205267. HeapBlock <MapiFileDesc> files;
  205268. files.calloc (filesToAttach.size());
  205269. message.nFileCount = filesToAttach.size();
  205270. message.lpFiles = files;
  205271. for (int i = 0; i < filesToAttach.size(); ++i)
  205272. {
  205273. files[i].nPosition = (ULONG) -1;
  205274. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205275. }
  205276. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205277. }
  205278. FreeLibrary (h);
  205279. return ok;
  205280. }
  205281. #endif
  205282. /*** End of inlined file: juce_win32_Network.cpp ***/
  205283. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205284. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205285. // compiled on its own).
  205286. #if JUCE_INCLUDED_FILE
  205287. static HKEY findKeyForPath (String name,
  205288. const bool createForWriting,
  205289. String& valueName)
  205290. {
  205291. HKEY rootKey = 0;
  205292. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205293. rootKey = HKEY_CURRENT_USER;
  205294. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205295. rootKey = HKEY_LOCAL_MACHINE;
  205296. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205297. rootKey = HKEY_CLASSES_ROOT;
  205298. if (rootKey != 0)
  205299. {
  205300. name = name.substring (name.indexOfChar ('\\') + 1);
  205301. const int lastSlash = name.lastIndexOfChar ('\\');
  205302. valueName = name.substring (lastSlash + 1);
  205303. name = name.substring (0, lastSlash);
  205304. HKEY key;
  205305. DWORD result;
  205306. if (createForWriting)
  205307. {
  205308. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205309. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205310. return key;
  205311. }
  205312. else
  205313. {
  205314. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205315. return key;
  205316. }
  205317. }
  205318. return 0;
  205319. }
  205320. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205321. const String& defaultValue)
  205322. {
  205323. String valueName, result (defaultValue);
  205324. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205325. if (k != 0)
  205326. {
  205327. WCHAR buffer [2048];
  205328. unsigned long bufferSize = sizeof (buffer);
  205329. DWORD type = REG_SZ;
  205330. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205331. {
  205332. if (type == REG_SZ)
  205333. result = buffer;
  205334. else if (type == REG_DWORD)
  205335. result = String ((int) *(DWORD*) buffer);
  205336. }
  205337. RegCloseKey (k);
  205338. }
  205339. return result;
  205340. }
  205341. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205342. const String& value)
  205343. {
  205344. String valueName;
  205345. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205346. if (k != 0)
  205347. {
  205348. RegSetValueEx (k, valueName, 0, REG_SZ,
  205349. (const BYTE*) (const WCHAR*) value,
  205350. sizeof (WCHAR) * (value.length() + 1));
  205351. RegCloseKey (k);
  205352. }
  205353. }
  205354. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205355. {
  205356. bool exists = false;
  205357. String valueName;
  205358. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205359. if (k != 0)
  205360. {
  205361. unsigned char buffer [2048];
  205362. unsigned long bufferSize = sizeof (buffer);
  205363. DWORD type = 0;
  205364. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205365. exists = true;
  205366. RegCloseKey (k);
  205367. }
  205368. return exists;
  205369. }
  205370. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205371. {
  205372. String valueName;
  205373. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205374. if (k != 0)
  205375. {
  205376. RegDeleteValue (k, valueName);
  205377. RegCloseKey (k);
  205378. }
  205379. }
  205380. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205381. {
  205382. String valueName;
  205383. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205384. if (k != 0)
  205385. {
  205386. RegDeleteKey (k, valueName);
  205387. RegCloseKey (k);
  205388. }
  205389. }
  205390. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205391. const String& symbolicDescription,
  205392. const String& fullDescription,
  205393. const File& targetExecutable,
  205394. int iconResourceNumber)
  205395. {
  205396. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205397. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205398. if (iconResourceNumber != 0)
  205399. setRegistryValue (key + "\\DefaultIcon\\",
  205400. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205401. setRegistryValue (key + "\\", fullDescription);
  205402. setRegistryValue (key + "\\shell\\open\\command\\",
  205403. targetExecutable.getFullPathName() + " %1");
  205404. }
  205405. bool juce_IsRunningInWine()
  205406. {
  205407. HKEY key;
  205408. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205409. {
  205410. RegCloseKey (key);
  205411. return true;
  205412. }
  205413. return false;
  205414. }
  205415. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205416. {
  205417. String s (::GetCommandLineW());
  205418. StringArray tokens;
  205419. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205420. return tokens.joinIntoString (" ", 1);
  205421. }
  205422. static void* currentModuleHandle = 0;
  205423. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205424. {
  205425. if (currentModuleHandle == 0)
  205426. currentModuleHandle = GetModuleHandle (0);
  205427. return currentModuleHandle;
  205428. }
  205429. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205430. {
  205431. currentModuleHandle = newHandle;
  205432. }
  205433. void PlatformUtilities::fpuReset()
  205434. {
  205435. #if JUCE_MSVC
  205436. _clearfp();
  205437. #endif
  205438. }
  205439. void PlatformUtilities::beep()
  205440. {
  205441. MessageBeep (MB_OK);
  205442. }
  205443. #endif
  205444. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205445. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205446. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205447. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205448. // compiled on its own).
  205449. #if JUCE_INCLUDED_FILE
  205450. static const unsigned int specialId = WM_APP + 0x4400;
  205451. static const unsigned int broadcastId = WM_APP + 0x4403;
  205452. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205453. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205454. HWND juce_messageWindowHandle = 0;
  205455. extern long improbableWindowNumber; // defined in windowing.cpp
  205456. #ifndef WM_APPCOMMAND
  205457. #define WM_APPCOMMAND 0x0319
  205458. #endif
  205459. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205460. const UINT message,
  205461. const WPARAM wParam,
  205462. const LPARAM lParam) throw()
  205463. {
  205464. JUCE_TRY
  205465. {
  205466. if (h == juce_messageWindowHandle)
  205467. {
  205468. if (message == specialCallbackId)
  205469. {
  205470. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205471. return (LRESULT) (*func) ((void*) lParam);
  205472. }
  205473. else if (message == specialId)
  205474. {
  205475. // these are trapped early in the dispatch call, but must also be checked
  205476. // here in case there are windows modal dialog boxes doing their own
  205477. // dispatch loop and not calling our version
  205478. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205479. return 0;
  205480. }
  205481. else if (message == broadcastId)
  205482. {
  205483. const ScopedPointer <String> messageString ((String*) lParam);
  205484. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205485. return 0;
  205486. }
  205487. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205488. {
  205489. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205490. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205491. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205492. return 0;
  205493. }
  205494. }
  205495. }
  205496. JUCE_CATCH_EXCEPTION
  205497. return DefWindowProc (h, message, wParam, lParam);
  205498. }
  205499. static bool isEventBlockedByModalComps (MSG& m)
  205500. {
  205501. if (Component::getNumCurrentlyModalComponents() == 0
  205502. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205503. return false;
  205504. switch (m.message)
  205505. {
  205506. case WM_MOUSEMOVE:
  205507. case WM_NCMOUSEMOVE:
  205508. case 0x020A: /* WM_MOUSEWHEEL */
  205509. case 0x020E: /* WM_MOUSEHWHEEL */
  205510. case WM_KEYUP:
  205511. case WM_SYSKEYUP:
  205512. case WM_CHAR:
  205513. case WM_APPCOMMAND:
  205514. case WM_LBUTTONUP:
  205515. case WM_MBUTTONUP:
  205516. case WM_RBUTTONUP:
  205517. case WM_MOUSEACTIVATE:
  205518. case WM_NCMOUSEHOVER:
  205519. case WM_MOUSEHOVER:
  205520. return true;
  205521. case WM_NCLBUTTONDOWN:
  205522. case WM_NCLBUTTONDBLCLK:
  205523. case WM_NCRBUTTONDOWN:
  205524. case WM_NCRBUTTONDBLCLK:
  205525. case WM_NCMBUTTONDOWN:
  205526. case WM_NCMBUTTONDBLCLK:
  205527. case WM_LBUTTONDOWN:
  205528. case WM_LBUTTONDBLCLK:
  205529. case WM_MBUTTONDOWN:
  205530. case WM_MBUTTONDBLCLK:
  205531. case WM_RBUTTONDOWN:
  205532. case WM_RBUTTONDBLCLK:
  205533. case WM_KEYDOWN:
  205534. case WM_SYSKEYDOWN:
  205535. {
  205536. Component* const modal = Component::getCurrentlyModalComponent (0);
  205537. if (modal != 0)
  205538. modal->inputAttemptWhenModal();
  205539. return true;
  205540. }
  205541. default:
  205542. break;
  205543. }
  205544. return false;
  205545. }
  205546. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205547. {
  205548. MSG m;
  205549. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205550. return false;
  205551. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205552. {
  205553. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205554. {
  205555. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205556. }
  205557. else if (m.message == WM_QUIT)
  205558. {
  205559. if (JUCEApplication::getInstance() != 0)
  205560. JUCEApplication::getInstance()->systemRequestedQuit();
  205561. }
  205562. else if (! isEventBlockedByModalComps (m))
  205563. {
  205564. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205565. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205566. {
  205567. // if it's someone else's window being clicked on, and the focus is
  205568. // currently on a juce window, pass the kb focus over..
  205569. HWND currentFocus = GetFocus();
  205570. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205571. SetFocus (m.hwnd);
  205572. }
  205573. TranslateMessage (&m);
  205574. DispatchMessage (&m);
  205575. }
  205576. }
  205577. return true;
  205578. }
  205579. bool juce_postMessageToSystemQueue (Message* message)
  205580. {
  205581. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205582. }
  205583. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205584. void* userData)
  205585. {
  205586. if (MessageManager::getInstance()->isThisTheMessageThread())
  205587. {
  205588. return (*callback) (userData);
  205589. }
  205590. else
  205591. {
  205592. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205593. // deadlock because the message manager is blocked from running, and can't
  205594. // call your function..
  205595. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205596. return (void*) SendMessage (juce_messageWindowHandle,
  205597. specialCallbackId,
  205598. (WPARAM) callback,
  205599. (LPARAM) userData);
  205600. }
  205601. }
  205602. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205603. {
  205604. if (hwnd != juce_messageWindowHandle)
  205605. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205606. return TRUE;
  205607. }
  205608. void MessageManager::broadcastMessage (const String& value)
  205609. {
  205610. Array<void*> windows;
  205611. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205612. const String localCopy (value);
  205613. COPYDATASTRUCT data;
  205614. data.dwData = broadcastId;
  205615. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205616. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205617. for (int i = windows.size(); --i >= 0;)
  205618. {
  205619. HWND hwnd = (HWND) windows.getUnchecked(i);
  205620. TCHAR windowName [64]; // no need to read longer strings than this
  205621. GetWindowText (hwnd, windowName, 64);
  205622. windowName [63] = 0;
  205623. if (String (windowName) == messageWindowName)
  205624. {
  205625. DWORD_PTR result;
  205626. SendMessageTimeout (hwnd, WM_COPYDATA,
  205627. (WPARAM) juce_messageWindowHandle,
  205628. (LPARAM) &data,
  205629. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205630. 8000,
  205631. &result);
  205632. }
  205633. }
  205634. }
  205635. static const String getMessageWindowClassName()
  205636. {
  205637. // this name has to be different for each app/dll instance because otherwise
  205638. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205639. // window class).
  205640. static int number = 0;
  205641. if (number == 0)
  205642. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205643. return "JUCEcs_" + String (number);
  205644. }
  205645. void MessageManager::doPlatformSpecificInitialisation()
  205646. {
  205647. OleInitialize (0);
  205648. const String className (getMessageWindowClassName());
  205649. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205650. WNDCLASSEX wc;
  205651. zerostruct (wc);
  205652. wc.cbSize = sizeof (wc);
  205653. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205654. wc.cbWndExtra = 4;
  205655. wc.hInstance = hmod;
  205656. wc.lpszClassName = className;
  205657. RegisterClassEx (&wc);
  205658. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205659. messageWindowName,
  205660. 0, 0, 0, 0, 0, 0, 0,
  205661. hmod, 0);
  205662. }
  205663. void MessageManager::doPlatformSpecificShutdown()
  205664. {
  205665. DestroyWindow (juce_messageWindowHandle);
  205666. UnregisterClass (getMessageWindowClassName(), 0);
  205667. OleUninitialize();
  205668. }
  205669. #endif
  205670. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205671. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205672. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205673. // compiled on its own).
  205674. #if JUCE_INCLUDED_FILE
  205675. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205676. NEWTEXTMETRICEXW*,
  205677. int type,
  205678. LPARAM lParam)
  205679. {
  205680. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205681. {
  205682. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205683. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205684. }
  205685. return 1;
  205686. }
  205687. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205688. NEWTEXTMETRICEXW*,
  205689. int type,
  205690. LPARAM lParam)
  205691. {
  205692. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205693. {
  205694. LOGFONTW lf;
  205695. zerostruct (lf);
  205696. lf.lfWeight = FW_DONTCARE;
  205697. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205698. lf.lfQuality = DEFAULT_QUALITY;
  205699. lf.lfCharSet = DEFAULT_CHARSET;
  205700. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205701. lf.lfPitchAndFamily = FF_DONTCARE;
  205702. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205703. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205704. HDC dc = CreateCompatibleDC (0);
  205705. EnumFontFamiliesEx (dc, &lf,
  205706. (FONTENUMPROCW) &wfontEnum2,
  205707. lParam, 0);
  205708. DeleteDC (dc);
  205709. }
  205710. return 1;
  205711. }
  205712. const StringArray Font::findAllTypefaceNames()
  205713. {
  205714. StringArray results;
  205715. HDC dc = CreateCompatibleDC (0);
  205716. {
  205717. LOGFONTW lf;
  205718. zerostruct (lf);
  205719. lf.lfWeight = FW_DONTCARE;
  205720. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205721. lf.lfQuality = DEFAULT_QUALITY;
  205722. lf.lfCharSet = DEFAULT_CHARSET;
  205723. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205724. lf.lfPitchAndFamily = FF_DONTCARE;
  205725. lf.lfFaceName[0] = 0;
  205726. EnumFontFamiliesEx (dc, &lf,
  205727. (FONTENUMPROCW) &wfontEnum1,
  205728. (LPARAM) &results, 0);
  205729. }
  205730. DeleteDC (dc);
  205731. results.sort (true);
  205732. return results;
  205733. }
  205734. extern bool juce_IsRunningInWine();
  205735. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205736. {
  205737. if (juce_IsRunningInWine())
  205738. {
  205739. // If we're running in Wine, then use fonts that might be available on Linux..
  205740. defaultSans = "Bitstream Vera Sans";
  205741. defaultSerif = "Bitstream Vera Serif";
  205742. defaultFixed = "Bitstream Vera Sans Mono";
  205743. }
  205744. else
  205745. {
  205746. defaultSans = "Verdana";
  205747. defaultSerif = "Times";
  205748. defaultFixed = "Lucida Console";
  205749. }
  205750. }
  205751. class FontDCHolder : private DeletedAtShutdown
  205752. {
  205753. public:
  205754. FontDCHolder()
  205755. : dc (0), numKPs (0), size (0),
  205756. bold (false), italic (false)
  205757. {
  205758. }
  205759. ~FontDCHolder()
  205760. {
  205761. if (dc != 0)
  205762. {
  205763. DeleteDC (dc);
  205764. DeleteObject (fontH);
  205765. }
  205766. clearSingletonInstance();
  205767. }
  205768. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205769. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205770. {
  205771. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205772. {
  205773. fontName = fontName_;
  205774. bold = bold_;
  205775. italic = italic_;
  205776. size = size_;
  205777. if (dc != 0)
  205778. {
  205779. DeleteDC (dc);
  205780. DeleteObject (fontH);
  205781. kps.free();
  205782. }
  205783. fontH = 0;
  205784. dc = CreateCompatibleDC (0);
  205785. SetMapperFlags (dc, 0);
  205786. SetMapMode (dc, MM_TEXT);
  205787. LOGFONTW lfw;
  205788. zerostruct (lfw);
  205789. lfw.lfCharSet = DEFAULT_CHARSET;
  205790. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205791. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205792. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205793. lfw.lfQuality = PROOF_QUALITY;
  205794. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205795. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205796. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205797. lfw.lfHeight = size > 0 ? size : -256;
  205798. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205799. if (standardSizedFont != 0)
  205800. {
  205801. if (SelectObject (dc, standardSizedFont) != 0)
  205802. {
  205803. fontH = standardSizedFont;
  205804. if (size == 0)
  205805. {
  205806. OUTLINETEXTMETRIC otm;
  205807. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205808. {
  205809. lfw.lfHeight = -(int) otm.otmEMSquare;
  205810. fontH = CreateFontIndirect (&lfw);
  205811. SelectObject (dc, fontH);
  205812. DeleteObject (standardSizedFont);
  205813. }
  205814. }
  205815. }
  205816. else
  205817. {
  205818. jassertfalse;
  205819. }
  205820. }
  205821. else
  205822. {
  205823. jassertfalse;
  205824. }
  205825. }
  205826. return dc;
  205827. }
  205828. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205829. {
  205830. if (kps == 0)
  205831. {
  205832. numKPs = GetKerningPairs (dc, 0, 0);
  205833. kps.calloc (numKPs);
  205834. GetKerningPairs (dc, numKPs, kps);
  205835. }
  205836. numKPs_ = numKPs;
  205837. return kps;
  205838. }
  205839. private:
  205840. HFONT fontH;
  205841. HDC dc;
  205842. String fontName;
  205843. HeapBlock <KERNINGPAIR> kps;
  205844. int numKPs, size;
  205845. bool bold, italic;
  205846. FontDCHolder (const FontDCHolder&);
  205847. FontDCHolder& operator= (const FontDCHolder&);
  205848. };
  205849. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205850. class WindowsTypeface : public CustomTypeface
  205851. {
  205852. public:
  205853. WindowsTypeface (const Font& font)
  205854. {
  205855. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205856. font.isBold(), font.isItalic(), 0);
  205857. TEXTMETRIC tm;
  205858. tm.tmAscent = tm.tmHeight = 1;
  205859. tm.tmDefaultChar = 0;
  205860. GetTextMetrics (dc, &tm);
  205861. setCharacteristics (font.getTypefaceName(),
  205862. tm.tmAscent / (float) tm.tmHeight,
  205863. font.isBold(), font.isItalic(),
  205864. tm.tmDefaultChar);
  205865. }
  205866. bool loadGlyphIfPossible (juce_wchar character)
  205867. {
  205868. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205869. GLYPHMETRICS gm;
  205870. {
  205871. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205872. WORD index = 0;
  205873. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205874. && index == 0xffff)
  205875. {
  205876. return false;
  205877. }
  205878. }
  205879. Path glyphPath;
  205880. TEXTMETRIC tm;
  205881. if (! GetTextMetrics (dc, &tm))
  205882. {
  205883. addGlyph (character, glyphPath, 0);
  205884. return true;
  205885. }
  205886. const float height = (float) tm.tmHeight;
  205887. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205888. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205889. &gm, 0, 0, &identityMatrix);
  205890. if (bufSize > 0)
  205891. {
  205892. HeapBlock<char> data (bufSize);
  205893. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205894. bufSize, data, &identityMatrix);
  205895. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205896. const float scaleX = 1.0f / height;
  205897. const float scaleY = -1.0f / height;
  205898. while ((char*) pheader < data + bufSize)
  205899. {
  205900. float x = scaleX * pheader->pfxStart.x.value;
  205901. float y = scaleY * pheader->pfxStart.y.value;
  205902. glyphPath.startNewSubPath (x, y);
  205903. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205904. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205905. while ((const char*) curve < curveEnd)
  205906. {
  205907. if (curve->wType == TT_PRIM_LINE)
  205908. {
  205909. for (int i = 0; i < curve->cpfx; ++i)
  205910. {
  205911. x = scaleX * curve->apfx[i].x.value;
  205912. y = scaleY * curve->apfx[i].y.value;
  205913. glyphPath.lineTo (x, y);
  205914. }
  205915. }
  205916. else if (curve->wType == TT_PRIM_QSPLINE)
  205917. {
  205918. for (int i = 0; i < curve->cpfx - 1; ++i)
  205919. {
  205920. const float x2 = scaleX * curve->apfx[i].x.value;
  205921. const float y2 = scaleY * curve->apfx[i].y.value;
  205922. float x3, y3;
  205923. if (i < curve->cpfx - 2)
  205924. {
  205925. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205926. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205927. }
  205928. else
  205929. {
  205930. x3 = scaleX * curve->apfx[i + 1].x.value;
  205931. y3 = scaleY * curve->apfx[i + 1].y.value;
  205932. }
  205933. glyphPath.quadraticTo (x2, y2, x3, y3);
  205934. x = x3;
  205935. y = y3;
  205936. }
  205937. }
  205938. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205939. }
  205940. pheader = (const TTPOLYGONHEADER*) curve;
  205941. glyphPath.closeSubPath();
  205942. }
  205943. }
  205944. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205945. int numKPs;
  205946. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205947. for (int i = 0; i < numKPs; ++i)
  205948. {
  205949. if (kps[i].wFirst == character)
  205950. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205951. kps[i].iKernAmount / height);
  205952. }
  205953. return true;
  205954. }
  205955. juce_UseDebuggingNewOperator
  205956. };
  205957. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205958. {
  205959. return new WindowsTypeface (font);
  205960. }
  205961. #endif
  205962. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205963. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205964. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205965. // compiled on its own).
  205966. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205967. class SharedD2DFactory : public DeletedAtShutdown
  205968. {
  205969. public:
  205970. SharedD2DFactory()
  205971. {
  205972. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205973. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205974. if (directWriteFactory != 0)
  205975. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205976. }
  205977. ~SharedD2DFactory()
  205978. {
  205979. clearSingletonInstance();
  205980. }
  205981. juce_DeclareSingleton (SharedD2DFactory, false);
  205982. ComSmartPtr <ID2D1Factory> d2dFactory;
  205983. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205984. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205985. };
  205986. juce_ImplementSingleton (SharedD2DFactory)
  205987. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205988. {
  205989. public:
  205990. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205991. : hwnd (hwnd_),
  205992. currentState (0)
  205993. {
  205994. RECT windowRect;
  205995. GetClientRect (hwnd, &windowRect);
  205996. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205997. bounds.setSize (size.width, size.height);
  205998. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205999. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  206000. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  206001. // xxx check for error
  206002. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  206003. }
  206004. ~Direct2DLowLevelGraphicsContext()
  206005. {
  206006. states.clear();
  206007. }
  206008. void resized()
  206009. {
  206010. RECT windowRect;
  206011. GetClientRect (hwnd, &windowRect);
  206012. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206013. renderingTarget->Resize (size);
  206014. bounds.setSize (size.width, size.height);
  206015. }
  206016. void clear()
  206017. {
  206018. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  206019. }
  206020. void start()
  206021. {
  206022. renderingTarget->BeginDraw();
  206023. saveState();
  206024. }
  206025. void end()
  206026. {
  206027. states.clear();
  206028. currentState = 0;
  206029. renderingTarget->EndDraw();
  206030. renderingTarget->CheckWindowState();
  206031. }
  206032. bool isVectorDevice() const { return false; }
  206033. void setOrigin (int x, int y)
  206034. {
  206035. currentState->origin.addXY (x, y);
  206036. }
  206037. bool clipToRectangle (const Rectangle<int>& r)
  206038. {
  206039. currentState->clipToRectangle (r);
  206040. return ! isClipEmpty();
  206041. }
  206042. bool clipToRectangleList (const RectangleList& clipRegion)
  206043. {
  206044. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  206045. return ! isClipEmpty();
  206046. }
  206047. void excludeClipRectangle (const Rectangle<int>&)
  206048. {
  206049. //xxx
  206050. }
  206051. void clipToPath (const Path& path, const AffineTransform& transform)
  206052. {
  206053. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  206054. }
  206055. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  206056. {
  206057. currentState->clipToImage (sourceImage,transform);
  206058. }
  206059. bool clipRegionIntersects (const Rectangle<int>& r)
  206060. {
  206061. const Rectangle<int> r2 (r + currentState->origin);
  206062. return currentState->clipRect.intersects (r2);
  206063. }
  206064. const Rectangle<int> getClipBounds() const
  206065. {
  206066. // xxx could this take into account complex clip regions?
  206067. return currentState->clipRect - currentState->origin;
  206068. }
  206069. bool isClipEmpty() const
  206070. {
  206071. return currentState->clipRect.isEmpty();
  206072. }
  206073. void saveState()
  206074. {
  206075. states.add (new SavedState (*this));
  206076. currentState = states.getLast();
  206077. }
  206078. void restoreState()
  206079. {
  206080. jassert (states.size() > 1) //you should never pop the last state!
  206081. states.removeLast (1);
  206082. currentState = states.getLast();
  206083. }
  206084. void setFill (const FillType& fillType)
  206085. {
  206086. currentState->setFill (fillType);
  206087. }
  206088. void setOpacity (float newOpacity)
  206089. {
  206090. currentState->setOpacity (newOpacity);
  206091. }
  206092. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  206093. {
  206094. }
  206095. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206096. {
  206097. currentState->createBrush();
  206098. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206099. }
  206100. void fillPath (const Path& p, const AffineTransform& transform)
  206101. {
  206102. currentState->createBrush();
  206103. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206104. if (renderingTarget != 0)
  206105. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206106. }
  206107. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206108. {
  206109. const int x = currentState->origin.getX();
  206110. const int y = currentState->origin.getY();
  206111. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206112. D2D1_SIZE_U size;
  206113. size.width = image.getWidth();
  206114. size.height = image.getHeight();
  206115. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206116. Image img (image.convertedToFormat (Image::ARGB));
  206117. Image::BitmapData bd (img, false);
  206118. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206119. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206120. {
  206121. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206122. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  206123. if (tempBitmap != 0)
  206124. renderingTarget->DrawBitmap (tempBitmap);
  206125. }
  206126. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206127. }
  206128. void drawLine (const Line <float>& line)
  206129. {
  206130. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206131. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206132. line.getEnd() + currentState->origin.toFloat());
  206133. currentState->createBrush();
  206134. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206135. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206136. currentState->currentBrush);
  206137. }
  206138. void drawVerticalLine (int x, float top, float bottom)
  206139. {
  206140. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206141. currentState->createBrush();
  206142. x += currentState->origin.getX();
  206143. const int y = currentState->origin.getY();
  206144. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206145. D2D1::Point2F (x, y + bottom),
  206146. currentState->currentBrush);
  206147. }
  206148. void drawHorizontalLine (int y, float left, float right)
  206149. {
  206150. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206151. currentState->createBrush();
  206152. y += currentState->origin.getY();
  206153. const int x = currentState->origin.getX();
  206154. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206155. D2D1::Point2F (x + right, y),
  206156. currentState->currentBrush);
  206157. }
  206158. void setFont (const Font& newFont)
  206159. {
  206160. currentState->setFont (newFont);
  206161. }
  206162. const Font getFont()
  206163. {
  206164. return currentState->font;
  206165. }
  206166. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206167. {
  206168. const float x = currentState->origin.getX();
  206169. const float y = currentState->origin.getY();
  206170. currentState->createBrush();
  206171. currentState->createFont();
  206172. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206173. float hScale = currentState->font.getHorizontalScale();
  206174. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206175. float dpiX = 0, dpiY = 0;
  206176. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206177. UINT32 glyphNum = glyphNumber;
  206178. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206179. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206180. DWRITE_GLYPH_OFFSET offset;
  206181. offset.advanceOffset = 0;
  206182. offset.ascenderOffset = 0;
  206183. float glyphAdvances = 0;
  206184. DWRITE_GLYPH_RUN glyph;
  206185. glyph.fontFace = currentState->currentFontFace;
  206186. glyph.glyphCount = 1;
  206187. glyph.glyphIndices = &glyphNum1;
  206188. glyph.isSideways = FALSE;
  206189. glyph.glyphAdvances = &glyphAdvances;
  206190. glyph.glyphOffsets = &offset;
  206191. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206192. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206193. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206194. }
  206195. class SavedState
  206196. {
  206197. public:
  206198. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206199. : owner (owner_), currentBrush (0),
  206200. fontScaling (1.0f), currentFontFace (0),
  206201. clipsRect (false), shouldClipRect (false),
  206202. clipsRectList (false), shouldClipRectList (false),
  206203. clipsComplex (false), shouldClipComplex (false),
  206204. clipsBitmap (false), shouldClipBitmap (false)
  206205. {
  206206. if (owner.currentState != 0)
  206207. {
  206208. // xxx seems like a very slow way to create one of these, and this is a performance
  206209. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206210. setFill (owner.currentState->fillType);
  206211. currentBrush = owner.currentState->currentBrush;
  206212. origin = owner.currentState->origin;
  206213. clipRect = owner.currentState->clipRect;
  206214. font = owner.currentState->font;
  206215. currentFontFace = owner.currentState->currentFontFace;
  206216. }
  206217. else
  206218. {
  206219. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206220. clipRect.setSize (size.width, size.height);
  206221. setFill (FillType (Colours::black));
  206222. }
  206223. }
  206224. ~SavedState()
  206225. {
  206226. clearClip();
  206227. clearFont();
  206228. clearFill();
  206229. clearPathClip();
  206230. clearImageClip();
  206231. complexClipLayer = 0;
  206232. bitmapMaskLayer = 0;
  206233. }
  206234. void clearClip()
  206235. {
  206236. popClips();
  206237. shouldClipRect = false;
  206238. }
  206239. void clipToRectangle (const Rectangle<int>& r)
  206240. {
  206241. clearClip();
  206242. clipRect = r + origin;
  206243. shouldClipRect = true;
  206244. pushClips();
  206245. }
  206246. void clearPathClip()
  206247. {
  206248. popClips();
  206249. if (shouldClipComplex)
  206250. {
  206251. complexClipGeometry = 0;
  206252. shouldClipComplex = false;
  206253. }
  206254. }
  206255. void clipToPath (ID2D1Geometry* geometry)
  206256. {
  206257. clearPathClip();
  206258. if (complexClipLayer == 0)
  206259. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206260. complexClipGeometry = geometry;
  206261. shouldClipComplex = true;
  206262. pushClips();
  206263. }
  206264. void clearRectListClip()
  206265. {
  206266. popClips();
  206267. if (shouldClipRectList)
  206268. {
  206269. rectListGeometry = 0;
  206270. shouldClipRectList = false;
  206271. }
  206272. }
  206273. void clipToRectList (ID2D1Geometry* geometry)
  206274. {
  206275. clearRectListClip();
  206276. if (rectListLayer == 0)
  206277. owner.renderingTarget->CreateLayer (&rectListLayer);
  206278. rectListGeometry = geometry;
  206279. shouldClipRectList = true;
  206280. pushClips();
  206281. }
  206282. void clearImageClip()
  206283. {
  206284. popClips();
  206285. if (shouldClipBitmap)
  206286. {
  206287. maskBitmap = 0;
  206288. bitmapMaskBrush = 0;
  206289. shouldClipBitmap = false;
  206290. }
  206291. }
  206292. void clipToImage (const Image& image, const AffineTransform& transform)
  206293. {
  206294. clearImageClip();
  206295. if (bitmapMaskLayer == 0)
  206296. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206297. D2D1_BRUSH_PROPERTIES brushProps;
  206298. brushProps.opacity = 1;
  206299. brushProps.transform = transfromToMatrix (transform);
  206300. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206301. D2D1_SIZE_U size;
  206302. size.width = image.getWidth();
  206303. size.height = image.getHeight();
  206304. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206305. maskImage = image.convertedToFormat (Image::ARGB);
  206306. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206307. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206308. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206309. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206310. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206311. imageMaskLayerParams = D2D1::LayerParameters();
  206312. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206313. shouldClipBitmap = true;
  206314. pushClips();
  206315. }
  206316. void popClips()
  206317. {
  206318. if (clipsBitmap)
  206319. {
  206320. owner.renderingTarget->PopLayer();
  206321. clipsBitmap = false;
  206322. }
  206323. if (clipsComplex)
  206324. {
  206325. owner.renderingTarget->PopLayer();
  206326. clipsComplex = false;
  206327. }
  206328. if (clipsRectList)
  206329. {
  206330. owner.renderingTarget->PopLayer();
  206331. clipsRectList = false;
  206332. }
  206333. if (clipsRect)
  206334. {
  206335. owner.renderingTarget->PopAxisAlignedClip();
  206336. clipsRect = false;
  206337. }
  206338. }
  206339. void pushClips()
  206340. {
  206341. if (shouldClipRect && ! clipsRect)
  206342. {
  206343. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206344. clipsRect = true;
  206345. }
  206346. if (shouldClipRectList && ! clipsRectList)
  206347. {
  206348. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206349. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206350. layerParams.geometricMask = rectListGeometry;
  206351. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206352. clipsRectList = true;
  206353. }
  206354. if (shouldClipComplex && ! clipsComplex)
  206355. {
  206356. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206357. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206358. layerParams.geometricMask = complexClipGeometry;
  206359. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206360. clipsComplex = true;
  206361. }
  206362. if (shouldClipBitmap && ! clipsBitmap)
  206363. {
  206364. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206365. clipsBitmap = true;
  206366. }
  206367. }
  206368. void setFill (const FillType& newFillType)
  206369. {
  206370. if (fillType != newFillType)
  206371. {
  206372. fillType = newFillType;
  206373. clearFill();
  206374. }
  206375. }
  206376. void clearFont()
  206377. {
  206378. currentFontFace = localFontFace = 0;
  206379. }
  206380. void setFont (const Font& newFont)
  206381. {
  206382. if (font != newFont)
  206383. {
  206384. font = newFont;
  206385. clearFont();
  206386. }
  206387. }
  206388. void createFont()
  206389. {
  206390. // xxx The font shouldn't be managed by the graphics context.
  206391. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206392. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206393. // WindowsTypeface class.
  206394. if (currentFontFace == 0)
  206395. {
  206396. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206397. fontScaling = systemType->getAscent();
  206398. BOOL fontFound;
  206399. uint32 fontIndex;
  206400. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206401. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206402. if (! fontFound)
  206403. fontIndex = 0;
  206404. ComSmartPtr <IDWriteFontFamily> fontFam;
  206405. fonts->GetFontFamily (fontIndex, &fontFam);
  206406. ComSmartPtr <IDWriteFont> font;
  206407. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206408. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206409. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206410. font->CreateFontFace (&localFontFace);
  206411. currentFontFace = localFontFace;
  206412. }
  206413. }
  206414. void setOpacity (float newOpacity)
  206415. {
  206416. fillType.setOpacity (newOpacity);
  206417. if (currentBrush != 0)
  206418. currentBrush->SetOpacity (newOpacity);
  206419. }
  206420. void clearFill()
  206421. {
  206422. gradientStops = 0;
  206423. linearGradient = 0;
  206424. radialGradient = 0;
  206425. bitmap = 0;
  206426. bitmapBrush = 0;
  206427. currentBrush = 0;
  206428. }
  206429. void createBrush()
  206430. {
  206431. if (currentBrush == 0)
  206432. {
  206433. const int x = origin.getX();
  206434. const int y = origin.getY();
  206435. if (fillType.isColour())
  206436. {
  206437. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206438. owner.colourBrush->SetColor (colour);
  206439. currentBrush = owner.colourBrush;
  206440. }
  206441. else if (fillType.isTiledImage())
  206442. {
  206443. D2D1_BRUSH_PROPERTIES brushProps;
  206444. brushProps.opacity = fillType.getOpacity();
  206445. brushProps.transform = transfromToMatrix (fillType.transform);
  206446. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206447. image = fillType.image;
  206448. D2D1_SIZE_U size;
  206449. size.width = image.getWidth();
  206450. size.height = image.getHeight();
  206451. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206452. this->image = image.convertedToFormat (Image::ARGB);
  206453. Image::BitmapData bd (this->image, false);
  206454. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206455. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206456. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206457. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206458. currentBrush = bitmapBrush;
  206459. }
  206460. else if (fillType.isGradient())
  206461. {
  206462. gradientStops = 0;
  206463. D2D1_BRUSH_PROPERTIES brushProps;
  206464. brushProps.opacity = fillType.getOpacity();
  206465. brushProps.transform = transfromToMatrix (fillType.transform);
  206466. const int numColors = fillType.gradient->getNumColours();
  206467. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206468. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206469. {
  206470. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206471. stops[i].position = fillType.gradient->getColourPosition(i);
  206472. }
  206473. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206474. if (fillType.gradient->isRadial)
  206475. {
  206476. radialGradient = 0;
  206477. const Point<float>& p1 = fillType.gradient->point1;
  206478. const Point<float>& p2 = fillType.gradient->point2;
  206479. float r = p1.getDistanceFrom (p2);
  206480. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206481. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206482. D2D1::Point2F (0, 0),
  206483. r, r);
  206484. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206485. currentBrush = radialGradient;
  206486. }
  206487. else
  206488. {
  206489. linearGradient = 0;
  206490. const Point<float>& p1 = fillType.gradient->point1;
  206491. const Point<float>& p2 = fillType.gradient->point2;
  206492. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206493. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206494. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206495. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206496. currentBrush = linearGradient;
  206497. }
  206498. }
  206499. }
  206500. }
  206501. juce_UseDebuggingNewOperator
  206502. //xxx most of these members should probably be private...
  206503. Direct2DLowLevelGraphicsContext& owner;
  206504. Point<int> origin;
  206505. Font font;
  206506. float fontScaling;
  206507. IDWriteFontFace* currentFontFace;
  206508. ComSmartPtr <IDWriteFontFace> localFontFace;
  206509. FillType fillType;
  206510. Image image;
  206511. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206512. Rectangle<int> clipRect;
  206513. bool clipsRect, shouldClipRect;
  206514. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206515. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206516. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206517. bool clipsComplex, shouldClipComplex;
  206518. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206519. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206520. ComSmartPtr <ID2D1Layer> rectListLayer;
  206521. bool clipsRectList, shouldClipRectList;
  206522. Image maskImage;
  206523. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206524. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206525. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206526. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206527. bool clipsBitmap, shouldClipBitmap;
  206528. ID2D1Brush* currentBrush;
  206529. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206530. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206531. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206532. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206533. private:
  206534. SavedState (const SavedState&);
  206535. SavedState& operator= (const SavedState& other);
  206536. };
  206537. juce_UseDebuggingNewOperator
  206538. private:
  206539. HWND hwnd;
  206540. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206541. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206542. Rectangle<int> bounds;
  206543. SavedState* currentState;
  206544. OwnedArray<SavedState> states;
  206545. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206546. {
  206547. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206548. }
  206549. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206550. {
  206551. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206552. }
  206553. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206554. {
  206555. transform.transformPoint (x, y);
  206556. return D2D1::Point2F (x, y);
  206557. }
  206558. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206559. {
  206560. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206561. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206562. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206563. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206564. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206565. }
  206566. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206567. {
  206568. ID2D1PathGeometry* p = 0;
  206569. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206570. ComSmartPtr <ID2D1GeometrySink> sink;
  206571. HRESULT hr = p->Open (&sink); // xxx handle error
  206572. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206573. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206574. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206575. hr = sink->Close();
  206576. return p;
  206577. }
  206578. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206579. {
  206580. Path::Iterator it (path);
  206581. while (it.next())
  206582. {
  206583. switch (it.elementType)
  206584. {
  206585. case Path::Iterator::cubicTo:
  206586. {
  206587. D2D1_BEZIER_SEGMENT seg;
  206588. transform.transformPoint (it.x1, it.y1);
  206589. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206590. transform.transformPoint (it.x2, it.y2);
  206591. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206592. transform.transformPoint(it.x3, it.y3);
  206593. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206594. sink->AddBezier (seg);
  206595. break;
  206596. }
  206597. case Path::Iterator::lineTo:
  206598. {
  206599. transform.transformPoint (it.x1, it.y1);
  206600. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206601. break;
  206602. }
  206603. case Path::Iterator::quadraticTo:
  206604. {
  206605. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206606. transform.transformPoint (it.x1, it.y1);
  206607. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206608. transform.transformPoint (it.x2, it.y2);
  206609. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206610. sink->AddQuadraticBezier (seg);
  206611. break;
  206612. }
  206613. case Path::Iterator::closePath:
  206614. {
  206615. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206616. break;
  206617. }
  206618. case Path::Iterator::startNewSubPath:
  206619. {
  206620. transform.transformPoint (it.x1, it.y1);
  206621. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206622. break;
  206623. }
  206624. }
  206625. }
  206626. }
  206627. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206628. {
  206629. ID2D1PathGeometry* p = 0;
  206630. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206631. ComSmartPtr <ID2D1GeometrySink> sink;
  206632. HRESULT hr = p->Open (&sink);
  206633. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206634. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206635. hr = sink->Close();
  206636. return p;
  206637. }
  206638. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206639. {
  206640. D2D1::Matrix3x2F matrix;
  206641. matrix._11 = transform.mat00;
  206642. matrix._12 = transform.mat10;
  206643. matrix._21 = transform.mat01;
  206644. matrix._22 = transform.mat11;
  206645. matrix._31 = transform.mat02;
  206646. matrix._32 = transform.mat12;
  206647. return matrix;
  206648. }
  206649. };
  206650. #endif
  206651. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206652. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206653. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206654. // compiled on its own).
  206655. #if JUCE_INCLUDED_FILE
  206656. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206657. // these are in the windows SDK, but need to be repeated here for GCC..
  206658. #ifndef GET_APPCOMMAND_LPARAM
  206659. #define FAPPCOMMAND_MASK 0xF000
  206660. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206661. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206662. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206663. #define APPCOMMAND_MEDIA_STOP 13
  206664. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206665. #define WM_APPCOMMAND 0x0319
  206666. #endif
  206667. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206668. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206669. extern bool juce_IsRunningInWine();
  206670. #ifndef ULW_ALPHA
  206671. #define ULW_ALPHA 0x00000002
  206672. #endif
  206673. #ifndef AC_SRC_ALPHA
  206674. #define AC_SRC_ALPHA 0x01
  206675. #endif
  206676. static HPALETTE palette = 0;
  206677. static bool createPaletteIfNeeded = true;
  206678. static bool shouldDeactivateTitleBar = true;
  206679. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206680. #define WM_TRAYNOTIFY WM_USER + 100
  206681. using ::abs;
  206682. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206683. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206684. bool Desktop::canUseSemiTransparentWindows() throw()
  206685. {
  206686. if (updateLayeredWindow == 0)
  206687. {
  206688. if (! juce_IsRunningInWine())
  206689. {
  206690. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206691. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206692. }
  206693. }
  206694. return updateLayeredWindow != 0;
  206695. }
  206696. const int extendedKeyModifier = 0x10000;
  206697. const int KeyPress::spaceKey = VK_SPACE;
  206698. const int KeyPress::returnKey = VK_RETURN;
  206699. const int KeyPress::escapeKey = VK_ESCAPE;
  206700. const int KeyPress::backspaceKey = VK_BACK;
  206701. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206702. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206703. const int KeyPress::tabKey = VK_TAB;
  206704. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206705. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206706. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206707. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206708. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206709. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206710. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206711. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206712. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206713. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206714. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206715. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206716. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206717. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206718. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206719. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206720. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206721. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206722. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206723. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206724. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206725. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206726. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206727. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206728. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206729. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206730. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206731. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206732. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206733. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206734. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206735. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206736. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206737. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206738. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206739. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206740. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206741. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206742. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206743. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206744. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206745. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206746. const int KeyPress::playKey = 0x30000;
  206747. const int KeyPress::stopKey = 0x30001;
  206748. const int KeyPress::fastForwardKey = 0x30002;
  206749. const int KeyPress::rewindKey = 0x30003;
  206750. class WindowsBitmapImage : public Image::SharedImage
  206751. {
  206752. public:
  206753. HBITMAP hBitmap;
  206754. BITMAPV4HEADER bitmapInfo;
  206755. HDC hdc;
  206756. unsigned char* bitmapData;
  206757. WindowsBitmapImage (const Image::PixelFormat format_,
  206758. const int w, const int h, const bool clearImage)
  206759. : Image::SharedImage (format_, w, h)
  206760. {
  206761. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206762. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206763. zerostruct (bitmapInfo);
  206764. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206765. bitmapInfo.bV4Width = w;
  206766. bitmapInfo.bV4Height = h;
  206767. bitmapInfo.bV4Planes = 1;
  206768. bitmapInfo.bV4CSType = 1;
  206769. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206770. if (format_ == Image::ARGB)
  206771. {
  206772. bitmapInfo.bV4AlphaMask = 0xff000000;
  206773. bitmapInfo.bV4RedMask = 0xff0000;
  206774. bitmapInfo.bV4GreenMask = 0xff00;
  206775. bitmapInfo.bV4BlueMask = 0xff;
  206776. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206777. }
  206778. else
  206779. {
  206780. bitmapInfo.bV4V4Compression = BI_RGB;
  206781. }
  206782. lineStride = -((w * pixelStride + 3) & ~3);
  206783. HDC dc = GetDC (0);
  206784. hdc = CreateCompatibleDC (dc);
  206785. ReleaseDC (0, dc);
  206786. SetMapMode (hdc, MM_TEXT);
  206787. hBitmap = CreateDIBSection (hdc,
  206788. (BITMAPINFO*) &(bitmapInfo),
  206789. DIB_RGB_COLORS,
  206790. (void**) &bitmapData,
  206791. 0, 0);
  206792. SelectObject (hdc, hBitmap);
  206793. if (format_ == Image::ARGB && clearImage)
  206794. zeromem (bitmapData, abs (h * lineStride));
  206795. imageData = bitmapData - (lineStride * (h - 1));
  206796. }
  206797. ~WindowsBitmapImage()
  206798. {
  206799. DeleteDC (hdc);
  206800. DeleteObject (hBitmap);
  206801. }
  206802. Image::ImageType getType() const { return Image::NativeImage; }
  206803. LowLevelGraphicsContext* createLowLevelContext()
  206804. {
  206805. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206806. }
  206807. SharedImage* clone()
  206808. {
  206809. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206810. for (int i = 0; i < height; ++i)
  206811. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206812. return im;
  206813. }
  206814. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206815. const int x, const int y,
  206816. const RectangleList& maskedRegion) throw()
  206817. {
  206818. static HDRAWDIB hdd = 0;
  206819. static bool needToCreateDrawDib = true;
  206820. if (needToCreateDrawDib)
  206821. {
  206822. needToCreateDrawDib = false;
  206823. HDC dc = GetDC (0);
  206824. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206825. ReleaseDC (0, dc);
  206826. // only open if we're not palettised
  206827. if (n > 8)
  206828. hdd = DrawDibOpen();
  206829. }
  206830. if (createPaletteIfNeeded)
  206831. {
  206832. HDC dc = GetDC (0);
  206833. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206834. ReleaseDC (0, dc);
  206835. if (n <= 8)
  206836. palette = CreateHalftonePalette (dc);
  206837. createPaletteIfNeeded = false;
  206838. }
  206839. if (palette != 0)
  206840. {
  206841. SelectPalette (dc, palette, FALSE);
  206842. RealizePalette (dc);
  206843. SetStretchBltMode (dc, HALFTONE);
  206844. }
  206845. SetMapMode (dc, MM_TEXT);
  206846. if (transparent)
  206847. {
  206848. POINT p, pos;
  206849. SIZE size;
  206850. RECT windowBounds;
  206851. GetWindowRect (hwnd, &windowBounds);
  206852. p.x = -x;
  206853. p.y = -y;
  206854. pos.x = windowBounds.left;
  206855. pos.y = windowBounds.top;
  206856. size.cx = windowBounds.right - windowBounds.left;
  206857. size.cy = windowBounds.bottom - windowBounds.top;
  206858. BLENDFUNCTION bf;
  206859. bf.AlphaFormat = AC_SRC_ALPHA;
  206860. bf.BlendFlags = 0;
  206861. bf.BlendOp = AC_SRC_OVER;
  206862. bf.SourceConstantAlpha = 0xff;
  206863. if (! maskedRegion.isEmpty())
  206864. {
  206865. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206866. {
  206867. const Rectangle<int>& r = *i.getRectangle();
  206868. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206869. }
  206870. }
  206871. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206872. }
  206873. else
  206874. {
  206875. int savedDC = 0;
  206876. if (! maskedRegion.isEmpty())
  206877. {
  206878. savedDC = SaveDC (dc);
  206879. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206880. {
  206881. const Rectangle<int>& r = *i.getRectangle();
  206882. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206883. }
  206884. }
  206885. if (hdd == 0)
  206886. {
  206887. StretchDIBits (dc,
  206888. x, y, width, height,
  206889. 0, 0, width, height,
  206890. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206891. DIB_RGB_COLORS, SRCCOPY);
  206892. }
  206893. else
  206894. {
  206895. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206896. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206897. 0, 0, width, height, 0);
  206898. }
  206899. if (! maskedRegion.isEmpty())
  206900. RestoreDC (dc, savedDC);
  206901. }
  206902. }
  206903. juce_UseDebuggingNewOperator
  206904. private:
  206905. WindowsBitmapImage (const WindowsBitmapImage&);
  206906. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206907. };
  206908. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206909. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206910. {
  206911. SHORT k = (SHORT) keyCode;
  206912. if ((keyCode & extendedKeyModifier) == 0
  206913. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206914. k += (SHORT) 'A' - (SHORT) 'a';
  206915. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206916. (SHORT) '+', VK_OEM_PLUS,
  206917. (SHORT) '-', VK_OEM_MINUS,
  206918. (SHORT) '.', VK_OEM_PERIOD,
  206919. (SHORT) ';', VK_OEM_1,
  206920. (SHORT) ':', VK_OEM_1,
  206921. (SHORT) '/', VK_OEM_2,
  206922. (SHORT) '?', VK_OEM_2,
  206923. (SHORT) '[', VK_OEM_4,
  206924. (SHORT) ']', VK_OEM_6 };
  206925. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206926. if (k == translatedValues [i])
  206927. k = translatedValues [i + 1];
  206928. return (GetKeyState (k) & 0x8000) != 0;
  206929. }
  206930. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206931. {
  206932. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206933. return callback (userData);
  206934. else
  206935. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206936. }
  206937. class Win32ComponentPeer : public ComponentPeer
  206938. {
  206939. public:
  206940. enum RenderingEngineType
  206941. {
  206942. softwareRenderingEngine = 0,
  206943. direct2DRenderingEngine
  206944. };
  206945. Win32ComponentPeer (Component* const component,
  206946. const int windowStyleFlags,
  206947. HWND parentToAddTo_)
  206948. : ComponentPeer (component, windowStyleFlags),
  206949. dontRepaint (false),
  206950. #if JUCE_DIRECT2D
  206951. currentRenderingEngine (direct2DRenderingEngine),
  206952. #else
  206953. currentRenderingEngine (softwareRenderingEngine),
  206954. #endif
  206955. fullScreen (false),
  206956. isDragging (false),
  206957. isMouseOver (false),
  206958. hasCreatedCaret (false),
  206959. currentWindowIcon (0),
  206960. dropTarget (0),
  206961. parentToAddTo (parentToAddTo_)
  206962. {
  206963. callFunctionIfNotLocked (&createWindowCallback, this);
  206964. setTitle (component->getName());
  206965. if ((windowStyleFlags & windowHasDropShadow) != 0
  206966. && Desktop::canUseSemiTransparentWindows())
  206967. {
  206968. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206969. if (shadower != 0)
  206970. shadower->setOwner (component);
  206971. }
  206972. }
  206973. ~Win32ComponentPeer()
  206974. {
  206975. setTaskBarIcon (Image());
  206976. shadower = 0;
  206977. // do this before the next bit to avoid messages arriving for this window
  206978. // before it's destroyed
  206979. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206980. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206981. if (currentWindowIcon != 0)
  206982. DestroyIcon (currentWindowIcon);
  206983. if (dropTarget != 0)
  206984. {
  206985. dropTarget->Release();
  206986. dropTarget = 0;
  206987. }
  206988. #if JUCE_DIRECT2D
  206989. direct2DContext = 0;
  206990. #endif
  206991. }
  206992. void* getNativeHandle() const
  206993. {
  206994. return hwnd;
  206995. }
  206996. void setVisible (bool shouldBeVisible)
  206997. {
  206998. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206999. if (shouldBeVisible)
  207000. InvalidateRect (hwnd, 0, 0);
  207001. else
  207002. lastPaintTime = 0;
  207003. }
  207004. void setTitle (const String& title)
  207005. {
  207006. SetWindowText (hwnd, title);
  207007. }
  207008. void setPosition (int x, int y)
  207009. {
  207010. offsetWithinParent (x, y);
  207011. SetWindowPos (hwnd, 0,
  207012. x - windowBorder.getLeft(),
  207013. y - windowBorder.getTop(),
  207014. 0, 0,
  207015. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207016. }
  207017. void repaintNowIfTransparent()
  207018. {
  207019. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  207020. handlePaintMessage();
  207021. }
  207022. void updateBorderSize()
  207023. {
  207024. WINDOWINFO info;
  207025. info.cbSize = sizeof (info);
  207026. if (GetWindowInfo (hwnd, &info))
  207027. {
  207028. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  207029. info.rcClient.left - info.rcWindow.left,
  207030. info.rcWindow.bottom - info.rcClient.bottom,
  207031. info.rcWindow.right - info.rcClient.right);
  207032. }
  207033. #if JUCE_DIRECT2D
  207034. if (direct2DContext != 0)
  207035. direct2DContext->resized();
  207036. #endif
  207037. }
  207038. void setSize (int w, int h)
  207039. {
  207040. SetWindowPos (hwnd, 0, 0, 0,
  207041. w + windowBorder.getLeftAndRight(),
  207042. h + windowBorder.getTopAndBottom(),
  207043. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207044. updateBorderSize();
  207045. repaintNowIfTransparent();
  207046. }
  207047. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  207048. {
  207049. fullScreen = isNowFullScreen;
  207050. offsetWithinParent (x, y);
  207051. SetWindowPos (hwnd, 0,
  207052. x - windowBorder.getLeft(),
  207053. y - windowBorder.getTop(),
  207054. w + windowBorder.getLeftAndRight(),
  207055. h + windowBorder.getTopAndBottom(),
  207056. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207057. updateBorderSize();
  207058. repaintNowIfTransparent();
  207059. }
  207060. const Rectangle<int> getBounds() const
  207061. {
  207062. RECT r;
  207063. GetWindowRect (hwnd, &r);
  207064. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207065. HWND parentH = GetParent (hwnd);
  207066. if (parentH != 0)
  207067. {
  207068. GetWindowRect (parentH, &r);
  207069. bounds.translate (-r.left, -r.top);
  207070. }
  207071. return windowBorder.subtractedFrom (bounds);
  207072. }
  207073. const Point<int> getScreenPosition() const
  207074. {
  207075. RECT r;
  207076. GetWindowRect (hwnd, &r);
  207077. return Point<int> (r.left + windowBorder.getLeft(),
  207078. r.top + windowBorder.getTop());
  207079. }
  207080. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  207081. {
  207082. return relativePosition + getScreenPosition();
  207083. }
  207084. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  207085. {
  207086. return screenPosition - getScreenPosition();
  207087. }
  207088. void setMinimised (bool shouldBeMinimised)
  207089. {
  207090. if (shouldBeMinimised != isMinimised())
  207091. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207092. }
  207093. bool isMinimised() const
  207094. {
  207095. WINDOWPLACEMENT wp;
  207096. wp.length = sizeof (WINDOWPLACEMENT);
  207097. GetWindowPlacement (hwnd, &wp);
  207098. return wp.showCmd == SW_SHOWMINIMIZED;
  207099. }
  207100. void setFullScreen (bool shouldBeFullScreen)
  207101. {
  207102. setMinimised (false);
  207103. if (fullScreen != shouldBeFullScreen)
  207104. {
  207105. fullScreen = shouldBeFullScreen;
  207106. const Component::SafePointer<Component> deletionChecker (component);
  207107. if (! fullScreen)
  207108. {
  207109. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207110. if (hasTitleBar())
  207111. ShowWindow (hwnd, SW_SHOWNORMAL);
  207112. if (! boundsCopy.isEmpty())
  207113. {
  207114. setBounds (boundsCopy.getX(),
  207115. boundsCopy.getY(),
  207116. boundsCopy.getWidth(),
  207117. boundsCopy.getHeight(),
  207118. false);
  207119. }
  207120. }
  207121. else
  207122. {
  207123. if (hasTitleBar())
  207124. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207125. else
  207126. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207127. }
  207128. if (deletionChecker != 0)
  207129. handleMovedOrResized();
  207130. }
  207131. }
  207132. bool isFullScreen() const
  207133. {
  207134. if (! hasTitleBar())
  207135. return fullScreen;
  207136. WINDOWPLACEMENT wp;
  207137. wp.length = sizeof (wp);
  207138. GetWindowPlacement (hwnd, &wp);
  207139. return wp.showCmd == SW_SHOWMAXIMIZED;
  207140. }
  207141. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207142. {
  207143. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  207144. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  207145. return false;
  207146. RECT r;
  207147. GetWindowRect (hwnd, &r);
  207148. POINT p;
  207149. p.x = position.getX() + r.left + windowBorder.getLeft();
  207150. p.y = position.getY() + r.top + windowBorder.getTop();
  207151. HWND w = WindowFromPoint (p);
  207152. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207153. }
  207154. const BorderSize getFrameSize() const
  207155. {
  207156. return windowBorder;
  207157. }
  207158. bool setAlwaysOnTop (bool alwaysOnTop)
  207159. {
  207160. const bool oldDeactivate = shouldDeactivateTitleBar;
  207161. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207162. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207163. 0, 0, 0, 0,
  207164. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207165. shouldDeactivateTitleBar = oldDeactivate;
  207166. if (shadower != 0)
  207167. shadower->componentBroughtToFront (*component);
  207168. return true;
  207169. }
  207170. void toFront (bool makeActive)
  207171. {
  207172. setMinimised (false);
  207173. const bool oldDeactivate = shouldDeactivateTitleBar;
  207174. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207175. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207176. shouldDeactivateTitleBar = oldDeactivate;
  207177. if (! makeActive)
  207178. {
  207179. // in this case a broughttofront call won't have occured, so do it now..
  207180. handleBroughtToFront();
  207181. }
  207182. }
  207183. void toBehind (ComponentPeer* other)
  207184. {
  207185. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207186. jassert (otherPeer != 0); // wrong type of window?
  207187. if (otherPeer != 0)
  207188. {
  207189. setMinimised (false);
  207190. // must be careful not to try to put a topmost window behind a normal one, or win32
  207191. // promotes the normal one to be topmost!
  207192. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207193. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207194. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207195. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207196. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207197. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207198. }
  207199. }
  207200. bool isFocused() const
  207201. {
  207202. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207203. }
  207204. void grabFocus()
  207205. {
  207206. const bool oldDeactivate = shouldDeactivateTitleBar;
  207207. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207208. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207209. shouldDeactivateTitleBar = oldDeactivate;
  207210. }
  207211. void textInputRequired (const Point<int>&)
  207212. {
  207213. if (! hasCreatedCaret)
  207214. {
  207215. hasCreatedCaret = true;
  207216. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207217. }
  207218. ShowCaret (hwnd);
  207219. SetCaretPos (0, 0);
  207220. }
  207221. void repaint (const Rectangle<int>& area)
  207222. {
  207223. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207224. InvalidateRect (hwnd, &r, FALSE);
  207225. }
  207226. void performAnyPendingRepaintsNow()
  207227. {
  207228. MSG m;
  207229. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207230. DispatchMessage (&m);
  207231. }
  207232. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207233. {
  207234. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207235. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207236. return 0;
  207237. }
  207238. void setTaskBarIcon (const Image& image)
  207239. {
  207240. if (image.isValid())
  207241. {
  207242. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  207243. if (taskBarIcon == 0)
  207244. {
  207245. taskBarIcon = new NOTIFYICONDATA();
  207246. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207247. taskBarIcon->hWnd = (HWND) hwnd;
  207248. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207249. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207250. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207251. taskBarIcon->hIcon = hicon;
  207252. taskBarIcon->szTip[0] = 0;
  207253. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207254. }
  207255. else
  207256. {
  207257. HICON oldIcon = taskBarIcon->hIcon;
  207258. taskBarIcon->hIcon = hicon;
  207259. taskBarIcon->uFlags = NIF_ICON;
  207260. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207261. DestroyIcon (oldIcon);
  207262. }
  207263. DestroyIcon (hicon);
  207264. }
  207265. else if (taskBarIcon != 0)
  207266. {
  207267. taskBarIcon->uFlags = 0;
  207268. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207269. DestroyIcon (taskBarIcon->hIcon);
  207270. taskBarIcon = 0;
  207271. }
  207272. }
  207273. void setTaskBarIconToolTip (const String& toolTip) const
  207274. {
  207275. if (taskBarIcon != 0)
  207276. {
  207277. taskBarIcon->uFlags = NIF_TIP;
  207278. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207279. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207280. }
  207281. }
  207282. bool isInside (HWND h) const
  207283. {
  207284. return GetAncestor (hwnd, GA_ROOT) == h;
  207285. }
  207286. static void updateKeyModifiers() throw()
  207287. {
  207288. int keyMods = 0;
  207289. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207290. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207291. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207292. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207293. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207294. }
  207295. static void updateModifiersFromWParam (const WPARAM wParam)
  207296. {
  207297. int mouseMods = 0;
  207298. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207299. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207300. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207301. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207302. updateKeyModifiers();
  207303. }
  207304. static int64 getMouseEventTime()
  207305. {
  207306. static int64 eventTimeOffset = 0;
  207307. static DWORD lastMessageTime = 0;
  207308. const DWORD thisMessageTime = GetMessageTime();
  207309. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207310. {
  207311. lastMessageTime = thisMessageTime;
  207312. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207313. }
  207314. return eventTimeOffset + thisMessageTime;
  207315. }
  207316. juce_UseDebuggingNewOperator
  207317. bool dontRepaint;
  207318. static ModifierKeys currentModifiers;
  207319. static ModifierKeys modifiersAtLastCallback;
  207320. private:
  207321. HWND hwnd, parentToAddTo;
  207322. ScopedPointer<DropShadower> shadower;
  207323. RenderingEngineType currentRenderingEngine;
  207324. #if JUCE_DIRECT2D
  207325. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207326. #endif
  207327. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207328. BorderSize windowBorder;
  207329. HICON currentWindowIcon;
  207330. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207331. IDropTarget* dropTarget;
  207332. class TemporaryImage : public Timer
  207333. {
  207334. public:
  207335. TemporaryImage() {}
  207336. ~TemporaryImage() {}
  207337. const Image& getImage (const bool transparent, const int w, const int h)
  207338. {
  207339. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207340. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207341. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207342. startTimer (3000);
  207343. return image;
  207344. }
  207345. void timerCallback()
  207346. {
  207347. stopTimer();
  207348. image = Image::null;
  207349. }
  207350. private:
  207351. Image image;
  207352. TemporaryImage (const TemporaryImage&);
  207353. TemporaryImage& operator= (const TemporaryImage&);
  207354. };
  207355. TemporaryImage offscreenImageGenerator;
  207356. class WindowClassHolder : public DeletedAtShutdown
  207357. {
  207358. public:
  207359. WindowClassHolder()
  207360. : windowClassName ("JUCE_")
  207361. {
  207362. // this name has to be different for each app/dll instance because otherwise
  207363. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207364. // window class).
  207365. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207366. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207367. TCHAR moduleFile [1024];
  207368. moduleFile[0] = 0;
  207369. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207370. WORD iconNum = 0;
  207371. WNDCLASSEX wcex;
  207372. wcex.cbSize = sizeof (wcex);
  207373. wcex.style = CS_OWNDC;
  207374. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207375. wcex.lpszClassName = windowClassName;
  207376. wcex.cbClsExtra = 0;
  207377. wcex.cbWndExtra = 32;
  207378. wcex.hInstance = moduleHandle;
  207379. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207380. iconNum = 1;
  207381. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207382. wcex.hCursor = 0;
  207383. wcex.hbrBackground = 0;
  207384. wcex.lpszMenuName = 0;
  207385. RegisterClassEx (&wcex);
  207386. }
  207387. ~WindowClassHolder()
  207388. {
  207389. if (ComponentPeer::getNumPeers() == 0)
  207390. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207391. clearSingletonInstance();
  207392. }
  207393. String windowClassName;
  207394. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207395. };
  207396. static void* createWindowCallback (void* userData)
  207397. {
  207398. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207399. return 0;
  207400. }
  207401. void createWindow()
  207402. {
  207403. DWORD exstyle = WS_EX_ACCEPTFILES;
  207404. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207405. if (hasTitleBar())
  207406. {
  207407. type |= WS_OVERLAPPED;
  207408. if ((styleFlags & windowHasCloseButton) != 0)
  207409. {
  207410. type |= WS_SYSMENU;
  207411. }
  207412. else
  207413. {
  207414. // annoyingly, windows won't let you have a min/max button without a close button
  207415. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207416. }
  207417. if ((styleFlags & windowIsResizable) != 0)
  207418. type |= WS_THICKFRAME;
  207419. }
  207420. else if (parentToAddTo != 0)
  207421. {
  207422. type |= WS_CHILD;
  207423. }
  207424. else
  207425. {
  207426. type |= WS_POPUP | WS_SYSMENU;
  207427. }
  207428. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207429. exstyle |= WS_EX_TOOLWINDOW;
  207430. else
  207431. exstyle |= WS_EX_APPWINDOW;
  207432. if ((styleFlags & windowHasMinimiseButton) != 0)
  207433. type |= WS_MINIMIZEBOX;
  207434. if ((styleFlags & windowHasMaximiseButton) != 0)
  207435. type |= WS_MAXIMIZEBOX;
  207436. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207437. exstyle |= WS_EX_TRANSPARENT;
  207438. if ((styleFlags & windowIsSemiTransparent) != 0
  207439. && Desktop::canUseSemiTransparentWindows())
  207440. exstyle |= WS_EX_LAYERED;
  207441. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207442. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207443. #if JUCE_DIRECT2D
  207444. updateDirect2DContext();
  207445. #endif
  207446. if (hwnd != 0)
  207447. {
  207448. SetWindowLongPtr (hwnd, 0, 0);
  207449. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207450. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207451. if (dropTarget == 0)
  207452. dropTarget = new JuceDropTarget (this);
  207453. RegisterDragDrop (hwnd, dropTarget);
  207454. updateBorderSize();
  207455. // Calling this function here is (for some reason) necessary to make Windows
  207456. // correctly enable the menu items that we specify in the wm_initmenu message.
  207457. GetSystemMenu (hwnd, false);
  207458. }
  207459. else
  207460. {
  207461. jassertfalse;
  207462. }
  207463. }
  207464. static void* destroyWindowCallback (void* handle)
  207465. {
  207466. RevokeDragDrop ((HWND) handle);
  207467. DestroyWindow ((HWND) handle);
  207468. return 0;
  207469. }
  207470. static void* toFrontCallback1 (void* h)
  207471. {
  207472. SetForegroundWindow ((HWND) h);
  207473. return 0;
  207474. }
  207475. static void* toFrontCallback2 (void* h)
  207476. {
  207477. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207478. return 0;
  207479. }
  207480. static void* setFocusCallback (void* h)
  207481. {
  207482. SetFocus ((HWND) h);
  207483. return 0;
  207484. }
  207485. static void* getFocusCallback (void*)
  207486. {
  207487. return GetFocus();
  207488. }
  207489. void offsetWithinParent (int& x, int& y) const
  207490. {
  207491. if (isTransparent())
  207492. {
  207493. HWND parentHwnd = GetParent (hwnd);
  207494. if (parentHwnd != 0)
  207495. {
  207496. RECT parentRect;
  207497. GetWindowRect (parentHwnd, &parentRect);
  207498. x += parentRect.left;
  207499. y += parentRect.top;
  207500. }
  207501. }
  207502. }
  207503. bool isTransparent() const
  207504. {
  207505. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207506. }
  207507. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207508. void setIcon (const Image& newIcon)
  207509. {
  207510. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207511. if (hicon != 0)
  207512. {
  207513. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207514. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207515. if (currentWindowIcon != 0)
  207516. DestroyIcon (currentWindowIcon);
  207517. currentWindowIcon = hicon;
  207518. }
  207519. }
  207520. void handlePaintMessage()
  207521. {
  207522. #if JUCE_DIRECT2D
  207523. if (direct2DContext != 0)
  207524. {
  207525. RECT r;
  207526. if (GetUpdateRect (hwnd, &r, false))
  207527. {
  207528. direct2DContext->start();
  207529. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207530. handlePaint (*direct2DContext);
  207531. direct2DContext->end();
  207532. }
  207533. }
  207534. else
  207535. #endif
  207536. {
  207537. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207538. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207539. PAINTSTRUCT paintStruct;
  207540. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207541. // message and become re-entrant, but that's OK
  207542. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207543. // corrupt the image it's using to paint into, so do a check here.
  207544. static bool reentrant = false;
  207545. if (reentrant)
  207546. {
  207547. DeleteObject (rgn);
  207548. EndPaint (hwnd, &paintStruct);
  207549. return;
  207550. }
  207551. reentrant = true;
  207552. // this is the rectangle to update..
  207553. int x = paintStruct.rcPaint.left;
  207554. int y = paintStruct.rcPaint.top;
  207555. int w = paintStruct.rcPaint.right - x;
  207556. int h = paintStruct.rcPaint.bottom - y;
  207557. const bool transparent = isTransparent();
  207558. if (transparent)
  207559. {
  207560. // it's not possible to have a transparent window with a title bar at the moment!
  207561. jassert (! hasTitleBar());
  207562. RECT r;
  207563. GetWindowRect (hwnd, &r);
  207564. x = y = 0;
  207565. w = r.right - r.left;
  207566. h = r.bottom - r.top;
  207567. }
  207568. if (w > 0 && h > 0)
  207569. {
  207570. clearMaskedRegion();
  207571. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207572. RectangleList contextClip;
  207573. const Rectangle<int> clipBounds (0, 0, w, h);
  207574. bool needToPaintAll = true;
  207575. if (regionType == COMPLEXREGION && ! transparent)
  207576. {
  207577. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207578. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207579. DeleteObject (clipRgn);
  207580. char rgnData [8192];
  207581. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207582. if (res > 0 && res <= sizeof (rgnData))
  207583. {
  207584. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207585. if (hdr->iType == RDH_RECTANGLES
  207586. && hdr->rcBound.right - hdr->rcBound.left >= w
  207587. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207588. {
  207589. needToPaintAll = false;
  207590. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207591. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207592. while (--num >= 0)
  207593. {
  207594. if (rects->right <= x + w && rects->bottom <= y + h)
  207595. {
  207596. const int cx = jmax (x, (int) rects->left);
  207597. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207598. .getIntersection (clipBounds));
  207599. }
  207600. else
  207601. {
  207602. needToPaintAll = true;
  207603. break;
  207604. }
  207605. ++rects;
  207606. }
  207607. }
  207608. }
  207609. }
  207610. if (needToPaintAll)
  207611. {
  207612. contextClip.clear();
  207613. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207614. }
  207615. if (transparent)
  207616. {
  207617. RectangleList::Iterator i (contextClip);
  207618. while (i.next())
  207619. offscreenImage.clear (*i.getRectangle());
  207620. }
  207621. // if the component's not opaque, this won't draw properly unless the platform can support this
  207622. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207623. updateCurrentModifiers();
  207624. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207625. handlePaint (context);
  207626. if (! dontRepaint)
  207627. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207628. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207629. }
  207630. DeleteObject (rgn);
  207631. EndPaint (hwnd, &paintStruct);
  207632. reentrant = false;
  207633. }
  207634. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207635. _fpreset(); // because some graphics cards can unmask FP exceptions
  207636. #endif
  207637. lastPaintTime = Time::getMillisecondCounter();
  207638. }
  207639. void doMouseEvent (const Point<int>& position)
  207640. {
  207641. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207642. }
  207643. const StringArray getAvailableRenderingEngines()
  207644. {
  207645. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207646. #if JUCE_DIRECT2D
  207647. // xxx is this correct? Seems to enable it on Vista too??
  207648. OSVERSIONINFO info;
  207649. zerostruct (info);
  207650. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207651. GetVersionEx (&info);
  207652. if (info.dwMajorVersion >= 6)
  207653. s.add ("Direct2D");
  207654. #endif
  207655. return s;
  207656. }
  207657. int getCurrentRenderingEngine() throw()
  207658. {
  207659. return currentRenderingEngine;
  207660. }
  207661. #if JUCE_DIRECT2D
  207662. void updateDirect2DContext()
  207663. {
  207664. if (currentRenderingEngine != direct2DRenderingEngine)
  207665. direct2DContext = 0;
  207666. else if (direct2DContext == 0)
  207667. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207668. }
  207669. #endif
  207670. void setCurrentRenderingEngine (int index)
  207671. {
  207672. (void) index;
  207673. #if JUCE_DIRECT2D
  207674. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207675. updateDirect2DContext();
  207676. repaint (component->getLocalBounds());
  207677. #endif
  207678. }
  207679. void doMouseMove (const Point<int>& position)
  207680. {
  207681. if (! isMouseOver)
  207682. {
  207683. isMouseOver = true;
  207684. updateKeyModifiers();
  207685. TRACKMOUSEEVENT tme;
  207686. tme.cbSize = sizeof (tme);
  207687. tme.dwFlags = TME_LEAVE;
  207688. tme.hwndTrack = hwnd;
  207689. tme.dwHoverTime = 0;
  207690. if (! TrackMouseEvent (&tme))
  207691. jassertfalse;
  207692. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207693. }
  207694. else if (! isDragging)
  207695. {
  207696. if (! contains (position, false))
  207697. return;
  207698. }
  207699. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207700. static uint32 lastMouseTime = 0;
  207701. const uint32 now = Time::getMillisecondCounter();
  207702. const int maxMouseMovesPerSecond = 60;
  207703. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207704. {
  207705. lastMouseTime = now;
  207706. doMouseEvent (position);
  207707. }
  207708. }
  207709. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207710. {
  207711. if (GetCapture() != hwnd)
  207712. SetCapture (hwnd);
  207713. doMouseMove (position);
  207714. updateModifiersFromWParam (wParam);
  207715. isDragging = true;
  207716. doMouseEvent (position);
  207717. }
  207718. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207719. {
  207720. updateModifiersFromWParam (wParam);
  207721. isDragging = false;
  207722. // release the mouse capture if the user has released all buttons
  207723. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207724. ReleaseCapture();
  207725. doMouseEvent (position);
  207726. }
  207727. void doCaptureChanged()
  207728. {
  207729. if (isDragging)
  207730. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207731. }
  207732. void doMouseExit()
  207733. {
  207734. isMouseOver = false;
  207735. doMouseEvent (getCurrentMousePos());
  207736. }
  207737. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207738. {
  207739. updateKeyModifiers();
  207740. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207741. handleMouseWheel (0, position, getMouseEventTime(),
  207742. isVertical ? 0.0f : amount,
  207743. isVertical ? amount : 0.0f);
  207744. }
  207745. void sendModifierKeyChangeIfNeeded()
  207746. {
  207747. if (modifiersAtLastCallback != currentModifiers)
  207748. {
  207749. modifiersAtLastCallback = currentModifiers;
  207750. handleModifierKeysChange();
  207751. }
  207752. }
  207753. bool doKeyUp (const WPARAM key)
  207754. {
  207755. updateKeyModifiers();
  207756. switch (key)
  207757. {
  207758. case VK_SHIFT:
  207759. case VK_CONTROL:
  207760. case VK_MENU:
  207761. case VK_CAPITAL:
  207762. case VK_LWIN:
  207763. case VK_RWIN:
  207764. case VK_APPS:
  207765. case VK_NUMLOCK:
  207766. case VK_SCROLL:
  207767. case VK_LSHIFT:
  207768. case VK_RSHIFT:
  207769. case VK_LCONTROL:
  207770. case VK_LMENU:
  207771. case VK_RCONTROL:
  207772. case VK_RMENU:
  207773. sendModifierKeyChangeIfNeeded();
  207774. }
  207775. return handleKeyUpOrDown (false)
  207776. || Component::getCurrentlyModalComponent() != 0;
  207777. }
  207778. bool doKeyDown (const WPARAM key)
  207779. {
  207780. updateKeyModifiers();
  207781. bool used = false;
  207782. switch (key)
  207783. {
  207784. case VK_SHIFT:
  207785. case VK_LSHIFT:
  207786. case VK_RSHIFT:
  207787. case VK_CONTROL:
  207788. case VK_LCONTROL:
  207789. case VK_RCONTROL:
  207790. case VK_MENU:
  207791. case VK_LMENU:
  207792. case VK_RMENU:
  207793. case VK_LWIN:
  207794. case VK_RWIN:
  207795. case VK_CAPITAL:
  207796. case VK_NUMLOCK:
  207797. case VK_SCROLL:
  207798. case VK_APPS:
  207799. sendModifierKeyChangeIfNeeded();
  207800. break;
  207801. case VK_LEFT:
  207802. case VK_RIGHT:
  207803. case VK_UP:
  207804. case VK_DOWN:
  207805. case VK_PRIOR:
  207806. case VK_NEXT:
  207807. case VK_HOME:
  207808. case VK_END:
  207809. case VK_DELETE:
  207810. case VK_INSERT:
  207811. case VK_F1:
  207812. case VK_F2:
  207813. case VK_F3:
  207814. case VK_F4:
  207815. case VK_F5:
  207816. case VK_F6:
  207817. case VK_F7:
  207818. case VK_F8:
  207819. case VK_F9:
  207820. case VK_F10:
  207821. case VK_F11:
  207822. case VK_F12:
  207823. case VK_F13:
  207824. case VK_F14:
  207825. case VK_F15:
  207826. case VK_F16:
  207827. used = handleKeyUpOrDown (true);
  207828. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207829. break;
  207830. case VK_ADD:
  207831. case VK_SUBTRACT:
  207832. case VK_MULTIPLY:
  207833. case VK_DIVIDE:
  207834. case VK_SEPARATOR:
  207835. case VK_DECIMAL:
  207836. used = handleKeyUpOrDown (true);
  207837. break;
  207838. default:
  207839. used = handleKeyUpOrDown (true);
  207840. {
  207841. MSG msg;
  207842. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207843. {
  207844. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207845. // manually generate the key-press event that matches this key-down.
  207846. const UINT keyChar = MapVirtualKey (key, 2);
  207847. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207848. }
  207849. }
  207850. break;
  207851. }
  207852. if (Component::getCurrentlyModalComponent() != 0)
  207853. used = true;
  207854. return used;
  207855. }
  207856. bool doKeyChar (int key, const LPARAM flags)
  207857. {
  207858. updateKeyModifiers();
  207859. juce_wchar textChar = (juce_wchar) key;
  207860. const int virtualScanCode = (flags >> 16) & 0xff;
  207861. if (key >= '0' && key <= '9')
  207862. {
  207863. switch (virtualScanCode) // check for a numeric keypad scan-code
  207864. {
  207865. case 0x52:
  207866. case 0x4f:
  207867. case 0x50:
  207868. case 0x51:
  207869. case 0x4b:
  207870. case 0x4c:
  207871. case 0x4d:
  207872. case 0x47:
  207873. case 0x48:
  207874. case 0x49:
  207875. key = (key - '0') + KeyPress::numberPad0;
  207876. break;
  207877. default:
  207878. break;
  207879. }
  207880. }
  207881. else
  207882. {
  207883. // convert the scan code to an unmodified character code..
  207884. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207885. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207886. keyChar = LOWORD (keyChar);
  207887. if (keyChar != 0)
  207888. key = (int) keyChar;
  207889. // avoid sending junk text characters for some control-key combinations
  207890. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207891. textChar = 0;
  207892. }
  207893. return handleKeyPress (key, textChar);
  207894. }
  207895. bool doAppCommand (const LPARAM lParam)
  207896. {
  207897. int key = 0;
  207898. switch (GET_APPCOMMAND_LPARAM (lParam))
  207899. {
  207900. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207901. key = KeyPress::playKey;
  207902. break;
  207903. case APPCOMMAND_MEDIA_STOP:
  207904. key = KeyPress::stopKey;
  207905. break;
  207906. case APPCOMMAND_MEDIA_NEXTTRACK:
  207907. key = KeyPress::fastForwardKey;
  207908. break;
  207909. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207910. key = KeyPress::rewindKey;
  207911. break;
  207912. }
  207913. if (key != 0)
  207914. {
  207915. updateKeyModifiers();
  207916. if (hwnd == GetActiveWindow())
  207917. {
  207918. handleKeyPress (key, 0);
  207919. return true;
  207920. }
  207921. }
  207922. return false;
  207923. }
  207924. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207925. {
  207926. public:
  207927. JuceDropTarget (Win32ComponentPeer* const owner_)
  207928. : owner (owner_)
  207929. {
  207930. }
  207931. ~JuceDropTarget() {}
  207932. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207933. {
  207934. updateFileList (pDataObject);
  207935. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207936. *pdwEffect = DROPEFFECT_COPY;
  207937. return S_OK;
  207938. }
  207939. HRESULT __stdcall DragLeave()
  207940. {
  207941. owner->handleFileDragExit (files);
  207942. return S_OK;
  207943. }
  207944. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207945. {
  207946. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207947. *pdwEffect = DROPEFFECT_COPY;
  207948. return S_OK;
  207949. }
  207950. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207951. {
  207952. updateFileList (pDataObject);
  207953. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207954. *pdwEffect = DROPEFFECT_COPY;
  207955. return S_OK;
  207956. }
  207957. private:
  207958. Win32ComponentPeer* const owner;
  207959. StringArray files;
  207960. void updateFileList (IDataObject* const pDataObject)
  207961. {
  207962. files.clear();
  207963. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207964. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207965. if (pDataObject->GetData (&format, &medium) == S_OK)
  207966. {
  207967. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207968. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207969. unsigned int i = 0;
  207970. if (pDropFiles->fWide)
  207971. {
  207972. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207973. for (;;)
  207974. {
  207975. unsigned int len = 0;
  207976. while (i + len < totalLen && fname [i + len] != 0)
  207977. ++len;
  207978. if (len == 0)
  207979. break;
  207980. files.add (String (fname + i, len));
  207981. i += len + 1;
  207982. }
  207983. }
  207984. else
  207985. {
  207986. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207987. for (;;)
  207988. {
  207989. unsigned int len = 0;
  207990. while (i + len < totalLen && fname [i + len] != 0)
  207991. ++len;
  207992. if (len == 0)
  207993. break;
  207994. files.add (String (fname + i, len));
  207995. i += len + 1;
  207996. }
  207997. }
  207998. GlobalUnlock (medium.hGlobal);
  207999. }
  208000. }
  208001. JuceDropTarget (const JuceDropTarget&);
  208002. JuceDropTarget& operator= (const JuceDropTarget&);
  208003. };
  208004. void doSettingChange()
  208005. {
  208006. Desktop::getInstance().refreshMonitorSizes();
  208007. if (fullScreen && ! isMinimised())
  208008. {
  208009. const Rectangle<int> r (component->getParentMonitorArea());
  208010. SetWindowPos (hwnd, 0,
  208011. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208012. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208013. }
  208014. }
  208015. public:
  208016. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208017. {
  208018. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208019. if (peer != 0)
  208020. return peer->peerWindowProc (h, message, wParam, lParam);
  208021. return DefWindowProcW (h, message, wParam, lParam);
  208022. }
  208023. private:
  208024. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208025. {
  208026. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208027. }
  208028. const Point<int> getCurrentMousePos() throw()
  208029. {
  208030. RECT wr;
  208031. GetWindowRect (hwnd, &wr);
  208032. const DWORD mp = GetMessagePos();
  208033. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208034. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208035. }
  208036. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208037. {
  208038. if (isValidPeer (this))
  208039. {
  208040. switch (message)
  208041. {
  208042. case WM_NCHITTEST:
  208043. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208044. return HTTRANSPARENT;
  208045. if (hasTitleBar())
  208046. break;
  208047. return HTCLIENT;
  208048. case WM_PAINT:
  208049. handlePaintMessage();
  208050. return 0;
  208051. case WM_NCPAINT:
  208052. if (wParam != 1)
  208053. handlePaintMessage();
  208054. if (hasTitleBar())
  208055. break;
  208056. return 0;
  208057. case WM_ERASEBKGND:
  208058. case WM_NCCALCSIZE:
  208059. if (hasTitleBar())
  208060. break;
  208061. return 1;
  208062. case WM_MOUSEMOVE:
  208063. doMouseMove (getPointFromLParam (lParam));
  208064. return 0;
  208065. case WM_MOUSELEAVE:
  208066. doMouseExit();
  208067. return 0;
  208068. case WM_LBUTTONDOWN:
  208069. case WM_MBUTTONDOWN:
  208070. case WM_RBUTTONDOWN:
  208071. doMouseDown (getPointFromLParam (lParam), wParam);
  208072. return 0;
  208073. case WM_LBUTTONUP:
  208074. case WM_MBUTTONUP:
  208075. case WM_RBUTTONUP:
  208076. doMouseUp (getPointFromLParam (lParam), wParam);
  208077. return 0;
  208078. case WM_CAPTURECHANGED:
  208079. doCaptureChanged();
  208080. return 0;
  208081. case WM_NCMOUSEMOVE:
  208082. if (hasTitleBar())
  208083. break;
  208084. return 0;
  208085. case 0x020A: /* WM_MOUSEWHEEL */
  208086. doMouseWheel (getCurrentMousePos(), wParam, true);
  208087. return 0;
  208088. case 0x020E: /* WM_MOUSEHWHEEL */
  208089. doMouseWheel (getCurrentMousePos(), wParam, false);
  208090. return 0;
  208091. case WM_WINDOWPOSCHANGING:
  208092. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  208093. {
  208094. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  208095. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  208096. {
  208097. if (constrainer != 0)
  208098. {
  208099. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  208100. component->getY() - windowBorder.getTop(),
  208101. component->getWidth() + windowBorder.getLeftAndRight(),
  208102. component->getHeight() + windowBorder.getTopAndBottom());
  208103. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208104. constrainer->checkBounds (pos, current,
  208105. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208106. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208107. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208108. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208109. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208110. wp->x = pos.getX();
  208111. wp->y = pos.getY();
  208112. wp->cx = pos.getWidth();
  208113. wp->cy = pos.getHeight();
  208114. }
  208115. }
  208116. }
  208117. return 0;
  208118. case WM_WINDOWPOSCHANGED:
  208119. handleMovedOrResized();
  208120. if (dontRepaint)
  208121. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208122. return 0;
  208123. case WM_KEYDOWN:
  208124. case WM_SYSKEYDOWN:
  208125. if (doKeyDown (wParam))
  208126. return 0;
  208127. break;
  208128. case WM_KEYUP:
  208129. case WM_SYSKEYUP:
  208130. if (doKeyUp (wParam))
  208131. return 0;
  208132. break;
  208133. case WM_CHAR:
  208134. if (doKeyChar ((int) wParam, lParam))
  208135. return 0;
  208136. break;
  208137. case WM_APPCOMMAND:
  208138. if (doAppCommand (lParam))
  208139. return TRUE;
  208140. break;
  208141. case WM_SETFOCUS:
  208142. updateKeyModifiers();
  208143. handleFocusGain();
  208144. break;
  208145. case WM_KILLFOCUS:
  208146. if (hasCreatedCaret)
  208147. {
  208148. hasCreatedCaret = false;
  208149. DestroyCaret();
  208150. }
  208151. handleFocusLoss();
  208152. break;
  208153. case WM_ACTIVATEAPP:
  208154. // Windows does weird things to process priority when you swap apps,
  208155. // so this forces an update when the app is brought to the front
  208156. if (wParam != FALSE)
  208157. juce_repeatLastProcessPriority();
  208158. else
  208159. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208160. juce_CheckCurrentlyFocusedTopLevelWindow();
  208161. modifiersAtLastCallback = -1;
  208162. return 0;
  208163. case WM_ACTIVATE:
  208164. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208165. {
  208166. modifiersAtLastCallback = -1;
  208167. updateKeyModifiers();
  208168. if (isMinimised())
  208169. {
  208170. component->repaint();
  208171. handleMovedOrResized();
  208172. if (! ComponentPeer::isValidPeer (this))
  208173. return 0;
  208174. }
  208175. if (LOWORD (wParam) == WA_CLICKACTIVE
  208176. && component->isCurrentlyBlockedByAnotherModalComponent())
  208177. {
  208178. const Point<int> mousePos (component->getMouseXYRelative());
  208179. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  208180. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208181. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208182. return 0;
  208183. }
  208184. handleBroughtToFront();
  208185. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208186. Component::getCurrentlyModalComponent()->toFront (true);
  208187. return 0;
  208188. }
  208189. break;
  208190. case WM_NCACTIVATE:
  208191. // while a temporary window is being shown, prevent Windows from deactivating the
  208192. // title bars of our main windows.
  208193. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208194. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208195. break;
  208196. case WM_MOUSEACTIVATE:
  208197. if (! component->getMouseClickGrabsKeyboardFocus())
  208198. return MA_NOACTIVATE;
  208199. break;
  208200. case WM_SHOWWINDOW:
  208201. if (wParam != 0)
  208202. handleBroughtToFront();
  208203. break;
  208204. case WM_CLOSE:
  208205. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208206. handleUserClosingWindow();
  208207. return 0;
  208208. case WM_QUERYENDSESSION:
  208209. if (JUCEApplication::getInstance() != 0)
  208210. {
  208211. JUCEApplication::getInstance()->systemRequestedQuit();
  208212. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208213. }
  208214. return TRUE;
  208215. case WM_TRAYNOTIFY:
  208216. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208217. {
  208218. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208219. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208220. {
  208221. Component* const current = Component::getCurrentlyModalComponent();
  208222. if (current != 0)
  208223. current->inputAttemptWhenModal();
  208224. }
  208225. }
  208226. else
  208227. {
  208228. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208229. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208230. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208231. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208232. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208233. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208234. eventMods = eventMods.withoutMouseButtons();
  208235. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208236. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208237. Point<int>(), getMouseEventTime(), 1, false);
  208238. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208239. {
  208240. SetFocus (hwnd);
  208241. SetForegroundWindow (hwnd);
  208242. component->mouseDown (e);
  208243. }
  208244. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208245. {
  208246. component->mouseUp (e);
  208247. }
  208248. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208249. {
  208250. component->mouseDoubleClick (e);
  208251. }
  208252. else if (lParam == WM_MOUSEMOVE)
  208253. {
  208254. component->mouseMove (e);
  208255. }
  208256. }
  208257. break;
  208258. case WM_SYNCPAINT:
  208259. return 0;
  208260. case WM_PALETTECHANGED:
  208261. InvalidateRect (h, 0, 0);
  208262. break;
  208263. case WM_DISPLAYCHANGE:
  208264. InvalidateRect (h, 0, 0);
  208265. createPaletteIfNeeded = true;
  208266. // intentional fall-through...
  208267. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208268. doSettingChange();
  208269. break;
  208270. case WM_INITMENU:
  208271. if (! hasTitleBar())
  208272. {
  208273. if (isFullScreen())
  208274. {
  208275. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208276. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208277. }
  208278. else if (! isMinimised())
  208279. {
  208280. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208281. }
  208282. }
  208283. break;
  208284. case WM_SYSCOMMAND:
  208285. switch (wParam & 0xfff0)
  208286. {
  208287. case SC_CLOSE:
  208288. if (sendInputAttemptWhenModalMessage())
  208289. return 0;
  208290. if (hasTitleBar())
  208291. {
  208292. PostMessage (h, WM_CLOSE, 0, 0);
  208293. return 0;
  208294. }
  208295. break;
  208296. case SC_KEYMENU:
  208297. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208298. // obscure situations that can arise if a modal loop is started from an alt-key
  208299. // keypress).
  208300. if (hasTitleBar() && h == GetCapture())
  208301. ReleaseCapture();
  208302. break;
  208303. case SC_MAXIMIZE:
  208304. if (sendInputAttemptWhenModalMessage())
  208305. return 0;
  208306. setFullScreen (true);
  208307. return 0;
  208308. case SC_MINIMIZE:
  208309. if (sendInputAttemptWhenModalMessage())
  208310. return 0;
  208311. if (! hasTitleBar())
  208312. {
  208313. setMinimised (true);
  208314. return 0;
  208315. }
  208316. break;
  208317. case SC_RESTORE:
  208318. if (sendInputAttemptWhenModalMessage())
  208319. return 0;
  208320. if (hasTitleBar())
  208321. {
  208322. if (isFullScreen())
  208323. {
  208324. setFullScreen (false);
  208325. return 0;
  208326. }
  208327. }
  208328. else
  208329. {
  208330. if (isMinimised())
  208331. setMinimised (false);
  208332. else if (isFullScreen())
  208333. setFullScreen (false);
  208334. return 0;
  208335. }
  208336. break;
  208337. }
  208338. break;
  208339. case WM_NCLBUTTONDOWN:
  208340. case WM_NCRBUTTONDOWN:
  208341. case WM_NCMBUTTONDOWN:
  208342. sendInputAttemptWhenModalMessage();
  208343. break;
  208344. //case WM_IME_STARTCOMPOSITION;
  208345. // return 0;
  208346. case WM_GETDLGCODE:
  208347. return DLGC_WANTALLKEYS;
  208348. default:
  208349. break;
  208350. }
  208351. }
  208352. return DefWindowProcW (h, message, wParam, lParam);
  208353. }
  208354. bool sendInputAttemptWhenModalMessage()
  208355. {
  208356. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208357. {
  208358. Component* const current = Component::getCurrentlyModalComponent();
  208359. if (current != 0)
  208360. current->inputAttemptWhenModal();
  208361. return true;
  208362. }
  208363. return false;
  208364. }
  208365. Win32ComponentPeer (const Win32ComponentPeer&);
  208366. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208367. };
  208368. ModifierKeys Win32ComponentPeer::currentModifiers;
  208369. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208370. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208371. {
  208372. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208373. }
  208374. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208375. void ModifierKeys::updateCurrentModifiers() throw()
  208376. {
  208377. currentModifiers = Win32ComponentPeer::currentModifiers;
  208378. }
  208379. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208380. {
  208381. Win32ComponentPeer::updateKeyModifiers();
  208382. int keyMods = 0;
  208383. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208384. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208385. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208386. Win32ComponentPeer::currentModifiers
  208387. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208388. return Win32ComponentPeer::currentModifiers;
  208389. }
  208390. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208391. {
  208392. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208393. if (wp != 0)
  208394. wp->setTaskBarIcon (newImage);
  208395. }
  208396. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208397. {
  208398. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208399. if (wp != 0)
  208400. wp->setTaskBarIconToolTip (tooltip);
  208401. }
  208402. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208403. {
  208404. DWORD val = GetWindowLong (h, styleType);
  208405. if (bitIsSet)
  208406. val |= feature;
  208407. else
  208408. val &= ~feature;
  208409. SetWindowLongPtr (h, styleType, val);
  208410. SetWindowPos (h, 0, 0, 0, 0, 0,
  208411. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208412. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208413. }
  208414. bool Process::isForegroundProcess()
  208415. {
  208416. HWND fg = GetForegroundWindow();
  208417. if (fg == 0)
  208418. return true;
  208419. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208420. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208421. // have to see if any of our windows are children of the foreground window
  208422. fg = GetAncestor (fg, GA_ROOT);
  208423. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208424. {
  208425. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208426. if (wp != 0 && wp->isInside (fg))
  208427. return true;
  208428. }
  208429. return false;
  208430. }
  208431. bool AlertWindow::showNativeDialogBox (const String& title,
  208432. const String& bodyText,
  208433. bool isOkCancel)
  208434. {
  208435. return MessageBox (0, bodyText, title,
  208436. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208437. : MB_OK)) == IDOK;
  208438. }
  208439. void Desktop::createMouseInputSources()
  208440. {
  208441. mouseSources.add (new MouseInputSource (0, true));
  208442. }
  208443. const Point<int> Desktop::getMousePosition()
  208444. {
  208445. POINT mousePos;
  208446. GetCursorPos (&mousePos);
  208447. return Point<int> (mousePos.x, mousePos.y);
  208448. }
  208449. void Desktop::setMousePosition (const Point<int>& newPosition)
  208450. {
  208451. SetCursorPos (newPosition.getX(), newPosition.getY());
  208452. }
  208453. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208454. {
  208455. return createSoftwareImage (format, width, height, clearImage);
  208456. }
  208457. class ScreenSaverDefeater : public Timer,
  208458. public DeletedAtShutdown
  208459. {
  208460. public:
  208461. ScreenSaverDefeater()
  208462. {
  208463. startTimer (10000);
  208464. timerCallback();
  208465. }
  208466. ~ScreenSaverDefeater() {}
  208467. void timerCallback()
  208468. {
  208469. if (Process::isForegroundProcess())
  208470. {
  208471. // simulate a shift key getting pressed..
  208472. INPUT input[2];
  208473. input[0].type = INPUT_KEYBOARD;
  208474. input[0].ki.wVk = VK_SHIFT;
  208475. input[0].ki.dwFlags = 0;
  208476. input[0].ki.dwExtraInfo = 0;
  208477. input[1].type = INPUT_KEYBOARD;
  208478. input[1].ki.wVk = VK_SHIFT;
  208479. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208480. input[1].ki.dwExtraInfo = 0;
  208481. SendInput (2, input, sizeof (INPUT));
  208482. }
  208483. }
  208484. };
  208485. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208486. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208487. {
  208488. if (isEnabled)
  208489. deleteAndZero (screenSaverDefeater);
  208490. else if (screenSaverDefeater == 0)
  208491. screenSaverDefeater = new ScreenSaverDefeater();
  208492. }
  208493. bool Desktop::isScreenSaverEnabled()
  208494. {
  208495. return screenSaverDefeater == 0;
  208496. }
  208497. /* (The code below is the "correct" way to disable the screen saver, but it
  208498. completely fails on winXP when the saver is password-protected...)
  208499. static bool juce_screenSaverEnabled = true;
  208500. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208501. {
  208502. juce_screenSaverEnabled = isEnabled;
  208503. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208504. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208505. }
  208506. bool Desktop::isScreenSaverEnabled() throw()
  208507. {
  208508. return juce_screenSaverEnabled;
  208509. }
  208510. */
  208511. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208512. {
  208513. if (enableOrDisable)
  208514. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208515. }
  208516. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208517. {
  208518. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208519. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208520. return TRUE;
  208521. }
  208522. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208523. {
  208524. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208525. // make sure the first in the list is the main monitor
  208526. for (int i = 1; i < monitorCoords.size(); ++i)
  208527. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208528. monitorCoords.swap (i, 0);
  208529. if (monitorCoords.size() == 0)
  208530. {
  208531. RECT r;
  208532. GetWindowRect (GetDesktopWindow(), &r);
  208533. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208534. }
  208535. if (clipToWorkArea)
  208536. {
  208537. // clip the main monitor to the active non-taskbar area
  208538. RECT r;
  208539. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208540. Rectangle<int>& screen = monitorCoords.getReference (0);
  208541. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208542. jmax (screen.getY(), (int) r.top));
  208543. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208544. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208545. }
  208546. }
  208547. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208548. {
  208549. Image im;
  208550. if (bitmap != 0)
  208551. {
  208552. BITMAP bm;
  208553. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208554. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208555. {
  208556. HDC tempDC = GetDC (0);
  208557. HDC dc = CreateCompatibleDC (tempDC);
  208558. ReleaseDC (0, tempDC);
  208559. SelectObject (dc, bitmap);
  208560. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208561. Image::BitmapData imageData (im, true);
  208562. for (int y = bm.bmHeight; --y >= 0;)
  208563. {
  208564. for (int x = bm.bmWidth; --x >= 0;)
  208565. {
  208566. COLORREF col = GetPixel (dc, x, y);
  208567. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208568. (uint8) GetGValue (col),
  208569. (uint8) GetBValue (col)));
  208570. }
  208571. }
  208572. DeleteDC (dc);
  208573. }
  208574. }
  208575. return im;
  208576. }
  208577. static const Image createImageFromHICON (HICON icon)
  208578. {
  208579. ICONINFO info;
  208580. if (GetIconInfo (icon, &info))
  208581. {
  208582. Image mask (createImageFromHBITMAP (info.hbmMask));
  208583. Image image (createImageFromHBITMAP (info.hbmColor));
  208584. if (mask.isValid() && image.isValid())
  208585. {
  208586. for (int y = image.getHeight(); --y >= 0;)
  208587. {
  208588. for (int x = image.getWidth(); --x >= 0;)
  208589. {
  208590. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208591. if (brightness > 0.0f)
  208592. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208593. }
  208594. }
  208595. return image;
  208596. }
  208597. }
  208598. return Image::null;
  208599. }
  208600. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208601. {
  208602. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208603. Image bitmap (nativeBitmap);
  208604. {
  208605. Graphics g (bitmap);
  208606. g.drawImageAt (image, 0, 0);
  208607. }
  208608. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208609. ICONINFO info;
  208610. info.fIcon = isIcon;
  208611. info.xHotspot = hotspotX;
  208612. info.yHotspot = hotspotY;
  208613. info.hbmMask = mask;
  208614. info.hbmColor = nativeBitmap->hBitmap;
  208615. HICON hi = CreateIconIndirect (&info);
  208616. DeleteObject (mask);
  208617. return hi;
  208618. }
  208619. const Image juce_createIconForFile (const File& file)
  208620. {
  208621. Image image;
  208622. WCHAR filename [1024];
  208623. file.getFullPathName().copyToUnicode (filename, 1023);
  208624. WORD iconNum = 0;
  208625. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208626. filename, &iconNum);
  208627. if (icon != 0)
  208628. {
  208629. image = createImageFromHICON (icon);
  208630. DestroyIcon (icon);
  208631. }
  208632. return image;
  208633. }
  208634. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208635. {
  208636. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208637. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208638. Image im (image);
  208639. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208640. {
  208641. im = im.rescaled (maxW, maxH);
  208642. hotspotX = (hotspotX * maxW) / image.getWidth();
  208643. hotspotY = (hotspotY * maxH) / image.getHeight();
  208644. }
  208645. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208646. }
  208647. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208648. {
  208649. if (cursorHandle != 0 && ! isStandard)
  208650. DestroyCursor ((HCURSOR) cursorHandle);
  208651. }
  208652. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208653. {
  208654. LPCTSTR cursorName = IDC_ARROW;
  208655. switch (type)
  208656. {
  208657. case NormalCursor: break;
  208658. case NoCursor: return 0;
  208659. case WaitCursor: cursorName = IDC_WAIT; break;
  208660. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208661. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208662. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208663. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208664. case LeftRightResizeCursor:
  208665. case LeftEdgeResizeCursor:
  208666. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208667. case UpDownResizeCursor:
  208668. case TopEdgeResizeCursor:
  208669. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208670. case TopLeftCornerResizeCursor:
  208671. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208672. case TopRightCornerResizeCursor:
  208673. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208674. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208675. case DraggingHandCursor:
  208676. {
  208677. static void* dragHandCursor = 0;
  208678. if (dragHandCursor == 0)
  208679. {
  208680. static const unsigned char dragHandData[] =
  208681. { 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,
  208682. 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,
  208683. 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 };
  208684. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208685. }
  208686. return dragHandCursor;
  208687. }
  208688. default:
  208689. jassertfalse; break;
  208690. }
  208691. HCURSOR cursorH = LoadCursor (0, cursorName);
  208692. if (cursorH == 0)
  208693. cursorH = LoadCursor (0, IDC_ARROW);
  208694. return cursorH;
  208695. }
  208696. void MouseCursor::showInWindow (ComponentPeer*) const
  208697. {
  208698. SetCursor ((HCURSOR) getHandle());
  208699. }
  208700. void MouseCursor::showInAllWindows() const
  208701. {
  208702. showInWindow (0);
  208703. }
  208704. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208705. {
  208706. public:
  208707. JuceDropSource() {}
  208708. ~JuceDropSource() {}
  208709. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208710. {
  208711. if (escapePressed)
  208712. return DRAGDROP_S_CANCEL;
  208713. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208714. return DRAGDROP_S_DROP;
  208715. return S_OK;
  208716. }
  208717. HRESULT __stdcall GiveFeedback (DWORD)
  208718. {
  208719. return DRAGDROP_S_USEDEFAULTCURSORS;
  208720. }
  208721. };
  208722. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208723. {
  208724. public:
  208725. JuceEnumFormatEtc (const FORMATETC* const format_)
  208726. : format (format_),
  208727. index (0)
  208728. {
  208729. }
  208730. ~JuceEnumFormatEtc() {}
  208731. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208732. {
  208733. if (result == 0)
  208734. return E_POINTER;
  208735. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208736. newOne->index = index;
  208737. *result = newOne;
  208738. return S_OK;
  208739. }
  208740. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208741. {
  208742. if (pceltFetched != 0)
  208743. *pceltFetched = 0;
  208744. else if (celt != 1)
  208745. return S_FALSE;
  208746. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208747. {
  208748. copyFormatEtc (lpFormatEtc [0], *format);
  208749. ++index;
  208750. if (pceltFetched != 0)
  208751. *pceltFetched = 1;
  208752. return S_OK;
  208753. }
  208754. return S_FALSE;
  208755. }
  208756. HRESULT __stdcall Skip (ULONG celt)
  208757. {
  208758. if (index + (int) celt >= 1)
  208759. return S_FALSE;
  208760. index += celt;
  208761. return S_OK;
  208762. }
  208763. HRESULT __stdcall Reset()
  208764. {
  208765. index = 0;
  208766. return S_OK;
  208767. }
  208768. private:
  208769. const FORMATETC* const format;
  208770. int index;
  208771. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208772. {
  208773. dest = source;
  208774. if (source.ptd != 0)
  208775. {
  208776. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208777. *(dest.ptd) = *(source.ptd);
  208778. }
  208779. }
  208780. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208781. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208782. };
  208783. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208784. {
  208785. public:
  208786. JuceDataObject (JuceDropSource* const dropSource_,
  208787. const FORMATETC* const format_,
  208788. const STGMEDIUM* const medium_)
  208789. : dropSource (dropSource_),
  208790. format (format_),
  208791. medium (medium_)
  208792. {
  208793. }
  208794. virtual ~JuceDataObject()
  208795. {
  208796. jassert (refCount == 0);
  208797. }
  208798. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208799. {
  208800. if ((pFormatEtc->tymed & format->tymed) != 0
  208801. && pFormatEtc->cfFormat == format->cfFormat
  208802. && pFormatEtc->dwAspect == format->dwAspect)
  208803. {
  208804. pMedium->tymed = format->tymed;
  208805. pMedium->pUnkForRelease = 0;
  208806. if (format->tymed == TYMED_HGLOBAL)
  208807. {
  208808. const SIZE_T len = GlobalSize (medium->hGlobal);
  208809. void* const src = GlobalLock (medium->hGlobal);
  208810. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208811. memcpy (dst, src, len);
  208812. GlobalUnlock (medium->hGlobal);
  208813. pMedium->hGlobal = dst;
  208814. return S_OK;
  208815. }
  208816. }
  208817. return DV_E_FORMATETC;
  208818. }
  208819. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208820. {
  208821. if (f == 0)
  208822. return E_INVALIDARG;
  208823. if (f->tymed == format->tymed
  208824. && f->cfFormat == format->cfFormat
  208825. && f->dwAspect == format->dwAspect)
  208826. return S_OK;
  208827. return DV_E_FORMATETC;
  208828. }
  208829. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208830. {
  208831. pFormatEtcOut->ptd = 0;
  208832. return E_NOTIMPL;
  208833. }
  208834. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208835. {
  208836. if (result == 0)
  208837. return E_POINTER;
  208838. if (direction == DATADIR_GET)
  208839. {
  208840. *result = new JuceEnumFormatEtc (format);
  208841. return S_OK;
  208842. }
  208843. *result = 0;
  208844. return E_NOTIMPL;
  208845. }
  208846. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208847. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208848. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208849. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208850. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208851. private:
  208852. JuceDropSource* const dropSource;
  208853. const FORMATETC* const format;
  208854. const STGMEDIUM* const medium;
  208855. JuceDataObject (const JuceDataObject&);
  208856. JuceDataObject& operator= (const JuceDataObject&);
  208857. };
  208858. static HDROP createHDrop (const StringArray& fileNames)
  208859. {
  208860. int totalChars = 0;
  208861. for (int i = fileNames.size(); --i >= 0;)
  208862. totalChars += fileNames[i].length() + 1;
  208863. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208864. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208865. if (hDrop != 0)
  208866. {
  208867. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208868. pDropFiles->pFiles = sizeof (DROPFILES);
  208869. pDropFiles->fWide = true;
  208870. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208871. for (int i = 0; i < fileNames.size(); ++i)
  208872. {
  208873. fileNames[i].copyToUnicode (fname, 2048);
  208874. fname += fileNames[i].length() + 1;
  208875. }
  208876. *fname = 0;
  208877. GlobalUnlock (hDrop);
  208878. }
  208879. return hDrop;
  208880. }
  208881. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208882. {
  208883. JuceDropSource* const source = new JuceDropSource();
  208884. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208885. DWORD effect;
  208886. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208887. data->Release();
  208888. source->Release();
  208889. return res == DRAGDROP_S_DROP;
  208890. }
  208891. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208892. {
  208893. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208894. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208895. medium.hGlobal = createHDrop (files);
  208896. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208897. : DROPEFFECT_COPY);
  208898. }
  208899. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208900. {
  208901. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208902. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208903. const int numChars = text.length();
  208904. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208905. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208906. text.copyToUnicode (data, numChars + 1);
  208907. format.cfFormat = CF_UNICODETEXT;
  208908. GlobalUnlock (medium.hGlobal);
  208909. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208910. }
  208911. #endif
  208912. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208913. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208914. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208915. // compiled on its own).
  208916. #if JUCE_INCLUDED_FILE
  208917. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  208918. namespace FileChooserHelpers
  208919. {
  208920. static const void* defaultDirPath = 0;
  208921. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  208922. static Component* currentExtraFileWin = 0;
  208923. static bool areThereAnyAlwaysOnTopWindows()
  208924. {
  208925. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208926. {
  208927. Component* c = Desktop::getInstance().getComponent (i);
  208928. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208929. return true;
  208930. }
  208931. return false;
  208932. }
  208933. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  208934. {
  208935. if (msg == BFFM_INITIALIZED)
  208936. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  208937. else if (msg == BFFM_VALIDATEFAILEDW)
  208938. returnedString = (LPCWSTR) lParam;
  208939. else if (msg == BFFM_VALIDATEFAILEDA)
  208940. returnedString = (const char*) lParam;
  208941. return 0;
  208942. }
  208943. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208944. {
  208945. if (currentExtraFileWin != 0)
  208946. {
  208947. if (uiMsg == WM_INITDIALOG)
  208948. {
  208949. HWND dialogH = GetParent (hdlg);
  208950. jassert (dialogH != 0);
  208951. if (dialogH == 0)
  208952. dialogH = hdlg;
  208953. RECT r, cr;
  208954. GetWindowRect (dialogH, &r);
  208955. GetClientRect (dialogH, &cr);
  208956. SetWindowPos (dialogH, 0,
  208957. r.left, r.top,
  208958. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  208959. jmax (150, (int) (r.bottom - r.top)),
  208960. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208961. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  208962. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  208963. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  208964. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  208965. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  208966. }
  208967. else if (uiMsg == WM_NOTIFY)
  208968. {
  208969. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208970. if (ofn->hdr.code == CDN_SELCHANGE)
  208971. {
  208972. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  208973. if (comp != 0)
  208974. {
  208975. TCHAR path [MAX_PATH * 2];
  208976. path[0] = 0;
  208977. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208978. const String fn ((const WCHAR*) path);
  208979. comp->selectedFileChanged (File (fn));
  208980. }
  208981. }
  208982. }
  208983. }
  208984. return 0;
  208985. }
  208986. class FPComponentHolder : public Component
  208987. {
  208988. public:
  208989. FPComponentHolder()
  208990. {
  208991. setVisible (true);
  208992. setOpaque (true);
  208993. }
  208994. ~FPComponentHolder()
  208995. {
  208996. }
  208997. void paint (Graphics& g)
  208998. {
  208999. g.fillAll (Colours::lightgrey);
  209000. }
  209001. private:
  209002. FPComponentHolder (const FPComponentHolder&);
  209003. FPComponentHolder& operator= (const FPComponentHolder&);
  209004. };
  209005. }
  209006. void FileChooser::showPlatformDialog (Array<File>& results,
  209007. const String& title,
  209008. const File& currentFileOrDirectory,
  209009. const String& filter,
  209010. bool selectsDirectory,
  209011. bool /*selectsFiles*/,
  209012. bool isSaveDialogue,
  209013. bool warnAboutOverwritingExistingFiles,
  209014. bool selectMultipleFiles,
  209015. FilePreviewComponent* extraInfoComponent)
  209016. {
  209017. using namespace FileChooserHelpers;
  209018. const int numCharsAvailable = 32768;
  209019. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  209020. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  209021. int fnameIdx = 0;
  209022. JUCE_TRY
  209023. {
  209024. // use a modal window as the parent for this dialog box
  209025. // to block input from other app windows
  209026. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  209027. Component w (String::empty);
  209028. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  209029. mainMon.getY() + mainMon.getHeight() / 4,
  209030. 0, 0);
  209031. w.setOpaque (true);
  209032. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  209033. w.addToDesktop (0);
  209034. if (extraInfoComponent == 0)
  209035. w.enterModalState();
  209036. String initialDir;
  209037. if (currentFileOrDirectory.isDirectory())
  209038. {
  209039. initialDir = currentFileOrDirectory.getFullPathName();
  209040. }
  209041. else
  209042. {
  209043. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  209044. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209045. }
  209046. if (currentExtraFileWin->isValidComponent())
  209047. {
  209048. jassertfalse;
  209049. return;
  209050. }
  209051. if (selectsDirectory)
  209052. {
  209053. LPITEMIDLIST list = 0;
  209054. filenameSpace.fillWith (0);
  209055. {
  209056. BROWSEINFO bi;
  209057. zerostruct (bi);
  209058. bi.hwndOwner = (HWND) w.getWindowHandle();
  209059. bi.pszDisplayName = fname;
  209060. bi.lpszTitle = title;
  209061. bi.lpfn = browseCallbackProc;
  209062. #ifdef BIF_USENEWUI
  209063. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209064. #else
  209065. bi.ulFlags = 0x50;
  209066. #endif
  209067. defaultDirPath = (const WCHAR*) initialDir;
  209068. list = SHBrowseForFolder (&bi);
  209069. if (! SHGetPathFromIDListW (list, fname))
  209070. {
  209071. fname[0] = 0;
  209072. returnedString = String::empty;
  209073. }
  209074. }
  209075. LPMALLOC al;
  209076. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209077. al->Free (list);
  209078. defaultDirPath = 0;
  209079. if (returnedString.isNotEmpty())
  209080. {
  209081. const String stringFName (fname);
  209082. results.add (File (stringFName).getSiblingFile (returnedString));
  209083. returnedString = String::empty;
  209084. return;
  209085. }
  209086. }
  209087. else
  209088. {
  209089. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209090. if (warnAboutOverwritingExistingFiles)
  209091. flags |= OFN_OVERWRITEPROMPT;
  209092. if (selectMultipleFiles)
  209093. flags |= OFN_ALLOWMULTISELECT;
  209094. if (extraInfoComponent != 0)
  209095. {
  209096. flags |= OFN_ENABLEHOOK;
  209097. currentExtraFileWin = new FPComponentHolder();
  209098. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  209099. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  209100. extraInfoComponent->getHeight());
  209101. currentExtraFileWin->addToDesktop (0);
  209102. currentExtraFileWin->enterModalState();
  209103. }
  209104. {
  209105. WCHAR filters [1024];
  209106. zeromem (filters, sizeof (filters));
  209107. filter.copyToUnicode (filters, 1024);
  209108. filter.copyToUnicode (filters + filter.length() + 1,
  209109. 1022 - filter.length());
  209110. OPENFILENAMEW of;
  209111. zerostruct (of);
  209112. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209113. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209114. #else
  209115. of.lStructSize = sizeof (of);
  209116. #endif
  209117. of.hwndOwner = (HWND) w.getWindowHandle();
  209118. of.lpstrFilter = filters;
  209119. of.nFilterIndex = 1;
  209120. of.lpstrFile = fname;
  209121. of.nMaxFile = numCharsAvailable;
  209122. of.lpstrInitialDir = initialDir;
  209123. of.lpstrTitle = title;
  209124. of.Flags = flags;
  209125. if (extraInfoComponent != 0)
  209126. of.lpfnHook = &openCallback;
  209127. if (isSaveDialogue)
  209128. {
  209129. if (! GetSaveFileName (&of))
  209130. fname[0] = 0;
  209131. else
  209132. fnameIdx = of.nFileOffset;
  209133. }
  209134. else
  209135. {
  209136. if (! GetOpenFileName (&of))
  209137. fname[0] = 0;
  209138. else
  209139. fnameIdx = of.nFileOffset;
  209140. }
  209141. }
  209142. }
  209143. }
  209144. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  209145. catch (...)
  209146. {
  209147. fname[0] = 0;
  209148. }
  209149. #endif
  209150. deleteAndZero (currentExtraFileWin);
  209151. const WCHAR* const files = fname;
  209152. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  209153. {
  209154. const WCHAR* filename = files + fnameIdx;
  209155. while (*filename != 0)
  209156. {
  209157. const String filepath (String (files) + "\\" + String (filename));
  209158. results.add (File (filepath));
  209159. filename += CharacterFunctions::length (filename) + 1;
  209160. }
  209161. }
  209162. else if (files[0] != 0)
  209163. {
  209164. results.add (File (files));
  209165. }
  209166. }
  209167. #endif
  209168. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209169. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209170. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209171. // compiled on its own).
  209172. #if JUCE_INCLUDED_FILE
  209173. void SystemClipboard::copyTextToClipboard (const String& text)
  209174. {
  209175. if (OpenClipboard (0) != 0)
  209176. {
  209177. if (EmptyClipboard() != 0)
  209178. {
  209179. const int len = text.length();
  209180. if (len > 0)
  209181. {
  209182. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209183. (len + 1) * sizeof (wchar_t));
  209184. if (bufH != 0)
  209185. {
  209186. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209187. text.copyToUnicode (data, len);
  209188. GlobalUnlock (bufH);
  209189. SetClipboardData (CF_UNICODETEXT, bufH);
  209190. }
  209191. }
  209192. }
  209193. CloseClipboard();
  209194. }
  209195. }
  209196. const String SystemClipboard::getTextFromClipboard()
  209197. {
  209198. String result;
  209199. if (OpenClipboard (0) != 0)
  209200. {
  209201. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209202. if (bufH != 0)
  209203. {
  209204. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209205. if (data != 0)
  209206. {
  209207. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209208. GlobalUnlock (bufH);
  209209. }
  209210. }
  209211. CloseClipboard();
  209212. }
  209213. return result;
  209214. }
  209215. #endif
  209216. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209217. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209218. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209219. // compiled on its own).
  209220. #if JUCE_INCLUDED_FILE
  209221. namespace ActiveXHelpers
  209222. {
  209223. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209224. {
  209225. public:
  209226. JuceIStorage() {}
  209227. ~JuceIStorage() {}
  209228. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209229. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209230. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209231. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209232. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209233. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209234. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209235. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209236. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209237. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209238. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209239. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209240. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209241. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209242. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209243. juce_UseDebuggingNewOperator
  209244. };
  209245. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209246. {
  209247. HWND window;
  209248. public:
  209249. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209250. ~JuceOleInPlaceFrame() {}
  209251. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209252. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209253. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209254. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209255. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209256. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209257. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209258. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209259. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209260. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209261. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209262. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209263. juce_UseDebuggingNewOperator
  209264. };
  209265. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209266. {
  209267. HWND window;
  209268. JuceOleInPlaceFrame* frame;
  209269. public:
  209270. JuceIOleInPlaceSite (HWND window_)
  209271. : window (window_),
  209272. frame (new JuceOleInPlaceFrame (window))
  209273. {}
  209274. ~JuceIOleInPlaceSite()
  209275. {
  209276. frame->Release();
  209277. }
  209278. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209279. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209280. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209281. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209282. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209283. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209284. {
  209285. *lplpFrame = frame;
  209286. *lplpDoc = 0;
  209287. lpFrameInfo->fMDIApp = FALSE;
  209288. lpFrameInfo->hwndFrame = window;
  209289. lpFrameInfo->haccel = 0;
  209290. lpFrameInfo->cAccelEntries = 0;
  209291. return S_OK;
  209292. }
  209293. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209294. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209295. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209296. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209297. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209298. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209299. juce_UseDebuggingNewOperator
  209300. };
  209301. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209302. {
  209303. JuceIOleInPlaceSite* inplaceSite;
  209304. public:
  209305. JuceIOleClientSite (HWND window)
  209306. : inplaceSite (new JuceIOleInPlaceSite (window))
  209307. {}
  209308. ~JuceIOleClientSite()
  209309. {
  209310. inplaceSite->Release();
  209311. }
  209312. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  209313. {
  209314. if (type == IID_IOleInPlaceSite)
  209315. {
  209316. inplaceSite->AddRef();
  209317. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209318. return S_OK;
  209319. }
  209320. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209321. }
  209322. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209323. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209324. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209325. HRESULT __stdcall ShowObject() { return S_OK; }
  209326. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209327. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209328. juce_UseDebuggingNewOperator
  209329. };
  209330. static Array<ActiveXControlComponent*> activeXComps;
  209331. static HWND getHWND (const ActiveXControlComponent* const component)
  209332. {
  209333. HWND hwnd = 0;
  209334. const IID iid = IID_IOleWindow;
  209335. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209336. if (window != 0)
  209337. {
  209338. window->GetWindow (&hwnd);
  209339. window->Release();
  209340. }
  209341. return hwnd;
  209342. }
  209343. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209344. {
  209345. RECT activeXRect, peerRect;
  209346. GetWindowRect (hwnd, &activeXRect);
  209347. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209348. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209349. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209350. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209351. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209352. switch (message)
  209353. {
  209354. case WM_MOUSEMOVE:
  209355. case WM_LBUTTONDOWN:
  209356. case WM_MBUTTONDOWN:
  209357. case WM_RBUTTONDOWN:
  209358. case WM_LBUTTONUP:
  209359. case WM_MBUTTONUP:
  209360. case WM_RBUTTONUP:
  209361. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209362. break;
  209363. default:
  209364. break;
  209365. }
  209366. }
  209367. }
  209368. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209369. {
  209370. ActiveXControlComponent* const owner;
  209371. bool wasShowing;
  209372. public:
  209373. HWND controlHWND;
  209374. IStorage* storage;
  209375. IOleClientSite* clientSite;
  209376. IOleObject* control;
  209377. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  209378. : ComponentMovementWatcher (owner_),
  209379. owner (owner_),
  209380. wasShowing (owner_ != 0 && owner_->isShowing()),
  209381. controlHWND (0),
  209382. storage (new ActiveXHelpers::JuceIStorage()),
  209383. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209384. control (0)
  209385. {
  209386. }
  209387. ~Pimpl()
  209388. {
  209389. if (control != 0)
  209390. {
  209391. control->Close (OLECLOSE_NOSAVE);
  209392. control->Release();
  209393. }
  209394. clientSite->Release();
  209395. storage->Release();
  209396. }
  209397. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209398. {
  209399. Component* const topComp = owner->getTopLevelComponent();
  209400. if (topComp->getPeer() != 0)
  209401. {
  209402. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  209403. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  209404. }
  209405. }
  209406. void componentPeerChanged()
  209407. {
  209408. const bool isShowingNow = owner->isShowing();
  209409. if (wasShowing != isShowingNow)
  209410. {
  209411. wasShowing = isShowingNow;
  209412. owner->setControlVisible (isShowingNow);
  209413. }
  209414. componentMovedOrResized (true, true);
  209415. }
  209416. void componentVisibilityChanged (Component&)
  209417. {
  209418. componentPeerChanged();
  209419. }
  209420. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209421. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209422. {
  209423. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209424. {
  209425. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209426. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209427. {
  209428. switch (message)
  209429. {
  209430. case WM_MOUSEMOVE:
  209431. case WM_LBUTTONDOWN:
  209432. case WM_MBUTTONDOWN:
  209433. case WM_RBUTTONDOWN:
  209434. case WM_LBUTTONUP:
  209435. case WM_MBUTTONUP:
  209436. case WM_RBUTTONUP:
  209437. case WM_LBUTTONDBLCLK:
  209438. case WM_MBUTTONDBLCLK:
  209439. case WM_RBUTTONDBLCLK:
  209440. if (ax->isShowing())
  209441. {
  209442. ComponentPeer* const peer = ax->getPeer();
  209443. if (peer != 0)
  209444. {
  209445. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209446. if (! ax->areMouseEventsAllowed())
  209447. return 0;
  209448. }
  209449. }
  209450. break;
  209451. default:
  209452. break;
  209453. }
  209454. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209455. }
  209456. }
  209457. return DefWindowProc (hwnd, message, wParam, lParam);
  209458. }
  209459. };
  209460. ActiveXControlComponent::ActiveXControlComponent()
  209461. : originalWndProc (0),
  209462. mouseEventsAllowed (true)
  209463. {
  209464. ActiveXHelpers::activeXComps.add (this);
  209465. }
  209466. ActiveXControlComponent::~ActiveXControlComponent()
  209467. {
  209468. deleteControl();
  209469. ActiveXHelpers::activeXComps.removeValue (this);
  209470. }
  209471. void ActiveXControlComponent::paint (Graphics& g)
  209472. {
  209473. if (control == 0)
  209474. g.fillAll (Colours::lightgrey);
  209475. }
  209476. bool ActiveXControlComponent::createControl (const void* controlIID)
  209477. {
  209478. deleteControl();
  209479. ComponentPeer* const peer = getPeer();
  209480. // the component must have already been added to a real window when you call this!
  209481. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209482. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209483. {
  209484. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209485. HWND hwnd = (HWND) peer->getNativeHandle();
  209486. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  209487. HRESULT hr;
  209488. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209489. newControl->clientSite, newControl->storage,
  209490. (void**) &(newControl->control))) == S_OK)
  209491. {
  209492. newControl->control->SetHostNames (L"Juce", 0);
  209493. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209494. {
  209495. RECT rect;
  209496. rect.left = pos.getX();
  209497. rect.top = pos.getY();
  209498. rect.right = pos.getX() + getWidth();
  209499. rect.bottom = pos.getY() + getHeight();
  209500. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209501. {
  209502. control = newControl;
  209503. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209504. control->controlHWND = ActiveXHelpers::getHWND (this);
  209505. if (control->controlHWND != 0)
  209506. {
  209507. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209508. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209509. }
  209510. return true;
  209511. }
  209512. }
  209513. }
  209514. }
  209515. return false;
  209516. }
  209517. void ActiveXControlComponent::deleteControl()
  209518. {
  209519. control = 0;
  209520. originalWndProc = 0;
  209521. }
  209522. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209523. {
  209524. void* result = 0;
  209525. if (control != 0 && control->control != 0
  209526. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209527. return result;
  209528. return 0;
  209529. }
  209530. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209531. {
  209532. if (control->controlHWND != 0)
  209533. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209534. }
  209535. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209536. {
  209537. if (control->controlHWND != 0)
  209538. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209539. }
  209540. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209541. {
  209542. mouseEventsAllowed = eventsCanReachControl;
  209543. }
  209544. #endif
  209545. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209546. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209547. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209548. // compiled on its own).
  209549. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209550. using namespace QTOLibrary;
  209551. using namespace QTOControlLib;
  209552. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209553. static bool isQTAvailable = false;
  209554. class QuickTimeMovieComponent::Pimpl
  209555. {
  209556. public:
  209557. Pimpl() : dataHandle (0)
  209558. {
  209559. }
  209560. ~Pimpl()
  209561. {
  209562. clearHandle();
  209563. }
  209564. void clearHandle()
  209565. {
  209566. if (dataHandle != 0)
  209567. {
  209568. DisposeHandle (dataHandle);
  209569. dataHandle = 0;
  209570. }
  209571. }
  209572. IQTControlPtr qtControl;
  209573. IQTMoviePtr qtMovie;
  209574. Handle dataHandle;
  209575. };
  209576. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209577. : movieLoaded (false),
  209578. controllerVisible (true)
  209579. {
  209580. pimpl = new Pimpl();
  209581. setMouseEventsAllowed (false);
  209582. }
  209583. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209584. {
  209585. closeMovie();
  209586. pimpl->qtControl = 0;
  209587. deleteControl();
  209588. pimpl = 0;
  209589. }
  209590. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209591. {
  209592. if (! isQTAvailable)
  209593. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209594. return isQTAvailable;
  209595. }
  209596. void QuickTimeMovieComponent::createControlIfNeeded()
  209597. {
  209598. if (isShowing() && ! isControlCreated())
  209599. {
  209600. const IID qtIID = __uuidof (QTControl);
  209601. if (createControl (&qtIID))
  209602. {
  209603. const IID qtInterfaceIID = __uuidof (IQTControl);
  209604. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209605. if (pimpl->qtControl != 0)
  209606. {
  209607. pimpl->qtControl->Release(); // it has one ref too many at this point
  209608. pimpl->qtControl->QuickTimeInitialize();
  209609. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209610. if (movieFile != File::nonexistent)
  209611. loadMovie (movieFile, controllerVisible);
  209612. }
  209613. }
  209614. }
  209615. }
  209616. bool QuickTimeMovieComponent::isControlCreated() const
  209617. {
  209618. return isControlOpen();
  209619. }
  209620. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209621. const bool isControllerVisible)
  209622. {
  209623. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209624. movieFile = File::nonexistent;
  209625. movieLoaded = false;
  209626. pimpl->qtMovie = 0;
  209627. controllerVisible = isControllerVisible;
  209628. createControlIfNeeded();
  209629. if (isControlCreated())
  209630. {
  209631. if (pimpl->qtControl != 0)
  209632. {
  209633. pimpl->qtControl->Put_MovieHandle (0);
  209634. pimpl->clearHandle();
  209635. Movie movie;
  209636. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209637. {
  209638. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209639. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209640. if (pimpl->qtMovie != 0)
  209641. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209642. : qtMovieControllerTypeNone);
  209643. }
  209644. if (movie == 0)
  209645. pimpl->clearHandle();
  209646. }
  209647. movieLoaded = (pimpl->qtMovie != 0);
  209648. }
  209649. else
  209650. {
  209651. // You're trying to open a movie when the control hasn't yet been created, probably because
  209652. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209653. jassertfalse;
  209654. }
  209655. return movieLoaded;
  209656. }
  209657. void QuickTimeMovieComponent::closeMovie()
  209658. {
  209659. stop();
  209660. movieFile = File::nonexistent;
  209661. movieLoaded = false;
  209662. pimpl->qtMovie = 0;
  209663. if (pimpl->qtControl != 0)
  209664. pimpl->qtControl->Put_MovieHandle (0);
  209665. pimpl->clearHandle();
  209666. }
  209667. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209668. {
  209669. return movieFile;
  209670. }
  209671. bool QuickTimeMovieComponent::isMovieOpen() const
  209672. {
  209673. return movieLoaded;
  209674. }
  209675. double QuickTimeMovieComponent::getMovieDuration() const
  209676. {
  209677. if (pimpl->qtMovie != 0)
  209678. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209679. return 0.0;
  209680. }
  209681. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209682. {
  209683. if (pimpl->qtMovie != 0)
  209684. {
  209685. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209686. width = r.right - r.left;
  209687. height = r.bottom - r.top;
  209688. }
  209689. else
  209690. {
  209691. width = height = 0;
  209692. }
  209693. }
  209694. void QuickTimeMovieComponent::play()
  209695. {
  209696. if (pimpl->qtMovie != 0)
  209697. pimpl->qtMovie->Play();
  209698. }
  209699. void QuickTimeMovieComponent::stop()
  209700. {
  209701. if (pimpl->qtMovie != 0)
  209702. pimpl->qtMovie->Stop();
  209703. }
  209704. bool QuickTimeMovieComponent::isPlaying() const
  209705. {
  209706. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209707. }
  209708. void QuickTimeMovieComponent::setPosition (const double seconds)
  209709. {
  209710. if (pimpl->qtMovie != 0)
  209711. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209712. }
  209713. double QuickTimeMovieComponent::getPosition() const
  209714. {
  209715. if (pimpl->qtMovie != 0)
  209716. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209717. return 0.0;
  209718. }
  209719. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209720. {
  209721. if (pimpl->qtMovie != 0)
  209722. pimpl->qtMovie->PutRate (newSpeed);
  209723. }
  209724. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209725. {
  209726. if (pimpl->qtMovie != 0)
  209727. {
  209728. pimpl->qtMovie->PutAudioVolume (newVolume);
  209729. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209730. }
  209731. }
  209732. float QuickTimeMovieComponent::getMovieVolume() const
  209733. {
  209734. if (pimpl->qtMovie != 0)
  209735. return pimpl->qtMovie->GetAudioVolume();
  209736. return 0.0f;
  209737. }
  209738. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209739. {
  209740. if (pimpl->qtMovie != 0)
  209741. pimpl->qtMovie->PutLoop (shouldLoop);
  209742. }
  209743. bool QuickTimeMovieComponent::isLooping() const
  209744. {
  209745. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209746. }
  209747. bool QuickTimeMovieComponent::isControllerVisible() const
  209748. {
  209749. return controllerVisible;
  209750. }
  209751. void QuickTimeMovieComponent::parentHierarchyChanged()
  209752. {
  209753. createControlIfNeeded();
  209754. QTCompBaseClass::parentHierarchyChanged();
  209755. }
  209756. void QuickTimeMovieComponent::visibilityChanged()
  209757. {
  209758. createControlIfNeeded();
  209759. QTCompBaseClass::visibilityChanged();
  209760. }
  209761. void QuickTimeMovieComponent::paint (Graphics& g)
  209762. {
  209763. if (! isControlCreated())
  209764. g.fillAll (Colours::black);
  209765. }
  209766. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209767. {
  209768. Handle dataRef = 0;
  209769. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209770. if (err == noErr)
  209771. {
  209772. Str255 suffix;
  209773. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209774. StringPtr name = suffix;
  209775. err = PtrAndHand (name, dataRef, name[0] + 1);
  209776. if (err == noErr)
  209777. {
  209778. long atoms[3];
  209779. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209780. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209781. atoms[2] = EndianU32_NtoB (MovieFileType);
  209782. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209783. if (err == noErr)
  209784. return dataRef;
  209785. }
  209786. DisposeHandle (dataRef);
  209787. }
  209788. return 0;
  209789. }
  209790. static CFStringRef juceStringToCFString (const String& s)
  209791. {
  209792. const int len = s.length();
  209793. const juce_wchar* const t = s;
  209794. HeapBlock <UniChar> temp (len + 2);
  209795. for (int i = 0; i <= len; ++i)
  209796. temp[i] = t[i];
  209797. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209798. }
  209799. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209800. {
  209801. Boolean trueBool = true;
  209802. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209803. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209804. props[prop].propValueSize = sizeof (trueBool);
  209805. props[prop].propValueAddress = &trueBool;
  209806. ++prop;
  209807. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209808. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209809. props[prop].propValueSize = sizeof (trueBool);
  209810. props[prop].propValueAddress = &trueBool;
  209811. ++prop;
  209812. Boolean isActive = true;
  209813. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209814. props[prop].propID = kQTNewMoviePropertyID_Active;
  209815. props[prop].propValueSize = sizeof (isActive);
  209816. props[prop].propValueAddress = &isActive;
  209817. ++prop;
  209818. MacSetPort (0);
  209819. jassert (prop <= 5);
  209820. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209821. return err == noErr;
  209822. }
  209823. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209824. {
  209825. if (input == 0)
  209826. return false;
  209827. dataHandle = 0;
  209828. bool ok = false;
  209829. QTNewMoviePropertyElement props[5];
  209830. zeromem (props, sizeof (props));
  209831. int prop = 0;
  209832. DataReferenceRecord dr;
  209833. props[prop].propClass = kQTPropertyClass_DataLocation;
  209834. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209835. props[prop].propValueSize = sizeof (dr);
  209836. props[prop].propValueAddress = &dr;
  209837. ++prop;
  209838. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209839. if (fin != 0)
  209840. {
  209841. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209842. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209843. &dr.dataRef, &dr.dataRefType);
  209844. ok = openMovie (props, prop, movie);
  209845. DisposeHandle (dr.dataRef);
  209846. CFRelease (filePath);
  209847. }
  209848. else
  209849. {
  209850. // sanity-check because this currently needs to load the whole stream into memory..
  209851. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209852. dataHandle = NewHandle ((Size) input->getTotalLength());
  209853. HLock (dataHandle);
  209854. // read the entire stream into memory - this is a pain, but can't get it to work
  209855. // properly using a custom callback to supply the data.
  209856. input->read (*dataHandle, (int) input->getTotalLength());
  209857. HUnlock (dataHandle);
  209858. // different types to get QT to try. (We should really be a bit smarter here by
  209859. // working out in advance which one the stream contains, rather than just trying
  209860. // each one)
  209861. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209862. "\04.avi", "\04.m4a" };
  209863. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209864. {
  209865. /* // this fails for some bizarre reason - it can be bodged to work with
  209866. // movies, but can't seem to do it for other file types..
  209867. QTNewMovieUserProcRecord procInfo;
  209868. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209869. procInfo.getMovieUserProcRefcon = this;
  209870. procInfo.defaultDataRef.dataRef = dataRef;
  209871. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209872. props[prop].propClass = kQTPropertyClass_DataLocation;
  209873. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209874. props[prop].propValueSize = sizeof (procInfo);
  209875. props[prop].propValueAddress = (void*) &procInfo;
  209876. ++prop; */
  209877. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209878. dr.dataRefType = HandleDataHandlerSubType;
  209879. ok = openMovie (props, prop, movie);
  209880. DisposeHandle (dr.dataRef);
  209881. }
  209882. }
  209883. return ok;
  209884. }
  209885. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209886. const bool isControllerVisible)
  209887. {
  209888. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209889. movieFile = movieFile_;
  209890. return ok;
  209891. }
  209892. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209893. const bool isControllerVisible)
  209894. {
  209895. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209896. }
  209897. void QuickTimeMovieComponent::goToStart()
  209898. {
  209899. setPosition (0.0);
  209900. }
  209901. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209902. const RectanglePlacement& placement)
  209903. {
  209904. int normalWidth, normalHeight;
  209905. getMovieNormalSize (normalWidth, normalHeight);
  209906. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209907. {
  209908. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209909. placement.applyTo (x, y, w, h,
  209910. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209911. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209912. if (w > 0 && h > 0)
  209913. {
  209914. setBounds (roundToInt (x), roundToInt (y),
  209915. roundToInt (w), roundToInt (h));
  209916. }
  209917. }
  209918. else
  209919. {
  209920. setBounds (spaceToFitWithin);
  209921. }
  209922. }
  209923. #endif
  209924. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209925. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209926. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209927. // compiled on its own).
  209928. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209929. class WebBrowserComponentInternal : public ActiveXControlComponent
  209930. {
  209931. public:
  209932. WebBrowserComponentInternal()
  209933. : browser (0),
  209934. connectionPoint (0),
  209935. adviseCookie (0)
  209936. {
  209937. }
  209938. ~WebBrowserComponentInternal()
  209939. {
  209940. if (connectionPoint != 0)
  209941. connectionPoint->Unadvise (adviseCookie);
  209942. if (browser != 0)
  209943. browser->Release();
  209944. }
  209945. void createBrowser()
  209946. {
  209947. createControl (&CLSID_WebBrowser);
  209948. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209949. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209950. if (connectionPointContainer != 0)
  209951. {
  209952. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209953. &connectionPoint);
  209954. if (connectionPoint != 0)
  209955. {
  209956. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209957. jassert (owner != 0);
  209958. EventHandler* handler = new EventHandler (owner);
  209959. connectionPoint->Advise (handler, &adviseCookie);
  209960. handler->Release();
  209961. }
  209962. }
  209963. }
  209964. void goToURL (const String& url,
  209965. const StringArray* headers,
  209966. const MemoryBlock* postData)
  209967. {
  209968. if (browser != 0)
  209969. {
  209970. LPSAFEARRAY sa = 0;
  209971. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209972. VariantInit (&flags);
  209973. VariantInit (&frame);
  209974. VariantInit (&postDataVar);
  209975. VariantInit (&headersVar);
  209976. if (headers != 0)
  209977. {
  209978. V_VT (&headersVar) = VT_BSTR;
  209979. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209980. }
  209981. if (postData != 0 && postData->getSize() > 0)
  209982. {
  209983. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209984. if (sa != 0)
  209985. {
  209986. void* data = 0;
  209987. SafeArrayAccessData (sa, &data);
  209988. jassert (data != 0);
  209989. if (data != 0)
  209990. {
  209991. postData->copyTo (data, 0, postData->getSize());
  209992. SafeArrayUnaccessData (sa);
  209993. VARIANT postDataVar2;
  209994. VariantInit (&postDataVar2);
  209995. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209996. V_ARRAY (&postDataVar2) = sa;
  209997. postDataVar = postDataVar2;
  209998. }
  209999. }
  210000. }
  210001. browser->Navigate ((BSTR) (const OLECHAR*) url,
  210002. &flags, &frame,
  210003. &postDataVar, &headersVar);
  210004. if (sa != 0)
  210005. SafeArrayDestroy (sa);
  210006. VariantClear (&flags);
  210007. VariantClear (&frame);
  210008. VariantClear (&postDataVar);
  210009. VariantClear (&headersVar);
  210010. }
  210011. }
  210012. IWebBrowser2* browser;
  210013. juce_UseDebuggingNewOperator
  210014. private:
  210015. IConnectionPoint* connectionPoint;
  210016. DWORD adviseCookie;
  210017. class EventHandler : public ComBaseClassHelper <IDispatch>,
  210018. public ComponentMovementWatcher
  210019. {
  210020. public:
  210021. EventHandler (WebBrowserComponent* owner_)
  210022. : ComponentMovementWatcher (owner_),
  210023. owner (owner_)
  210024. {
  210025. }
  210026. ~EventHandler()
  210027. {
  210028. }
  210029. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  210030. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  210031. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  210032. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  210033. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  210034. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  210035. UINT __RPC_FAR* /*puArgErr*/)
  210036. {
  210037. switch (dispIdMember)
  210038. {
  210039. case DISPID_BEFORENAVIGATE2:
  210040. {
  210041. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  210042. String url;
  210043. if ((vurl->vt & VT_BYREF) != 0)
  210044. url = *vurl->pbstrVal;
  210045. else
  210046. url = vurl->bstrVal;
  210047. *pDispParams->rgvarg->pboolVal
  210048. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  210049. : VARIANT_TRUE;
  210050. return S_OK;
  210051. }
  210052. default:
  210053. break;
  210054. }
  210055. return E_NOTIMPL;
  210056. }
  210057. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  210058. void componentPeerChanged() {}
  210059. void componentVisibilityChanged (Component&)
  210060. {
  210061. owner->visibilityChanged();
  210062. }
  210063. juce_UseDebuggingNewOperator
  210064. private:
  210065. WebBrowserComponent* const owner;
  210066. EventHandler (const EventHandler&);
  210067. EventHandler& operator= (const EventHandler&);
  210068. };
  210069. };
  210070. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  210071. : browser (0),
  210072. blankPageShown (false),
  210073. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  210074. {
  210075. setOpaque (true);
  210076. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  210077. }
  210078. WebBrowserComponent::~WebBrowserComponent()
  210079. {
  210080. delete browser;
  210081. }
  210082. void WebBrowserComponent::goToURL (const String& url,
  210083. const StringArray* headers,
  210084. const MemoryBlock* postData)
  210085. {
  210086. lastURL = url;
  210087. lastHeaders.clear();
  210088. if (headers != 0)
  210089. lastHeaders = *headers;
  210090. lastPostData.setSize (0);
  210091. if (postData != 0)
  210092. lastPostData = *postData;
  210093. blankPageShown = false;
  210094. browser->goToURL (url, headers, postData);
  210095. }
  210096. void WebBrowserComponent::stop()
  210097. {
  210098. if (browser->browser != 0)
  210099. browser->browser->Stop();
  210100. }
  210101. void WebBrowserComponent::goBack()
  210102. {
  210103. lastURL = String::empty;
  210104. blankPageShown = false;
  210105. if (browser->browser != 0)
  210106. browser->browser->GoBack();
  210107. }
  210108. void WebBrowserComponent::goForward()
  210109. {
  210110. lastURL = String::empty;
  210111. if (browser->browser != 0)
  210112. browser->browser->GoForward();
  210113. }
  210114. void WebBrowserComponent::refresh()
  210115. {
  210116. if (browser->browser != 0)
  210117. browser->browser->Refresh();
  210118. }
  210119. void WebBrowserComponent::paint (Graphics& g)
  210120. {
  210121. if (browser->browser == 0)
  210122. g.fillAll (Colours::white);
  210123. }
  210124. void WebBrowserComponent::checkWindowAssociation()
  210125. {
  210126. if (isShowing())
  210127. {
  210128. if (browser->browser == 0 && getPeer() != 0)
  210129. {
  210130. browser->createBrowser();
  210131. reloadLastURL();
  210132. }
  210133. else
  210134. {
  210135. if (blankPageShown)
  210136. goBack();
  210137. }
  210138. }
  210139. else
  210140. {
  210141. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210142. {
  210143. // when the component becomes invisible, some stuff like flash
  210144. // carries on playing audio, so we need to force it onto a blank
  210145. // page to avoid this..
  210146. blankPageShown = true;
  210147. browser->goToURL ("about:blank", 0, 0);
  210148. }
  210149. }
  210150. }
  210151. void WebBrowserComponent::reloadLastURL()
  210152. {
  210153. if (lastURL.isNotEmpty())
  210154. {
  210155. goToURL (lastURL, &lastHeaders, &lastPostData);
  210156. lastURL = String::empty;
  210157. }
  210158. }
  210159. void WebBrowserComponent::parentHierarchyChanged()
  210160. {
  210161. checkWindowAssociation();
  210162. }
  210163. void WebBrowserComponent::resized()
  210164. {
  210165. browser->setSize (getWidth(), getHeight());
  210166. }
  210167. void WebBrowserComponent::visibilityChanged()
  210168. {
  210169. checkWindowAssociation();
  210170. }
  210171. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210172. {
  210173. return true;
  210174. }
  210175. #endif
  210176. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210177. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210178. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210179. // compiled on its own).
  210180. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210181. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210182. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210183. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210184. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210185. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210186. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210187. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210188. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210189. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210190. #define WGL_ACCELERATION_ARB 0x2003
  210191. #define WGL_SWAP_METHOD_ARB 0x2007
  210192. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210193. #define WGL_PIXEL_TYPE_ARB 0x2013
  210194. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210195. #define WGL_COLOR_BITS_ARB 0x2014
  210196. #define WGL_RED_BITS_ARB 0x2015
  210197. #define WGL_GREEN_BITS_ARB 0x2017
  210198. #define WGL_BLUE_BITS_ARB 0x2019
  210199. #define WGL_ALPHA_BITS_ARB 0x201B
  210200. #define WGL_DEPTH_BITS_ARB 0x2022
  210201. #define WGL_STENCIL_BITS_ARB 0x2023
  210202. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210203. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210204. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210205. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210206. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210207. #define WGL_STEREO_ARB 0x2012
  210208. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210209. #define WGL_SAMPLES_ARB 0x2042
  210210. #define WGL_TYPE_RGBA_ARB 0x202B
  210211. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210212. {
  210213. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210214. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210215. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210216. else
  210217. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210218. }
  210219. class WindowedGLContext : public OpenGLContext
  210220. {
  210221. public:
  210222. WindowedGLContext (Component* const component_,
  210223. HGLRC contextToShareWith,
  210224. const OpenGLPixelFormat& pixelFormat)
  210225. : renderContext (0),
  210226. dc (0),
  210227. component (component_)
  210228. {
  210229. jassert (component != 0);
  210230. createNativeWindow();
  210231. // Use a default pixel format that should be supported everywhere
  210232. PIXELFORMATDESCRIPTOR pfd;
  210233. zerostruct (pfd);
  210234. pfd.nSize = sizeof (pfd);
  210235. pfd.nVersion = 1;
  210236. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210237. pfd.iPixelType = PFD_TYPE_RGBA;
  210238. pfd.cColorBits = 24;
  210239. pfd.cDepthBits = 16;
  210240. const int format = ChoosePixelFormat (dc, &pfd);
  210241. if (format != 0)
  210242. SetPixelFormat (dc, format, &pfd);
  210243. renderContext = wglCreateContext (dc);
  210244. makeActive();
  210245. setPixelFormat (pixelFormat);
  210246. if (contextToShareWith != 0 && renderContext != 0)
  210247. wglShareLists (contextToShareWith, renderContext);
  210248. }
  210249. ~WindowedGLContext()
  210250. {
  210251. deleteContext();
  210252. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210253. nativeWindow = 0;
  210254. }
  210255. void deleteContext()
  210256. {
  210257. makeInactive();
  210258. if (renderContext != 0)
  210259. {
  210260. wglDeleteContext (renderContext);
  210261. renderContext = 0;
  210262. }
  210263. }
  210264. bool makeActive() const throw()
  210265. {
  210266. jassert (renderContext != 0);
  210267. return wglMakeCurrent (dc, renderContext) != 0;
  210268. }
  210269. bool makeInactive() const throw()
  210270. {
  210271. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210272. }
  210273. bool isActive() const throw()
  210274. {
  210275. return wglGetCurrentContext() == renderContext;
  210276. }
  210277. const OpenGLPixelFormat getPixelFormat() const
  210278. {
  210279. OpenGLPixelFormat pf;
  210280. makeActive();
  210281. StringArray availableExtensions;
  210282. getWglExtensions (dc, availableExtensions);
  210283. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210284. return pf;
  210285. }
  210286. void* getRawContext() const throw()
  210287. {
  210288. return renderContext;
  210289. }
  210290. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210291. {
  210292. makeActive();
  210293. PIXELFORMATDESCRIPTOR pfd;
  210294. zerostruct (pfd);
  210295. pfd.nSize = sizeof (pfd);
  210296. pfd.nVersion = 1;
  210297. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210298. pfd.iPixelType = PFD_TYPE_RGBA;
  210299. pfd.iLayerType = PFD_MAIN_PLANE;
  210300. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210301. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210302. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210303. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210304. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210305. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210306. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210307. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210308. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210309. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210310. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210311. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210312. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210313. int format = 0;
  210314. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210315. StringArray availableExtensions;
  210316. getWglExtensions (dc, availableExtensions);
  210317. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210318. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210319. {
  210320. int attributes[64];
  210321. int n = 0;
  210322. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210323. attributes[n++] = GL_TRUE;
  210324. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210325. attributes[n++] = GL_TRUE;
  210326. attributes[n++] = WGL_ACCELERATION_ARB;
  210327. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210328. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210329. attributes[n++] = GL_TRUE;
  210330. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210331. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210332. attributes[n++] = WGL_COLOR_BITS_ARB;
  210333. attributes[n++] = pfd.cColorBits;
  210334. attributes[n++] = WGL_RED_BITS_ARB;
  210335. attributes[n++] = pixelFormat.redBits;
  210336. attributes[n++] = WGL_GREEN_BITS_ARB;
  210337. attributes[n++] = pixelFormat.greenBits;
  210338. attributes[n++] = WGL_BLUE_BITS_ARB;
  210339. attributes[n++] = pixelFormat.blueBits;
  210340. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210341. attributes[n++] = pixelFormat.alphaBits;
  210342. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210343. attributes[n++] = pixelFormat.depthBufferBits;
  210344. if (pixelFormat.stencilBufferBits > 0)
  210345. {
  210346. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210347. attributes[n++] = pixelFormat.stencilBufferBits;
  210348. }
  210349. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210350. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210351. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210352. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210353. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210354. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210355. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210356. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210357. if (availableExtensions.contains ("WGL_ARB_multisample")
  210358. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210359. {
  210360. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210361. attributes[n++] = 1;
  210362. attributes[n++] = WGL_SAMPLES_ARB;
  210363. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210364. }
  210365. attributes[n++] = 0;
  210366. UINT formatsCount;
  210367. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210368. (void) ok;
  210369. jassert (ok);
  210370. }
  210371. else
  210372. {
  210373. format = ChoosePixelFormat (dc, &pfd);
  210374. }
  210375. if (format != 0)
  210376. {
  210377. makeInactive();
  210378. // win32 can't change the pixel format of a window, so need to delete the
  210379. // old one and create a new one..
  210380. jassert (nativeWindow != 0);
  210381. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210382. nativeWindow = 0;
  210383. createNativeWindow();
  210384. if (SetPixelFormat (dc, format, &pfd))
  210385. {
  210386. wglDeleteContext (renderContext);
  210387. renderContext = wglCreateContext (dc);
  210388. jassert (renderContext != 0);
  210389. return renderContext != 0;
  210390. }
  210391. }
  210392. return false;
  210393. }
  210394. void updateWindowPosition (int x, int y, int w, int h, int)
  210395. {
  210396. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210397. x, y, w, h,
  210398. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210399. }
  210400. void repaint()
  210401. {
  210402. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210403. }
  210404. void swapBuffers()
  210405. {
  210406. SwapBuffers (dc);
  210407. }
  210408. bool setSwapInterval (int numFramesPerSwap)
  210409. {
  210410. makeActive();
  210411. StringArray availableExtensions;
  210412. getWglExtensions (dc, availableExtensions);
  210413. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210414. return availableExtensions.contains ("WGL_EXT_swap_control")
  210415. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210416. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210417. }
  210418. int getSwapInterval() const
  210419. {
  210420. makeActive();
  210421. StringArray availableExtensions;
  210422. getWglExtensions (dc, availableExtensions);
  210423. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210424. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210425. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210426. return wglGetSwapIntervalEXT();
  210427. return 0;
  210428. }
  210429. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210430. {
  210431. jassert (isActive());
  210432. StringArray availableExtensions;
  210433. getWglExtensions (dc, availableExtensions);
  210434. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210435. int numTypes = 0;
  210436. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210437. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210438. {
  210439. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210440. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210441. jassertfalse;
  210442. }
  210443. else
  210444. {
  210445. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210446. }
  210447. OpenGLPixelFormat pf;
  210448. for (int i = 0; i < numTypes; ++i)
  210449. {
  210450. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210451. {
  210452. bool alreadyListed = false;
  210453. for (int j = results.size(); --j >= 0;)
  210454. if (pf == *results.getUnchecked(j))
  210455. alreadyListed = true;
  210456. if (! alreadyListed)
  210457. results.add (new OpenGLPixelFormat (pf));
  210458. }
  210459. }
  210460. }
  210461. void* getNativeWindowHandle() const
  210462. {
  210463. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210464. }
  210465. juce_UseDebuggingNewOperator
  210466. HGLRC renderContext;
  210467. private:
  210468. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210469. Component* const component;
  210470. HDC dc;
  210471. void createNativeWindow()
  210472. {
  210473. nativeWindow = new Win32ComponentPeer (component, 0, 0);
  210474. nativeWindow->dontRepaint = true;
  210475. nativeWindow->setVisible (true);
  210476. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  210477. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210478. if (peer != 0)
  210479. {
  210480. SetParent (hwnd, (HWND) peer->getNativeHandle());
  210481. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  210482. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  210483. }
  210484. dc = GetDC (hwnd);
  210485. }
  210486. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210487. OpenGLPixelFormat& result,
  210488. const StringArray& availableExtensions) const throw()
  210489. {
  210490. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210491. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210492. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210493. {
  210494. int attributes[32];
  210495. int numAttributes = 0;
  210496. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210497. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210498. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210499. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210500. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210501. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210502. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210503. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210504. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210505. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210506. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210507. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210508. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210509. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210510. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210511. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210512. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210513. int values[32];
  210514. zeromem (values, sizeof (values));
  210515. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210516. {
  210517. int n = 0;
  210518. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210519. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210520. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210521. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210522. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210523. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210524. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210525. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210526. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210527. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210528. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210529. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210530. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210531. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210532. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210533. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210534. return isValidFormat;
  210535. }
  210536. else
  210537. {
  210538. jassertfalse;
  210539. }
  210540. }
  210541. else
  210542. {
  210543. PIXELFORMATDESCRIPTOR pfd;
  210544. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210545. {
  210546. result.redBits = pfd.cRedBits;
  210547. result.greenBits = pfd.cGreenBits;
  210548. result.blueBits = pfd.cBlueBits;
  210549. result.alphaBits = pfd.cAlphaBits;
  210550. result.depthBufferBits = pfd.cDepthBits;
  210551. result.stencilBufferBits = pfd.cStencilBits;
  210552. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210553. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210554. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210555. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210556. result.fullSceneAntiAliasingNumSamples = 0;
  210557. return true;
  210558. }
  210559. else
  210560. {
  210561. jassertfalse;
  210562. }
  210563. }
  210564. return false;
  210565. }
  210566. WindowedGLContext (const WindowedGLContext&);
  210567. WindowedGLContext& operator= (const WindowedGLContext&);
  210568. };
  210569. OpenGLContext* OpenGLComponent::createContext()
  210570. {
  210571. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210572. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210573. preferredPixelFormat));
  210574. return (c->renderContext != 0) ? c.release() : 0;
  210575. }
  210576. void* OpenGLComponent::getNativeWindowHandle() const
  210577. {
  210578. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210579. }
  210580. void juce_glViewport (const int w, const int h)
  210581. {
  210582. glViewport (0, 0, w, h);
  210583. }
  210584. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210585. OwnedArray <OpenGLPixelFormat>& results)
  210586. {
  210587. Component tempComp;
  210588. {
  210589. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210590. wc.makeActive();
  210591. wc.findAlternativeOpenGLPixelFormats (results);
  210592. }
  210593. }
  210594. #endif
  210595. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210596. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210597. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210598. // compiled on its own).
  210599. #if JUCE_INCLUDED_FILE
  210600. #if JUCE_USE_CDREADER
  210601. namespace CDReaderHelpers
  210602. {
  210603. //***************************************************************************
  210604. // %%% TARGET STATUS VALUES %%%
  210605. //***************************************************************************
  210606. #define STATUS_GOOD 0x00 // Status Good
  210607. #define STATUS_CHKCOND 0x02 // Check Condition
  210608. #define STATUS_CONDMET 0x04 // Condition Met
  210609. #define STATUS_BUSY 0x08 // Busy
  210610. #define STATUS_INTERM 0x10 // Intermediate
  210611. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210612. #define STATUS_RESCONF 0x18 // Reservation conflict
  210613. #define STATUS_COMTERM 0x22 // Command Terminated
  210614. #define STATUS_QFULL 0x28 // Queue full
  210615. //***************************************************************************
  210616. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210617. //***************************************************************************
  210618. #define MAXLUN 7 // Maximum Logical Unit Id
  210619. #define MAXTARG 7 // Maximum Target Id
  210620. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210621. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210622. //***************************************************************************
  210623. // %%% Commands for all Device Types %%%
  210624. //***************************************************************************
  210625. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210626. #define SCSI_COMPARE 0x39 // Compare (O)
  210627. #define SCSI_COPY 0x18 // Copy (O)
  210628. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210629. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210630. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210631. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210632. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210633. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210634. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210635. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210636. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210637. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210638. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210639. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210640. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210641. //***************************************************************************
  210642. // %%% Commands Unique to Direct Access Devices %%%
  210643. //***************************************************************************
  210644. #define SCSI_COMPARE 0x39 // Compare (O)
  210645. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210646. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210647. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210648. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210649. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210650. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210651. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210652. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210653. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210654. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210655. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210656. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210657. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210658. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210659. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210660. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210661. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210662. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210663. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210664. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210665. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210666. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210667. #define SCSI_VERIFY 0x2F // Verify (O)
  210668. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210669. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210670. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210671. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210672. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210673. //***************************************************************************
  210674. // %%% Commands Unique to Sequential Access Devices %%%
  210675. //***************************************************************************
  210676. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210677. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210678. #define SCSI_LOCATE 0x2B // Locate (O)
  210679. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210680. #define SCSI_READ_POS 0x34 // Read Position (O)
  210681. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210682. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210683. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210684. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210685. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210686. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210687. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210688. //***************************************************************************
  210689. // %%% Commands Unique to Printer Devices %%%
  210690. //***************************************************************************
  210691. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210692. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210693. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210694. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210695. //***************************************************************************
  210696. // %%% Commands Unique to Processor Devices %%%
  210697. //***************************************************************************
  210698. #define SCSI_RECEIVE 0x08 // Receive (O)
  210699. #define SCSI_SEND 0x0A // Send (O)
  210700. //***************************************************************************
  210701. // %%% Commands Unique to Write-Once Devices %%%
  210702. //***************************************************************************
  210703. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210704. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210705. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210706. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210707. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210708. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210709. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210710. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210711. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210712. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210713. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210714. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210715. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210716. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210717. //***************************************************************************
  210718. // %%% Commands Unique to CD-ROM Devices %%%
  210719. //***************************************************************************
  210720. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210721. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210722. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210723. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210724. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210725. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210726. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210727. #define SCSI_READHEADER 0x44 // Read Header (O)
  210728. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210729. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210730. //***************************************************************************
  210731. // %%% Commands Unique to Scanner Devices %%%
  210732. //***************************************************************************
  210733. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210734. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210735. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210736. #define SCSI_SCAN 0x1B // Scan (O)
  210737. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210738. //***************************************************************************
  210739. // %%% Commands Unique to Optical Memory Devices %%%
  210740. //***************************************************************************
  210741. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210742. //***************************************************************************
  210743. // %%% Commands Unique to Medium Changer Devices %%%
  210744. //***************************************************************************
  210745. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210746. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210747. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210748. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210749. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210750. //***************************************************************************
  210751. // %%% Commands Unique to Communication Devices %%%
  210752. //***************************************************************************
  210753. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210754. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210755. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210756. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210757. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210758. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210759. //***************************************************************************
  210760. // %%% Request Sense Data Format %%%
  210761. //***************************************************************************
  210762. typedef struct {
  210763. BYTE ErrorCode; // Error Code (70H or 71H)
  210764. BYTE SegmentNum; // Number of current segment descriptor
  210765. BYTE SenseKey; // Sense Key(See bit definitions too)
  210766. BYTE InfoByte0; // Information MSB
  210767. BYTE InfoByte1; // Information MID
  210768. BYTE InfoByte2; // Information MID
  210769. BYTE InfoByte3; // Information LSB
  210770. BYTE AddSenLen; // Additional Sense Length
  210771. BYTE ComSpecInf0; // Command Specific Information MSB
  210772. BYTE ComSpecInf1; // Command Specific Information MID
  210773. BYTE ComSpecInf2; // Command Specific Information MID
  210774. BYTE ComSpecInf3; // Command Specific Information LSB
  210775. BYTE AddSenseCode; // Additional Sense Code
  210776. BYTE AddSenQual; // Additional Sense Code Qualifier
  210777. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210778. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210779. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210780. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210781. BYTE AddSenseBytes; // Additional Sense Bytes
  210782. } SENSE_DATA_FMT;
  210783. //***************************************************************************
  210784. // %%% REQUEST SENSE ERROR CODE %%%
  210785. //***************************************************************************
  210786. #define SERROR_CURRENT 0x70 // Current Errors
  210787. #define SERROR_DEFERED 0x71 // Deferred Errors
  210788. //***************************************************************************
  210789. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210790. //***************************************************************************
  210791. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210792. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210793. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210794. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210795. //***************************************************************************
  210796. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210797. //***************************************************************************
  210798. #define KEY_NOSENSE 0x00 // No Sense
  210799. #define KEY_RECERROR 0x01 // Recovered Error
  210800. #define KEY_NOTREADY 0x02 // Not Ready
  210801. #define KEY_MEDIUMERR 0x03 // Medium Error
  210802. #define KEY_HARDERROR 0x04 // Hardware Error
  210803. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210804. #define KEY_UNITATT 0x06 // Unit Attention
  210805. #define KEY_DATAPROT 0x07 // Data Protect
  210806. #define KEY_BLANKCHK 0x08 // Blank Check
  210807. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210808. #define KEY_COPYABORT 0x0A // Copy Abort
  210809. #define KEY_EQUAL 0x0C // Equal (Search)
  210810. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210811. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210812. #define KEY_RESERVED 0x0F // Reserved
  210813. //***************************************************************************
  210814. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210815. //***************************************************************************
  210816. #define DTYPE_DASD 0x00 // Disk Device
  210817. #define DTYPE_SEQD 0x01 // Tape Device
  210818. #define DTYPE_PRNT 0x02 // Printer
  210819. #define DTYPE_PROC 0x03 // Processor
  210820. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210821. #define DTYPE_CROM 0x05 // CD-ROM device
  210822. #define DTYPE_SCAN 0x06 // Scanner device
  210823. #define DTYPE_OPTI 0x07 // Optical memory device
  210824. #define DTYPE_JUKE 0x08 // Medium Changer device
  210825. #define DTYPE_COMM 0x09 // Communications device
  210826. #define DTYPE_RESL 0x0A // Reserved (low)
  210827. #define DTYPE_RESH 0x1E // Reserved (high)
  210828. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210829. //***************************************************************************
  210830. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210831. //***************************************************************************
  210832. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210833. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210834. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210835. #define ANSI_RESLO 0x3 // Reserved (low)
  210836. #define ANSI_RESHI 0x7 // Reserved (high)
  210837. typedef struct
  210838. {
  210839. USHORT Length;
  210840. UCHAR ScsiStatus;
  210841. UCHAR PathId;
  210842. UCHAR TargetId;
  210843. UCHAR Lun;
  210844. UCHAR CdbLength;
  210845. UCHAR SenseInfoLength;
  210846. UCHAR DataIn;
  210847. ULONG DataTransferLength;
  210848. ULONG TimeOutValue;
  210849. ULONG DataBufferOffset;
  210850. ULONG SenseInfoOffset;
  210851. UCHAR Cdb[16];
  210852. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210853. typedef struct
  210854. {
  210855. USHORT Length;
  210856. UCHAR ScsiStatus;
  210857. UCHAR PathId;
  210858. UCHAR TargetId;
  210859. UCHAR Lun;
  210860. UCHAR CdbLength;
  210861. UCHAR SenseInfoLength;
  210862. UCHAR DataIn;
  210863. ULONG DataTransferLength;
  210864. ULONG TimeOutValue;
  210865. PVOID DataBuffer;
  210866. ULONG SenseInfoOffset;
  210867. UCHAR Cdb[16];
  210868. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210869. typedef struct
  210870. {
  210871. SCSI_PASS_THROUGH_DIRECT spt;
  210872. ULONG Filler;
  210873. UCHAR ucSenseBuf[32];
  210874. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210875. typedef struct
  210876. {
  210877. ULONG Length;
  210878. UCHAR PortNumber;
  210879. UCHAR PathId;
  210880. UCHAR TargetId;
  210881. UCHAR Lun;
  210882. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210883. #define METHOD_BUFFERED 0
  210884. #define METHOD_IN_DIRECT 1
  210885. #define METHOD_OUT_DIRECT 2
  210886. #define METHOD_NEITHER 3
  210887. #define FILE_ANY_ACCESS 0
  210888. #ifndef FILE_READ_ACCESS
  210889. #define FILE_READ_ACCESS (0x0001)
  210890. #endif
  210891. #ifndef FILE_WRITE_ACCESS
  210892. #define FILE_WRITE_ACCESS (0x0002)
  210893. #endif
  210894. #define IOCTL_SCSI_BASE 0x00000004
  210895. #define SCSI_IOCTL_DATA_OUT 0
  210896. #define SCSI_IOCTL_DATA_IN 1
  210897. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210898. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210899. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210900. )
  210901. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210902. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210903. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210904. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210905. #define SENSE_LEN 14
  210906. #define SRB_DIR_SCSI 0x00
  210907. #define SRB_POSTING 0x01
  210908. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210909. #define SRB_DIR_IN 0x08
  210910. #define SRB_DIR_OUT 0x10
  210911. #define SRB_EVENT_NOTIFY 0x40
  210912. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210913. #define MAX_SRB_TIMEOUT 1080001u
  210914. #define DEFAULT_SRB_TIMEOUT 1080001u
  210915. #define SC_HA_INQUIRY 0x00
  210916. #define SC_GET_DEV_TYPE 0x01
  210917. #define SC_EXEC_SCSI_CMD 0x02
  210918. #define SC_ABORT_SRB 0x03
  210919. #define SC_RESET_DEV 0x04
  210920. #define SC_SET_HA_PARMS 0x05
  210921. #define SC_GET_DISK_INFO 0x06
  210922. #define SC_RESCAN_SCSI_BUS 0x07
  210923. #define SC_GETSET_TIMEOUTS 0x08
  210924. #define SS_PENDING 0x00
  210925. #define SS_COMP 0x01
  210926. #define SS_ABORTED 0x02
  210927. #define SS_ABORT_FAIL 0x03
  210928. #define SS_ERR 0x04
  210929. #define SS_INVALID_CMD 0x80
  210930. #define SS_INVALID_HA 0x81
  210931. #define SS_NO_DEVICE 0x82
  210932. #define SS_INVALID_SRB 0xE0
  210933. #define SS_OLD_MANAGER 0xE1
  210934. #define SS_BUFFER_ALIGN 0xE1
  210935. #define SS_ILLEGAL_MODE 0xE2
  210936. #define SS_NO_ASPI 0xE3
  210937. #define SS_FAILED_INIT 0xE4
  210938. #define SS_ASPI_IS_BUSY 0xE5
  210939. #define SS_BUFFER_TO_BIG 0xE6
  210940. #define SS_BUFFER_TOO_BIG 0xE6
  210941. #define SS_MISMATCHED_COMPONENTS 0xE7
  210942. #define SS_NO_ADAPTERS 0xE8
  210943. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210944. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210945. #define SS_BAD_INSTALL 0xEB
  210946. #define HASTAT_OK 0x00
  210947. #define HASTAT_SEL_TO 0x11
  210948. #define HASTAT_DO_DU 0x12
  210949. #define HASTAT_BUS_FREE 0x13
  210950. #define HASTAT_PHASE_ERR 0x14
  210951. #define HASTAT_TIMEOUT 0x09
  210952. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210953. #define HASTAT_MESSAGE_REJECT 0x0D
  210954. #define HASTAT_BUS_RESET 0x0E
  210955. #define HASTAT_PARITY_ERROR 0x0F
  210956. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210957. #define PACKED
  210958. #pragma pack(1)
  210959. typedef struct
  210960. {
  210961. BYTE SRB_Cmd;
  210962. BYTE SRB_Status;
  210963. BYTE SRB_HaID;
  210964. BYTE SRB_Flags;
  210965. DWORD SRB_Hdr_Rsvd;
  210966. BYTE HA_Count;
  210967. BYTE HA_SCSI_ID;
  210968. BYTE HA_ManagerId[16];
  210969. BYTE HA_Identifier[16];
  210970. BYTE HA_Unique[16];
  210971. WORD HA_Rsvd1;
  210972. BYTE pad[20];
  210973. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210974. typedef struct
  210975. {
  210976. BYTE SRB_Cmd;
  210977. BYTE SRB_Status;
  210978. BYTE SRB_HaID;
  210979. BYTE SRB_Flags;
  210980. DWORD SRB_Hdr_Rsvd;
  210981. BYTE SRB_Target;
  210982. BYTE SRB_Lun;
  210983. BYTE SRB_DeviceType;
  210984. BYTE SRB_Rsvd1;
  210985. BYTE pad[68];
  210986. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210987. typedef struct
  210988. {
  210989. BYTE SRB_Cmd;
  210990. BYTE SRB_Status;
  210991. BYTE SRB_HaID;
  210992. BYTE SRB_Flags;
  210993. DWORD SRB_Hdr_Rsvd;
  210994. BYTE SRB_Target;
  210995. BYTE SRB_Lun;
  210996. WORD SRB_Rsvd1;
  210997. DWORD SRB_BufLen;
  210998. BYTE FAR *SRB_BufPointer;
  210999. BYTE SRB_SenseLen;
  211000. BYTE SRB_CDBLen;
  211001. BYTE SRB_HaStat;
  211002. BYTE SRB_TargStat;
  211003. VOID FAR *SRB_PostProc;
  211004. BYTE SRB_Rsvd2[20];
  211005. BYTE CDBByte[16];
  211006. BYTE SenseArea[SENSE_LEN+2];
  211007. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  211008. typedef struct
  211009. {
  211010. BYTE SRB_Cmd;
  211011. BYTE SRB_Status;
  211012. BYTE SRB_HaId;
  211013. BYTE SRB_Flags;
  211014. DWORD SRB_Hdr_Rsvd;
  211015. } PACKED SRB, *PSRB, FAR *LPSRB;
  211016. #pragma pack()
  211017. struct CDDeviceInfo
  211018. {
  211019. char vendor[9];
  211020. char productId[17];
  211021. char rev[5];
  211022. char vendorSpec[21];
  211023. BYTE ha;
  211024. BYTE tgt;
  211025. BYTE lun;
  211026. char scsiDriveLetter; // will be 0 if not using scsi
  211027. };
  211028. class CDReadBuffer
  211029. {
  211030. public:
  211031. int startFrame;
  211032. int numFrames;
  211033. int dataStartOffset;
  211034. int dataLength;
  211035. int bufferSize;
  211036. HeapBlock<BYTE> buffer;
  211037. int index;
  211038. bool wantsIndex;
  211039. CDReadBuffer (const int numberOfFrames)
  211040. : startFrame (0),
  211041. numFrames (0),
  211042. dataStartOffset (0),
  211043. dataLength (0),
  211044. bufferSize (2352 * numberOfFrames),
  211045. buffer (bufferSize),
  211046. index (0),
  211047. wantsIndex (false)
  211048. {
  211049. }
  211050. bool isZero() const throw()
  211051. {
  211052. BYTE* p = buffer + dataStartOffset;
  211053. for (int i = dataLength; --i >= 0;)
  211054. if (*p++ != 0)
  211055. return false;
  211056. return true;
  211057. }
  211058. };
  211059. class CDDeviceHandle;
  211060. class CDController
  211061. {
  211062. public:
  211063. CDController();
  211064. virtual ~CDController();
  211065. virtual bool read (CDReadBuffer* t) = 0;
  211066. virtual void shutDown();
  211067. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  211068. int getLastIndex();
  211069. public:
  211070. bool initialised;
  211071. CDDeviceHandle* deviceInfo;
  211072. int framesToCheck, framesOverlap;
  211073. void prepare (SRB_ExecSCSICmd& s);
  211074. void perform (SRB_ExecSCSICmd& s);
  211075. void setPaused (bool paused);
  211076. };
  211077. #pragma pack(1)
  211078. struct TOCTRACK
  211079. {
  211080. BYTE rsvd;
  211081. BYTE ADR;
  211082. BYTE trackNumber;
  211083. BYTE rsvd2;
  211084. BYTE addr[4];
  211085. };
  211086. struct TOC
  211087. {
  211088. WORD tocLen;
  211089. BYTE firstTrack;
  211090. BYTE lastTrack;
  211091. TOCTRACK tracks[100];
  211092. };
  211093. #pragma pack()
  211094. enum
  211095. {
  211096. READTYPE_ANY = 0,
  211097. READTYPE_ATAPI1 = 1,
  211098. READTYPE_ATAPI2 = 2,
  211099. READTYPE_READ6 = 3,
  211100. READTYPE_READ10 = 4,
  211101. READTYPE_READ_D8 = 5,
  211102. READTYPE_READ_D4 = 6,
  211103. READTYPE_READ_D4_1 = 7,
  211104. READTYPE_READ10_2 = 8
  211105. };
  211106. class CDDeviceHandle
  211107. {
  211108. public:
  211109. CDDeviceHandle (const CDDeviceInfo* const device)
  211110. : scsiHandle (0),
  211111. readType (READTYPE_ANY),
  211112. controller (0)
  211113. {
  211114. memcpy (&info, device, sizeof (info));
  211115. }
  211116. ~CDDeviceHandle()
  211117. {
  211118. if (controller != 0)
  211119. {
  211120. controller->shutDown();
  211121. controller = 0;
  211122. }
  211123. if (scsiHandle != 0)
  211124. CloseHandle (scsiHandle);
  211125. }
  211126. bool readTOC (TOC* lpToc);
  211127. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  211128. void openDrawer (bool shouldBeOpen);
  211129. CDDeviceInfo info;
  211130. HANDLE scsiHandle;
  211131. BYTE readType;
  211132. private:
  211133. ScopedPointer<CDController> controller;
  211134. bool testController (const int readType,
  211135. CDController* const newController,
  211136. CDReadBuffer* const bufferToUse);
  211137. };
  211138. DWORD (*fGetASPI32SupportInfo)(void);
  211139. DWORD (*fSendASPI32Command)(LPSRB);
  211140. static HINSTANCE winAspiLib = 0;
  211141. static bool usingScsi = false;
  211142. static bool initialised = false;
  211143. static bool InitialiseCDRipper()
  211144. {
  211145. if (! initialised)
  211146. {
  211147. initialised = true;
  211148. OSVERSIONINFO info;
  211149. info.dwOSVersionInfoSize = sizeof (info);
  211150. GetVersionEx (&info);
  211151. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  211152. if (! usingScsi)
  211153. {
  211154. fGetASPI32SupportInfo = 0;
  211155. fSendASPI32Command = 0;
  211156. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  211157. if (winAspiLib != 0)
  211158. {
  211159. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  211160. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  211161. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  211162. return false;
  211163. }
  211164. else
  211165. {
  211166. usingScsi = true;
  211167. }
  211168. }
  211169. }
  211170. return true;
  211171. }
  211172. static void DeinitialiseCDRipper()
  211173. {
  211174. if (winAspiLib != 0)
  211175. {
  211176. fGetASPI32SupportInfo = 0;
  211177. fSendASPI32Command = 0;
  211178. FreeLibrary (winAspiLib);
  211179. winAspiLib = 0;
  211180. }
  211181. initialised = false;
  211182. }
  211183. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  211184. {
  211185. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  211186. OSVERSIONINFO info;
  211187. info.dwOSVersionInfoSize = sizeof (info);
  211188. GetVersionEx (&info);
  211189. DWORD flags = GENERIC_READ;
  211190. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  211191. flags = GENERIC_READ | GENERIC_WRITE;
  211192. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211193. if (h == INVALID_HANDLE_VALUE)
  211194. {
  211195. flags ^= GENERIC_WRITE;
  211196. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211197. }
  211198. return h;
  211199. }
  211200. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  211201. const char driveLetter,
  211202. HANDLE& deviceHandle,
  211203. const bool retryOnFailure = true)
  211204. {
  211205. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  211206. zerostruct (s);
  211207. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  211208. s.spt.CdbLength = srb->SRB_CDBLen;
  211209. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  211210. ? SCSI_IOCTL_DATA_IN
  211211. : ((srb->SRB_Flags & SRB_DIR_OUT)
  211212. ? SCSI_IOCTL_DATA_OUT
  211213. : SCSI_IOCTL_DATA_UNSPECIFIED));
  211214. s.spt.DataTransferLength = srb->SRB_BufLen;
  211215. s.spt.TimeOutValue = 5;
  211216. s.spt.DataBuffer = srb->SRB_BufPointer;
  211217. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211218. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211219. srb->SRB_Status = SS_ERR;
  211220. srb->SRB_TargStat = 0x0004;
  211221. DWORD bytesReturned = 0;
  211222. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211223. &s, sizeof (s),
  211224. &s, sizeof (s),
  211225. &bytesReturned, 0) != 0)
  211226. {
  211227. srb->SRB_Status = SS_COMP;
  211228. }
  211229. else if (retryOnFailure)
  211230. {
  211231. const DWORD error = GetLastError();
  211232. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211233. {
  211234. if (error != ERROR_INVALID_HANDLE)
  211235. CloseHandle (deviceHandle);
  211236. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211237. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211238. }
  211239. }
  211240. return srb->SRB_Status;
  211241. }
  211242. // Controller types..
  211243. class ControllerType1 : public CDController
  211244. {
  211245. public:
  211246. ControllerType1() {}
  211247. ~ControllerType1() {}
  211248. bool read (CDReadBuffer* rb)
  211249. {
  211250. if (rb->numFrames * 2352 > rb->bufferSize)
  211251. return false;
  211252. SRB_ExecSCSICmd s;
  211253. prepare (s);
  211254. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211255. s.SRB_BufLen = rb->bufferSize;
  211256. s.SRB_BufPointer = rb->buffer;
  211257. s.SRB_CDBLen = 12;
  211258. s.CDBByte[0] = 0xBE;
  211259. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211260. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211261. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211262. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211263. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211264. perform (s);
  211265. if (s.SRB_Status != SS_COMP)
  211266. return false;
  211267. rb->dataLength = rb->numFrames * 2352;
  211268. rb->dataStartOffset = 0;
  211269. return true;
  211270. }
  211271. };
  211272. class ControllerType2 : public CDController
  211273. {
  211274. public:
  211275. ControllerType2() {}
  211276. ~ControllerType2() {}
  211277. void shutDown()
  211278. {
  211279. if (initialised)
  211280. {
  211281. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211282. SRB_ExecSCSICmd s;
  211283. prepare (s);
  211284. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211285. s.SRB_BufLen = 0x0C;
  211286. s.SRB_BufPointer = bufPointer;
  211287. s.SRB_CDBLen = 6;
  211288. s.CDBByte[0] = 0x15;
  211289. s.CDBByte[4] = 0x0C;
  211290. perform (s);
  211291. }
  211292. }
  211293. bool init()
  211294. {
  211295. SRB_ExecSCSICmd s;
  211296. s.SRB_Status = SS_ERR;
  211297. if (deviceInfo->readType == READTYPE_READ10_2)
  211298. {
  211299. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211300. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211301. for (int i = 0; i < 2; ++i)
  211302. {
  211303. prepare (s);
  211304. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211305. s.SRB_BufLen = 0x14;
  211306. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211307. s.SRB_CDBLen = 6;
  211308. s.CDBByte[0] = 0x15;
  211309. s.CDBByte[1] = 0x10;
  211310. s.CDBByte[4] = 0x14;
  211311. perform (s);
  211312. if (s.SRB_Status != SS_COMP)
  211313. return false;
  211314. }
  211315. }
  211316. else
  211317. {
  211318. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211319. prepare (s);
  211320. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211321. s.SRB_BufLen = 0x0C;
  211322. s.SRB_BufPointer = bufPointer;
  211323. s.SRB_CDBLen = 6;
  211324. s.CDBByte[0] = 0x15;
  211325. s.CDBByte[4] = 0x0C;
  211326. perform (s);
  211327. }
  211328. return s.SRB_Status == SS_COMP;
  211329. }
  211330. bool read (CDReadBuffer* rb)
  211331. {
  211332. if (rb->numFrames * 2352 > rb->bufferSize)
  211333. return false;
  211334. if (!initialised)
  211335. {
  211336. initialised = init();
  211337. if (!initialised)
  211338. return false;
  211339. }
  211340. SRB_ExecSCSICmd s;
  211341. prepare (s);
  211342. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211343. s.SRB_BufLen = rb->bufferSize;
  211344. s.SRB_BufPointer = rb->buffer;
  211345. s.SRB_CDBLen = 10;
  211346. s.CDBByte[0] = 0x28;
  211347. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211348. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211349. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211350. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211351. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211352. perform (s);
  211353. if (s.SRB_Status != SS_COMP)
  211354. return false;
  211355. rb->dataLength = rb->numFrames * 2352;
  211356. rb->dataStartOffset = 0;
  211357. return true;
  211358. }
  211359. };
  211360. class ControllerType3 : public CDController
  211361. {
  211362. public:
  211363. ControllerType3() {}
  211364. ~ControllerType3() {}
  211365. bool read (CDReadBuffer* rb)
  211366. {
  211367. if (rb->numFrames * 2352 > rb->bufferSize)
  211368. return false;
  211369. if (!initialised)
  211370. {
  211371. setPaused (false);
  211372. initialised = true;
  211373. }
  211374. SRB_ExecSCSICmd s;
  211375. prepare (s);
  211376. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211377. s.SRB_BufLen = rb->numFrames * 2352;
  211378. s.SRB_BufPointer = rb->buffer;
  211379. s.SRB_CDBLen = 12;
  211380. s.CDBByte[0] = 0xD8;
  211381. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211382. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211383. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211384. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211385. perform (s);
  211386. if (s.SRB_Status != SS_COMP)
  211387. return false;
  211388. rb->dataLength = rb->numFrames * 2352;
  211389. rb->dataStartOffset = 0;
  211390. return true;
  211391. }
  211392. };
  211393. class ControllerType4 : public CDController
  211394. {
  211395. public:
  211396. ControllerType4() {}
  211397. ~ControllerType4() {}
  211398. bool selectD4Mode()
  211399. {
  211400. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211401. SRB_ExecSCSICmd s;
  211402. prepare (s);
  211403. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211404. s.SRB_CDBLen = 6;
  211405. s.SRB_BufLen = 12;
  211406. s.SRB_BufPointer = bufPointer;
  211407. s.CDBByte[0] = 0x15;
  211408. s.CDBByte[1] = 0x10;
  211409. s.CDBByte[4] = 0x08;
  211410. perform (s);
  211411. return s.SRB_Status == SS_COMP;
  211412. }
  211413. bool read (CDReadBuffer* rb)
  211414. {
  211415. if (rb->numFrames * 2352 > rb->bufferSize)
  211416. return false;
  211417. if (!initialised)
  211418. {
  211419. setPaused (true);
  211420. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211421. selectD4Mode();
  211422. initialised = true;
  211423. }
  211424. SRB_ExecSCSICmd s;
  211425. prepare (s);
  211426. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211427. s.SRB_BufLen = rb->bufferSize;
  211428. s.SRB_BufPointer = rb->buffer;
  211429. s.SRB_CDBLen = 10;
  211430. s.CDBByte[0] = 0xD4;
  211431. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211432. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211433. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211434. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211435. perform (s);
  211436. if (s.SRB_Status != SS_COMP)
  211437. return false;
  211438. rb->dataLength = rb->numFrames * 2352;
  211439. rb->dataStartOffset = 0;
  211440. return true;
  211441. }
  211442. };
  211443. CDController::CDController() : initialised (false)
  211444. {
  211445. }
  211446. CDController::~CDController()
  211447. {
  211448. }
  211449. void CDController::prepare (SRB_ExecSCSICmd& s)
  211450. {
  211451. zerostruct (s);
  211452. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211453. s.SRB_HaID = deviceInfo->info.ha;
  211454. s.SRB_Target = deviceInfo->info.tgt;
  211455. s.SRB_Lun = deviceInfo->info.lun;
  211456. s.SRB_SenseLen = SENSE_LEN;
  211457. }
  211458. void CDController::perform (SRB_ExecSCSICmd& s)
  211459. {
  211460. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211461. s.SRB_PostProc = event;
  211462. ResetEvent (event);
  211463. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211464. deviceInfo->info.scsiDriveLetter,
  211465. deviceInfo->scsiHandle)
  211466. : fSendASPI32Command ((LPSRB)&s);
  211467. if (status == SS_PENDING)
  211468. WaitForSingleObject (event, 4000);
  211469. CloseHandle (event);
  211470. }
  211471. void CDController::setPaused (bool paused)
  211472. {
  211473. SRB_ExecSCSICmd s;
  211474. prepare (s);
  211475. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211476. s.SRB_CDBLen = 10;
  211477. s.CDBByte[0] = 0x4B;
  211478. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211479. perform (s);
  211480. }
  211481. void CDController::shutDown()
  211482. {
  211483. }
  211484. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211485. {
  211486. if (overlapBuffer != 0)
  211487. {
  211488. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211489. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211490. if (doJitter
  211491. && overlapBuffer->startFrame > 0
  211492. && overlapBuffer->numFrames > 0
  211493. && overlapBuffer->dataLength > 0)
  211494. {
  211495. const int numFrames = rb->numFrames;
  211496. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211497. {
  211498. rb->startFrame -= framesOverlap;
  211499. if (framesToCheck < framesOverlap
  211500. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211501. rb->numFrames += framesOverlap;
  211502. }
  211503. else
  211504. {
  211505. overlapBuffer->dataLength = 0;
  211506. overlapBuffer->startFrame = 0;
  211507. overlapBuffer->numFrames = 0;
  211508. }
  211509. }
  211510. if (! read (rb))
  211511. return false;
  211512. if (doJitter)
  211513. {
  211514. const int checkLen = framesToCheck * 2352;
  211515. const int maxToCheck = rb->dataLength - checkLen;
  211516. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211517. return true;
  211518. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211519. bool found = false;
  211520. for (int i = 0; i < maxToCheck; ++i)
  211521. {
  211522. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211523. {
  211524. i += checkLen;
  211525. rb->dataStartOffset = i;
  211526. rb->dataLength -= i;
  211527. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211528. found = true;
  211529. break;
  211530. }
  211531. }
  211532. rb->numFrames = rb->dataLength / 2352;
  211533. rb->dataLength = 2352 * rb->numFrames;
  211534. if (!found)
  211535. return false;
  211536. }
  211537. if (canDoJitter)
  211538. {
  211539. memcpy (overlapBuffer->buffer,
  211540. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211541. 2352 * framesToCheck);
  211542. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211543. overlapBuffer->numFrames = framesToCheck;
  211544. overlapBuffer->dataLength = 2352 * framesToCheck;
  211545. overlapBuffer->dataStartOffset = 0;
  211546. }
  211547. else
  211548. {
  211549. overlapBuffer->startFrame = 0;
  211550. overlapBuffer->numFrames = 0;
  211551. overlapBuffer->dataLength = 0;
  211552. }
  211553. return true;
  211554. }
  211555. else
  211556. {
  211557. return read (rb);
  211558. }
  211559. }
  211560. int CDController::getLastIndex()
  211561. {
  211562. char qdata[100];
  211563. SRB_ExecSCSICmd s;
  211564. prepare (s);
  211565. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211566. s.SRB_BufLen = sizeof (qdata);
  211567. s.SRB_BufPointer = (BYTE*)qdata;
  211568. s.SRB_CDBLen = 12;
  211569. s.CDBByte[0] = 0x42;
  211570. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211571. s.CDBByte[2] = 64;
  211572. s.CDBByte[3] = 1; // get current position
  211573. s.CDBByte[7] = 0;
  211574. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211575. perform (s);
  211576. if (s.SRB_Status == SS_COMP)
  211577. return qdata[7];
  211578. return 0;
  211579. }
  211580. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211581. {
  211582. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211583. SRB_ExecSCSICmd s;
  211584. zerostruct (s);
  211585. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211586. s.SRB_HaID = info.ha;
  211587. s.SRB_Target = info.tgt;
  211588. s.SRB_Lun = info.lun;
  211589. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211590. s.SRB_BufLen = 0x324;
  211591. s.SRB_BufPointer = (BYTE*)lpToc;
  211592. s.SRB_SenseLen = 0x0E;
  211593. s.SRB_CDBLen = 0x0A;
  211594. s.SRB_PostProc = event;
  211595. s.CDBByte[0] = 0x43;
  211596. s.CDBByte[1] = 0x00;
  211597. s.CDBByte[7] = 0x03;
  211598. s.CDBByte[8] = 0x24;
  211599. ResetEvent (event);
  211600. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211601. : fSendASPI32Command ((LPSRB)&s);
  211602. if (status == SS_PENDING)
  211603. WaitForSingleObject (event, 4000);
  211604. CloseHandle (event);
  211605. return (s.SRB_Status == SS_COMP);
  211606. }
  211607. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211608. CDReadBuffer* const overlapBuffer)
  211609. {
  211610. if (controller == 0)
  211611. {
  211612. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211613. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211614. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211615. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211616. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211617. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211618. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211619. }
  211620. buffer->index = 0;
  211621. if ((controller != 0)
  211622. && controller->readAudio (buffer, overlapBuffer))
  211623. {
  211624. if (buffer->wantsIndex)
  211625. buffer->index = controller->getLastIndex();
  211626. return true;
  211627. }
  211628. return false;
  211629. }
  211630. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211631. {
  211632. if (shouldBeOpen)
  211633. {
  211634. if (controller != 0)
  211635. {
  211636. controller->shutDown();
  211637. controller = 0;
  211638. }
  211639. if (scsiHandle != 0)
  211640. {
  211641. CloseHandle (scsiHandle);
  211642. scsiHandle = 0;
  211643. }
  211644. }
  211645. SRB_ExecSCSICmd s;
  211646. zerostruct (s);
  211647. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211648. s.SRB_HaID = info.ha;
  211649. s.SRB_Target = info.tgt;
  211650. s.SRB_Lun = info.lun;
  211651. s.SRB_SenseLen = SENSE_LEN;
  211652. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211653. s.SRB_BufLen = 0;
  211654. s.SRB_BufPointer = 0;
  211655. s.SRB_CDBLen = 12;
  211656. s.CDBByte[0] = 0x1b;
  211657. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211658. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211659. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211660. s.SRB_PostProc = event;
  211661. ResetEvent (event);
  211662. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211663. : fSendASPI32Command ((LPSRB)&s);
  211664. if (status == SS_PENDING)
  211665. WaitForSingleObject (event, 4000);
  211666. CloseHandle (event);
  211667. }
  211668. bool CDDeviceHandle::testController (const int type,
  211669. CDController* const newController,
  211670. CDReadBuffer* const rb)
  211671. {
  211672. controller = newController;
  211673. readType = (BYTE)type;
  211674. controller->deviceInfo = this;
  211675. controller->framesToCheck = 1;
  211676. controller->framesOverlap = 3;
  211677. bool passed = false;
  211678. memset (rb->buffer, 0xcd, rb->bufferSize);
  211679. if (controller->read (rb))
  211680. {
  211681. passed = true;
  211682. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211683. int wrong = 0;
  211684. for (int i = rb->dataLength / 4; --i >= 0;)
  211685. {
  211686. if (*p++ == (int) 0xcdcdcdcd)
  211687. {
  211688. if (++wrong == 4)
  211689. {
  211690. passed = false;
  211691. break;
  211692. }
  211693. }
  211694. else
  211695. {
  211696. wrong = 0;
  211697. }
  211698. }
  211699. }
  211700. if (! passed)
  211701. {
  211702. controller->shutDown();
  211703. controller = 0;
  211704. }
  211705. return passed;
  211706. }
  211707. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211708. {
  211709. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211710. const int bufSize = 128;
  211711. BYTE buffer[bufSize];
  211712. zeromem (buffer, bufSize);
  211713. SRB_ExecSCSICmd s;
  211714. zerostruct (s);
  211715. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211716. s.SRB_HaID = ha;
  211717. s.SRB_Target = tgt;
  211718. s.SRB_Lun = lun;
  211719. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211720. s.SRB_BufLen = bufSize;
  211721. s.SRB_BufPointer = buffer;
  211722. s.SRB_SenseLen = SENSE_LEN;
  211723. s.SRB_CDBLen = 6;
  211724. s.SRB_PostProc = event;
  211725. s.CDBByte[0] = SCSI_INQUIRY;
  211726. s.CDBByte[4] = 100;
  211727. ResetEvent (event);
  211728. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211729. WaitForSingleObject (event, 4000);
  211730. CloseHandle (event);
  211731. if (s.SRB_Status == SS_COMP)
  211732. {
  211733. memcpy (dev->vendor, &buffer[8], 8);
  211734. memcpy (dev->productId, &buffer[16], 16);
  211735. memcpy (dev->rev, &buffer[32], 4);
  211736. memcpy (dev->vendorSpec, &buffer[36], 20);
  211737. }
  211738. }
  211739. static int FindCDDevices (CDDeviceInfo* const list,
  211740. int maxItems)
  211741. {
  211742. int count = 0;
  211743. if (usingScsi)
  211744. {
  211745. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211746. {
  211747. TCHAR drivePath[8];
  211748. drivePath[0] = driveLetter;
  211749. drivePath[1] = ':';
  211750. drivePath[2] = '\\';
  211751. drivePath[3] = 0;
  211752. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211753. {
  211754. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211755. if (h != INVALID_HANDLE_VALUE)
  211756. {
  211757. BYTE buffer[100], passThroughStruct[1024];
  211758. zeromem (buffer, sizeof (buffer));
  211759. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211760. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211761. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211762. p->spt.CdbLength = 6;
  211763. p->spt.SenseInfoLength = 24;
  211764. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211765. p->spt.DataTransferLength = 100;
  211766. p->spt.TimeOutValue = 2;
  211767. p->spt.DataBuffer = buffer;
  211768. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211769. p->spt.Cdb[0] = 0x12;
  211770. p->spt.Cdb[4] = 100;
  211771. DWORD bytesReturned = 0;
  211772. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211773. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211774. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211775. &bytesReturned, 0) != 0)
  211776. {
  211777. zeromem (&list[count], sizeof (CDDeviceInfo));
  211778. list[count].scsiDriveLetter = driveLetter;
  211779. memcpy (list[count].vendor, &buffer[8], 8);
  211780. memcpy (list[count].productId, &buffer[16], 16);
  211781. memcpy (list[count].rev, &buffer[32], 4);
  211782. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211783. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211784. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211785. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211786. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211787. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211788. &bytesReturned, 0) != 0)
  211789. {
  211790. list[count].ha = scsiAddr->PortNumber;
  211791. list[count].tgt = scsiAddr->TargetId;
  211792. list[count].lun = scsiAddr->Lun;
  211793. ++count;
  211794. }
  211795. }
  211796. CloseHandle (h);
  211797. }
  211798. }
  211799. }
  211800. }
  211801. else
  211802. {
  211803. const DWORD d = fGetASPI32SupportInfo();
  211804. BYTE status = HIBYTE (LOWORD (d));
  211805. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211806. return 0;
  211807. const int numAdapters = LOBYTE (LOWORD (d));
  211808. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211809. {
  211810. SRB_HAInquiry s;
  211811. zerostruct (s);
  211812. s.SRB_Cmd = SC_HA_INQUIRY;
  211813. s.SRB_HaID = ha;
  211814. fSendASPI32Command ((LPSRB)&s);
  211815. if (s.SRB_Status == SS_COMP)
  211816. {
  211817. maxItems = (int)s.HA_Unique[3];
  211818. if (maxItems == 0)
  211819. maxItems = 8;
  211820. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211821. {
  211822. for (BYTE lun = 0; lun < 8; ++lun)
  211823. {
  211824. SRB_GDEVBlock sb;
  211825. zerostruct (sb);
  211826. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211827. sb.SRB_HaID = ha;
  211828. sb.SRB_Target = tgt;
  211829. sb.SRB_Lun = lun;
  211830. fSendASPI32Command ((LPSRB) &sb);
  211831. if (sb.SRB_Status == SS_COMP
  211832. && sb.SRB_DeviceType == DTYPE_CROM)
  211833. {
  211834. zeromem (&list[count], sizeof (CDDeviceInfo));
  211835. list[count].ha = ha;
  211836. list[count].tgt = tgt;
  211837. list[count].lun = lun;
  211838. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211839. ++count;
  211840. }
  211841. }
  211842. }
  211843. }
  211844. }
  211845. }
  211846. return count;
  211847. }
  211848. static int ripperUsers = 0;
  211849. static bool initialisedOk = false;
  211850. class DeinitialiseTimer : private Timer,
  211851. private DeletedAtShutdown
  211852. {
  211853. DeinitialiseTimer (const DeinitialiseTimer&);
  211854. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211855. public:
  211856. DeinitialiseTimer()
  211857. {
  211858. startTimer (4000);
  211859. }
  211860. ~DeinitialiseTimer()
  211861. {
  211862. if (--ripperUsers == 0)
  211863. DeinitialiseCDRipper();
  211864. }
  211865. void timerCallback()
  211866. {
  211867. delete this;
  211868. }
  211869. juce_UseDebuggingNewOperator
  211870. };
  211871. static void incUserCount()
  211872. {
  211873. if (ripperUsers++ == 0)
  211874. initialisedOk = InitialiseCDRipper();
  211875. }
  211876. static void decUserCount()
  211877. {
  211878. new DeinitialiseTimer();
  211879. }
  211880. struct CDDeviceWrapper
  211881. {
  211882. ScopedPointer<CDDeviceHandle> cdH;
  211883. ScopedPointer<CDReadBuffer> overlapBuffer;
  211884. bool jitter;
  211885. };
  211886. static int getAddressOf (const TOCTRACK* const t)
  211887. {
  211888. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211889. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211890. }
  211891. static const int samplesPerFrame = 44100 / 75;
  211892. static const int bytesPerFrame = samplesPerFrame * 4;
  211893. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211894. {
  211895. SRB_GDEVBlock s;
  211896. zerostruct (s);
  211897. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211898. s.SRB_HaID = device->ha;
  211899. s.SRB_Target = device->tgt;
  211900. s.SRB_Lun = device->lun;
  211901. if (usingScsi)
  211902. {
  211903. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211904. if (h != INVALID_HANDLE_VALUE)
  211905. {
  211906. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211907. cdh->scsiHandle = h;
  211908. return cdh;
  211909. }
  211910. }
  211911. else
  211912. {
  211913. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211914. && s.SRB_DeviceType == DTYPE_CROM)
  211915. {
  211916. return new CDDeviceHandle (device);
  211917. }
  211918. }
  211919. return 0;
  211920. }
  211921. }
  211922. const StringArray AudioCDReader::getAvailableCDNames()
  211923. {
  211924. using namespace CDReaderHelpers;
  211925. StringArray results;
  211926. incUserCount();
  211927. if (initialisedOk)
  211928. {
  211929. CDDeviceInfo list[8];
  211930. const int num = FindCDDevices (list, 8);
  211931. decUserCount();
  211932. for (int i = 0; i < num; ++i)
  211933. {
  211934. String s;
  211935. if (list[i].scsiDriveLetter > 0)
  211936. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211937. s << String (list[i].vendor).trim()
  211938. << ' ' << String (list[i].productId).trim()
  211939. << ' ' << String (list[i].rev).trim();
  211940. results.add (s);
  211941. }
  211942. }
  211943. return results;
  211944. }
  211945. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211946. {
  211947. using namespace CDReaderHelpers;
  211948. incUserCount();
  211949. if (initialisedOk)
  211950. {
  211951. CDDeviceInfo list[8];
  211952. const int num = FindCDDevices (list, 8);
  211953. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211954. {
  211955. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211956. if (handle != 0)
  211957. {
  211958. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211959. d->cdH = handle;
  211960. d->overlapBuffer = new CDReadBuffer(3);
  211961. return new AudioCDReader (d);
  211962. }
  211963. }
  211964. }
  211965. decUserCount();
  211966. return 0;
  211967. }
  211968. AudioCDReader::AudioCDReader (void* handle_)
  211969. : AudioFormatReader (0, "CD Audio"),
  211970. handle (handle_),
  211971. indexingEnabled (false),
  211972. lastIndex (0),
  211973. firstFrameInBuffer (0),
  211974. samplesInBuffer (0)
  211975. {
  211976. using namespace CDReaderHelpers;
  211977. jassert (handle_ != 0);
  211978. refreshTrackLengths();
  211979. sampleRate = 44100.0;
  211980. bitsPerSample = 16;
  211981. numChannels = 2;
  211982. usesFloatingPointData = false;
  211983. buffer.setSize (4 * bytesPerFrame, true);
  211984. }
  211985. AudioCDReader::~AudioCDReader()
  211986. {
  211987. using namespace CDReaderHelpers;
  211988. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211989. delete device;
  211990. decUserCount();
  211991. }
  211992. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211993. int64 startSampleInFile, int numSamples)
  211994. {
  211995. using namespace CDReaderHelpers;
  211996. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211997. bool ok = true;
  211998. while (numSamples > 0)
  211999. {
  212000. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  212001. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  212002. if (startSampleInFile >= bufferStartSample
  212003. && startSampleInFile < bufferEndSample)
  212004. {
  212005. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  212006. int* const l = destSamples[0] + startOffsetInDestBuffer;
  212007. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  212008. const short* src = (const short*) buffer.getData();
  212009. src += 2 * (startSampleInFile - bufferStartSample);
  212010. for (int i = 0; i < toDo; ++i)
  212011. {
  212012. l[i] = src [i << 1] << 16;
  212013. if (r != 0)
  212014. r[i] = src [(i << 1) + 1] << 16;
  212015. }
  212016. startOffsetInDestBuffer += toDo;
  212017. startSampleInFile += toDo;
  212018. numSamples -= toDo;
  212019. }
  212020. else
  212021. {
  212022. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  212023. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  212024. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  212025. {
  212026. device->overlapBuffer->dataLength = 0;
  212027. device->overlapBuffer->startFrame = 0;
  212028. device->overlapBuffer->numFrames = 0;
  212029. device->jitter = false;
  212030. }
  212031. firstFrameInBuffer = frameNeeded;
  212032. lastIndex = 0;
  212033. CDReadBuffer readBuffer (framesInBuffer + 4);
  212034. readBuffer.wantsIndex = indexingEnabled;
  212035. int i;
  212036. for (i = 5; --i >= 0;)
  212037. {
  212038. readBuffer.startFrame = frameNeeded;
  212039. readBuffer.numFrames = framesInBuffer;
  212040. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  212041. break;
  212042. else
  212043. device->overlapBuffer->dataLength = 0;
  212044. }
  212045. if (i >= 0)
  212046. {
  212047. memcpy ((char*) buffer.getData(),
  212048. readBuffer.buffer + readBuffer.dataStartOffset,
  212049. readBuffer.dataLength);
  212050. samplesInBuffer = readBuffer.dataLength >> 2;
  212051. lastIndex = readBuffer.index;
  212052. }
  212053. else
  212054. {
  212055. int* l = destSamples[0] + startOffsetInDestBuffer;
  212056. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  212057. while (--numSamples >= 0)
  212058. {
  212059. *l++ = 0;
  212060. if (r != 0)
  212061. *r++ = 0;
  212062. }
  212063. // sometimes the read fails for just the very last couple of blocks, so
  212064. // we'll ignore and errors in the last half-second of the disk..
  212065. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  212066. break;
  212067. }
  212068. }
  212069. }
  212070. return ok;
  212071. }
  212072. bool AudioCDReader::isCDStillPresent() const
  212073. {
  212074. using namespace CDReaderHelpers;
  212075. TOC toc;
  212076. zerostruct (toc);
  212077. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  212078. }
  212079. void AudioCDReader::refreshTrackLengths()
  212080. {
  212081. using namespace CDReaderHelpers;
  212082. trackStartSamples.clear();
  212083. zeromem (audioTracks, sizeof (audioTracks));
  212084. TOC toc;
  212085. zerostruct (toc);
  212086. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  212087. {
  212088. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  212089. for (int i = 0; i <= numTracks; ++i)
  212090. {
  212091. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  212092. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  212093. }
  212094. }
  212095. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  212096. }
  212097. bool AudioCDReader::isTrackAudio (int trackNum) const
  212098. {
  212099. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  212100. }
  212101. void AudioCDReader::enableIndexScanning (bool b)
  212102. {
  212103. indexingEnabled = b;
  212104. }
  212105. int AudioCDReader::getLastIndex() const
  212106. {
  212107. return lastIndex;
  212108. }
  212109. const int framesPerIndexRead = 4;
  212110. int AudioCDReader::getIndexAt (int samplePos)
  212111. {
  212112. using namespace CDReaderHelpers;
  212113. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212114. const int frameNeeded = samplePos / samplesPerFrame;
  212115. device->overlapBuffer->dataLength = 0;
  212116. device->overlapBuffer->startFrame = 0;
  212117. device->overlapBuffer->numFrames = 0;
  212118. device->jitter = false;
  212119. firstFrameInBuffer = 0;
  212120. lastIndex = 0;
  212121. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  212122. readBuffer.wantsIndex = true;
  212123. int i;
  212124. for (i = 5; --i >= 0;)
  212125. {
  212126. readBuffer.startFrame = frameNeeded;
  212127. readBuffer.numFrames = framesPerIndexRead;
  212128. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212129. break;
  212130. }
  212131. if (i >= 0)
  212132. return readBuffer.index;
  212133. return -1;
  212134. }
  212135. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  212136. {
  212137. using namespace CDReaderHelpers;
  212138. Array <int> indexes;
  212139. const int trackStart = getPositionOfTrackStart (trackNumber);
  212140. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  212141. bool needToScan = true;
  212142. if (trackEnd - trackStart > 20 * 44100)
  212143. {
  212144. // check the end of the track for indexes before scanning the whole thing
  212145. needToScan = false;
  212146. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  212147. bool seenAnIndex = false;
  212148. while (pos <= trackEnd - samplesPerFrame)
  212149. {
  212150. const int index = getIndexAt (pos);
  212151. if (index == 0)
  212152. {
  212153. // lead-out, so skip back a bit if we've not found any indexes yet..
  212154. if (seenAnIndex)
  212155. break;
  212156. pos -= 44100 * 5;
  212157. if (pos < trackStart)
  212158. break;
  212159. }
  212160. else
  212161. {
  212162. if (index > 0)
  212163. seenAnIndex = true;
  212164. if (index > 1)
  212165. {
  212166. needToScan = true;
  212167. break;
  212168. }
  212169. pos += samplesPerFrame * framesPerIndexRead;
  212170. }
  212171. }
  212172. }
  212173. if (needToScan)
  212174. {
  212175. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212176. int pos = trackStart;
  212177. int last = -1;
  212178. while (pos < trackEnd - samplesPerFrame * 10)
  212179. {
  212180. const int frameNeeded = pos / samplesPerFrame;
  212181. device->overlapBuffer->dataLength = 0;
  212182. device->overlapBuffer->startFrame = 0;
  212183. device->overlapBuffer->numFrames = 0;
  212184. device->jitter = false;
  212185. firstFrameInBuffer = 0;
  212186. CDReadBuffer readBuffer (4);
  212187. readBuffer.wantsIndex = true;
  212188. int i;
  212189. for (i = 5; --i >= 0;)
  212190. {
  212191. readBuffer.startFrame = frameNeeded;
  212192. readBuffer.numFrames = framesPerIndexRead;
  212193. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212194. break;
  212195. }
  212196. if (i < 0)
  212197. break;
  212198. if (readBuffer.index > last && readBuffer.index > 1)
  212199. {
  212200. last = readBuffer.index;
  212201. indexes.add (pos);
  212202. }
  212203. pos += samplesPerFrame * framesPerIndexRead;
  212204. }
  212205. indexes.removeValue (trackStart);
  212206. }
  212207. return indexes;
  212208. }
  212209. void AudioCDReader::ejectDisk()
  212210. {
  212211. using namespace CDReaderHelpers;
  212212. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  212213. }
  212214. #endif
  212215. #if JUCE_USE_CDBURNER
  212216. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212217. {
  212218. CoInitialize (0);
  212219. IDiscMaster* dm;
  212220. IDiscRecorder* result = 0;
  212221. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212222. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212223. IID_IDiscMaster,
  212224. (void**) &dm)))
  212225. {
  212226. if (SUCCEEDED (dm->Open()))
  212227. {
  212228. IEnumDiscRecorders* drEnum = 0;
  212229. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212230. {
  212231. IDiscRecorder* dr = 0;
  212232. DWORD dummy;
  212233. int index = 0;
  212234. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212235. {
  212236. if (indexToOpen == index)
  212237. {
  212238. result = dr;
  212239. break;
  212240. }
  212241. else if (list != 0)
  212242. {
  212243. BSTR path;
  212244. if (SUCCEEDED (dr->GetPath (&path)))
  212245. list->add ((const WCHAR*) path);
  212246. }
  212247. ++index;
  212248. dr->Release();
  212249. }
  212250. drEnum->Release();
  212251. }
  212252. if (master == 0)
  212253. dm->Close();
  212254. }
  212255. if (master != 0)
  212256. *master = dm;
  212257. else
  212258. dm->Release();
  212259. }
  212260. return result;
  212261. }
  212262. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212263. public Timer
  212264. {
  212265. public:
  212266. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212267. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212268. listener (0), progress (0), shouldCancel (false)
  212269. {
  212270. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212271. jassert (SUCCEEDED (hr));
  212272. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212273. //jassert (SUCCEEDED (hr));
  212274. lastState = getDiskState();
  212275. startTimer (2000);
  212276. }
  212277. ~Pimpl() {}
  212278. void releaseObjects()
  212279. {
  212280. discRecorder->Close();
  212281. if (redbook != 0)
  212282. redbook->Release();
  212283. discRecorder->Release();
  212284. discMaster->Release();
  212285. Release();
  212286. }
  212287. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212288. {
  212289. if (listener != 0 && ! shouldCancel)
  212290. shouldCancel = listener->audioCDBurnProgress (progress);
  212291. *pbCancel = shouldCancel;
  212292. return S_OK;
  212293. }
  212294. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212295. {
  212296. progress = nCompleted / (float) nTotal;
  212297. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212298. return E_NOTIMPL;
  212299. }
  212300. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212301. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212302. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212303. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212304. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212305. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212306. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212307. class ScopedDiscOpener
  212308. {
  212309. public:
  212310. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212311. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212312. private:
  212313. Pimpl& pimpl;
  212314. ScopedDiscOpener (const ScopedDiscOpener&);
  212315. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212316. };
  212317. DiskState getDiskState()
  212318. {
  212319. const ScopedDiscOpener opener (*this);
  212320. long type, flags;
  212321. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212322. if (FAILED (hr))
  212323. return unknown;
  212324. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212325. return writableDiskPresent;
  212326. if (type == 0)
  212327. return noDisc;
  212328. else
  212329. return readOnlyDiskPresent;
  212330. }
  212331. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212332. {
  212333. ComSmartPtr<IPropertyStorage> prop;
  212334. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  212335. return defaultReturn;
  212336. PROPSPEC iPropSpec;
  212337. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212338. iPropSpec.lpwstr = name;
  212339. PROPVARIANT iPropVariant;
  212340. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212341. ? defaultReturn : (int) iPropVariant.lVal;
  212342. }
  212343. bool setIntProperty (const LPOLESTR name, const int value) const
  212344. {
  212345. ComSmartPtr<IPropertyStorage> prop;
  212346. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  212347. return false;
  212348. PROPSPEC iPropSpec;
  212349. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212350. iPropSpec.lpwstr = name;
  212351. PROPVARIANT iPropVariant;
  212352. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212353. return false;
  212354. iPropVariant.lVal = (long) value;
  212355. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212356. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212357. }
  212358. void timerCallback()
  212359. {
  212360. const DiskState state = getDiskState();
  212361. if (state != lastState)
  212362. {
  212363. lastState = state;
  212364. owner.sendChangeMessage (&owner);
  212365. }
  212366. }
  212367. AudioCDBurner& owner;
  212368. DiskState lastState;
  212369. IDiscMaster* discMaster;
  212370. IDiscRecorder* discRecorder;
  212371. IRedbookDiscMaster* redbook;
  212372. AudioCDBurner::BurnProgressListener* listener;
  212373. float progress;
  212374. bool shouldCancel;
  212375. };
  212376. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212377. {
  212378. IDiscMaster* discMaster = 0;
  212379. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212380. if (discRecorder != 0)
  212381. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212382. }
  212383. AudioCDBurner::~AudioCDBurner()
  212384. {
  212385. if (pimpl != 0)
  212386. pimpl.release()->releaseObjects();
  212387. }
  212388. const StringArray AudioCDBurner::findAvailableDevices()
  212389. {
  212390. StringArray devs;
  212391. enumCDBurners (&devs, -1, 0);
  212392. return devs;
  212393. }
  212394. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212395. {
  212396. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212397. if (b->pimpl == 0)
  212398. b = 0;
  212399. return b.release();
  212400. }
  212401. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212402. {
  212403. return pimpl->getDiskState();
  212404. }
  212405. bool AudioCDBurner::isDiskPresent() const
  212406. {
  212407. return getDiskState() == writableDiskPresent;
  212408. }
  212409. bool AudioCDBurner::openTray()
  212410. {
  212411. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212412. return SUCCEEDED (pimpl->discRecorder->Eject());
  212413. }
  212414. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212415. {
  212416. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212417. DiskState oldState = getDiskState();
  212418. DiskState newState = oldState;
  212419. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212420. {
  212421. newState = getDiskState();
  212422. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212423. }
  212424. return newState;
  212425. }
  212426. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212427. {
  212428. Array<int> results;
  212429. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212430. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212431. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212432. if (speeds[i] <= maxSpeed)
  212433. results.add (speeds[i]);
  212434. results.addIfNotAlreadyThere (maxSpeed);
  212435. return results;
  212436. }
  212437. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212438. {
  212439. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212440. return false;
  212441. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212442. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212443. }
  212444. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212445. {
  212446. long blocksFree = 0;
  212447. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212448. return blocksFree;
  212449. }
  212450. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212451. bool performFakeBurnForTesting, int writeSpeed)
  212452. {
  212453. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212454. pimpl->listener = listener;
  212455. pimpl->progress = 0;
  212456. pimpl->shouldCancel = false;
  212457. UINT_PTR cookie;
  212458. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212459. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212460. ejectDiscAfterwards);
  212461. String error;
  212462. if (hr != S_OK)
  212463. {
  212464. const char* e = "Couldn't open or write to the CD device";
  212465. if (hr == IMAPI_E_USERABORT)
  212466. e = "User cancelled the write operation";
  212467. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212468. e = "No Disk present";
  212469. error = e;
  212470. }
  212471. pimpl->discMaster->ProgressUnadvise (cookie);
  212472. pimpl->listener = 0;
  212473. return error;
  212474. }
  212475. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212476. {
  212477. if (audioSource == 0)
  212478. return false;
  212479. ScopedPointer<AudioSource> source (audioSource);
  212480. long bytesPerBlock;
  212481. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212482. const int samplesPerBlock = bytesPerBlock / 4;
  212483. bool ok = true;
  212484. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212485. HeapBlock <byte> buffer (bytesPerBlock);
  212486. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212487. int samplesDone = 0;
  212488. source->prepareToPlay (samplesPerBlock, 44100.0);
  212489. while (ok)
  212490. {
  212491. {
  212492. AudioSourceChannelInfo info;
  212493. info.buffer = &sourceBuffer;
  212494. info.numSamples = samplesPerBlock;
  212495. info.startSample = 0;
  212496. sourceBuffer.clear();
  212497. source->getNextAudioBlock (info);
  212498. }
  212499. zeromem (buffer, bytesPerBlock);
  212500. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  212501. buffer, samplesPerBlock, 4);
  212502. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  212503. buffer + 2, samplesPerBlock, 4);
  212504. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212505. if (FAILED (hr))
  212506. ok = false;
  212507. samplesDone += samplesPerBlock;
  212508. if (samplesDone >= numSamples)
  212509. break;
  212510. }
  212511. hr = pimpl->redbook->CloseAudioTrack();
  212512. return ok && hr == S_OK;
  212513. }
  212514. #endif
  212515. #endif
  212516. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212517. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212518. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212519. // compiled on its own).
  212520. #if JUCE_INCLUDED_FILE
  212521. class MidiInThread : public Thread
  212522. {
  212523. public:
  212524. MidiInThread (MidiInput* const input_,
  212525. MidiInputCallback* const callback_)
  212526. : Thread ("Juce Midi"),
  212527. deviceHandle (0),
  212528. input (input_),
  212529. callback (callback_),
  212530. isStarted (false),
  212531. startTime (0)
  212532. {
  212533. pending.ensureSize ((int) defaultBufferSize);
  212534. for (int i = (int) numInHeaders; --i >= 0;)
  212535. {
  212536. zeromem (&hdr[i], sizeof (MIDIHDR));
  212537. hdr[i].lpData = inData[i];
  212538. hdr[i].dwBufferLength = (int) inBufferSize;
  212539. }
  212540. };
  212541. ~MidiInThread()
  212542. {
  212543. stop();
  212544. if (deviceHandle != 0)
  212545. {
  212546. int count = 5;
  212547. while (--count >= 0)
  212548. {
  212549. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212550. break;
  212551. Sleep (20);
  212552. }
  212553. }
  212554. }
  212555. void handle (const uint32 message, const uint32 timeStamp)
  212556. {
  212557. const int byte = message & 0xff;
  212558. if (byte < 0x80)
  212559. return;
  212560. const int time = timeStampToMs (timeStamp);
  212561. {
  212562. const ScopedLock sl (lock);
  212563. pending.addEvent (&message, 3, time);
  212564. }
  212565. notify();
  212566. }
  212567. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212568. {
  212569. const int time = timeStampToMs (timeStamp);
  212570. const int num = hdr->dwBytesRecorded;
  212571. if (num > 0)
  212572. {
  212573. {
  212574. const ScopedLock sl (lock);
  212575. pending.addEvent (hdr->lpData, num, time);
  212576. }
  212577. notify();
  212578. }
  212579. }
  212580. void writeBlock (const int i)
  212581. {
  212582. hdr[i].dwBytesRecorded = 0;
  212583. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr[i], sizeof (MIDIHDR));
  212584. jassert (res == MMSYSERR_NOERROR);
  212585. res = midiInAddBuffer (deviceHandle, &hdr[i], sizeof (MIDIHDR));
  212586. jassert (res == MMSYSERR_NOERROR);
  212587. }
  212588. void run()
  212589. {
  212590. MidiBuffer newEvents;
  212591. newEvents.ensureSize ((int) defaultBufferSize);
  212592. while (! threadShouldExit())
  212593. {
  212594. for (int i = 0; i < (int) numInHeaders; ++i)
  212595. {
  212596. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212597. {
  212598. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr[i], sizeof (MIDIHDR));
  212599. (void) res;
  212600. jassert (res == MMSYSERR_NOERROR);
  212601. writeBlock (i);
  212602. }
  212603. }
  212604. newEvents.clear(); // (resets it without freeing allocated storage)
  212605. {
  212606. const ScopedLock sl (lock);
  212607. newEvents.swapWith (pending);
  212608. }
  212609. //xxx needs to figure out if blocks are broken up or not
  212610. if (newEvents.isEmpty())
  212611. {
  212612. wait (500);
  212613. }
  212614. else
  212615. {
  212616. MidiMessage message (0xf4, 0.0);
  212617. int time;
  212618. for (MidiBuffer::Iterator i (newEvents); i.getNextEvent (message, time);)
  212619. {
  212620. message.setTimeStamp (time * 0.001);
  212621. callback->handleIncomingMidiMessage (input, message);
  212622. }
  212623. }
  212624. }
  212625. }
  212626. void start()
  212627. {
  212628. jassert (deviceHandle != 0);
  212629. if (deviceHandle != 0 && ! isStarted)
  212630. {
  212631. stop();
  212632. activeMidiThreads.addIfNotAlreadyThere (this);
  212633. int i;
  212634. for (i = 0; i < (int) numInHeaders; ++i)
  212635. writeBlock (i);
  212636. startTime = Time::getMillisecondCounter();
  212637. MMRESULT res = midiInStart (deviceHandle);
  212638. jassert (res == MMSYSERR_NOERROR);
  212639. if (res == MMSYSERR_NOERROR)
  212640. {
  212641. isStarted = true;
  212642. pending.clear();
  212643. startThread (6);
  212644. }
  212645. }
  212646. }
  212647. void stop()
  212648. {
  212649. if (isStarted)
  212650. {
  212651. stopThread (5000);
  212652. midiInReset (deviceHandle);
  212653. midiInStop (deviceHandle);
  212654. activeMidiThreads.removeValue (this);
  212655. { const ScopedLock sl (lock); }
  212656. for (int i = (int) numInHeaders; --i >= 0;)
  212657. {
  212658. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212659. {
  212660. int c = 10;
  212661. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  212662. Sleep (20);
  212663. jassert (c >= 0);
  212664. }
  212665. }
  212666. isStarted = false;
  212667. pending.clear();
  212668. }
  212669. }
  212670. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212671. {
  212672. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  212673. if (thread != 0 && activeMidiThreads.contains (thread))
  212674. {
  212675. if (uMsg == MIM_DATA)
  212676. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  212677. else if (uMsg == MIM_LONGDATA)
  212678. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212679. }
  212680. }
  212681. juce_UseDebuggingNewOperator
  212682. HMIDIIN deviceHandle;
  212683. private:
  212684. static Array <void*, CriticalSection> activeMidiThreads;
  212685. MidiInput* input;
  212686. MidiInputCallback* callback;
  212687. bool isStarted;
  212688. uint32 startTime;
  212689. CriticalSection lock;
  212690. enum { defaultBufferSize = 8192,
  212691. numInHeaders = 32,
  212692. inBufferSize = 256 };
  212693. MIDIHDR hdr [(int) numInHeaders];
  212694. char inData [(int) numInHeaders] [(int) inBufferSize];
  212695. MidiBuffer pending;
  212696. int timeStampToMs (uint32 timeStamp)
  212697. {
  212698. timeStamp += startTime;
  212699. const uint32 now = Time::getMillisecondCounter();
  212700. if (timeStamp > now)
  212701. {
  212702. if (timeStamp > now + 2)
  212703. --startTime;
  212704. timeStamp = now;
  212705. }
  212706. return (int) timeStamp;
  212707. }
  212708. MidiInThread (const MidiInThread&);
  212709. MidiInThread& operator= (const MidiInThread&);
  212710. };
  212711. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  212712. const StringArray MidiInput::getDevices()
  212713. {
  212714. StringArray s;
  212715. const int num = midiInGetNumDevs();
  212716. for (int i = 0; i < num; ++i)
  212717. {
  212718. MIDIINCAPS mc;
  212719. zerostruct (mc);
  212720. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212721. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212722. }
  212723. return s;
  212724. }
  212725. int MidiInput::getDefaultDeviceIndex()
  212726. {
  212727. return 0;
  212728. }
  212729. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212730. {
  212731. if (callback == 0)
  212732. return 0;
  212733. UINT deviceId = MIDI_MAPPER;
  212734. int n = 0;
  212735. String name;
  212736. const int num = midiInGetNumDevs();
  212737. for (int i = 0; i < num; ++i)
  212738. {
  212739. MIDIINCAPS mc;
  212740. zerostruct (mc);
  212741. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212742. {
  212743. if (index == n)
  212744. {
  212745. deviceId = i;
  212746. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212747. break;
  212748. }
  212749. ++n;
  212750. }
  212751. }
  212752. ScopedPointer <MidiInput> in (new MidiInput (name));
  212753. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  212754. HMIDIIN h;
  212755. HRESULT err = midiInOpen (&h, deviceId,
  212756. (DWORD_PTR) &MidiInThread::midiInCallback,
  212757. (DWORD_PTR) (MidiInThread*) thread,
  212758. CALLBACK_FUNCTION);
  212759. if (err == MMSYSERR_NOERROR)
  212760. {
  212761. thread->deviceHandle = h;
  212762. in->internal = thread.release();
  212763. return in.release();
  212764. }
  212765. return 0;
  212766. }
  212767. MidiInput::MidiInput (const String& name_)
  212768. : name (name_),
  212769. internal (0)
  212770. {
  212771. }
  212772. MidiInput::~MidiInput()
  212773. {
  212774. delete static_cast <MidiInThread*> (internal);
  212775. }
  212776. void MidiInput::start()
  212777. {
  212778. static_cast <MidiInThread*> (internal)->start();
  212779. }
  212780. void MidiInput::stop()
  212781. {
  212782. static_cast <MidiInThread*> (internal)->stop();
  212783. }
  212784. struct MidiOutHandle
  212785. {
  212786. int refCount;
  212787. UINT deviceId;
  212788. HMIDIOUT handle;
  212789. static Array<MidiOutHandle*> activeHandles;
  212790. juce_UseDebuggingNewOperator
  212791. };
  212792. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212793. const StringArray MidiOutput::getDevices()
  212794. {
  212795. StringArray s;
  212796. const int num = midiOutGetNumDevs();
  212797. for (int i = 0; i < num; ++i)
  212798. {
  212799. MIDIOUTCAPS mc;
  212800. zerostruct (mc);
  212801. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212802. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212803. }
  212804. return s;
  212805. }
  212806. int MidiOutput::getDefaultDeviceIndex()
  212807. {
  212808. const int num = midiOutGetNumDevs();
  212809. int n = 0;
  212810. for (int i = 0; i < num; ++i)
  212811. {
  212812. MIDIOUTCAPS mc;
  212813. zerostruct (mc);
  212814. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212815. {
  212816. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212817. return n;
  212818. ++n;
  212819. }
  212820. }
  212821. return 0;
  212822. }
  212823. MidiOutput* MidiOutput::openDevice (int index)
  212824. {
  212825. UINT deviceId = MIDI_MAPPER;
  212826. const int num = midiOutGetNumDevs();
  212827. int i, n = 0;
  212828. for (i = 0; i < num; ++i)
  212829. {
  212830. MIDIOUTCAPS mc;
  212831. zerostruct (mc);
  212832. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212833. {
  212834. // use the microsoft sw synth as a default - best not to allow deviceId
  212835. // to be MIDI_MAPPER, or else device sharing breaks
  212836. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212837. deviceId = i;
  212838. if (index == n)
  212839. {
  212840. deviceId = i;
  212841. break;
  212842. }
  212843. ++n;
  212844. }
  212845. }
  212846. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212847. {
  212848. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212849. if (han != 0 && han->deviceId == deviceId)
  212850. {
  212851. han->refCount++;
  212852. MidiOutput* const out = new MidiOutput();
  212853. out->internal = han;
  212854. return out;
  212855. }
  212856. }
  212857. for (i = 4; --i >= 0;)
  212858. {
  212859. HMIDIOUT h = 0;
  212860. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212861. if (res == MMSYSERR_NOERROR)
  212862. {
  212863. MidiOutHandle* const han = new MidiOutHandle();
  212864. han->deviceId = deviceId;
  212865. han->refCount = 1;
  212866. han->handle = h;
  212867. MidiOutHandle::activeHandles.add (han);
  212868. MidiOutput* const out = new MidiOutput();
  212869. out->internal = han;
  212870. return out;
  212871. }
  212872. else if (res == MMSYSERR_ALLOCATED)
  212873. {
  212874. Sleep (100);
  212875. }
  212876. else
  212877. {
  212878. break;
  212879. }
  212880. }
  212881. return 0;
  212882. }
  212883. MidiOutput::~MidiOutput()
  212884. {
  212885. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212886. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212887. {
  212888. midiOutClose (h->handle);
  212889. MidiOutHandle::activeHandles.removeValue (h);
  212890. delete h;
  212891. }
  212892. }
  212893. void MidiOutput::reset()
  212894. {
  212895. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212896. midiOutReset (h->handle);
  212897. }
  212898. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212899. {
  212900. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212901. DWORD n;
  212902. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212903. {
  212904. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212905. rightVol = nn[0] / (float) 0xffff;
  212906. leftVol = nn[1] / (float) 0xffff;
  212907. return true;
  212908. }
  212909. else
  212910. {
  212911. rightVol = leftVol = 1.0f;
  212912. return false;
  212913. }
  212914. }
  212915. void MidiOutput::setVolume (float leftVol, float rightVol)
  212916. {
  212917. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212918. DWORD n;
  212919. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212920. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212921. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212922. midiOutSetVolume (handle->handle, n);
  212923. }
  212924. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212925. {
  212926. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212927. if (message.getRawDataSize() > 3
  212928. || message.isSysEx())
  212929. {
  212930. MIDIHDR h;
  212931. zerostruct (h);
  212932. h.lpData = (char*) message.getRawData();
  212933. h.dwBufferLength = message.getRawDataSize();
  212934. h.dwBytesRecorded = message.getRawDataSize();
  212935. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212936. {
  212937. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212938. if (res == MMSYSERR_NOERROR)
  212939. {
  212940. while ((h.dwFlags & MHDR_DONE) == 0)
  212941. Sleep (1);
  212942. int count = 500; // 1 sec timeout
  212943. while (--count >= 0)
  212944. {
  212945. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212946. if (res == MIDIERR_STILLPLAYING)
  212947. Sleep (2);
  212948. else
  212949. break;
  212950. }
  212951. }
  212952. }
  212953. }
  212954. else
  212955. {
  212956. midiOutShortMsg (handle->handle,
  212957. *(unsigned int*) message.getRawData());
  212958. }
  212959. }
  212960. #endif
  212961. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212962. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212963. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212964. // compiled on its own).
  212965. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212966. #undef WINDOWS
  212967. // #define ASIO_DEBUGGING 1
  212968. #if ASIO_DEBUGGING
  212969. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212970. #else
  212971. #define log(a) {}
  212972. #endif
  212973. #if ASIO_DEBUGGING
  212974. static void logError (const String& context, long error)
  212975. {
  212976. String err ("unknown error");
  212977. if (error == ASE_NotPresent) err = "Not Present";
  212978. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212979. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212980. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212981. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212982. else if (error == ASE_NoClock) err = "No Clock";
  212983. else if (error == ASE_NoMemory) err = "Out of memory";
  212984. log ("!!error: " + context + " - " + err);
  212985. }
  212986. #else
  212987. #define logError(a, b) {}
  212988. #endif
  212989. class ASIOAudioIODevice;
  212990. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212991. static const int maxASIOChannels = 160;
  212992. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212993. private Timer
  212994. {
  212995. public:
  212996. Component ourWindow;
  212997. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212998. const String& optionalDllForDirectLoading_)
  212999. : AudioIODevice (name_, "ASIO"),
  213000. asioObject (0),
  213001. classId (classId_),
  213002. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  213003. currentBitDepth (16),
  213004. currentSampleRate (0),
  213005. isOpen_ (false),
  213006. isStarted (false),
  213007. postOutput (true),
  213008. insideControlPanelModalLoop (false),
  213009. shouldUsePreferredSize (false)
  213010. {
  213011. name = name_;
  213012. ourWindow.addToDesktop (0);
  213013. windowHandle = ourWindow.getWindowHandle();
  213014. jassert (currentASIODev [slotNumber] == 0);
  213015. currentASIODev [slotNumber] = this;
  213016. openDevice();
  213017. }
  213018. ~ASIOAudioIODevice()
  213019. {
  213020. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213021. if (currentASIODev[i] == this)
  213022. currentASIODev[i] = 0;
  213023. close();
  213024. log ("ASIO - exiting");
  213025. removeCurrentDriver();
  213026. }
  213027. void updateSampleRates()
  213028. {
  213029. // find a list of sample rates..
  213030. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  213031. sampleRates.clear();
  213032. if (asioObject != 0)
  213033. {
  213034. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  213035. {
  213036. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  213037. if (err == 0)
  213038. {
  213039. sampleRates.add ((int) possibleSampleRates[index]);
  213040. log ("rate: " + String ((int) possibleSampleRates[index]));
  213041. }
  213042. else if (err != ASE_NoClock)
  213043. {
  213044. logError ("CanSampleRate", err);
  213045. }
  213046. }
  213047. if (sampleRates.size() == 0)
  213048. {
  213049. double cr = 0;
  213050. const long err = asioObject->getSampleRate (&cr);
  213051. log ("No sample rates supported - current rate: " + String ((int) cr));
  213052. if (err == 0)
  213053. sampleRates.add ((int) cr);
  213054. }
  213055. }
  213056. }
  213057. const StringArray getOutputChannelNames()
  213058. {
  213059. return outputChannelNames;
  213060. }
  213061. const StringArray getInputChannelNames()
  213062. {
  213063. return inputChannelNames;
  213064. }
  213065. int getNumSampleRates()
  213066. {
  213067. return sampleRates.size();
  213068. }
  213069. double getSampleRate (int index)
  213070. {
  213071. return sampleRates [index];
  213072. }
  213073. int getNumBufferSizesAvailable()
  213074. {
  213075. return bufferSizes.size();
  213076. }
  213077. int getBufferSizeSamples (int index)
  213078. {
  213079. return bufferSizes [index];
  213080. }
  213081. int getDefaultBufferSize()
  213082. {
  213083. return preferredSize;
  213084. }
  213085. const String open (const BigInteger& inputChannels,
  213086. const BigInteger& outputChannels,
  213087. double sr,
  213088. int bufferSizeSamples)
  213089. {
  213090. close();
  213091. currentCallback = 0;
  213092. if (bufferSizeSamples <= 0)
  213093. shouldUsePreferredSize = true;
  213094. if (asioObject == 0 || ! isASIOOpen)
  213095. {
  213096. log ("Warning: device not open");
  213097. const String err (openDevice());
  213098. if (asioObject == 0 || ! isASIOOpen)
  213099. return err;
  213100. }
  213101. isStarted = false;
  213102. bufferIndex = -1;
  213103. long err = 0;
  213104. long newPreferredSize = 0;
  213105. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  213106. minSize = 0;
  213107. maxSize = 0;
  213108. newPreferredSize = 0;
  213109. granularity = 0;
  213110. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  213111. {
  213112. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  213113. shouldUsePreferredSize = true;
  213114. preferredSize = newPreferredSize;
  213115. }
  213116. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  213117. // dynamic changes to the buffer size...
  213118. shouldUsePreferredSize = shouldUsePreferredSize
  213119. || getName().containsIgnoreCase ("Digidesign");
  213120. if (shouldUsePreferredSize)
  213121. {
  213122. log ("Using preferred size for buffer..");
  213123. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213124. {
  213125. bufferSizeSamples = preferredSize;
  213126. }
  213127. else
  213128. {
  213129. bufferSizeSamples = 1024;
  213130. logError ("GetBufferSize1", err);
  213131. }
  213132. shouldUsePreferredSize = false;
  213133. }
  213134. int sampleRate = roundDoubleToInt (sr);
  213135. currentSampleRate = sampleRate;
  213136. currentBlockSizeSamples = bufferSizeSamples;
  213137. currentChansOut.clear();
  213138. currentChansIn.clear();
  213139. zeromem (inBuffers, sizeof (inBuffers));
  213140. zeromem (outBuffers, sizeof (outBuffers));
  213141. updateSampleRates();
  213142. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  213143. sampleRate = sampleRates[0];
  213144. jassert (sampleRate != 0);
  213145. if (sampleRate == 0)
  213146. sampleRate = 44100;
  213147. long numSources = 32;
  213148. ASIOClockSource clocks[32];
  213149. zeromem (clocks, sizeof (clocks));
  213150. asioObject->getClockSources (clocks, &numSources);
  213151. bool isSourceSet = false;
  213152. // careful not to remove this loop because it does more than just logging!
  213153. int i;
  213154. for (i = 0; i < numSources; ++i)
  213155. {
  213156. String s ("clock: ");
  213157. s += clocks[i].name;
  213158. if (clocks[i].isCurrentSource)
  213159. {
  213160. isSourceSet = true;
  213161. s << " (cur)";
  213162. }
  213163. log (s);
  213164. }
  213165. if (numSources > 1 && ! isSourceSet)
  213166. {
  213167. log ("setting clock source");
  213168. asioObject->setClockSource (clocks[0].index);
  213169. Thread::sleep (20);
  213170. }
  213171. else
  213172. {
  213173. if (numSources == 0)
  213174. {
  213175. log ("ASIO - no clock sources!");
  213176. }
  213177. }
  213178. double cr = 0;
  213179. err = asioObject->getSampleRate (&cr);
  213180. if (err == 0)
  213181. {
  213182. currentSampleRate = cr;
  213183. }
  213184. else
  213185. {
  213186. logError ("GetSampleRate", err);
  213187. currentSampleRate = 0;
  213188. }
  213189. error = String::empty;
  213190. needToReset = false;
  213191. isReSync = false;
  213192. err = 0;
  213193. bool buffersCreated = false;
  213194. if (currentSampleRate != sampleRate)
  213195. {
  213196. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  213197. err = asioObject->setSampleRate (sampleRate);
  213198. if (err == ASE_NoClock && numSources > 0)
  213199. {
  213200. log ("trying to set a clock source..");
  213201. Thread::sleep (10);
  213202. err = asioObject->setClockSource (clocks[0].index);
  213203. if (err != 0)
  213204. {
  213205. logError ("SetClock", err);
  213206. }
  213207. Thread::sleep (10);
  213208. err = asioObject->setSampleRate (sampleRate);
  213209. }
  213210. }
  213211. if (err == 0)
  213212. {
  213213. currentSampleRate = sampleRate;
  213214. if (needToReset)
  213215. {
  213216. if (isReSync)
  213217. {
  213218. log ("Resync request");
  213219. }
  213220. log ("! Resetting ASIO after sample rate change");
  213221. removeCurrentDriver();
  213222. loadDriver();
  213223. const String error (initDriver());
  213224. if (error.isNotEmpty())
  213225. {
  213226. log ("ASIOInit: " + error);
  213227. }
  213228. needToReset = false;
  213229. isReSync = false;
  213230. }
  213231. numActiveInputChans = 0;
  213232. numActiveOutputChans = 0;
  213233. ASIOBufferInfo* info = bufferInfos;
  213234. int i;
  213235. for (i = 0; i < totalNumInputChans; ++i)
  213236. {
  213237. if (inputChannels[i])
  213238. {
  213239. currentChansIn.setBit (i);
  213240. info->isInput = 1;
  213241. info->channelNum = i;
  213242. info->buffers[0] = info->buffers[1] = 0;
  213243. ++info;
  213244. ++numActiveInputChans;
  213245. }
  213246. }
  213247. for (i = 0; i < totalNumOutputChans; ++i)
  213248. {
  213249. if (outputChannels[i])
  213250. {
  213251. currentChansOut.setBit (i);
  213252. info->isInput = 0;
  213253. info->channelNum = i;
  213254. info->buffers[0] = info->buffers[1] = 0;
  213255. ++info;
  213256. ++numActiveOutputChans;
  213257. }
  213258. }
  213259. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213260. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213261. if (currentASIODev[0] == this)
  213262. {
  213263. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213264. callbacks.asioMessage = &asioMessagesCallback0;
  213265. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213266. }
  213267. else if (currentASIODev[1] == this)
  213268. {
  213269. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213270. callbacks.asioMessage = &asioMessagesCallback1;
  213271. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213272. }
  213273. else if (currentASIODev[2] == this)
  213274. {
  213275. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213276. callbacks.asioMessage = &asioMessagesCallback2;
  213277. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213278. }
  213279. else
  213280. {
  213281. jassertfalse;
  213282. }
  213283. log ("disposing buffers");
  213284. err = asioObject->disposeBuffers();
  213285. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213286. err = asioObject->createBuffers (bufferInfos,
  213287. totalBuffers,
  213288. currentBlockSizeSamples,
  213289. &callbacks);
  213290. if (err != 0)
  213291. {
  213292. currentBlockSizeSamples = preferredSize;
  213293. logError ("create buffers 2", err);
  213294. asioObject->disposeBuffers();
  213295. err = asioObject->createBuffers (bufferInfos,
  213296. totalBuffers,
  213297. currentBlockSizeSamples,
  213298. &callbacks);
  213299. }
  213300. if (err == 0)
  213301. {
  213302. buffersCreated = true;
  213303. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213304. int n = 0;
  213305. Array <int> types;
  213306. currentBitDepth = 16;
  213307. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213308. {
  213309. if (inputChannels[i])
  213310. {
  213311. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213312. ASIOChannelInfo channelInfo;
  213313. zerostruct (channelInfo);
  213314. channelInfo.channel = i;
  213315. channelInfo.isInput = 1;
  213316. asioObject->getChannelInfo (&channelInfo);
  213317. types.addIfNotAlreadyThere (channelInfo.type);
  213318. typeToFormatParameters (channelInfo.type,
  213319. inputChannelBitDepths[n],
  213320. inputChannelBytesPerSample[n],
  213321. inputChannelIsFloat[n],
  213322. inputChannelLittleEndian[n]);
  213323. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213324. ++n;
  213325. }
  213326. }
  213327. jassert (numActiveInputChans == n);
  213328. n = 0;
  213329. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213330. {
  213331. if (outputChannels[i])
  213332. {
  213333. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213334. ASIOChannelInfo channelInfo;
  213335. zerostruct (channelInfo);
  213336. channelInfo.channel = i;
  213337. channelInfo.isInput = 0;
  213338. asioObject->getChannelInfo (&channelInfo);
  213339. types.addIfNotAlreadyThere (channelInfo.type);
  213340. typeToFormatParameters (channelInfo.type,
  213341. outputChannelBitDepths[n],
  213342. outputChannelBytesPerSample[n],
  213343. outputChannelIsFloat[n],
  213344. outputChannelLittleEndian[n]);
  213345. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213346. ++n;
  213347. }
  213348. }
  213349. jassert (numActiveOutputChans == n);
  213350. for (i = types.size(); --i >= 0;)
  213351. {
  213352. log ("channel format: " + String (types[i]));
  213353. }
  213354. jassert (n <= totalBuffers);
  213355. for (i = 0; i < numActiveOutputChans; ++i)
  213356. {
  213357. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213358. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213359. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213360. {
  213361. log ("!! Null buffers");
  213362. }
  213363. else
  213364. {
  213365. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213366. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213367. }
  213368. }
  213369. inputLatency = outputLatency = 0;
  213370. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213371. {
  213372. log ("ASIO - no latencies");
  213373. }
  213374. else
  213375. {
  213376. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213377. }
  213378. isOpen_ = true;
  213379. log ("starting ASIO");
  213380. calledback = false;
  213381. err = asioObject->start();
  213382. if (err != 0)
  213383. {
  213384. isOpen_ = false;
  213385. log ("ASIO - stop on failure");
  213386. Thread::sleep (10);
  213387. asioObject->stop();
  213388. error = "Can't start device";
  213389. Thread::sleep (10);
  213390. }
  213391. else
  213392. {
  213393. int count = 300;
  213394. while (--count > 0 && ! calledback)
  213395. Thread::sleep (10);
  213396. isStarted = true;
  213397. if (! calledback)
  213398. {
  213399. error = "Device didn't start correctly";
  213400. log ("ASIO didn't callback - stopping..");
  213401. asioObject->stop();
  213402. }
  213403. }
  213404. }
  213405. else
  213406. {
  213407. error = "Can't create i/o buffers";
  213408. }
  213409. }
  213410. else
  213411. {
  213412. error = "Can't set sample rate: ";
  213413. error << sampleRate;
  213414. }
  213415. if (error.isNotEmpty())
  213416. {
  213417. logError (error, err);
  213418. if (asioObject != 0 && buffersCreated)
  213419. asioObject->disposeBuffers();
  213420. Thread::sleep (20);
  213421. isStarted = false;
  213422. isOpen_ = false;
  213423. const String errorCopy (error);
  213424. close(); // (this resets the error string)
  213425. error = errorCopy;
  213426. }
  213427. needToReset = false;
  213428. isReSync = false;
  213429. return error;
  213430. }
  213431. void close()
  213432. {
  213433. error = String::empty;
  213434. stopTimer();
  213435. stop();
  213436. if (isASIOOpen && isOpen_)
  213437. {
  213438. const ScopedLock sl (callbackLock);
  213439. isOpen_ = false;
  213440. isStarted = false;
  213441. needToReset = false;
  213442. isReSync = false;
  213443. log ("ASIO - stopping");
  213444. if (asioObject != 0)
  213445. {
  213446. Thread::sleep (20);
  213447. asioObject->stop();
  213448. Thread::sleep (10);
  213449. asioObject->disposeBuffers();
  213450. }
  213451. Thread::sleep (10);
  213452. }
  213453. }
  213454. bool isOpen()
  213455. {
  213456. return isOpen_ || insideControlPanelModalLoop;
  213457. }
  213458. int getCurrentBufferSizeSamples()
  213459. {
  213460. return currentBlockSizeSamples;
  213461. }
  213462. double getCurrentSampleRate()
  213463. {
  213464. return currentSampleRate;
  213465. }
  213466. const BigInteger getActiveOutputChannels() const
  213467. {
  213468. return currentChansOut;
  213469. }
  213470. const BigInteger getActiveInputChannels() const
  213471. {
  213472. return currentChansIn;
  213473. }
  213474. int getCurrentBitDepth()
  213475. {
  213476. return currentBitDepth;
  213477. }
  213478. int getOutputLatencyInSamples()
  213479. {
  213480. return outputLatency + currentBlockSizeSamples / 4;
  213481. }
  213482. int getInputLatencyInSamples()
  213483. {
  213484. return inputLatency + currentBlockSizeSamples / 4;
  213485. }
  213486. void start (AudioIODeviceCallback* callback)
  213487. {
  213488. if (callback != 0)
  213489. {
  213490. callback->audioDeviceAboutToStart (this);
  213491. const ScopedLock sl (callbackLock);
  213492. currentCallback = callback;
  213493. }
  213494. }
  213495. void stop()
  213496. {
  213497. AudioIODeviceCallback* const lastCallback = currentCallback;
  213498. {
  213499. const ScopedLock sl (callbackLock);
  213500. currentCallback = 0;
  213501. }
  213502. if (lastCallback != 0)
  213503. lastCallback->audioDeviceStopped();
  213504. }
  213505. bool isPlaying()
  213506. {
  213507. return isASIOOpen && (currentCallback != 0);
  213508. }
  213509. const String getLastError()
  213510. {
  213511. return error;
  213512. }
  213513. bool hasControlPanel() const
  213514. {
  213515. return true;
  213516. }
  213517. bool showControlPanel()
  213518. {
  213519. log ("ASIO - showing control panel");
  213520. Component modalWindow (String::empty);
  213521. modalWindow.setOpaque (true);
  213522. modalWindow.addToDesktop (0);
  213523. modalWindow.enterModalState();
  213524. bool done = false;
  213525. JUCE_TRY
  213526. {
  213527. // are there are devices that need to be closed before showing their control panel?
  213528. // close();
  213529. insideControlPanelModalLoop = true;
  213530. const uint32 started = Time::getMillisecondCounter();
  213531. if (asioObject != 0)
  213532. {
  213533. asioObject->controlPanel();
  213534. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213535. log ("spent: " + String (spent));
  213536. if (spent > 300)
  213537. {
  213538. shouldUsePreferredSize = true;
  213539. done = true;
  213540. }
  213541. }
  213542. }
  213543. JUCE_CATCH_ALL
  213544. insideControlPanelModalLoop = false;
  213545. return done;
  213546. }
  213547. void resetRequest() throw()
  213548. {
  213549. needToReset = true;
  213550. }
  213551. void resyncRequest() throw()
  213552. {
  213553. needToReset = true;
  213554. isReSync = true;
  213555. }
  213556. void timerCallback()
  213557. {
  213558. if (! insideControlPanelModalLoop)
  213559. {
  213560. stopTimer();
  213561. // used to cause a reset
  213562. log ("! ASIO restart request!");
  213563. if (isOpen_)
  213564. {
  213565. AudioIODeviceCallback* const oldCallback = currentCallback;
  213566. close();
  213567. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213568. currentSampleRate, currentBlockSizeSamples);
  213569. if (oldCallback != 0)
  213570. start (oldCallback);
  213571. }
  213572. }
  213573. else
  213574. {
  213575. startTimer (100);
  213576. }
  213577. }
  213578. juce_UseDebuggingNewOperator
  213579. private:
  213580. IASIO* volatile asioObject;
  213581. ASIOCallbacks callbacks;
  213582. void* windowHandle;
  213583. CLSID classId;
  213584. const String optionalDllForDirectLoading;
  213585. String error;
  213586. long totalNumInputChans, totalNumOutputChans;
  213587. StringArray inputChannelNames, outputChannelNames;
  213588. Array<int> sampleRates, bufferSizes;
  213589. long inputLatency, outputLatency;
  213590. long minSize, maxSize, preferredSize, granularity;
  213591. int volatile currentBlockSizeSamples;
  213592. int volatile currentBitDepth;
  213593. double volatile currentSampleRate;
  213594. BigInteger currentChansOut, currentChansIn;
  213595. AudioIODeviceCallback* volatile currentCallback;
  213596. CriticalSection callbackLock;
  213597. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213598. float* inBuffers [maxASIOChannels];
  213599. float* outBuffers [maxASIOChannels];
  213600. int inputChannelBitDepths [maxASIOChannels];
  213601. int outputChannelBitDepths [maxASIOChannels];
  213602. int inputChannelBytesPerSample [maxASIOChannels];
  213603. int outputChannelBytesPerSample [maxASIOChannels];
  213604. bool inputChannelIsFloat [maxASIOChannels];
  213605. bool outputChannelIsFloat [maxASIOChannels];
  213606. bool inputChannelLittleEndian [maxASIOChannels];
  213607. bool outputChannelLittleEndian [maxASIOChannels];
  213608. WaitableEvent event1;
  213609. HeapBlock <float> tempBuffer;
  213610. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213611. bool isOpen_, isStarted;
  213612. bool volatile isASIOOpen;
  213613. bool volatile calledback;
  213614. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213615. bool volatile insideControlPanelModalLoop;
  213616. bool volatile shouldUsePreferredSize;
  213617. void removeCurrentDriver()
  213618. {
  213619. if (asioObject != 0)
  213620. {
  213621. asioObject->Release();
  213622. asioObject = 0;
  213623. }
  213624. }
  213625. bool loadDriver()
  213626. {
  213627. removeCurrentDriver();
  213628. JUCE_TRY
  213629. {
  213630. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213631. classId, (void**) &asioObject) == S_OK)
  213632. {
  213633. return true;
  213634. }
  213635. // If a class isn't registered but we have a path for it, we can fallback to
  213636. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213637. if (optionalDllForDirectLoading.isNotEmpty())
  213638. {
  213639. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213640. if (h != 0)
  213641. {
  213642. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213643. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213644. if (dllGetClassObject != 0)
  213645. {
  213646. IClassFactory* classFactory = 0;
  213647. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213648. if (classFactory != 0)
  213649. {
  213650. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213651. classFactory->Release();
  213652. }
  213653. return asioObject != 0;
  213654. }
  213655. }
  213656. }
  213657. }
  213658. JUCE_CATCH_ALL
  213659. asioObject = 0;
  213660. return false;
  213661. }
  213662. const String initDriver()
  213663. {
  213664. if (asioObject != 0)
  213665. {
  213666. char buffer [256];
  213667. zeromem (buffer, sizeof (buffer));
  213668. if (! asioObject->init (windowHandle))
  213669. {
  213670. asioObject->getErrorMessage (buffer);
  213671. return String (buffer, sizeof (buffer) - 1);
  213672. }
  213673. // just in case any daft drivers expect this to be called..
  213674. asioObject->getDriverName (buffer);
  213675. return String::empty;
  213676. }
  213677. return "No Driver";
  213678. }
  213679. const String openDevice()
  213680. {
  213681. // use this in case the driver starts opening dialog boxes..
  213682. Component modalWindow (String::empty);
  213683. modalWindow.setOpaque (true);
  213684. modalWindow.addToDesktop (0);
  213685. modalWindow.enterModalState();
  213686. // open the device and get its info..
  213687. log ("opening ASIO device: " + getName());
  213688. needToReset = false;
  213689. isReSync = false;
  213690. outputChannelNames.clear();
  213691. inputChannelNames.clear();
  213692. bufferSizes.clear();
  213693. sampleRates.clear();
  213694. isASIOOpen = false;
  213695. isOpen_ = false;
  213696. totalNumInputChans = 0;
  213697. totalNumOutputChans = 0;
  213698. numActiveInputChans = 0;
  213699. numActiveOutputChans = 0;
  213700. currentCallback = 0;
  213701. error = String::empty;
  213702. if (getName().isEmpty())
  213703. return error;
  213704. long err = 0;
  213705. if (loadDriver())
  213706. {
  213707. if ((error = initDriver()).isEmpty())
  213708. {
  213709. numActiveInputChans = 0;
  213710. numActiveOutputChans = 0;
  213711. totalNumInputChans = 0;
  213712. totalNumOutputChans = 0;
  213713. if (asioObject != 0
  213714. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213715. {
  213716. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213717. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213718. {
  213719. // find a list of buffer sizes..
  213720. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213721. if (granularity >= 0)
  213722. {
  213723. granularity = jmax (1, (int) granularity);
  213724. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213725. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213726. }
  213727. else if (granularity < 0)
  213728. {
  213729. for (int i = 0; i < 18; ++i)
  213730. {
  213731. const int s = (1 << i);
  213732. if (s >= minSize && s <= maxSize)
  213733. bufferSizes.add (s);
  213734. }
  213735. }
  213736. if (! bufferSizes.contains (preferredSize))
  213737. bufferSizes.insert (0, preferredSize);
  213738. double currentRate = 0;
  213739. asioObject->getSampleRate (&currentRate);
  213740. if (currentRate <= 0.0 || currentRate > 192001.0)
  213741. {
  213742. log ("setting sample rate");
  213743. err = asioObject->setSampleRate (44100.0);
  213744. if (err != 0)
  213745. {
  213746. logError ("setting sample rate", err);
  213747. }
  213748. asioObject->getSampleRate (&currentRate);
  213749. }
  213750. currentSampleRate = currentRate;
  213751. postOutput = (asioObject->outputReady() == 0);
  213752. if (postOutput)
  213753. {
  213754. log ("ASIO outputReady = ok");
  213755. }
  213756. updateSampleRates();
  213757. // ..because cubase does it at this point
  213758. inputLatency = outputLatency = 0;
  213759. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213760. {
  213761. log ("ASIO - no latencies");
  213762. }
  213763. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213764. // create some dummy buffers now.. because cubase does..
  213765. numActiveInputChans = 0;
  213766. numActiveOutputChans = 0;
  213767. ASIOBufferInfo* info = bufferInfos;
  213768. int i, numChans = 0;
  213769. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213770. {
  213771. info->isInput = 1;
  213772. info->channelNum = i;
  213773. info->buffers[0] = info->buffers[1] = 0;
  213774. ++info;
  213775. ++numChans;
  213776. }
  213777. const int outputBufferIndex = numChans;
  213778. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213779. {
  213780. info->isInput = 0;
  213781. info->channelNum = i;
  213782. info->buffers[0] = info->buffers[1] = 0;
  213783. ++info;
  213784. ++numChans;
  213785. }
  213786. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213787. if (currentASIODev[0] == this)
  213788. {
  213789. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213790. callbacks.asioMessage = &asioMessagesCallback0;
  213791. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213792. }
  213793. else if (currentASIODev[1] == this)
  213794. {
  213795. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213796. callbacks.asioMessage = &asioMessagesCallback1;
  213797. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213798. }
  213799. else if (currentASIODev[2] == this)
  213800. {
  213801. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213802. callbacks.asioMessage = &asioMessagesCallback2;
  213803. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213804. }
  213805. else
  213806. {
  213807. jassertfalse;
  213808. }
  213809. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213810. if (preferredSize > 0)
  213811. {
  213812. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213813. if (err != 0)
  213814. {
  213815. logError ("dummy buffers", err);
  213816. }
  213817. }
  213818. long newInps = 0, newOuts = 0;
  213819. asioObject->getChannels (&newInps, &newOuts);
  213820. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213821. {
  213822. totalNumInputChans = newInps;
  213823. totalNumOutputChans = newOuts;
  213824. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213825. }
  213826. updateSampleRates();
  213827. ASIOChannelInfo channelInfo;
  213828. channelInfo.type = 0;
  213829. for (i = 0; i < totalNumInputChans; ++i)
  213830. {
  213831. zerostruct (channelInfo);
  213832. channelInfo.channel = i;
  213833. channelInfo.isInput = 1;
  213834. asioObject->getChannelInfo (&channelInfo);
  213835. inputChannelNames.add (String (channelInfo.name));
  213836. }
  213837. for (i = 0; i < totalNumOutputChans; ++i)
  213838. {
  213839. zerostruct (channelInfo);
  213840. channelInfo.channel = i;
  213841. channelInfo.isInput = 0;
  213842. asioObject->getChannelInfo (&channelInfo);
  213843. outputChannelNames.add (String (channelInfo.name));
  213844. typeToFormatParameters (channelInfo.type,
  213845. outputChannelBitDepths[i],
  213846. outputChannelBytesPerSample[i],
  213847. outputChannelIsFloat[i],
  213848. outputChannelLittleEndian[i]);
  213849. if (i < 2)
  213850. {
  213851. // clear the channels that are used with the dummy stuff
  213852. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213853. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213854. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213855. }
  213856. }
  213857. outputChannelNames.trim();
  213858. inputChannelNames.trim();
  213859. outputChannelNames.appendNumbersToDuplicates (false, true);
  213860. inputChannelNames.appendNumbersToDuplicates (false, true);
  213861. // start and stop because cubase does it..
  213862. asioObject->getLatencies (&inputLatency, &outputLatency);
  213863. if ((err = asioObject->start()) != 0)
  213864. {
  213865. // ignore an error here, as it might start later after setting other stuff up
  213866. logError ("ASIO start", err);
  213867. }
  213868. Thread::sleep (100);
  213869. asioObject->stop();
  213870. }
  213871. else
  213872. {
  213873. error = "Can't detect buffer sizes";
  213874. }
  213875. }
  213876. else
  213877. {
  213878. error = "Can't detect asio channels";
  213879. }
  213880. }
  213881. }
  213882. else
  213883. {
  213884. error = "No such device";
  213885. }
  213886. if (error.isNotEmpty())
  213887. {
  213888. logError (error, err);
  213889. if (asioObject != 0)
  213890. asioObject->disposeBuffers();
  213891. removeCurrentDriver();
  213892. isASIOOpen = false;
  213893. }
  213894. else
  213895. {
  213896. isASIOOpen = true;
  213897. log ("ASIO device open");
  213898. }
  213899. isOpen_ = false;
  213900. needToReset = false;
  213901. isReSync = false;
  213902. return error;
  213903. }
  213904. void callback (const long index)
  213905. {
  213906. if (isStarted)
  213907. {
  213908. bufferIndex = index;
  213909. processBuffer();
  213910. }
  213911. else
  213912. {
  213913. if (postOutput && (asioObject != 0))
  213914. asioObject->outputReady();
  213915. }
  213916. calledback = true;
  213917. }
  213918. void processBuffer()
  213919. {
  213920. const ASIOBufferInfo* const infos = bufferInfos;
  213921. const int bi = bufferIndex;
  213922. const ScopedLock sl (callbackLock);
  213923. if (needToReset)
  213924. {
  213925. needToReset = false;
  213926. if (isReSync)
  213927. {
  213928. log ("! ASIO resync");
  213929. isReSync = false;
  213930. }
  213931. else
  213932. {
  213933. startTimer (20);
  213934. }
  213935. }
  213936. if (bi >= 0)
  213937. {
  213938. const int samps = currentBlockSizeSamples;
  213939. if (currentCallback != 0)
  213940. {
  213941. int i;
  213942. for (i = 0; i < numActiveInputChans; ++i)
  213943. {
  213944. float* const dst = inBuffers[i];
  213945. jassert (dst != 0);
  213946. const char* const src = (const char*) (infos[i].buffers[bi]);
  213947. if (inputChannelIsFloat[i])
  213948. {
  213949. memcpy (dst, src, samps * sizeof (float));
  213950. }
  213951. else
  213952. {
  213953. jassert (dst == tempBuffer + (samps * i));
  213954. switch (inputChannelBitDepths[i])
  213955. {
  213956. case 16:
  213957. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213958. samps, inputChannelLittleEndian[i]);
  213959. break;
  213960. case 24:
  213961. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213962. samps, inputChannelLittleEndian[i]);
  213963. break;
  213964. case 32:
  213965. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213966. samps, inputChannelLittleEndian[i]);
  213967. break;
  213968. case 64:
  213969. jassertfalse;
  213970. break;
  213971. }
  213972. }
  213973. }
  213974. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  213975. numActiveInputChans,
  213976. outBuffers,
  213977. numActiveOutputChans,
  213978. samps);
  213979. for (i = 0; i < numActiveOutputChans; ++i)
  213980. {
  213981. float* const src = outBuffers[i];
  213982. jassert (src != 0);
  213983. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213984. if (outputChannelIsFloat[i])
  213985. {
  213986. memcpy (dst, src, samps * sizeof (float));
  213987. }
  213988. else
  213989. {
  213990. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213991. switch (outputChannelBitDepths[i])
  213992. {
  213993. case 16:
  213994. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213995. samps, outputChannelLittleEndian[i]);
  213996. break;
  213997. case 24:
  213998. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213999. samps, outputChannelLittleEndian[i]);
  214000. break;
  214001. case 32:
  214002. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  214003. samps, outputChannelLittleEndian[i]);
  214004. break;
  214005. case 64:
  214006. jassertfalse;
  214007. break;
  214008. }
  214009. }
  214010. }
  214011. }
  214012. else
  214013. {
  214014. for (int i = 0; i < numActiveOutputChans; ++i)
  214015. {
  214016. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  214017. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  214018. }
  214019. }
  214020. }
  214021. if (postOutput)
  214022. asioObject->outputReady();
  214023. }
  214024. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  214025. {
  214026. if (currentASIODev[0] != 0)
  214027. currentASIODev[0]->callback (index);
  214028. return 0;
  214029. }
  214030. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  214031. {
  214032. if (currentASIODev[1] != 0)
  214033. currentASIODev[1]->callback (index);
  214034. return 0;
  214035. }
  214036. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  214037. {
  214038. if (currentASIODev[2] != 0)
  214039. currentASIODev[2]->callback (index);
  214040. return 0;
  214041. }
  214042. static void bufferSwitchCallback0 (long index, long)
  214043. {
  214044. if (currentASIODev[0] != 0)
  214045. currentASIODev[0]->callback (index);
  214046. }
  214047. static void bufferSwitchCallback1 (long index, long)
  214048. {
  214049. if (currentASIODev[1] != 0)
  214050. currentASIODev[1]->callback (index);
  214051. }
  214052. static void bufferSwitchCallback2 (long index, long)
  214053. {
  214054. if (currentASIODev[2] != 0)
  214055. currentASIODev[2]->callback (index);
  214056. }
  214057. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  214058. {
  214059. return asioMessagesCallback (selector, value, 0);
  214060. }
  214061. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  214062. {
  214063. return asioMessagesCallback (selector, value, 1);
  214064. }
  214065. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  214066. {
  214067. return asioMessagesCallback (selector, value, 2);
  214068. }
  214069. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  214070. {
  214071. switch (selector)
  214072. {
  214073. case kAsioSelectorSupported:
  214074. if (value == kAsioResetRequest
  214075. || value == kAsioEngineVersion
  214076. || value == kAsioResyncRequest
  214077. || value == kAsioLatenciesChanged
  214078. || value == kAsioSupportsInputMonitor)
  214079. return 1;
  214080. break;
  214081. case kAsioBufferSizeChange:
  214082. break;
  214083. case kAsioResetRequest:
  214084. if (currentASIODev[deviceIndex] != 0)
  214085. currentASIODev[deviceIndex]->resetRequest();
  214086. return 1;
  214087. case kAsioResyncRequest:
  214088. if (currentASIODev[deviceIndex] != 0)
  214089. currentASIODev[deviceIndex]->resyncRequest();
  214090. return 1;
  214091. case kAsioLatenciesChanged:
  214092. return 1;
  214093. case kAsioEngineVersion:
  214094. return 2;
  214095. case kAsioSupportsTimeInfo:
  214096. case kAsioSupportsTimeCode:
  214097. return 0;
  214098. }
  214099. return 0;
  214100. }
  214101. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  214102. {
  214103. }
  214104. static void convertInt16ToFloat (const char* src,
  214105. float* dest,
  214106. const int srcStrideBytes,
  214107. int numSamples,
  214108. const bool littleEndian) throw()
  214109. {
  214110. const double g = 1.0 / 32768.0;
  214111. if (littleEndian)
  214112. {
  214113. while (--numSamples >= 0)
  214114. {
  214115. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  214116. src += srcStrideBytes;
  214117. }
  214118. }
  214119. else
  214120. {
  214121. while (--numSamples >= 0)
  214122. {
  214123. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  214124. src += srcStrideBytes;
  214125. }
  214126. }
  214127. }
  214128. static void convertFloatToInt16 (const float* src,
  214129. char* dest,
  214130. const int dstStrideBytes,
  214131. int numSamples,
  214132. const bool littleEndian) throw()
  214133. {
  214134. const double maxVal = (double) 0x7fff;
  214135. if (littleEndian)
  214136. {
  214137. while (--numSamples >= 0)
  214138. {
  214139. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214140. dest += dstStrideBytes;
  214141. }
  214142. }
  214143. else
  214144. {
  214145. while (--numSamples >= 0)
  214146. {
  214147. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214148. dest += dstStrideBytes;
  214149. }
  214150. }
  214151. }
  214152. static void convertInt24ToFloat (const char* src,
  214153. float* dest,
  214154. const int srcStrideBytes,
  214155. int numSamples,
  214156. const bool littleEndian) throw()
  214157. {
  214158. const double g = 1.0 / 0x7fffff;
  214159. if (littleEndian)
  214160. {
  214161. while (--numSamples >= 0)
  214162. {
  214163. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  214164. src += srcStrideBytes;
  214165. }
  214166. }
  214167. else
  214168. {
  214169. while (--numSamples >= 0)
  214170. {
  214171. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  214172. src += srcStrideBytes;
  214173. }
  214174. }
  214175. }
  214176. static void convertFloatToInt24 (const float* src,
  214177. char* dest,
  214178. const int dstStrideBytes,
  214179. int numSamples,
  214180. const bool littleEndian) throw()
  214181. {
  214182. const double maxVal = (double) 0x7fffff;
  214183. if (littleEndian)
  214184. {
  214185. while (--numSamples >= 0)
  214186. {
  214187. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214188. dest += dstStrideBytes;
  214189. }
  214190. }
  214191. else
  214192. {
  214193. while (--numSamples >= 0)
  214194. {
  214195. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214196. dest += dstStrideBytes;
  214197. }
  214198. }
  214199. }
  214200. static void convertInt32ToFloat (const char* src,
  214201. float* dest,
  214202. const int srcStrideBytes,
  214203. int numSamples,
  214204. const bool littleEndian) throw()
  214205. {
  214206. const double g = 1.0 / 0x7fffffff;
  214207. if (littleEndian)
  214208. {
  214209. while (--numSamples >= 0)
  214210. {
  214211. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  214212. src += srcStrideBytes;
  214213. }
  214214. }
  214215. else
  214216. {
  214217. while (--numSamples >= 0)
  214218. {
  214219. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  214220. src += srcStrideBytes;
  214221. }
  214222. }
  214223. }
  214224. static void convertFloatToInt32 (const float* src,
  214225. char* dest,
  214226. const int dstStrideBytes,
  214227. int numSamples,
  214228. const bool littleEndian) throw()
  214229. {
  214230. const double maxVal = (double) 0x7fffffff;
  214231. if (littleEndian)
  214232. {
  214233. while (--numSamples >= 0)
  214234. {
  214235. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214236. dest += dstStrideBytes;
  214237. }
  214238. }
  214239. else
  214240. {
  214241. while (--numSamples >= 0)
  214242. {
  214243. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214244. dest += dstStrideBytes;
  214245. }
  214246. }
  214247. }
  214248. static void typeToFormatParameters (const long type,
  214249. int& bitDepth,
  214250. int& byteStride,
  214251. bool& formatIsFloat,
  214252. bool& littleEndian) throw()
  214253. {
  214254. bitDepth = 0;
  214255. littleEndian = false;
  214256. formatIsFloat = false;
  214257. switch (type)
  214258. {
  214259. case ASIOSTInt16MSB:
  214260. case ASIOSTInt16LSB:
  214261. case ASIOSTInt32MSB16:
  214262. case ASIOSTInt32LSB16:
  214263. bitDepth = 16; break;
  214264. case ASIOSTFloat32MSB:
  214265. case ASIOSTFloat32LSB:
  214266. formatIsFloat = true;
  214267. bitDepth = 32; break;
  214268. case ASIOSTInt32MSB:
  214269. case ASIOSTInt32LSB:
  214270. bitDepth = 32; break;
  214271. case ASIOSTInt24MSB:
  214272. case ASIOSTInt24LSB:
  214273. case ASIOSTInt32MSB24:
  214274. case ASIOSTInt32LSB24:
  214275. case ASIOSTInt32MSB18:
  214276. case ASIOSTInt32MSB20:
  214277. case ASIOSTInt32LSB18:
  214278. case ASIOSTInt32LSB20:
  214279. bitDepth = 24; break;
  214280. case ASIOSTFloat64MSB:
  214281. case ASIOSTFloat64LSB:
  214282. default:
  214283. bitDepth = 64;
  214284. break;
  214285. }
  214286. switch (type)
  214287. {
  214288. case ASIOSTInt16MSB:
  214289. case ASIOSTInt32MSB16:
  214290. case ASIOSTFloat32MSB:
  214291. case ASIOSTFloat64MSB:
  214292. case ASIOSTInt32MSB:
  214293. case ASIOSTInt32MSB18:
  214294. case ASIOSTInt32MSB20:
  214295. case ASIOSTInt32MSB24:
  214296. case ASIOSTInt24MSB:
  214297. littleEndian = false; break;
  214298. case ASIOSTInt16LSB:
  214299. case ASIOSTInt32LSB16:
  214300. case ASIOSTFloat32LSB:
  214301. case ASIOSTFloat64LSB:
  214302. case ASIOSTInt32LSB:
  214303. case ASIOSTInt32LSB18:
  214304. case ASIOSTInt32LSB20:
  214305. case ASIOSTInt32LSB24:
  214306. case ASIOSTInt24LSB:
  214307. littleEndian = true; break;
  214308. default:
  214309. break;
  214310. }
  214311. switch (type)
  214312. {
  214313. case ASIOSTInt16LSB:
  214314. case ASIOSTInt16MSB:
  214315. byteStride = 2; break;
  214316. case ASIOSTInt24LSB:
  214317. case ASIOSTInt24MSB:
  214318. byteStride = 3; break;
  214319. case ASIOSTInt32MSB16:
  214320. case ASIOSTInt32LSB16:
  214321. case ASIOSTInt32MSB:
  214322. case ASIOSTInt32MSB18:
  214323. case ASIOSTInt32MSB20:
  214324. case ASIOSTInt32MSB24:
  214325. case ASIOSTInt32LSB:
  214326. case ASIOSTInt32LSB18:
  214327. case ASIOSTInt32LSB20:
  214328. case ASIOSTInt32LSB24:
  214329. case ASIOSTFloat32LSB:
  214330. case ASIOSTFloat32MSB:
  214331. byteStride = 4; break;
  214332. case ASIOSTFloat64MSB:
  214333. case ASIOSTFloat64LSB:
  214334. byteStride = 8; break;
  214335. default:
  214336. break;
  214337. }
  214338. }
  214339. };
  214340. class ASIOAudioIODeviceType : public AudioIODeviceType
  214341. {
  214342. public:
  214343. ASIOAudioIODeviceType()
  214344. : AudioIODeviceType ("ASIO"),
  214345. hasScanned (false)
  214346. {
  214347. CoInitialize (0);
  214348. }
  214349. ~ASIOAudioIODeviceType()
  214350. {
  214351. }
  214352. void scanForDevices()
  214353. {
  214354. hasScanned = true;
  214355. deviceNames.clear();
  214356. classIds.clear();
  214357. HKEY hk = 0;
  214358. int index = 0;
  214359. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214360. {
  214361. for (;;)
  214362. {
  214363. char name [256];
  214364. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214365. {
  214366. addDriverInfo (name, hk);
  214367. }
  214368. else
  214369. {
  214370. break;
  214371. }
  214372. }
  214373. RegCloseKey (hk);
  214374. }
  214375. }
  214376. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214377. {
  214378. jassert (hasScanned); // need to call scanForDevices() before doing this
  214379. return deviceNames;
  214380. }
  214381. int getDefaultDeviceIndex (bool) const
  214382. {
  214383. jassert (hasScanned); // need to call scanForDevices() before doing this
  214384. for (int i = deviceNames.size(); --i >= 0;)
  214385. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214386. return i; // asio4all is a safe choice for a default..
  214387. #if JUCE_DEBUG
  214388. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214389. return 1; // (the digi m-box driver crashes the app when you run
  214390. // it in the debugger, which can be a bit annoying)
  214391. #endif
  214392. return 0;
  214393. }
  214394. static int findFreeSlot()
  214395. {
  214396. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214397. if (currentASIODev[i] == 0)
  214398. return i;
  214399. jassertfalse; // unfortunately you can only have a finite number
  214400. // of ASIO devices open at the same time..
  214401. return -1;
  214402. }
  214403. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214404. {
  214405. jassert (hasScanned); // need to call scanForDevices() before doing this
  214406. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214407. }
  214408. bool hasSeparateInputsAndOutputs() const { return false; }
  214409. AudioIODevice* createDevice (const String& outputDeviceName,
  214410. const String& inputDeviceName)
  214411. {
  214412. // ASIO can't open two different devices for input and output - they must be the same one.
  214413. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214414. jassert (hasScanned); // need to call scanForDevices() before doing this
  214415. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214416. : inputDeviceName);
  214417. if (index >= 0)
  214418. {
  214419. const int freeSlot = findFreeSlot();
  214420. if (freeSlot >= 0)
  214421. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214422. }
  214423. return 0;
  214424. }
  214425. juce_UseDebuggingNewOperator
  214426. private:
  214427. StringArray deviceNames;
  214428. OwnedArray <CLSID> classIds;
  214429. bool hasScanned;
  214430. static bool checkClassIsOk (const String& classId)
  214431. {
  214432. HKEY hk = 0;
  214433. bool ok = false;
  214434. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214435. {
  214436. int index = 0;
  214437. for (;;)
  214438. {
  214439. WCHAR buf [512];
  214440. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214441. {
  214442. if (classId.equalsIgnoreCase (buf))
  214443. {
  214444. HKEY subKey, pathKey;
  214445. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214446. {
  214447. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214448. {
  214449. WCHAR pathName [1024];
  214450. DWORD dtype = REG_SZ;
  214451. DWORD dsize = sizeof (pathName);
  214452. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214453. ok = File (pathName).exists();
  214454. RegCloseKey (pathKey);
  214455. }
  214456. RegCloseKey (subKey);
  214457. }
  214458. break;
  214459. }
  214460. }
  214461. else
  214462. {
  214463. break;
  214464. }
  214465. }
  214466. RegCloseKey (hk);
  214467. }
  214468. return ok;
  214469. }
  214470. void addDriverInfo (const String& keyName, HKEY hk)
  214471. {
  214472. HKEY subKey;
  214473. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214474. {
  214475. WCHAR buf [256];
  214476. zerostruct (buf);
  214477. DWORD dtype = REG_SZ;
  214478. DWORD dsize = sizeof (buf);
  214479. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214480. {
  214481. if (dsize > 0 && checkClassIsOk (buf))
  214482. {
  214483. CLSID classId;
  214484. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214485. {
  214486. dtype = REG_SZ;
  214487. dsize = sizeof (buf);
  214488. String deviceName;
  214489. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214490. deviceName = buf;
  214491. else
  214492. deviceName = keyName;
  214493. log ("found " + deviceName);
  214494. deviceNames.add (deviceName);
  214495. classIds.add (new CLSID (classId));
  214496. }
  214497. }
  214498. RegCloseKey (subKey);
  214499. }
  214500. }
  214501. }
  214502. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214503. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214504. };
  214505. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214506. {
  214507. return new ASIOAudioIODeviceType();
  214508. }
  214509. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214510. void* guid,
  214511. const String& optionalDllForDirectLoading)
  214512. {
  214513. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214514. if (freeSlot < 0)
  214515. return 0;
  214516. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214517. }
  214518. #undef log
  214519. #endif
  214520. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214521. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214522. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214523. // compiled on its own).
  214524. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214525. END_JUCE_NAMESPACE
  214526. extern "C"
  214527. {
  214528. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214529. typedef struct typeDSBUFFERDESC
  214530. {
  214531. DWORD dwSize;
  214532. DWORD dwFlags;
  214533. DWORD dwBufferBytes;
  214534. DWORD dwReserved;
  214535. LPWAVEFORMATEX lpwfxFormat;
  214536. GUID guid3DAlgorithm;
  214537. } DSBUFFERDESC;
  214538. struct IDirectSoundBuffer;
  214539. #undef INTERFACE
  214540. #define INTERFACE IDirectSound
  214541. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214542. {
  214543. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214544. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214545. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214546. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214547. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214548. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214549. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214550. STDMETHOD(Compact) (THIS) PURE;
  214551. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214552. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214553. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214554. };
  214555. #undef INTERFACE
  214556. #define INTERFACE IDirectSoundBuffer
  214557. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214558. {
  214559. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214560. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214561. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214562. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214563. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214564. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214565. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214566. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214567. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214568. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214569. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214570. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214571. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214572. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214573. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214574. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214575. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214576. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214577. STDMETHOD(Stop) (THIS) PURE;
  214578. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214579. STDMETHOD(Restore) (THIS) PURE;
  214580. };
  214581. typedef struct typeDSCBUFFERDESC
  214582. {
  214583. DWORD dwSize;
  214584. DWORD dwFlags;
  214585. DWORD dwBufferBytes;
  214586. DWORD dwReserved;
  214587. LPWAVEFORMATEX lpwfxFormat;
  214588. } DSCBUFFERDESC;
  214589. struct IDirectSoundCaptureBuffer;
  214590. #undef INTERFACE
  214591. #define INTERFACE IDirectSoundCapture
  214592. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214593. {
  214594. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214595. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214596. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214597. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214598. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214599. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214600. };
  214601. #undef INTERFACE
  214602. #define INTERFACE IDirectSoundCaptureBuffer
  214603. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214604. {
  214605. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214606. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214607. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214608. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214609. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214610. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214611. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214612. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214613. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214614. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214615. STDMETHOD(Stop) (THIS) PURE;
  214616. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214617. };
  214618. };
  214619. BEGIN_JUCE_NAMESPACE
  214620. static const String getDSErrorMessage (HRESULT hr)
  214621. {
  214622. const char* result = 0;
  214623. switch (hr)
  214624. {
  214625. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214626. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214627. case E_INVALIDARG: result = "Invalid parameter"; break;
  214628. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214629. case E_FAIL: result = "Generic error"; break;
  214630. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214631. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214632. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214633. case E_NOTIMPL: result = "Unsupported function"; break;
  214634. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214635. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214636. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214637. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214638. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214639. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214640. case E_NOINTERFACE: result = "No interface"; break;
  214641. case S_OK: result = "No error"; break;
  214642. default: return "Unknown error: " + String ((int) hr);
  214643. }
  214644. return result;
  214645. }
  214646. #define DS_DEBUGGING 1
  214647. #ifdef DS_DEBUGGING
  214648. #define CATCH JUCE_CATCH_EXCEPTION
  214649. #undef log
  214650. #define log(a) Logger::writeToLog(a);
  214651. #undef logError
  214652. #define logError(a) logDSError(a, __LINE__);
  214653. static void logDSError (HRESULT hr, int lineNum)
  214654. {
  214655. if (hr != S_OK)
  214656. {
  214657. String error ("DS error at line ");
  214658. error << lineNum << " - " << getDSErrorMessage (hr);
  214659. log (error);
  214660. }
  214661. }
  214662. #else
  214663. #define CATCH JUCE_CATCH_ALL
  214664. #define log(a)
  214665. #define logError(a)
  214666. #endif
  214667. #define DSOUND_FUNCTION(functionName, params) \
  214668. typedef HRESULT (WINAPI *type##functionName) params; \
  214669. static type##functionName ds##functionName = 0;
  214670. #define DSOUND_FUNCTION_LOAD(functionName) \
  214671. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214672. jassert (ds##functionName != 0);
  214673. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214674. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214675. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214676. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214677. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214678. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214679. static void initialiseDSoundFunctions()
  214680. {
  214681. if (dsDirectSoundCreate == 0)
  214682. {
  214683. HMODULE h = LoadLibraryA ("dsound.dll");
  214684. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214685. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214686. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214687. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214688. }
  214689. }
  214690. class DSoundInternalOutChannel
  214691. {
  214692. String name;
  214693. LPGUID guid;
  214694. int sampleRate, bufferSizeSamples;
  214695. float* leftBuffer;
  214696. float* rightBuffer;
  214697. IDirectSound* pDirectSound;
  214698. IDirectSoundBuffer* pOutputBuffer;
  214699. DWORD writeOffset;
  214700. int totalBytesPerBuffer;
  214701. int bytesPerBuffer;
  214702. unsigned int lastPlayCursor;
  214703. public:
  214704. int bitDepth;
  214705. bool doneFlag;
  214706. DSoundInternalOutChannel (const String& name_,
  214707. LPGUID guid_,
  214708. int rate,
  214709. int bufferSize,
  214710. float* left,
  214711. float* right)
  214712. : name (name_),
  214713. guid (guid_),
  214714. sampleRate (rate),
  214715. bufferSizeSamples (bufferSize),
  214716. leftBuffer (left),
  214717. rightBuffer (right),
  214718. pDirectSound (0),
  214719. pOutputBuffer (0),
  214720. bitDepth (16)
  214721. {
  214722. }
  214723. ~DSoundInternalOutChannel()
  214724. {
  214725. close();
  214726. }
  214727. void close()
  214728. {
  214729. HRESULT hr;
  214730. if (pOutputBuffer != 0)
  214731. {
  214732. JUCE_TRY
  214733. {
  214734. log ("closing dsound out: " + name);
  214735. hr = pOutputBuffer->Stop();
  214736. logError (hr);
  214737. }
  214738. CATCH
  214739. JUCE_TRY
  214740. {
  214741. hr = pOutputBuffer->Release();
  214742. logError (hr);
  214743. }
  214744. CATCH
  214745. pOutputBuffer = 0;
  214746. }
  214747. if (pDirectSound != 0)
  214748. {
  214749. JUCE_TRY
  214750. {
  214751. hr = pDirectSound->Release();
  214752. logError (hr);
  214753. }
  214754. CATCH
  214755. pDirectSound = 0;
  214756. }
  214757. }
  214758. const String open()
  214759. {
  214760. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214761. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214762. pDirectSound = 0;
  214763. pOutputBuffer = 0;
  214764. writeOffset = 0;
  214765. String error;
  214766. HRESULT hr = E_NOINTERFACE;
  214767. if (dsDirectSoundCreate != 0)
  214768. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214769. if (hr == S_OK)
  214770. {
  214771. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214772. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214773. const int numChannels = 2;
  214774. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214775. logError (hr);
  214776. if (hr == S_OK)
  214777. {
  214778. IDirectSoundBuffer* pPrimaryBuffer;
  214779. DSBUFFERDESC primaryDesc;
  214780. zerostruct (primaryDesc);
  214781. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214782. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214783. primaryDesc.dwBufferBytes = 0;
  214784. primaryDesc.lpwfxFormat = 0;
  214785. log ("opening dsound out step 2");
  214786. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214787. logError (hr);
  214788. if (hr == S_OK)
  214789. {
  214790. WAVEFORMATEX wfFormat;
  214791. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214792. wfFormat.nChannels = (unsigned short) numChannels;
  214793. wfFormat.nSamplesPerSec = sampleRate;
  214794. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214795. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214796. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214797. wfFormat.cbSize = 0;
  214798. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214799. logError (hr);
  214800. if (hr == S_OK)
  214801. {
  214802. DSBUFFERDESC secondaryDesc;
  214803. zerostruct (secondaryDesc);
  214804. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214805. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214806. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214807. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214808. secondaryDesc.lpwfxFormat = &wfFormat;
  214809. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214810. logError (hr);
  214811. if (hr == S_OK)
  214812. {
  214813. log ("opening dsound out step 3");
  214814. DWORD dwDataLen;
  214815. unsigned char* pDSBuffData;
  214816. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214817. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214818. logError (hr);
  214819. if (hr == S_OK)
  214820. {
  214821. zeromem (pDSBuffData, dwDataLen);
  214822. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214823. if (hr == S_OK)
  214824. {
  214825. hr = pOutputBuffer->SetCurrentPosition (0);
  214826. if (hr == S_OK)
  214827. {
  214828. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214829. if (hr == S_OK)
  214830. return String::empty;
  214831. }
  214832. }
  214833. }
  214834. }
  214835. }
  214836. }
  214837. }
  214838. }
  214839. error = getDSErrorMessage (hr);
  214840. close();
  214841. return error;
  214842. }
  214843. void synchronisePosition()
  214844. {
  214845. if (pOutputBuffer != 0)
  214846. {
  214847. DWORD playCursor;
  214848. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214849. }
  214850. }
  214851. bool service()
  214852. {
  214853. if (pOutputBuffer == 0)
  214854. return true;
  214855. DWORD playCursor, writeCursor;
  214856. for (;;)
  214857. {
  214858. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214859. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214860. {
  214861. pOutputBuffer->Restore();
  214862. continue;
  214863. }
  214864. if (hr == S_OK)
  214865. break;
  214866. logError (hr);
  214867. jassertfalse;
  214868. return true;
  214869. }
  214870. int playWriteGap = writeCursor - playCursor;
  214871. if (playWriteGap < 0)
  214872. playWriteGap += totalBytesPerBuffer;
  214873. int bytesEmpty = playCursor - writeOffset;
  214874. if (bytesEmpty < 0)
  214875. bytesEmpty += totalBytesPerBuffer;
  214876. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214877. {
  214878. writeOffset = writeCursor;
  214879. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214880. }
  214881. if (bytesEmpty >= bytesPerBuffer)
  214882. {
  214883. void* lpbuf1 = 0;
  214884. void* lpbuf2 = 0;
  214885. DWORD dwSize1 = 0;
  214886. DWORD dwSize2 = 0;
  214887. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214888. bytesPerBuffer,
  214889. &lpbuf1, &dwSize1,
  214890. &lpbuf2, &dwSize2, 0);
  214891. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214892. {
  214893. pOutputBuffer->Restore();
  214894. hr = pOutputBuffer->Lock (writeOffset,
  214895. bytesPerBuffer,
  214896. &lpbuf1, &dwSize1,
  214897. &lpbuf2, &dwSize2, 0);
  214898. }
  214899. if (hr == S_OK)
  214900. {
  214901. if (bitDepth == 16)
  214902. {
  214903. const float gainL = 32767.0f;
  214904. const float gainR = 32767.0f;
  214905. int* dest = static_cast<int*> (lpbuf1);
  214906. const float* left = leftBuffer;
  214907. const float* right = rightBuffer;
  214908. int samples1 = dwSize1 >> 2;
  214909. int samples2 = dwSize2 >> 2;
  214910. if (left == 0)
  214911. {
  214912. while (--samples1 >= 0)
  214913. {
  214914. int r = roundToInt (gainR * *right++);
  214915. if (r < -32768)
  214916. r = -32768;
  214917. else if (r > 32767)
  214918. r = 32767;
  214919. *dest++ = (r << 16);
  214920. }
  214921. dest = static_cast<int*> (lpbuf2);
  214922. while (--samples2 >= 0)
  214923. {
  214924. int r = roundToInt (gainR * *right++);
  214925. if (r < -32768)
  214926. r = -32768;
  214927. else if (r > 32767)
  214928. r = 32767;
  214929. *dest++ = (r << 16);
  214930. }
  214931. }
  214932. else if (right == 0)
  214933. {
  214934. while (--samples1 >= 0)
  214935. {
  214936. int l = roundToInt (gainL * *left++);
  214937. if (l < -32768)
  214938. l = -32768;
  214939. else if (l > 32767)
  214940. l = 32767;
  214941. l &= 0xffff;
  214942. *dest++ = l;
  214943. }
  214944. dest = static_cast<int*> (lpbuf2);
  214945. while (--samples2 >= 0)
  214946. {
  214947. int l = roundToInt (gainL * *left++);
  214948. if (l < -32768)
  214949. l = -32768;
  214950. else if (l > 32767)
  214951. l = 32767;
  214952. l &= 0xffff;
  214953. *dest++ = l;
  214954. }
  214955. }
  214956. else
  214957. {
  214958. while (--samples1 >= 0)
  214959. {
  214960. int l = roundToInt (gainL * *left++);
  214961. if (l < -32768)
  214962. l = -32768;
  214963. else if (l > 32767)
  214964. l = 32767;
  214965. l &= 0xffff;
  214966. int r = roundToInt (gainR * *right++);
  214967. if (r < -32768)
  214968. r = -32768;
  214969. else if (r > 32767)
  214970. r = 32767;
  214971. *dest++ = (r << 16) | l;
  214972. }
  214973. dest = static_cast<int*> (lpbuf2);
  214974. while (--samples2 >= 0)
  214975. {
  214976. int l = roundToInt (gainL * *left++);
  214977. if (l < -32768)
  214978. l = -32768;
  214979. else if (l > 32767)
  214980. l = 32767;
  214981. l &= 0xffff;
  214982. int r = roundToInt (gainR * *right++);
  214983. if (r < -32768)
  214984. r = -32768;
  214985. else if (r > 32767)
  214986. r = 32767;
  214987. *dest++ = (r << 16) | l;
  214988. }
  214989. }
  214990. }
  214991. else
  214992. {
  214993. jassertfalse;
  214994. }
  214995. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214996. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214997. }
  214998. else
  214999. {
  215000. jassertfalse;
  215001. logError (hr);
  215002. }
  215003. bytesEmpty -= bytesPerBuffer;
  215004. return true;
  215005. }
  215006. else
  215007. {
  215008. return false;
  215009. }
  215010. }
  215011. };
  215012. struct DSoundInternalInChannel
  215013. {
  215014. String name;
  215015. LPGUID guid;
  215016. int sampleRate, bufferSizeSamples;
  215017. float* leftBuffer;
  215018. float* rightBuffer;
  215019. IDirectSound* pDirectSound;
  215020. IDirectSoundCapture* pDirectSoundCapture;
  215021. IDirectSoundCaptureBuffer* pInputBuffer;
  215022. public:
  215023. unsigned int readOffset;
  215024. int bytesPerBuffer, totalBytesPerBuffer;
  215025. int bitDepth;
  215026. bool doneFlag;
  215027. DSoundInternalInChannel (const String& name_,
  215028. LPGUID guid_,
  215029. int rate,
  215030. int bufferSize,
  215031. float* left,
  215032. float* right)
  215033. : name (name_),
  215034. guid (guid_),
  215035. sampleRate (rate),
  215036. bufferSizeSamples (bufferSize),
  215037. leftBuffer (left),
  215038. rightBuffer (right),
  215039. pDirectSound (0),
  215040. pDirectSoundCapture (0),
  215041. pInputBuffer (0),
  215042. bitDepth (16)
  215043. {
  215044. }
  215045. ~DSoundInternalInChannel()
  215046. {
  215047. close();
  215048. }
  215049. void close()
  215050. {
  215051. HRESULT hr;
  215052. if (pInputBuffer != 0)
  215053. {
  215054. JUCE_TRY
  215055. {
  215056. log ("closing dsound in: " + name);
  215057. hr = pInputBuffer->Stop();
  215058. logError (hr);
  215059. }
  215060. CATCH
  215061. JUCE_TRY
  215062. {
  215063. hr = pInputBuffer->Release();
  215064. logError (hr);
  215065. }
  215066. CATCH
  215067. pInputBuffer = 0;
  215068. }
  215069. if (pDirectSoundCapture != 0)
  215070. {
  215071. JUCE_TRY
  215072. {
  215073. hr = pDirectSoundCapture->Release();
  215074. logError (hr);
  215075. }
  215076. CATCH
  215077. pDirectSoundCapture = 0;
  215078. }
  215079. if (pDirectSound != 0)
  215080. {
  215081. JUCE_TRY
  215082. {
  215083. hr = pDirectSound->Release();
  215084. logError (hr);
  215085. }
  215086. CATCH
  215087. pDirectSound = 0;
  215088. }
  215089. }
  215090. const String open()
  215091. {
  215092. log ("opening dsound in device: " + name
  215093. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  215094. pDirectSound = 0;
  215095. pDirectSoundCapture = 0;
  215096. pInputBuffer = 0;
  215097. readOffset = 0;
  215098. totalBytesPerBuffer = 0;
  215099. String error;
  215100. HRESULT hr = E_NOINTERFACE;
  215101. if (dsDirectSoundCaptureCreate != 0)
  215102. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  215103. logError (hr);
  215104. if (hr == S_OK)
  215105. {
  215106. const int numChannels = 2;
  215107. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  215108. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  215109. WAVEFORMATEX wfFormat;
  215110. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  215111. wfFormat.nChannels = (unsigned short)numChannels;
  215112. wfFormat.nSamplesPerSec = sampleRate;
  215113. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  215114. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  215115. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  215116. wfFormat.cbSize = 0;
  215117. DSCBUFFERDESC captureDesc;
  215118. zerostruct (captureDesc);
  215119. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  215120. captureDesc.dwFlags = 0;
  215121. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  215122. captureDesc.lpwfxFormat = &wfFormat;
  215123. log ("opening dsound in step 2");
  215124. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  215125. logError (hr);
  215126. if (hr == S_OK)
  215127. {
  215128. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  215129. logError (hr);
  215130. if (hr == S_OK)
  215131. return String::empty;
  215132. }
  215133. }
  215134. error = getDSErrorMessage (hr);
  215135. close();
  215136. return error;
  215137. }
  215138. void synchronisePosition()
  215139. {
  215140. if (pInputBuffer != 0)
  215141. {
  215142. DWORD capturePos;
  215143. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  215144. }
  215145. }
  215146. bool service()
  215147. {
  215148. if (pInputBuffer == 0)
  215149. return true;
  215150. DWORD capturePos, readPos;
  215151. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  215152. logError (hr);
  215153. if (hr != S_OK)
  215154. return true;
  215155. int bytesFilled = readPos - readOffset;
  215156. if (bytesFilled < 0)
  215157. bytesFilled += totalBytesPerBuffer;
  215158. if (bytesFilled >= bytesPerBuffer)
  215159. {
  215160. LPBYTE lpbuf1 = 0;
  215161. LPBYTE lpbuf2 = 0;
  215162. DWORD dwsize1 = 0;
  215163. DWORD dwsize2 = 0;
  215164. HRESULT hr = pInputBuffer->Lock (readOffset,
  215165. bytesPerBuffer,
  215166. (void**) &lpbuf1, &dwsize1,
  215167. (void**) &lpbuf2, &dwsize2, 0);
  215168. if (hr == S_OK)
  215169. {
  215170. if (bitDepth == 16)
  215171. {
  215172. const float g = 1.0f / 32768.0f;
  215173. float* destL = leftBuffer;
  215174. float* destR = rightBuffer;
  215175. int samples1 = dwsize1 >> 2;
  215176. int samples2 = dwsize2 >> 2;
  215177. const short* src = (const short*)lpbuf1;
  215178. if (destL == 0)
  215179. {
  215180. while (--samples1 >= 0)
  215181. {
  215182. ++src;
  215183. *destR++ = *src++ * g;
  215184. }
  215185. src = (const short*)lpbuf2;
  215186. while (--samples2 >= 0)
  215187. {
  215188. ++src;
  215189. *destR++ = *src++ * g;
  215190. }
  215191. }
  215192. else if (destR == 0)
  215193. {
  215194. while (--samples1 >= 0)
  215195. {
  215196. *destL++ = *src++ * g;
  215197. ++src;
  215198. }
  215199. src = (const short*)lpbuf2;
  215200. while (--samples2 >= 0)
  215201. {
  215202. *destL++ = *src++ * g;
  215203. ++src;
  215204. }
  215205. }
  215206. else
  215207. {
  215208. while (--samples1 >= 0)
  215209. {
  215210. *destL++ = *src++ * g;
  215211. *destR++ = *src++ * g;
  215212. }
  215213. src = (const short*)lpbuf2;
  215214. while (--samples2 >= 0)
  215215. {
  215216. *destL++ = *src++ * g;
  215217. *destR++ = *src++ * g;
  215218. }
  215219. }
  215220. }
  215221. else
  215222. {
  215223. jassertfalse;
  215224. }
  215225. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  215226. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  215227. }
  215228. else
  215229. {
  215230. logError (hr);
  215231. jassertfalse;
  215232. }
  215233. bytesFilled -= bytesPerBuffer;
  215234. return true;
  215235. }
  215236. else
  215237. {
  215238. return false;
  215239. }
  215240. }
  215241. };
  215242. class DSoundAudioIODevice : public AudioIODevice,
  215243. public Thread
  215244. {
  215245. public:
  215246. DSoundAudioIODevice (const String& deviceName,
  215247. const int outputDeviceIndex_,
  215248. const int inputDeviceIndex_)
  215249. : AudioIODevice (deviceName, "DirectSound"),
  215250. Thread ("Juce DSound"),
  215251. isOpen_ (false),
  215252. isStarted (false),
  215253. outputDeviceIndex (outputDeviceIndex_),
  215254. inputDeviceIndex (inputDeviceIndex_),
  215255. totalSamplesOut (0),
  215256. sampleRate (0.0),
  215257. inputBuffers (1, 1),
  215258. outputBuffers (1, 1),
  215259. callback (0),
  215260. bufferSizeSamples (0)
  215261. {
  215262. if (outputDeviceIndex_ >= 0)
  215263. {
  215264. outChannels.add (TRANS("Left"));
  215265. outChannels.add (TRANS("Right"));
  215266. }
  215267. if (inputDeviceIndex_ >= 0)
  215268. {
  215269. inChannels.add (TRANS("Left"));
  215270. inChannels.add (TRANS("Right"));
  215271. }
  215272. }
  215273. ~DSoundAudioIODevice()
  215274. {
  215275. close();
  215276. }
  215277. const StringArray getOutputChannelNames()
  215278. {
  215279. return outChannels;
  215280. }
  215281. const StringArray getInputChannelNames()
  215282. {
  215283. return inChannels;
  215284. }
  215285. int getNumSampleRates()
  215286. {
  215287. return 4;
  215288. }
  215289. double getSampleRate (int index)
  215290. {
  215291. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215292. return samps [jlimit (0, 3, index)];
  215293. }
  215294. int getNumBufferSizesAvailable()
  215295. {
  215296. return 50;
  215297. }
  215298. int getBufferSizeSamples (int index)
  215299. {
  215300. int n = 64;
  215301. for (int i = 0; i < index; ++i)
  215302. n += (n < 512) ? 32
  215303. : ((n < 1024) ? 64
  215304. : ((n < 2048) ? 128 : 256));
  215305. return n;
  215306. }
  215307. int getDefaultBufferSize()
  215308. {
  215309. return 2560;
  215310. }
  215311. const String open (const BigInteger& inputChannels,
  215312. const BigInteger& outputChannels,
  215313. double sampleRate,
  215314. int bufferSizeSamples)
  215315. {
  215316. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215317. isOpen_ = lastError.isEmpty();
  215318. return lastError;
  215319. }
  215320. void close()
  215321. {
  215322. stop();
  215323. if (isOpen_)
  215324. {
  215325. closeDevice();
  215326. isOpen_ = false;
  215327. }
  215328. }
  215329. bool isOpen()
  215330. {
  215331. return isOpen_ && isThreadRunning();
  215332. }
  215333. int getCurrentBufferSizeSamples()
  215334. {
  215335. return bufferSizeSamples;
  215336. }
  215337. double getCurrentSampleRate()
  215338. {
  215339. return sampleRate;
  215340. }
  215341. int getCurrentBitDepth()
  215342. {
  215343. int i, bits = 256;
  215344. for (i = inChans.size(); --i >= 0;)
  215345. bits = jmin (bits, inChans[i]->bitDepth);
  215346. for (i = outChans.size(); --i >= 0;)
  215347. bits = jmin (bits, outChans[i]->bitDepth);
  215348. if (bits > 32)
  215349. bits = 16;
  215350. return bits;
  215351. }
  215352. const BigInteger getActiveOutputChannels() const
  215353. {
  215354. return enabledOutputs;
  215355. }
  215356. const BigInteger getActiveInputChannels() const
  215357. {
  215358. return enabledInputs;
  215359. }
  215360. int getOutputLatencyInSamples()
  215361. {
  215362. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215363. }
  215364. int getInputLatencyInSamples()
  215365. {
  215366. return getOutputLatencyInSamples();
  215367. }
  215368. void start (AudioIODeviceCallback* call)
  215369. {
  215370. if (isOpen_ && call != 0 && ! isStarted)
  215371. {
  215372. if (! isThreadRunning())
  215373. {
  215374. // something gone wrong and the thread's stopped..
  215375. isOpen_ = false;
  215376. return;
  215377. }
  215378. call->audioDeviceAboutToStart (this);
  215379. const ScopedLock sl (startStopLock);
  215380. callback = call;
  215381. isStarted = true;
  215382. }
  215383. }
  215384. void stop()
  215385. {
  215386. if (isStarted)
  215387. {
  215388. AudioIODeviceCallback* const callbackLocal = callback;
  215389. {
  215390. const ScopedLock sl (startStopLock);
  215391. isStarted = false;
  215392. }
  215393. if (callbackLocal != 0)
  215394. callbackLocal->audioDeviceStopped();
  215395. }
  215396. }
  215397. bool isPlaying()
  215398. {
  215399. return isStarted && isOpen_ && isThreadRunning();
  215400. }
  215401. const String getLastError()
  215402. {
  215403. return lastError;
  215404. }
  215405. juce_UseDebuggingNewOperator
  215406. StringArray inChannels, outChannels;
  215407. int outputDeviceIndex, inputDeviceIndex;
  215408. private:
  215409. bool isOpen_;
  215410. bool isStarted;
  215411. String lastError;
  215412. OwnedArray <DSoundInternalInChannel> inChans;
  215413. OwnedArray <DSoundInternalOutChannel> outChans;
  215414. WaitableEvent startEvent;
  215415. int bufferSizeSamples;
  215416. int volatile totalSamplesOut;
  215417. int64 volatile lastBlockTime;
  215418. double sampleRate;
  215419. BigInteger enabledInputs, enabledOutputs;
  215420. AudioSampleBuffer inputBuffers, outputBuffers;
  215421. AudioIODeviceCallback* callback;
  215422. CriticalSection startStopLock;
  215423. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215424. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215425. const String openDevice (const BigInteger& inputChannels,
  215426. const BigInteger& outputChannels,
  215427. double sampleRate_,
  215428. int bufferSizeSamples_);
  215429. void closeDevice()
  215430. {
  215431. isStarted = false;
  215432. stopThread (5000);
  215433. inChans.clear();
  215434. outChans.clear();
  215435. inputBuffers.setSize (1, 1);
  215436. outputBuffers.setSize (1, 1);
  215437. }
  215438. void resync()
  215439. {
  215440. if (! threadShouldExit())
  215441. {
  215442. sleep (5);
  215443. int i;
  215444. for (i = 0; i < outChans.size(); ++i)
  215445. outChans.getUnchecked(i)->synchronisePosition();
  215446. for (i = 0; i < inChans.size(); ++i)
  215447. inChans.getUnchecked(i)->synchronisePosition();
  215448. }
  215449. }
  215450. public:
  215451. void run()
  215452. {
  215453. while (! threadShouldExit())
  215454. {
  215455. if (wait (100))
  215456. break;
  215457. }
  215458. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215459. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215460. while (! threadShouldExit())
  215461. {
  215462. int numToDo = 0;
  215463. uint32 startTime = Time::getMillisecondCounter();
  215464. int i;
  215465. for (i = inChans.size(); --i >= 0;)
  215466. {
  215467. inChans.getUnchecked(i)->doneFlag = false;
  215468. ++numToDo;
  215469. }
  215470. for (i = outChans.size(); --i >= 0;)
  215471. {
  215472. outChans.getUnchecked(i)->doneFlag = false;
  215473. ++numToDo;
  215474. }
  215475. if (numToDo > 0)
  215476. {
  215477. const int maxCount = 3;
  215478. int count = maxCount;
  215479. for (;;)
  215480. {
  215481. for (i = inChans.size(); --i >= 0;)
  215482. {
  215483. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215484. if ((! in->doneFlag) && in->service())
  215485. {
  215486. in->doneFlag = true;
  215487. --numToDo;
  215488. }
  215489. }
  215490. for (i = outChans.size(); --i >= 0;)
  215491. {
  215492. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215493. if ((! out->doneFlag) && out->service())
  215494. {
  215495. out->doneFlag = true;
  215496. --numToDo;
  215497. }
  215498. }
  215499. if (numToDo <= 0)
  215500. break;
  215501. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215502. {
  215503. resync();
  215504. break;
  215505. }
  215506. if (--count <= 0)
  215507. {
  215508. Sleep (1);
  215509. count = maxCount;
  215510. }
  215511. if (threadShouldExit())
  215512. return;
  215513. }
  215514. }
  215515. else
  215516. {
  215517. sleep (1);
  215518. }
  215519. const ScopedLock sl (startStopLock);
  215520. if (isStarted)
  215521. {
  215522. JUCE_TRY
  215523. {
  215524. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215525. inputBuffers.getNumChannels(),
  215526. outputBuffers.getArrayOfChannels(),
  215527. outputBuffers.getNumChannels(),
  215528. bufferSizeSamples);
  215529. }
  215530. JUCE_CATCH_EXCEPTION
  215531. totalSamplesOut += bufferSizeSamples;
  215532. }
  215533. else
  215534. {
  215535. outputBuffers.clear();
  215536. totalSamplesOut = 0;
  215537. sleep (1);
  215538. }
  215539. }
  215540. }
  215541. };
  215542. class DSoundAudioIODeviceType : public AudioIODeviceType
  215543. {
  215544. public:
  215545. DSoundAudioIODeviceType()
  215546. : AudioIODeviceType ("DirectSound"),
  215547. hasScanned (false)
  215548. {
  215549. initialiseDSoundFunctions();
  215550. }
  215551. ~DSoundAudioIODeviceType()
  215552. {
  215553. }
  215554. void scanForDevices()
  215555. {
  215556. hasScanned = true;
  215557. outputDeviceNames.clear();
  215558. outputGuids.clear();
  215559. inputDeviceNames.clear();
  215560. inputGuids.clear();
  215561. if (dsDirectSoundEnumerateW != 0)
  215562. {
  215563. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215564. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215565. }
  215566. }
  215567. const StringArray getDeviceNames (bool wantInputNames) const
  215568. {
  215569. jassert (hasScanned); // need to call scanForDevices() before doing this
  215570. return wantInputNames ? inputDeviceNames
  215571. : outputDeviceNames;
  215572. }
  215573. int getDefaultDeviceIndex (bool /*forInput*/) const
  215574. {
  215575. jassert (hasScanned); // need to call scanForDevices() before doing this
  215576. return 0;
  215577. }
  215578. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215579. {
  215580. jassert (hasScanned); // need to call scanForDevices() before doing this
  215581. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215582. if (d == 0)
  215583. return -1;
  215584. return asInput ? d->inputDeviceIndex
  215585. : d->outputDeviceIndex;
  215586. }
  215587. bool hasSeparateInputsAndOutputs() const { return true; }
  215588. AudioIODevice* createDevice (const String& outputDeviceName,
  215589. const String& inputDeviceName)
  215590. {
  215591. jassert (hasScanned); // need to call scanForDevices() before doing this
  215592. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215593. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215594. if (outputIndex >= 0 || inputIndex >= 0)
  215595. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215596. : inputDeviceName,
  215597. outputIndex, inputIndex);
  215598. return 0;
  215599. }
  215600. juce_UseDebuggingNewOperator
  215601. StringArray outputDeviceNames;
  215602. OwnedArray <GUID> outputGuids;
  215603. StringArray inputDeviceNames;
  215604. OwnedArray <GUID> inputGuids;
  215605. private:
  215606. bool hasScanned;
  215607. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215608. {
  215609. desc = desc.trim();
  215610. if (desc.isNotEmpty())
  215611. {
  215612. const String origDesc (desc);
  215613. int n = 2;
  215614. while (outputDeviceNames.contains (desc))
  215615. desc = origDesc + " (" + String (n++) + ")";
  215616. outputDeviceNames.add (desc);
  215617. if (lpGUID != 0)
  215618. outputGuids.add (new GUID (*lpGUID));
  215619. else
  215620. outputGuids.add (0);
  215621. }
  215622. return TRUE;
  215623. }
  215624. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215625. {
  215626. return ((DSoundAudioIODeviceType*) object)
  215627. ->outputEnumProc (lpGUID, String (description));
  215628. }
  215629. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215630. {
  215631. return ((DSoundAudioIODeviceType*) object)
  215632. ->outputEnumProc (lpGUID, String (description));
  215633. }
  215634. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215635. {
  215636. desc = desc.trim();
  215637. if (desc.isNotEmpty())
  215638. {
  215639. const String origDesc (desc);
  215640. int n = 2;
  215641. while (inputDeviceNames.contains (desc))
  215642. desc = origDesc + " (" + String (n++) + ")";
  215643. inputDeviceNames.add (desc);
  215644. if (lpGUID != 0)
  215645. inputGuids.add (new GUID (*lpGUID));
  215646. else
  215647. inputGuids.add (0);
  215648. }
  215649. return TRUE;
  215650. }
  215651. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215652. {
  215653. return ((DSoundAudioIODeviceType*) object)
  215654. ->inputEnumProc (lpGUID, String (description));
  215655. }
  215656. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215657. {
  215658. return ((DSoundAudioIODeviceType*) object)
  215659. ->inputEnumProc (lpGUID, String (description));
  215660. }
  215661. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215662. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215663. };
  215664. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215665. const BigInteger& outputChannels,
  215666. double sampleRate_,
  215667. int bufferSizeSamples_)
  215668. {
  215669. closeDevice();
  215670. totalSamplesOut = 0;
  215671. sampleRate = sampleRate_;
  215672. if (bufferSizeSamples_ <= 0)
  215673. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215674. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215675. DSoundAudioIODeviceType dlh;
  215676. dlh.scanForDevices();
  215677. enabledInputs = inputChannels;
  215678. enabledInputs.setRange (inChannels.size(),
  215679. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215680. false);
  215681. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215682. inputBuffers.clear();
  215683. int i, numIns = 0;
  215684. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215685. {
  215686. float* left = 0;
  215687. if (enabledInputs[i])
  215688. left = inputBuffers.getSampleData (numIns++);
  215689. float* right = 0;
  215690. if (enabledInputs[i + 1])
  215691. right = inputBuffers.getSampleData (numIns++);
  215692. if (left != 0 || right != 0)
  215693. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215694. dlh.inputGuids [inputDeviceIndex],
  215695. (int) sampleRate, bufferSizeSamples,
  215696. left, right));
  215697. }
  215698. enabledOutputs = outputChannels;
  215699. enabledOutputs.setRange (outChannels.size(),
  215700. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215701. false);
  215702. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215703. outputBuffers.clear();
  215704. int numOuts = 0;
  215705. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215706. {
  215707. float* left = 0;
  215708. if (enabledOutputs[i])
  215709. left = outputBuffers.getSampleData (numOuts++);
  215710. float* right = 0;
  215711. if (enabledOutputs[i + 1])
  215712. right = outputBuffers.getSampleData (numOuts++);
  215713. if (left != 0 || right != 0)
  215714. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215715. dlh.outputGuids [outputDeviceIndex],
  215716. (int) sampleRate, bufferSizeSamples,
  215717. left, right));
  215718. }
  215719. String error;
  215720. // boost our priority while opening the devices to try to get better sync between them
  215721. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215722. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215723. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215724. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215725. for (i = 0; i < outChans.size(); ++i)
  215726. {
  215727. error = outChans[i]->open();
  215728. if (error.isNotEmpty())
  215729. {
  215730. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215731. break;
  215732. }
  215733. }
  215734. if (error.isEmpty())
  215735. {
  215736. for (i = 0; i < inChans.size(); ++i)
  215737. {
  215738. error = inChans[i]->open();
  215739. if (error.isNotEmpty())
  215740. {
  215741. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215742. break;
  215743. }
  215744. }
  215745. }
  215746. if (error.isEmpty())
  215747. {
  215748. totalSamplesOut = 0;
  215749. for (i = 0; i < outChans.size(); ++i)
  215750. outChans.getUnchecked(i)->synchronisePosition();
  215751. for (i = 0; i < inChans.size(); ++i)
  215752. inChans.getUnchecked(i)->synchronisePosition();
  215753. startThread (9);
  215754. sleep (10);
  215755. notify();
  215756. }
  215757. else
  215758. {
  215759. log (error);
  215760. }
  215761. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215762. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215763. return error;
  215764. }
  215765. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215766. {
  215767. return new DSoundAudioIODeviceType();
  215768. }
  215769. #undef log
  215770. #endif
  215771. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215772. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215773. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215774. // compiled on its own).
  215775. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215776. #if 1
  215777. const String getAudioErrorDesc (HRESULT hr)
  215778. {
  215779. const char* e = 0;
  215780. switch (hr)
  215781. {
  215782. case E_POINTER: e = "E_POINTER"; break;
  215783. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  215784. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  215785. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215786. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215787. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215788. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  215789. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215790. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  215791. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215792. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  215793. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  215794. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215795. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215796. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215797. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215798. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215799. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215800. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215801. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215802. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215803. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215804. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215805. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  215806. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215807. default: return String::toHexString ((int) hr);
  215808. }
  215809. return e;
  215810. }
  215811. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  215812. #define OK(a) wasapi_checkResult(a)
  215813. static bool wasapi_checkResult (HRESULT hr)
  215814. {
  215815. logFailure (hr);
  215816. return SUCCEEDED (hr);
  215817. }
  215818. #else
  215819. #define logFailure(hr) {}
  215820. #define OK(a) SUCCEEDED(a)
  215821. #endif
  215822. static const String wasapi_getDeviceID (IMMDevice* const device)
  215823. {
  215824. String s;
  215825. WCHAR* deviceId = 0;
  215826. if (OK (device->GetId (&deviceId)))
  215827. {
  215828. s = String (deviceId);
  215829. CoTaskMemFree (deviceId);
  215830. }
  215831. return s;
  215832. }
  215833. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  215834. {
  215835. EDataFlow flow = eRender;
  215836. ComSmartPtr <IMMEndpoint> endPoint;
  215837. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  215838. (void) OK (endPoint->GetDataFlow (&flow));
  215839. return flow;
  215840. }
  215841. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215842. {
  215843. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215844. }
  215845. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215846. {
  215847. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215848. : sizeof (WAVEFORMATEX));
  215849. }
  215850. class WASAPIDeviceBase
  215851. {
  215852. public:
  215853. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215854. : device (device_),
  215855. sampleRate (0),
  215856. numChannels (0),
  215857. actualNumChannels (0),
  215858. defaultSampleRate (0),
  215859. minBufferSize (0),
  215860. defaultBufferSize (0),
  215861. latencySamples (0),
  215862. useExclusiveMode (useExclusiveMode_)
  215863. {
  215864. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215865. ComSmartPtr <IAudioClient> tempClient (createClient());
  215866. if (tempClient == 0)
  215867. return;
  215868. REFERENCE_TIME defaultPeriod, minPeriod;
  215869. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215870. return;
  215871. WAVEFORMATEX* mixFormat = 0;
  215872. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  215873. return;
  215874. WAVEFORMATEXTENSIBLE format;
  215875. wasapi_copyWavFormat (format, mixFormat);
  215876. CoTaskMemFree (mixFormat);
  215877. actualNumChannels = numChannels = format.Format.nChannels;
  215878. defaultSampleRate = format.Format.nSamplesPerSec;
  215879. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  215880. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  215881. rates.addUsingDefaultSort (defaultSampleRate);
  215882. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215883. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215884. {
  215885. if (ratesToTest[i] == defaultSampleRate)
  215886. continue;
  215887. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215888. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215889. (WAVEFORMATEX*) &format, 0)))
  215890. if (! rates.contains (ratesToTest[i]))
  215891. rates.addUsingDefaultSort (ratesToTest[i]);
  215892. }
  215893. }
  215894. ~WASAPIDeviceBase()
  215895. {
  215896. device = 0;
  215897. CloseHandle (clientEvent);
  215898. }
  215899. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215900. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215901. {
  215902. sampleRate = newSampleRate;
  215903. channels = newChannels;
  215904. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215905. numChannels = channels.getHighestBit() + 1;
  215906. if (numChannels == 0)
  215907. return true;
  215908. client = createClient();
  215909. if (client != 0
  215910. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215911. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215912. {
  215913. channelMaps.clear();
  215914. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215915. if (channels[i])
  215916. channelMaps.add (i);
  215917. REFERENCE_TIME latency;
  215918. if (OK (client->GetStreamLatency (&latency)))
  215919. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  215920. (void) OK (client->GetBufferSize (&actualBufferSize));
  215921. return OK (client->SetEventHandle (clientEvent));
  215922. }
  215923. return false;
  215924. }
  215925. void closeClient()
  215926. {
  215927. if (client != 0)
  215928. client->Stop();
  215929. client = 0;
  215930. ResetEvent (clientEvent);
  215931. }
  215932. ComSmartPtr <IMMDevice> device;
  215933. ComSmartPtr <IAudioClient> client;
  215934. double sampleRate, defaultSampleRate;
  215935. int numChannels, actualNumChannels;
  215936. int minBufferSize, defaultBufferSize, latencySamples;
  215937. const bool useExclusiveMode;
  215938. Array <double> rates;
  215939. HANDLE clientEvent;
  215940. BigInteger channels;
  215941. AudioDataConverters::DataFormat dataFormat;
  215942. Array <int> channelMaps;
  215943. UINT32 actualBufferSize;
  215944. int bytesPerSample;
  215945. private:
  215946. const ComSmartPtr <IAudioClient> createClient()
  215947. {
  215948. ComSmartPtr <IAudioClient> client;
  215949. if (device != 0)
  215950. {
  215951. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  215952. logFailure (hr);
  215953. }
  215954. return client;
  215955. }
  215956. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215957. {
  215958. WAVEFORMATEXTENSIBLE format;
  215959. zerostruct (format);
  215960. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215961. {
  215962. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215963. }
  215964. else
  215965. {
  215966. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215967. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215968. }
  215969. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215970. format.Format.nChannels = (WORD) numChannels;
  215971. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215972. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215973. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215974. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215975. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215976. switch (numChannels)
  215977. {
  215978. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215979. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215980. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215981. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215982. 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;
  215983. default: break;
  215984. }
  215985. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215986. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215987. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215988. logFailure (hr);
  215989. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215990. {
  215991. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215992. hr = S_OK;
  215993. }
  215994. CoTaskMemFree (nearestFormat);
  215995. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215996. if (useExclusiveMode)
  215997. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215998. GUID session;
  215999. if (hr == S_OK
  216000. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  216001. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  216002. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  216003. {
  216004. actualNumChannels = format.Format.nChannels;
  216005. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  216006. bytesPerSample = format.Format.wBitsPerSample / 8;
  216007. dataFormat = isFloat ? AudioDataConverters::float32LE
  216008. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  216009. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  216010. : AudioDataConverters::int16LE)));
  216011. return true;
  216012. }
  216013. return false;
  216014. }
  216015. WASAPIDeviceBase (const WASAPIDeviceBase&);
  216016. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  216017. };
  216018. class WASAPIInputDevice : public WASAPIDeviceBase
  216019. {
  216020. public:
  216021. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  216022. : WASAPIDeviceBase (device_, useExclusiveMode_),
  216023. reservoir (1, 1)
  216024. {
  216025. }
  216026. ~WASAPIInputDevice()
  216027. {
  216028. close();
  216029. }
  216030. bool open (const double newSampleRate, const BigInteger& newChannels)
  216031. {
  216032. reservoirSize = 0;
  216033. reservoirCapacity = 16384;
  216034. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  216035. return openClient (newSampleRate, newChannels)
  216036. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  216037. }
  216038. void close()
  216039. {
  216040. closeClient();
  216041. captureClient = 0;
  216042. reservoir.setSize (0);
  216043. }
  216044. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  216045. {
  216046. if (numChannels <= 0)
  216047. return;
  216048. int offset = 0;
  216049. while (bufferSize > 0)
  216050. {
  216051. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  216052. {
  216053. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  216054. for (int i = 0; i < numDestBuffers; ++i)
  216055. {
  216056. float* const dest = destBuffers[i] + offset;
  216057. const int srcChan = channelMaps.getUnchecked(i);
  216058. switch (dataFormat)
  216059. {
  216060. case AudioDataConverters::float32LE:
  216061. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  216062. break;
  216063. case AudioDataConverters::int32LE:
  216064. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  216065. break;
  216066. case AudioDataConverters::int24LE:
  216067. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  216068. break;
  216069. case AudioDataConverters::int16LE:
  216070. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  216071. break;
  216072. default: jassertfalse; break;
  216073. }
  216074. }
  216075. bufferSize -= samplesToDo;
  216076. offset += samplesToDo;
  216077. reservoirSize -= samplesToDo;
  216078. }
  216079. else
  216080. {
  216081. UINT32 packetLength = 0;
  216082. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  216083. break;
  216084. if (packetLength == 0)
  216085. {
  216086. if (thread.threadShouldExit())
  216087. break;
  216088. Thread::sleep (1);
  216089. continue;
  216090. }
  216091. uint8* inputData = 0;
  216092. UINT32 numSamplesAvailable;
  216093. DWORD flags;
  216094. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  216095. {
  216096. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  216097. for (int i = 0; i < numDestBuffers; ++i)
  216098. {
  216099. float* const dest = destBuffers[i] + offset;
  216100. const int srcChan = channelMaps.getUnchecked(i);
  216101. switch (dataFormat)
  216102. {
  216103. case AudioDataConverters::float32LE:
  216104. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  216105. break;
  216106. case AudioDataConverters::int32LE:
  216107. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  216108. break;
  216109. case AudioDataConverters::int24LE:
  216110. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  216111. break;
  216112. case AudioDataConverters::int16LE:
  216113. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  216114. break;
  216115. default: jassertfalse; break;
  216116. }
  216117. }
  216118. bufferSize -= samplesToDo;
  216119. offset += samplesToDo;
  216120. if (samplesToDo < (int) numSamplesAvailable)
  216121. {
  216122. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  216123. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  216124. bytesPerSample * actualNumChannels * reservoirSize);
  216125. }
  216126. captureClient->ReleaseBuffer (numSamplesAvailable);
  216127. }
  216128. }
  216129. }
  216130. }
  216131. ComSmartPtr <IAudioCaptureClient> captureClient;
  216132. MemoryBlock reservoir;
  216133. int reservoirSize, reservoirCapacity;
  216134. private:
  216135. WASAPIInputDevice (const WASAPIInputDevice&);
  216136. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  216137. };
  216138. class WASAPIOutputDevice : public WASAPIDeviceBase
  216139. {
  216140. public:
  216141. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  216142. : WASAPIDeviceBase (device_, useExclusiveMode_)
  216143. {
  216144. }
  216145. ~WASAPIOutputDevice()
  216146. {
  216147. close();
  216148. }
  216149. bool open (const double newSampleRate, const BigInteger& newChannels)
  216150. {
  216151. return openClient (newSampleRate, newChannels)
  216152. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  216153. }
  216154. void close()
  216155. {
  216156. closeClient();
  216157. renderClient = 0;
  216158. }
  216159. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  216160. {
  216161. if (numChannels <= 0)
  216162. return;
  216163. int offset = 0;
  216164. while (bufferSize > 0)
  216165. {
  216166. UINT32 padding = 0;
  216167. if (! OK (client->GetCurrentPadding (&padding)))
  216168. return;
  216169. int samplesToDo = useExclusiveMode ? bufferSize
  216170. : jmin ((int) (actualBufferSize - padding), bufferSize);
  216171. if (samplesToDo <= 0)
  216172. {
  216173. if (thread.threadShouldExit())
  216174. break;
  216175. Thread::sleep (0);
  216176. continue;
  216177. }
  216178. uint8* outputData = 0;
  216179. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  216180. {
  216181. for (int i = 0; i < numSrcBuffers; ++i)
  216182. {
  216183. const float* const source = srcBuffers[i] + offset;
  216184. const int destChan = channelMaps.getUnchecked(i);
  216185. switch (dataFormat)
  216186. {
  216187. case AudioDataConverters::float32LE:
  216188. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  216189. break;
  216190. case AudioDataConverters::int32LE:
  216191. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  216192. break;
  216193. case AudioDataConverters::int24LE:
  216194. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  216195. break;
  216196. case AudioDataConverters::int16LE:
  216197. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  216198. break;
  216199. default: jassertfalse; break;
  216200. }
  216201. }
  216202. renderClient->ReleaseBuffer (samplesToDo, 0);
  216203. offset += samplesToDo;
  216204. bufferSize -= samplesToDo;
  216205. }
  216206. }
  216207. }
  216208. ComSmartPtr <IAudioRenderClient> renderClient;
  216209. private:
  216210. WASAPIOutputDevice (const WASAPIOutputDevice&);
  216211. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  216212. };
  216213. class WASAPIAudioIODevice : public AudioIODevice,
  216214. public Thread
  216215. {
  216216. public:
  216217. WASAPIAudioIODevice (const String& deviceName,
  216218. const String& outputDeviceId_,
  216219. const String& inputDeviceId_,
  216220. const bool useExclusiveMode_)
  216221. : AudioIODevice (deviceName, "Windows Audio"),
  216222. Thread ("Juce WASAPI"),
  216223. isOpen_ (false),
  216224. isStarted (false),
  216225. outputDeviceId (outputDeviceId_),
  216226. inputDeviceId (inputDeviceId_),
  216227. useExclusiveMode (useExclusiveMode_),
  216228. currentBufferSizeSamples (0),
  216229. currentSampleRate (0),
  216230. callback (0)
  216231. {
  216232. }
  216233. ~WASAPIAudioIODevice()
  216234. {
  216235. close();
  216236. }
  216237. bool initialise()
  216238. {
  216239. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  216240. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  216241. latencyIn = latencyOut = 0;
  216242. Array <double> ratesIn, ratesOut;
  216243. if (createDevices())
  216244. {
  216245. jassert (inputDevice != 0 || outputDevice != 0);
  216246. if (inputDevice != 0 && outputDevice != 0)
  216247. {
  216248. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  216249. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  216250. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  216251. sampleRates = inputDevice->rates;
  216252. sampleRates.removeValuesNotIn (outputDevice->rates);
  216253. }
  216254. else
  216255. {
  216256. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  216257. : static_cast<WASAPIDeviceBase*> (outputDevice);
  216258. defaultSampleRate = d->defaultSampleRate;
  216259. minBufferSize = d->minBufferSize;
  216260. defaultBufferSize = d->defaultBufferSize;
  216261. sampleRates = d->rates;
  216262. }
  216263. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  216264. if (minBufferSize != defaultBufferSize)
  216265. bufferSizes.addUsingDefaultSort (minBufferSize);
  216266. int n = 64;
  216267. for (int i = 0; i < 40; ++i)
  216268. {
  216269. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  216270. bufferSizes.addUsingDefaultSort (n);
  216271. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216272. }
  216273. return true;
  216274. }
  216275. return false;
  216276. }
  216277. const StringArray getOutputChannelNames()
  216278. {
  216279. StringArray outChannels;
  216280. if (outputDevice != 0)
  216281. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216282. outChannels.add ("Output channel " + String (i));
  216283. return outChannels;
  216284. }
  216285. const StringArray getInputChannelNames()
  216286. {
  216287. StringArray inChannels;
  216288. if (inputDevice != 0)
  216289. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216290. inChannels.add ("Input channel " + String (i));
  216291. return inChannels;
  216292. }
  216293. int getNumSampleRates() { return sampleRates.size(); }
  216294. double getSampleRate (int index) { return sampleRates [index]; }
  216295. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216296. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216297. int getDefaultBufferSize() { return defaultBufferSize; }
  216298. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216299. double getCurrentSampleRate() { return currentSampleRate; }
  216300. int getCurrentBitDepth() { return 32; }
  216301. int getOutputLatencyInSamples() { return latencyOut; }
  216302. int getInputLatencyInSamples() { return latencyIn; }
  216303. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216304. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216305. const String getLastError() { return lastError; }
  216306. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216307. double sampleRate, int bufferSizeSamples)
  216308. {
  216309. close();
  216310. lastError = String::empty;
  216311. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216312. {
  216313. lastError = "The input and output devices don't share a common sample rate!";
  216314. return lastError;
  216315. }
  216316. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216317. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216318. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216319. {
  216320. lastError = "Couldn't open the input device!";
  216321. return lastError;
  216322. }
  216323. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216324. {
  216325. close();
  216326. lastError = "Couldn't open the output device!";
  216327. return lastError;
  216328. }
  216329. if (inputDevice != 0)
  216330. ResetEvent (inputDevice->clientEvent);
  216331. if (outputDevice != 0)
  216332. ResetEvent (outputDevice->clientEvent);
  216333. startThread (8);
  216334. Thread::sleep (5);
  216335. if (inputDevice != 0 && inputDevice->client != 0)
  216336. {
  216337. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216338. HRESULT hr = inputDevice->client->Start();
  216339. logFailure (hr); //xxx handle this
  216340. }
  216341. if (outputDevice != 0 && outputDevice->client != 0)
  216342. {
  216343. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216344. HRESULT hr = outputDevice->client->Start();
  216345. logFailure (hr); //xxx handle this
  216346. }
  216347. isOpen_ = true;
  216348. return lastError;
  216349. }
  216350. void close()
  216351. {
  216352. stop();
  216353. if (inputDevice != 0)
  216354. SetEvent (inputDevice->clientEvent);
  216355. if (outputDevice != 0)
  216356. SetEvent (outputDevice->clientEvent);
  216357. stopThread (5000);
  216358. if (inputDevice != 0)
  216359. inputDevice->close();
  216360. if (outputDevice != 0)
  216361. outputDevice->close();
  216362. isOpen_ = false;
  216363. }
  216364. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216365. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216366. void start (AudioIODeviceCallback* call)
  216367. {
  216368. if (isOpen_ && call != 0 && ! isStarted)
  216369. {
  216370. if (! isThreadRunning())
  216371. {
  216372. // something's gone wrong and the thread's stopped..
  216373. isOpen_ = false;
  216374. return;
  216375. }
  216376. call->audioDeviceAboutToStart (this);
  216377. const ScopedLock sl (startStopLock);
  216378. callback = call;
  216379. isStarted = true;
  216380. }
  216381. }
  216382. void stop()
  216383. {
  216384. if (isStarted)
  216385. {
  216386. AudioIODeviceCallback* const callbackLocal = callback;
  216387. {
  216388. const ScopedLock sl (startStopLock);
  216389. isStarted = false;
  216390. }
  216391. if (callbackLocal != 0)
  216392. callbackLocal->audioDeviceStopped();
  216393. }
  216394. }
  216395. void setMMThreadPriority()
  216396. {
  216397. DynamicLibraryLoader dll ("avrt.dll");
  216398. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216399. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216400. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216401. {
  216402. DWORD dummy = 0;
  216403. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216404. if (h != 0)
  216405. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216406. }
  216407. }
  216408. void run()
  216409. {
  216410. setMMThreadPriority();
  216411. const int bufferSize = currentBufferSizeSamples;
  216412. HANDLE events[2];
  216413. int numEvents = 0;
  216414. if (inputDevice != 0)
  216415. events [numEvents++] = inputDevice->clientEvent;
  216416. if (outputDevice != 0)
  216417. events [numEvents++] = outputDevice->clientEvent;
  216418. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216419. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216420. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216421. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216422. float** const inputBuffers = ins.getArrayOfChannels();
  216423. float** const outputBuffers = outs.getArrayOfChannels();
  216424. ins.clear();
  216425. while (! threadShouldExit())
  216426. {
  216427. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216428. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216429. if (result == WAIT_TIMEOUT)
  216430. continue;
  216431. if (threadShouldExit())
  216432. break;
  216433. if (inputDevice != 0)
  216434. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216435. // Make the callback..
  216436. {
  216437. const ScopedLock sl (startStopLock);
  216438. if (isStarted)
  216439. {
  216440. JUCE_TRY
  216441. {
  216442. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216443. numInputBuffers,
  216444. outputBuffers,
  216445. numOutputBuffers,
  216446. bufferSize);
  216447. }
  216448. JUCE_CATCH_EXCEPTION
  216449. }
  216450. else
  216451. {
  216452. outs.clear();
  216453. }
  216454. }
  216455. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216456. continue;
  216457. if (outputDevice != 0)
  216458. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216459. }
  216460. }
  216461. juce_UseDebuggingNewOperator
  216462. String outputDeviceId, inputDeviceId;
  216463. String lastError;
  216464. private:
  216465. // Device stats...
  216466. ScopedPointer<WASAPIInputDevice> inputDevice;
  216467. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216468. const bool useExclusiveMode;
  216469. double defaultSampleRate;
  216470. int minBufferSize, defaultBufferSize;
  216471. int latencyIn, latencyOut;
  216472. Array <double> sampleRates;
  216473. Array <int> bufferSizes;
  216474. // Active state...
  216475. bool isOpen_, isStarted;
  216476. int currentBufferSizeSamples;
  216477. double currentSampleRate;
  216478. AudioIODeviceCallback* callback;
  216479. CriticalSection startStopLock;
  216480. bool createDevices()
  216481. {
  216482. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216483. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216484. return false;
  216485. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216486. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  216487. return false;
  216488. UINT32 numDevices = 0;
  216489. if (! OK (deviceCollection->GetCount (&numDevices)))
  216490. return false;
  216491. for (UINT32 i = 0; i < numDevices; ++i)
  216492. {
  216493. ComSmartPtr <IMMDevice> device;
  216494. if (! OK (deviceCollection->Item (i, &device)))
  216495. continue;
  216496. const String deviceId (wasapi_getDeviceID (device));
  216497. if (deviceId.isEmpty())
  216498. continue;
  216499. const EDataFlow flow = wasapi_getDataFlow (device);
  216500. if (deviceId == inputDeviceId && flow == eCapture)
  216501. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216502. else if (deviceId == outputDeviceId && flow == eRender)
  216503. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216504. }
  216505. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216506. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216507. }
  216508. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216509. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216510. };
  216511. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216512. {
  216513. public:
  216514. WASAPIAudioIODeviceType()
  216515. : AudioIODeviceType ("Windows Audio"),
  216516. hasScanned (false)
  216517. {
  216518. }
  216519. ~WASAPIAudioIODeviceType()
  216520. {
  216521. }
  216522. void scanForDevices()
  216523. {
  216524. hasScanned = true;
  216525. outputDeviceNames.clear();
  216526. inputDeviceNames.clear();
  216527. outputDeviceIds.clear();
  216528. inputDeviceIds.clear();
  216529. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216530. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216531. return;
  216532. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216533. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216534. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216535. UINT32 numDevices = 0;
  216536. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  216537. && OK (deviceCollection->GetCount (&numDevices))))
  216538. return;
  216539. for (UINT32 i = 0; i < numDevices; ++i)
  216540. {
  216541. ComSmartPtr <IMMDevice> device;
  216542. if (! OK (deviceCollection->Item (i, &device)))
  216543. continue;
  216544. const String deviceId (wasapi_getDeviceID (device));
  216545. DWORD state = 0;
  216546. if (! OK (device->GetState (&state)))
  216547. continue;
  216548. if (state != DEVICE_STATE_ACTIVE)
  216549. continue;
  216550. String name;
  216551. {
  216552. ComSmartPtr <IPropertyStore> properties;
  216553. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  216554. continue;
  216555. PROPVARIANT value;
  216556. PropVariantInit (&value);
  216557. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216558. name = value.pwszVal;
  216559. PropVariantClear (&value);
  216560. }
  216561. const EDataFlow flow = wasapi_getDataFlow (device);
  216562. if (flow == eRender)
  216563. {
  216564. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216565. outputDeviceIds.insert (index, deviceId);
  216566. outputDeviceNames.insert (index, name);
  216567. }
  216568. else if (flow == eCapture)
  216569. {
  216570. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216571. inputDeviceIds.insert (index, deviceId);
  216572. inputDeviceNames.insert (index, name);
  216573. }
  216574. }
  216575. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216576. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216577. }
  216578. const StringArray getDeviceNames (bool wantInputNames) const
  216579. {
  216580. jassert (hasScanned); // need to call scanForDevices() before doing this
  216581. return wantInputNames ? inputDeviceNames
  216582. : outputDeviceNames;
  216583. }
  216584. int getDefaultDeviceIndex (bool /*forInput*/) const
  216585. {
  216586. jassert (hasScanned); // need to call scanForDevices() before doing this
  216587. return 0;
  216588. }
  216589. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216590. {
  216591. jassert (hasScanned); // need to call scanForDevices() before doing this
  216592. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216593. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216594. : outputDeviceIds.indexOf (d->outputDeviceId));
  216595. }
  216596. bool hasSeparateInputsAndOutputs() const { return true; }
  216597. AudioIODevice* createDevice (const String& outputDeviceName,
  216598. const String& inputDeviceName)
  216599. {
  216600. jassert (hasScanned); // need to call scanForDevices() before doing this
  216601. const bool useExclusiveMode = false;
  216602. ScopedPointer<WASAPIAudioIODevice> device;
  216603. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216604. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216605. if (outputIndex >= 0 || inputIndex >= 0)
  216606. {
  216607. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216608. : inputDeviceName,
  216609. outputDeviceIds [outputIndex],
  216610. inputDeviceIds [inputIndex],
  216611. useExclusiveMode);
  216612. if (! device->initialise())
  216613. device = 0;
  216614. }
  216615. return device.release();
  216616. }
  216617. juce_UseDebuggingNewOperator
  216618. StringArray outputDeviceNames, outputDeviceIds;
  216619. StringArray inputDeviceNames, inputDeviceIds;
  216620. private:
  216621. bool hasScanned;
  216622. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216623. {
  216624. String s;
  216625. IMMDevice* dev = 0;
  216626. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216627. eMultimedia, &dev)))
  216628. {
  216629. WCHAR* deviceId = 0;
  216630. if (OK (dev->GetId (&deviceId)))
  216631. {
  216632. s = String (deviceId);
  216633. CoTaskMemFree (deviceId);
  216634. }
  216635. dev->Release();
  216636. }
  216637. return s;
  216638. }
  216639. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216640. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216641. };
  216642. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216643. {
  216644. return new WASAPIAudioIODeviceType();
  216645. }
  216646. #undef logFailure
  216647. #undef OK
  216648. #endif
  216649. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216650. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216651. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216652. // compiled on its own).
  216653. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216654. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216655. {
  216656. public:
  216657. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216658. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216659. const ComSmartPtr <IBaseFilter>& filter_,
  216660. int minWidth, int minHeight,
  216661. int maxWidth, int maxHeight)
  216662. : owner (owner_),
  216663. captureGraphBuilder (captureGraphBuilder_),
  216664. filter (filter_),
  216665. ok (false),
  216666. imageNeedsFlipping (false),
  216667. width (0),
  216668. height (0),
  216669. activeUsers (0),
  216670. recordNextFrameTime (false)
  216671. {
  216672. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216673. if (FAILED (hr))
  216674. return;
  216675. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216676. if (FAILED (hr))
  216677. return;
  216678. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  216679. if (FAILED (hr))
  216680. return;
  216681. {
  216682. ComSmartPtr <IAMStreamConfig> streamConfig;
  216683. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216684. IID_IAMStreamConfig, (void**) &streamConfig);
  216685. if (streamConfig != 0)
  216686. {
  216687. getVideoSizes (streamConfig);
  216688. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216689. return;
  216690. }
  216691. }
  216692. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216693. if (FAILED (hr))
  216694. return;
  216695. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216696. if (FAILED (hr))
  216697. return;
  216698. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216699. if (FAILED (hr))
  216700. return;
  216701. if (! connectFilters (filter, smartTee))
  216702. return;
  216703. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216704. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216705. if (FAILED (hr))
  216706. return;
  216707. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  216708. if (FAILED (hr))
  216709. return;
  216710. AM_MEDIA_TYPE mt;
  216711. zerostruct (mt);
  216712. mt.majortype = MEDIATYPE_Video;
  216713. mt.subtype = MEDIASUBTYPE_RGB24;
  216714. mt.formattype = FORMAT_VideoInfo;
  216715. sampleGrabber->SetMediaType (&mt);
  216716. callback = new GrabberCallback (*this);
  216717. sampleGrabber->SetCallback (callback, 1);
  216718. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216719. if (FAILED (hr))
  216720. return;
  216721. ComSmartPtr <IPin> grabberInputPin;
  216722. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  216723. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  216724. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  216725. return;
  216726. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216727. if (FAILED (hr))
  216728. return;
  216729. zerostruct (mt);
  216730. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216731. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216732. width = pVih->bmiHeader.biWidth;
  216733. height = pVih->bmiHeader.biHeight;
  216734. ComSmartPtr <IBaseFilter> nullFilter;
  216735. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216736. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216737. if (connectFilters (sampleGrabberBase, nullFilter)
  216738. && addGraphToRot())
  216739. {
  216740. activeImage = Image (Image::RGB, width, height, true);
  216741. loadingImage = Image (Image::RGB, width, height, true);
  216742. ok = true;
  216743. }
  216744. }
  216745. ~DShowCameraDeviceInteral()
  216746. {
  216747. if (mediaControl != 0)
  216748. mediaControl->Stop();
  216749. removeGraphFromRot();
  216750. for (int i = viewerComps.size(); --i >= 0;)
  216751. viewerComps.getUnchecked(i)->ownerDeleted();
  216752. callback = 0;
  216753. graphBuilder = 0;
  216754. sampleGrabber = 0;
  216755. mediaControl = 0;
  216756. filter = 0;
  216757. captureGraphBuilder = 0;
  216758. smartTee = 0;
  216759. smartTeePreviewOutputPin = 0;
  216760. smartTeeCaptureOutputPin = 0;
  216761. asfWriter = 0;
  216762. }
  216763. void addUser()
  216764. {
  216765. if (ok && activeUsers++ == 0)
  216766. mediaControl->Run();
  216767. }
  216768. void removeUser()
  216769. {
  216770. if (ok && --activeUsers == 0)
  216771. mediaControl->Stop();
  216772. }
  216773. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216774. {
  216775. if (recordNextFrameTime)
  216776. {
  216777. const double defaultCameraLatency = 0.1;
  216778. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216779. recordNextFrameTime = false;
  216780. ComSmartPtr <IPin> pin;
  216781. if (getPin (filter, PINDIR_OUTPUT, &pin))
  216782. {
  216783. ComSmartPtr <IAMPushSource> pushSource;
  216784. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  216785. if (pushSource != 0)
  216786. {
  216787. REFERENCE_TIME latency = 0;
  216788. hr = pushSource->GetLatency (&latency);
  216789. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216790. }
  216791. }
  216792. }
  216793. {
  216794. const int lineStride = width * 3;
  216795. const ScopedLock sl (imageSwapLock);
  216796. {
  216797. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216798. for (int i = 0; i < height; ++i)
  216799. memcpy (destData.getLinePointer ((height - 1) - i),
  216800. buffer + lineStride * i,
  216801. lineStride);
  216802. }
  216803. imageNeedsFlipping = true;
  216804. }
  216805. if (listeners.size() > 0)
  216806. callListeners (loadingImage);
  216807. sendChangeMessage (this);
  216808. }
  216809. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216810. {
  216811. if (imageNeedsFlipping)
  216812. {
  216813. const ScopedLock sl (imageSwapLock);
  216814. swapVariables (loadingImage, activeImage);
  216815. imageNeedsFlipping = false;
  216816. }
  216817. RectanglePlacement rp (RectanglePlacement::centred);
  216818. double dx = 0, dy = 0, dw = width, dh = height;
  216819. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216820. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216821. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216822. g.saveState();
  216823. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216824. g.fillAll (Colours::black);
  216825. g.restoreState();
  216826. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216827. }
  216828. bool createFileCaptureFilter (const File& file)
  216829. {
  216830. removeFileCaptureFilter();
  216831. file.deleteFile();
  216832. mediaControl->Stop();
  216833. firstRecordedTime = Time();
  216834. recordNextFrameTime = true;
  216835. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216836. if (SUCCEEDED (hr))
  216837. {
  216838. ComSmartPtr <IFileSinkFilter> fileSink;
  216839. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  216840. if (SUCCEEDED (hr))
  216841. {
  216842. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216843. if (SUCCEEDED (hr))
  216844. {
  216845. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216846. if (SUCCEEDED (hr))
  216847. {
  216848. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216849. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  216850. asfConfig->SetIndexMode (true);
  216851. ComSmartPtr <IWMProfileManager> profileManager;
  216852. hr = WMCreateProfileManager (&profileManager);
  216853. // This gibberish is the DirectShow profile for a video-only wmv file.
  216854. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  216855. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216856. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216857. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  216858. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  216859. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216860. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  216861. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  216862. prof = prof.replace ("$WIDTH", String (width))
  216863. .replace ("$HEIGHT", String (height));
  216864. ComSmartPtr <IWMProfile> currentProfile;
  216865. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  216866. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216867. if (SUCCEEDED (hr))
  216868. {
  216869. ComSmartPtr <IPin> asfWriterInputPin;
  216870. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  216871. {
  216872. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216873. if (SUCCEEDED (hr)
  216874. && ok && activeUsers > 0
  216875. && SUCCEEDED (mediaControl->Run()))
  216876. {
  216877. return true;
  216878. }
  216879. }
  216880. }
  216881. }
  216882. }
  216883. }
  216884. }
  216885. removeFileCaptureFilter();
  216886. if (ok && activeUsers > 0)
  216887. mediaControl->Run();
  216888. return false;
  216889. }
  216890. void removeFileCaptureFilter()
  216891. {
  216892. mediaControl->Stop();
  216893. if (asfWriter != 0)
  216894. {
  216895. graphBuilder->RemoveFilter (asfWriter);
  216896. asfWriter = 0;
  216897. }
  216898. if (ok && activeUsers > 0)
  216899. mediaControl->Run();
  216900. }
  216901. void addListener (CameraDevice::Listener* listenerToAdd)
  216902. {
  216903. const ScopedLock sl (listenerLock);
  216904. if (listeners.size() == 0)
  216905. addUser();
  216906. listeners.addIfNotAlreadyThere (listenerToAdd);
  216907. }
  216908. void removeListener (CameraDevice::Listener* listenerToRemove)
  216909. {
  216910. const ScopedLock sl (listenerLock);
  216911. listeners.removeValue (listenerToRemove);
  216912. if (listeners.size() == 0)
  216913. removeUser();
  216914. }
  216915. void callListeners (const Image& image)
  216916. {
  216917. const ScopedLock sl (listenerLock);
  216918. for (int i = listeners.size(); --i >= 0;)
  216919. {
  216920. CameraDevice::Listener* const l = listeners[i];
  216921. if (l != 0)
  216922. l->imageReceived (image);
  216923. }
  216924. }
  216925. class DShowCaptureViewerComp : public Component,
  216926. public ChangeListener
  216927. {
  216928. public:
  216929. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216930. : owner (owner_)
  216931. {
  216932. setOpaque (true);
  216933. owner->addChangeListener (this);
  216934. owner->addUser();
  216935. owner->viewerComps.add (this);
  216936. setSize (owner_->width, owner_->height);
  216937. }
  216938. ~DShowCaptureViewerComp()
  216939. {
  216940. if (owner != 0)
  216941. {
  216942. owner->viewerComps.removeValue (this);
  216943. owner->removeUser();
  216944. owner->removeChangeListener (this);
  216945. }
  216946. }
  216947. void ownerDeleted()
  216948. {
  216949. owner = 0;
  216950. }
  216951. void paint (Graphics& g)
  216952. {
  216953. g.setColour (Colours::black);
  216954. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216955. if (owner != 0)
  216956. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216957. else
  216958. g.fillAll (Colours::black);
  216959. }
  216960. void changeListenerCallback (void*)
  216961. {
  216962. repaint();
  216963. }
  216964. private:
  216965. DShowCameraDeviceInteral* owner;
  216966. };
  216967. bool ok;
  216968. int width, height;
  216969. Time firstRecordedTime;
  216970. Array <DShowCaptureViewerComp*> viewerComps;
  216971. private:
  216972. CameraDevice* const owner;
  216973. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216974. ComSmartPtr <IBaseFilter> filter;
  216975. ComSmartPtr <IBaseFilter> smartTee;
  216976. ComSmartPtr <IGraphBuilder> graphBuilder;
  216977. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216978. ComSmartPtr <IMediaControl> mediaControl;
  216979. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216980. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216981. ComSmartPtr <IBaseFilter> asfWriter;
  216982. int activeUsers;
  216983. Array <int> widths, heights;
  216984. DWORD graphRegistrationID;
  216985. CriticalSection imageSwapLock;
  216986. bool imageNeedsFlipping;
  216987. Image loadingImage;
  216988. Image activeImage;
  216989. bool recordNextFrameTime;
  216990. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216991. {
  216992. widths.clear();
  216993. heights.clear();
  216994. int count = 0, size = 0;
  216995. streamConfig->GetNumberOfCapabilities (&count, &size);
  216996. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216997. {
  216998. for (int i = 0; i < count; ++i)
  216999. {
  217000. VIDEO_STREAM_CONFIG_CAPS scc;
  217001. AM_MEDIA_TYPE* config;
  217002. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  217003. if (SUCCEEDED (hr))
  217004. {
  217005. const int w = scc.InputSize.cx;
  217006. const int h = scc.InputSize.cy;
  217007. bool duplicate = false;
  217008. for (int j = widths.size(); --j >= 0;)
  217009. {
  217010. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  217011. {
  217012. duplicate = true;
  217013. break;
  217014. }
  217015. }
  217016. if (! duplicate)
  217017. {
  217018. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  217019. widths.add (w);
  217020. heights.add (h);
  217021. }
  217022. deleteMediaType (config);
  217023. }
  217024. }
  217025. }
  217026. }
  217027. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  217028. const int minWidth, const int minHeight,
  217029. const int maxWidth, const int maxHeight)
  217030. {
  217031. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  217032. streamConfig->GetNumberOfCapabilities (&count, &size);
  217033. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  217034. {
  217035. AM_MEDIA_TYPE* config;
  217036. VIDEO_STREAM_CONFIG_CAPS scc;
  217037. for (int i = 0; i < count; ++i)
  217038. {
  217039. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  217040. if (SUCCEEDED (hr))
  217041. {
  217042. if (scc.InputSize.cx >= minWidth
  217043. && scc.InputSize.cy >= minHeight
  217044. && scc.InputSize.cx <= maxWidth
  217045. && scc.InputSize.cy <= maxHeight)
  217046. {
  217047. int area = scc.InputSize.cx * scc.InputSize.cy;
  217048. if (area > bestArea)
  217049. {
  217050. bestIndex = i;
  217051. bestArea = area;
  217052. }
  217053. }
  217054. deleteMediaType (config);
  217055. }
  217056. }
  217057. if (bestIndex >= 0)
  217058. {
  217059. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  217060. hr = streamConfig->SetFormat (config);
  217061. deleteMediaType (config);
  217062. return SUCCEEDED (hr);
  217063. }
  217064. }
  217065. return false;
  217066. }
  217067. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  217068. {
  217069. ComSmartPtr <IEnumPins> enumerator;
  217070. ComSmartPtr <IPin> pin;
  217071. filter->EnumPins (&enumerator);
  217072. while (enumerator->Next (1, &pin, 0) == S_OK)
  217073. {
  217074. PIN_DIRECTION dir;
  217075. pin->QueryDirection (&dir);
  217076. if (wantedDirection == dir)
  217077. {
  217078. PIN_INFO info;
  217079. zerostruct (info);
  217080. pin->QueryPinInfo (&info);
  217081. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  217082. {
  217083. pin->AddRef();
  217084. *result = pin;
  217085. return true;
  217086. }
  217087. }
  217088. }
  217089. return false;
  217090. }
  217091. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  217092. {
  217093. ComSmartPtr <IPin> in, out;
  217094. return getPin (first, PINDIR_OUTPUT, &out)
  217095. && getPin (second, PINDIR_INPUT, &in)
  217096. && SUCCEEDED (graphBuilder->Connect (out, in));
  217097. }
  217098. bool addGraphToRot()
  217099. {
  217100. ComSmartPtr <IRunningObjectTable> rot;
  217101. if (FAILED (GetRunningObjectTable (0, &rot)))
  217102. return false;
  217103. ComSmartPtr <IMoniker> moniker;
  217104. WCHAR buffer[128];
  217105. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  217106. if (FAILED (hr))
  217107. return false;
  217108. graphRegistrationID = 0;
  217109. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  217110. }
  217111. void removeGraphFromRot()
  217112. {
  217113. ComSmartPtr <IRunningObjectTable> rot;
  217114. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  217115. rot->Revoke (graphRegistrationID);
  217116. }
  217117. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  217118. {
  217119. if (pmt->cbFormat != 0)
  217120. CoTaskMemFree ((PVOID) pmt->pbFormat);
  217121. if (pmt->pUnk != 0)
  217122. pmt->pUnk->Release();
  217123. CoTaskMemFree (pmt);
  217124. }
  217125. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  217126. {
  217127. public:
  217128. GrabberCallback (DShowCameraDeviceInteral& owner_)
  217129. : owner (owner_)
  217130. {
  217131. }
  217132. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  217133. {
  217134. return E_FAIL;
  217135. }
  217136. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  217137. {
  217138. owner.handleFrame (time, buffer, bufferSize);
  217139. return S_OK;
  217140. }
  217141. private:
  217142. DShowCameraDeviceInteral& owner;
  217143. GrabberCallback (const GrabberCallback&);
  217144. GrabberCallback& operator= (const GrabberCallback&);
  217145. };
  217146. ComSmartPtr <GrabberCallback> callback;
  217147. Array <CameraDevice::Listener*> listeners;
  217148. CriticalSection listenerLock;
  217149. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  217150. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  217151. };
  217152. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  217153. : name (name_)
  217154. {
  217155. isRecording = false;
  217156. }
  217157. CameraDevice::~CameraDevice()
  217158. {
  217159. stopRecording();
  217160. delete static_cast <DShowCameraDeviceInteral*> (internal);
  217161. internal = 0;
  217162. }
  217163. Component* CameraDevice::createViewerComponent()
  217164. {
  217165. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  217166. }
  217167. const String CameraDevice::getFileExtension()
  217168. {
  217169. return ".wmv";
  217170. }
  217171. void CameraDevice::startRecordingToFile (const File& file, int quality)
  217172. {
  217173. stopRecording();
  217174. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217175. d->addUser();
  217176. isRecording = d->createFileCaptureFilter (file);
  217177. }
  217178. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  217179. {
  217180. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217181. return d->firstRecordedTime;
  217182. }
  217183. void CameraDevice::stopRecording()
  217184. {
  217185. if (isRecording)
  217186. {
  217187. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217188. d->removeFileCaptureFilter();
  217189. d->removeUser();
  217190. isRecording = false;
  217191. }
  217192. }
  217193. void CameraDevice::addListener (Listener* listenerToAdd)
  217194. {
  217195. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217196. if (listenerToAdd != 0)
  217197. d->addListener (listenerToAdd);
  217198. }
  217199. void CameraDevice::removeListener (Listener* listenerToRemove)
  217200. {
  217201. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217202. if (listenerToRemove != 0)
  217203. d->removeListener (listenerToRemove);
  217204. }
  217205. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  217206. const int deviceIndexToOpen,
  217207. String& name)
  217208. {
  217209. int index = 0;
  217210. ComSmartPtr <IBaseFilter> result;
  217211. ComSmartPtr <ICreateDevEnum> pDevEnum;
  217212. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  217213. if (SUCCEEDED (hr))
  217214. {
  217215. ComSmartPtr <IEnumMoniker> enumerator;
  217216. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  217217. if (SUCCEEDED (hr) && enumerator != 0)
  217218. {
  217219. ComSmartPtr <IBaseFilter> captureFilter;
  217220. ComSmartPtr <IMoniker> moniker;
  217221. ULONG fetched;
  217222. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  217223. {
  217224. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  217225. if (SUCCEEDED (hr))
  217226. {
  217227. ComSmartPtr <IPropertyBag> propertyBag;
  217228. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  217229. if (SUCCEEDED (hr))
  217230. {
  217231. VARIANT var;
  217232. var.vt = VT_BSTR;
  217233. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  217234. propertyBag = 0;
  217235. if (SUCCEEDED (hr))
  217236. {
  217237. if (names != 0)
  217238. names->add (var.bstrVal);
  217239. if (index == deviceIndexToOpen)
  217240. {
  217241. name = var.bstrVal;
  217242. result = captureFilter;
  217243. captureFilter = 0;
  217244. break;
  217245. }
  217246. ++index;
  217247. }
  217248. moniker = 0;
  217249. }
  217250. captureFilter = 0;
  217251. }
  217252. }
  217253. }
  217254. }
  217255. return result;
  217256. }
  217257. const StringArray CameraDevice::getAvailableDevices()
  217258. {
  217259. StringArray devs;
  217260. String dummy;
  217261. enumerateCameras (&devs, -1, dummy);
  217262. return devs;
  217263. }
  217264. CameraDevice* CameraDevice::openDevice (int index,
  217265. int minWidth, int minHeight,
  217266. int maxWidth, int maxHeight)
  217267. {
  217268. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  217269. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  217270. if (SUCCEEDED (hr))
  217271. {
  217272. String name;
  217273. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  217274. if (filter != 0)
  217275. {
  217276. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217277. DShowCameraDeviceInteral* const intern
  217278. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217279. minWidth, minHeight, maxWidth, maxHeight);
  217280. cam->internal = intern;
  217281. if (intern->ok)
  217282. return cam.release();
  217283. }
  217284. }
  217285. return 0;
  217286. }
  217287. #endif
  217288. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217289. #endif
  217290. // Auto-link the other win32 libs that are needed by library calls..
  217291. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217292. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217293. // Auto-links to various win32 libs that are needed by library calls..
  217294. #pragma comment(lib, "kernel32.lib")
  217295. #pragma comment(lib, "user32.lib")
  217296. #pragma comment(lib, "shell32.lib")
  217297. #pragma comment(lib, "gdi32.lib")
  217298. #pragma comment(lib, "vfw32.lib")
  217299. #pragma comment(lib, "comdlg32.lib")
  217300. #pragma comment(lib, "winmm.lib")
  217301. #pragma comment(lib, "wininet.lib")
  217302. #pragma comment(lib, "ole32.lib")
  217303. #pragma comment(lib, "oleaut32.lib")
  217304. #pragma comment(lib, "advapi32.lib")
  217305. #pragma comment(lib, "ws2_32.lib")
  217306. #pragma comment(lib, "version.lib")
  217307. #ifdef _NATIVE_WCHAR_T_DEFINED
  217308. #ifdef _DEBUG
  217309. #pragma comment(lib, "comsuppwd.lib")
  217310. #else
  217311. #pragma comment(lib, "comsuppw.lib")
  217312. #endif
  217313. #else
  217314. #ifdef _DEBUG
  217315. #pragma comment(lib, "comsuppd.lib")
  217316. #else
  217317. #pragma comment(lib, "comsupp.lib")
  217318. #endif
  217319. #endif
  217320. #if JUCE_OPENGL
  217321. #pragma comment(lib, "OpenGL32.Lib")
  217322. #pragma comment(lib, "GlU32.Lib")
  217323. #endif
  217324. #if JUCE_QUICKTIME
  217325. #pragma comment (lib, "QTMLClient.lib")
  217326. #endif
  217327. #if JUCE_USE_CAMERA
  217328. #pragma comment (lib, "Strmiids.lib")
  217329. #pragma comment (lib, "wmvcore.lib")
  217330. #endif
  217331. #if JUCE_DIRECT2D
  217332. #pragma comment (lib, "Dwrite.lib")
  217333. #pragma comment (lib, "D2d1.lib")
  217334. #endif
  217335. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217336. #endif
  217337. END_JUCE_NAMESPACE
  217338. #endif
  217339. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217340. #endif
  217341. #if JUCE_LINUX
  217342. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217343. /*
  217344. This file wraps together all the mac-specific code, so that
  217345. we can include all the native headers just once, and compile all our
  217346. platform-specific stuff in one big lump, keeping it out of the way of
  217347. the rest of the codebase.
  217348. */
  217349. #if JUCE_LINUX
  217350. BEGIN_JUCE_NAMESPACE
  217351. #define JUCE_INCLUDED_FILE 1
  217352. // Now include the actual code files..
  217353. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217354. /*
  217355. This file contains posix routines that are common to both the Linux and Mac builds.
  217356. It gets included directly in the cpp files for these platforms.
  217357. */
  217358. CriticalSection::CriticalSection() throw()
  217359. {
  217360. pthread_mutexattr_t atts;
  217361. pthread_mutexattr_init (&atts);
  217362. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217363. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217364. pthread_mutex_init (&internal, &atts);
  217365. }
  217366. CriticalSection::~CriticalSection() throw()
  217367. {
  217368. pthread_mutex_destroy (&internal);
  217369. }
  217370. void CriticalSection::enter() const throw()
  217371. {
  217372. pthread_mutex_lock (&internal);
  217373. }
  217374. bool CriticalSection::tryEnter() const throw()
  217375. {
  217376. return pthread_mutex_trylock (&internal) == 0;
  217377. }
  217378. void CriticalSection::exit() const throw()
  217379. {
  217380. pthread_mutex_unlock (&internal);
  217381. }
  217382. class WaitableEventImpl
  217383. {
  217384. public:
  217385. WaitableEventImpl (const bool manualReset_)
  217386. : triggered (false),
  217387. manualReset (manualReset_)
  217388. {
  217389. pthread_cond_init (&condition, 0);
  217390. pthread_mutexattr_t atts;
  217391. pthread_mutexattr_init (&atts);
  217392. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217393. pthread_mutex_init (&mutex, &atts);
  217394. }
  217395. ~WaitableEventImpl()
  217396. {
  217397. pthread_cond_destroy (&condition);
  217398. pthread_mutex_destroy (&mutex);
  217399. }
  217400. bool wait (const int timeOutMillisecs) throw()
  217401. {
  217402. pthread_mutex_lock (&mutex);
  217403. if (! triggered)
  217404. {
  217405. if (timeOutMillisecs < 0)
  217406. {
  217407. do
  217408. {
  217409. pthread_cond_wait (&condition, &mutex);
  217410. }
  217411. while (! triggered);
  217412. }
  217413. else
  217414. {
  217415. struct timeval now;
  217416. gettimeofday (&now, 0);
  217417. struct timespec time;
  217418. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217419. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217420. if (time.tv_nsec >= 1000000000)
  217421. {
  217422. time.tv_nsec -= 1000000000;
  217423. time.tv_sec++;
  217424. }
  217425. do
  217426. {
  217427. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217428. {
  217429. pthread_mutex_unlock (&mutex);
  217430. return false;
  217431. }
  217432. }
  217433. while (! triggered);
  217434. }
  217435. }
  217436. if (! manualReset)
  217437. triggered = false;
  217438. pthread_mutex_unlock (&mutex);
  217439. return true;
  217440. }
  217441. void signal() throw()
  217442. {
  217443. pthread_mutex_lock (&mutex);
  217444. triggered = true;
  217445. pthread_cond_broadcast (&condition);
  217446. pthread_mutex_unlock (&mutex);
  217447. }
  217448. void reset() throw()
  217449. {
  217450. pthread_mutex_lock (&mutex);
  217451. triggered = false;
  217452. pthread_mutex_unlock (&mutex);
  217453. }
  217454. private:
  217455. pthread_cond_t condition;
  217456. pthread_mutex_t mutex;
  217457. bool triggered;
  217458. const bool manualReset;
  217459. WaitableEventImpl (const WaitableEventImpl&);
  217460. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217461. };
  217462. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217463. : internal (new WaitableEventImpl (manualReset))
  217464. {
  217465. }
  217466. WaitableEvent::~WaitableEvent() throw()
  217467. {
  217468. delete static_cast <WaitableEventImpl*> (internal);
  217469. }
  217470. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217471. {
  217472. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217473. }
  217474. void WaitableEvent::signal() const throw()
  217475. {
  217476. static_cast <WaitableEventImpl*> (internal)->signal();
  217477. }
  217478. void WaitableEvent::reset() const throw()
  217479. {
  217480. static_cast <WaitableEventImpl*> (internal)->reset();
  217481. }
  217482. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217483. {
  217484. struct timespec time;
  217485. time.tv_sec = millisecs / 1000;
  217486. time.tv_nsec = (millisecs % 1000) * 1000000;
  217487. nanosleep (&time, 0);
  217488. }
  217489. const juce_wchar File::separator = '/';
  217490. const String File::separatorString ("/");
  217491. const File File::getCurrentWorkingDirectory()
  217492. {
  217493. HeapBlock<char> heapBuffer;
  217494. char localBuffer [1024];
  217495. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217496. int bufferSize = 4096;
  217497. while (cwd == 0 && errno == ERANGE)
  217498. {
  217499. heapBuffer.malloc (bufferSize);
  217500. cwd = getcwd (heapBuffer, bufferSize - 1);
  217501. bufferSize += 1024;
  217502. }
  217503. return File (String::fromUTF8 (cwd));
  217504. }
  217505. bool File::setAsCurrentWorkingDirectory() const
  217506. {
  217507. return chdir (getFullPathName().toUTF8()) == 0;
  217508. }
  217509. static bool juce_stat (const String& fileName, struct stat& info)
  217510. {
  217511. return fileName.isNotEmpty()
  217512. && (stat (fileName.toUTF8(), &info) == 0);
  217513. }
  217514. bool File::isDirectory() const
  217515. {
  217516. struct stat info;
  217517. return fullPath.isEmpty()
  217518. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217519. }
  217520. bool File::exists() const
  217521. {
  217522. return fullPath.isNotEmpty()
  217523. && access (fullPath.toUTF8(), F_OK) == 0;
  217524. }
  217525. bool File::existsAsFile() const
  217526. {
  217527. return exists() && ! isDirectory();
  217528. }
  217529. int64 File::getSize() const
  217530. {
  217531. struct stat info;
  217532. return juce_stat (fullPath, info) ? info.st_size : 0;
  217533. }
  217534. bool File::hasWriteAccess() const
  217535. {
  217536. if (exists())
  217537. return access (fullPath.toUTF8(), W_OK) == 0;
  217538. if ((! isDirectory()) && fullPath.containsChar (separator))
  217539. return getParentDirectory().hasWriteAccess();
  217540. return false;
  217541. }
  217542. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217543. {
  217544. struct stat info;
  217545. const int res = stat (fullPath.toUTF8(), &info);
  217546. if (res != 0)
  217547. return false;
  217548. info.st_mode &= 0777; // Just permissions
  217549. if (shouldBeReadOnly)
  217550. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217551. else
  217552. // Give everybody write permission?
  217553. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217554. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217555. }
  217556. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217557. {
  217558. modificationTime = 0;
  217559. accessTime = 0;
  217560. creationTime = 0;
  217561. struct stat info;
  217562. const int res = stat (fullPath.toUTF8(), &info);
  217563. if (res == 0)
  217564. {
  217565. modificationTime = (int64) info.st_mtime * 1000;
  217566. accessTime = (int64) info.st_atime * 1000;
  217567. creationTime = (int64) info.st_ctime * 1000;
  217568. }
  217569. }
  217570. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217571. {
  217572. struct utimbuf times;
  217573. times.actime = (time_t) (accessTime / 1000);
  217574. times.modtime = (time_t) (modificationTime / 1000);
  217575. return utime (fullPath.toUTF8(), &times) == 0;
  217576. }
  217577. bool File::deleteFile() const
  217578. {
  217579. if (! exists())
  217580. return true;
  217581. else if (isDirectory())
  217582. return rmdir (fullPath.toUTF8()) == 0;
  217583. else
  217584. return remove (fullPath.toUTF8()) == 0;
  217585. }
  217586. bool File::moveInternal (const File& dest) const
  217587. {
  217588. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217589. return true;
  217590. if (hasWriteAccess() && copyInternal (dest))
  217591. {
  217592. if (deleteFile())
  217593. return true;
  217594. dest.deleteFile();
  217595. }
  217596. return false;
  217597. }
  217598. void File::createDirectoryInternal (const String& fileName) const
  217599. {
  217600. mkdir (fileName.toUTF8(), 0777);
  217601. }
  217602. int64 juce_fileSetPosition (void* handle, int64 pos)
  217603. {
  217604. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217605. return pos;
  217606. return -1;
  217607. }
  217608. void FileInputStream::openHandle()
  217609. {
  217610. totalSize = file.getSize();
  217611. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217612. if (f != -1)
  217613. fileHandle = (void*) f;
  217614. }
  217615. void FileInputStream::closeHandle()
  217616. {
  217617. if (fileHandle != 0)
  217618. {
  217619. close ((int) (pointer_sized_int) fileHandle);
  217620. fileHandle = 0;
  217621. }
  217622. }
  217623. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217624. {
  217625. if (fileHandle != 0)
  217626. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217627. return 0;
  217628. }
  217629. void FileOutputStream::openHandle()
  217630. {
  217631. if (file.exists())
  217632. {
  217633. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217634. if (f != -1)
  217635. {
  217636. currentPosition = lseek (f, 0, SEEK_END);
  217637. if (currentPosition >= 0)
  217638. fileHandle = (void*) f;
  217639. else
  217640. close (f);
  217641. }
  217642. }
  217643. else
  217644. {
  217645. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217646. if (f != -1)
  217647. fileHandle = (void*) f;
  217648. }
  217649. }
  217650. void FileOutputStream::closeHandle()
  217651. {
  217652. if (fileHandle != 0)
  217653. {
  217654. close ((int) (pointer_sized_int) fileHandle);
  217655. fileHandle = 0;
  217656. }
  217657. }
  217658. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217659. {
  217660. if (fileHandle != 0)
  217661. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217662. return 0;
  217663. }
  217664. void FileOutputStream::flushInternal()
  217665. {
  217666. if (fileHandle != 0)
  217667. fsync ((int) (pointer_sized_int) fileHandle);
  217668. }
  217669. const File juce_getExecutableFile()
  217670. {
  217671. Dl_info exeInfo;
  217672. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217673. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217674. }
  217675. // if this file doesn't exist, find a parent of it that does..
  217676. static bool juce_doStatFS (File f, struct statfs& result)
  217677. {
  217678. for (int i = 5; --i >= 0;)
  217679. {
  217680. if (f.exists())
  217681. break;
  217682. f = f.getParentDirectory();
  217683. }
  217684. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217685. }
  217686. int64 File::getBytesFreeOnVolume() const
  217687. {
  217688. struct statfs buf;
  217689. if (juce_doStatFS (*this, buf))
  217690. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217691. return 0;
  217692. }
  217693. int64 File::getVolumeTotalSize() const
  217694. {
  217695. struct statfs buf;
  217696. if (juce_doStatFS (*this, buf))
  217697. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217698. return 0;
  217699. }
  217700. const String File::getVolumeLabel() const
  217701. {
  217702. #if JUCE_MAC
  217703. struct VolAttrBuf
  217704. {
  217705. u_int32_t length;
  217706. attrreference_t mountPointRef;
  217707. char mountPointSpace [MAXPATHLEN];
  217708. } attrBuf;
  217709. struct attrlist attrList;
  217710. zerostruct (attrList);
  217711. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217712. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217713. File f (*this);
  217714. for (;;)
  217715. {
  217716. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217717. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217718. (int) attrBuf.mountPointRef.attr_length);
  217719. const File parent (f.getParentDirectory());
  217720. if (f == parent)
  217721. break;
  217722. f = parent;
  217723. }
  217724. #endif
  217725. return String::empty;
  217726. }
  217727. int File::getVolumeSerialNumber() const
  217728. {
  217729. return 0; // xxx
  217730. }
  217731. void juce_runSystemCommand (const String& command)
  217732. {
  217733. int result = system (command.toUTF8());
  217734. (void) result;
  217735. }
  217736. const String juce_getOutputFromCommand (const String& command)
  217737. {
  217738. // slight bodge here, as we just pipe the output into a temp file and read it...
  217739. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217740. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217741. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217742. String result (tempFile.loadFileAsString());
  217743. tempFile.deleteFile();
  217744. return result;
  217745. }
  217746. class InterProcessLock::Pimpl
  217747. {
  217748. public:
  217749. Pimpl (const String& name, const int timeOutMillisecs)
  217750. : handle (0), refCount (1)
  217751. {
  217752. #if JUCE_MAC
  217753. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217754. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217755. #else
  217756. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217757. #endif
  217758. temp.create();
  217759. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217760. if (handle != 0)
  217761. {
  217762. struct flock fl;
  217763. zerostruct (fl);
  217764. fl.l_whence = SEEK_SET;
  217765. fl.l_type = F_WRLCK;
  217766. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217767. for (;;)
  217768. {
  217769. const int result = fcntl (handle, F_SETLK, &fl);
  217770. if (result >= 0)
  217771. return;
  217772. if (errno != EINTR)
  217773. {
  217774. if (timeOutMillisecs == 0
  217775. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217776. break;
  217777. Thread::sleep (10);
  217778. }
  217779. }
  217780. }
  217781. closeFile();
  217782. }
  217783. ~Pimpl()
  217784. {
  217785. closeFile();
  217786. }
  217787. void closeFile()
  217788. {
  217789. if (handle != 0)
  217790. {
  217791. struct flock fl;
  217792. zerostruct (fl);
  217793. fl.l_whence = SEEK_SET;
  217794. fl.l_type = F_UNLCK;
  217795. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217796. {}
  217797. close (handle);
  217798. handle = 0;
  217799. }
  217800. }
  217801. int handle, refCount;
  217802. };
  217803. InterProcessLock::InterProcessLock (const String& name_)
  217804. : name (name_)
  217805. {
  217806. }
  217807. InterProcessLock::~InterProcessLock()
  217808. {
  217809. }
  217810. bool InterProcessLock::enter (const int timeOutMillisecs)
  217811. {
  217812. const ScopedLock sl (lock);
  217813. if (pimpl == 0)
  217814. {
  217815. pimpl = new Pimpl (name, timeOutMillisecs);
  217816. if (pimpl->handle == 0)
  217817. pimpl = 0;
  217818. }
  217819. else
  217820. {
  217821. pimpl->refCount++;
  217822. }
  217823. return pimpl != 0;
  217824. }
  217825. void InterProcessLock::exit()
  217826. {
  217827. const ScopedLock sl (lock);
  217828. // Trying to release the lock too many times!
  217829. jassert (pimpl != 0);
  217830. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217831. pimpl = 0;
  217832. }
  217833. void JUCE_API juce_threadEntryPoint (void*);
  217834. void* threadEntryProc (void* userData)
  217835. {
  217836. JUCE_AUTORELEASEPOOL
  217837. juce_threadEntryPoint (userData);
  217838. return 0;
  217839. }
  217840. void* juce_createThread (void* userData)
  217841. {
  217842. pthread_t handle = 0;
  217843. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217844. {
  217845. pthread_detach (handle);
  217846. return (void*) handle;
  217847. }
  217848. return 0;
  217849. }
  217850. void juce_killThread (void* handle)
  217851. {
  217852. if (handle != 0)
  217853. pthread_cancel ((pthread_t) handle);
  217854. }
  217855. void juce_setCurrentThreadName (const String& /*name*/)
  217856. {
  217857. }
  217858. bool juce_setThreadPriority (void* handle, int priority)
  217859. {
  217860. struct sched_param param;
  217861. int policy;
  217862. priority = jlimit (0, 10, priority);
  217863. if (handle == 0)
  217864. handle = (void*) pthread_self();
  217865. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217866. return false;
  217867. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217868. const int minPriority = sched_get_priority_min (policy);
  217869. const int maxPriority = sched_get_priority_max (policy);
  217870. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217871. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217872. }
  217873. Thread::ThreadID Thread::getCurrentThreadId()
  217874. {
  217875. return (ThreadID) pthread_self();
  217876. }
  217877. void Thread::yield()
  217878. {
  217879. sched_yield();
  217880. }
  217881. /* Remove this macro if you're having problems compiling the cpu affinity
  217882. calls (the API for these has changed about quite a bit in various Linux
  217883. versions, and a lot of distros seem to ship with obsolete versions)
  217884. */
  217885. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217886. #define SUPPORT_AFFINITIES 1
  217887. #endif
  217888. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217889. {
  217890. #if SUPPORT_AFFINITIES
  217891. cpu_set_t affinity;
  217892. CPU_ZERO (&affinity);
  217893. for (int i = 0; i < 32; ++i)
  217894. if ((affinityMask & (1 << i)) != 0)
  217895. CPU_SET (i, &affinity);
  217896. /*
  217897. N.B. If this line causes a compile error, then you've probably not got the latest
  217898. version of glibc installed.
  217899. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217900. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217901. */
  217902. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217903. sched_yield();
  217904. #else
  217905. /* affinities aren't supported because either the appropriate header files weren't found,
  217906. or the SUPPORT_AFFINITIES macro was turned off
  217907. */
  217908. jassertfalse;
  217909. #endif
  217910. }
  217911. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217912. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217913. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217914. // compiled on its own).
  217915. #if JUCE_INCLUDED_FILE
  217916. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217917. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217918. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217919. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217920. bool File::copyInternal (const File& dest) const
  217921. {
  217922. FileInputStream in (*this);
  217923. if (dest.deleteFile())
  217924. {
  217925. {
  217926. FileOutputStream out (dest);
  217927. if (out.failedToOpen())
  217928. return false;
  217929. if (out.writeFromInputStream (in, -1) == getSize())
  217930. return true;
  217931. }
  217932. dest.deleteFile();
  217933. }
  217934. return false;
  217935. }
  217936. void File::findFileSystemRoots (Array<File>& destArray)
  217937. {
  217938. destArray.add (File ("/"));
  217939. }
  217940. bool File::isOnCDRomDrive() const
  217941. {
  217942. struct statfs buf;
  217943. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217944. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217945. }
  217946. bool File::isOnHardDisk() const
  217947. {
  217948. struct statfs buf;
  217949. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217950. {
  217951. switch (buf.f_type)
  217952. {
  217953. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217954. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217955. case U_NFS_SUPER_MAGIC: // Network NFS
  217956. case U_SMB_SUPER_MAGIC: // Network Samba
  217957. return false;
  217958. default:
  217959. // Assume anything else is a hard-disk (but note it could
  217960. // be a RAM disk. There isn't a good way of determining
  217961. // this for sure)
  217962. return true;
  217963. }
  217964. }
  217965. // Assume so if this fails for some reason
  217966. return true;
  217967. }
  217968. bool File::isOnRemovableDrive() const
  217969. {
  217970. jassertfalse; // xxx not implemented for linux!
  217971. return false;
  217972. }
  217973. bool File::isHidden() const
  217974. {
  217975. return getFileName().startsWithChar ('.');
  217976. }
  217977. static const File juce_readlink (const char* const utf8, const File& defaultFile)
  217978. {
  217979. const int size = 8192;
  217980. HeapBlock<char> buffer;
  217981. buffer.malloc (size + 4);
  217982. const size_t numBytes = readlink (utf8, buffer, size);
  217983. if (numBytes > 0 && numBytes <= size)
  217984. return File (String::fromUTF8 (buffer, (int) numBytes));
  217985. return defaultFile;
  217986. }
  217987. const File File::getLinkedTarget() const
  217988. {
  217989. return juce_readlink (getFullPathName().toUTF8(), *this);
  217990. }
  217991. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217992. const File File::getSpecialLocation (const SpecialLocationType type)
  217993. {
  217994. switch (type)
  217995. {
  217996. case userHomeDirectory:
  217997. {
  217998. const char* homeDir = getenv ("HOME");
  217999. if (homeDir == 0)
  218000. {
  218001. struct passwd* const pw = getpwuid (getuid());
  218002. if (pw != 0)
  218003. homeDir = pw->pw_dir;
  218004. }
  218005. return File (String::fromUTF8 (homeDir));
  218006. }
  218007. case userDocumentsDirectory:
  218008. case userMusicDirectory:
  218009. case userMoviesDirectory:
  218010. case userApplicationDataDirectory:
  218011. return File ("~");
  218012. case userDesktopDirectory:
  218013. return File ("~/Desktop");
  218014. case commonApplicationDataDirectory:
  218015. return File ("/var");
  218016. case globalApplicationsDirectory:
  218017. return File ("/usr");
  218018. case tempDirectory:
  218019. {
  218020. File tmp ("/var/tmp");
  218021. if (! tmp.isDirectory())
  218022. {
  218023. tmp = "/tmp";
  218024. if (! tmp.isDirectory())
  218025. tmp = File::getCurrentWorkingDirectory();
  218026. }
  218027. return tmp;
  218028. }
  218029. case invokedExecutableFile:
  218030. if (juce_Argv0 != 0)
  218031. return File (String::fromUTF8 (juce_Argv0));
  218032. // deliberate fall-through...
  218033. case currentExecutableFile:
  218034. case currentApplicationFile:
  218035. return juce_getExecutableFile();
  218036. case hostApplicationPath:
  218037. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  218038. default:
  218039. jassertfalse; // unknown type?
  218040. break;
  218041. }
  218042. return File::nonexistent;
  218043. }
  218044. const String File::getVersion() const
  218045. {
  218046. return String::empty; // xxx not yet implemented
  218047. }
  218048. bool File::moveToTrash() const
  218049. {
  218050. if (! exists())
  218051. return true;
  218052. File trashCan ("~/.Trash");
  218053. if (! trashCan.isDirectory())
  218054. trashCan = "~/.local/share/Trash/files";
  218055. if (! trashCan.isDirectory())
  218056. return false;
  218057. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  218058. getFileExtension()));
  218059. }
  218060. class DirectoryIterator::NativeIterator::Pimpl
  218061. {
  218062. public:
  218063. Pimpl (const File& directory, const String& wildCard_)
  218064. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  218065. wildCard (wildCard_),
  218066. dir (opendir (directory.getFullPathName().toUTF8()))
  218067. {
  218068. if (wildCard == "*.*")
  218069. wildCard = "*";
  218070. wildcardUTF8 = wildCard.toUTF8();
  218071. }
  218072. ~Pimpl()
  218073. {
  218074. if (dir != 0)
  218075. closedir (dir);
  218076. }
  218077. bool next (String& filenameFound,
  218078. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218079. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218080. {
  218081. if (dir == 0)
  218082. return false;
  218083. for (;;)
  218084. {
  218085. struct dirent* const de = readdir (dir);
  218086. if (de == 0)
  218087. return false;
  218088. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  218089. {
  218090. filenameFound = String::fromUTF8 (de->d_name);
  218091. const String path (parentDir + filenameFound);
  218092. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  218093. {
  218094. struct stat info;
  218095. const bool statOk = juce_stat (path, info);
  218096. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  218097. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  218098. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  218099. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  218100. }
  218101. if (isHidden != 0)
  218102. *isHidden = filenameFound.startsWithChar ('.');
  218103. if (isReadOnly != 0)
  218104. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  218105. return true;
  218106. }
  218107. }
  218108. }
  218109. private:
  218110. String parentDir, wildCard;
  218111. const char* wildcardUTF8;
  218112. DIR* dir;
  218113. Pimpl (const Pimpl&);
  218114. Pimpl& operator= (const Pimpl&);
  218115. };
  218116. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  218117. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  218118. {
  218119. }
  218120. DirectoryIterator::NativeIterator::~NativeIterator()
  218121. {
  218122. }
  218123. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  218124. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218125. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218126. {
  218127. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  218128. }
  218129. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  218130. {
  218131. String cmdString (fileName.replace (" ", "\\ ",false));
  218132. cmdString << " " << parameters;
  218133. if (URL::isProbablyAWebsiteURL (fileName)
  218134. || cmdString.startsWithIgnoreCase ("file:")
  218135. || URL::isProbablyAnEmailAddress (fileName))
  218136. {
  218137. // create a command that tries to launch a bunch of likely browsers
  218138. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  218139. StringArray cmdLines;
  218140. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  218141. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  218142. cmdString = cmdLines.joinIntoString (" || ");
  218143. }
  218144. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  218145. const int cpid = fork();
  218146. if (cpid == 0)
  218147. {
  218148. setsid();
  218149. // Child process
  218150. execve (argv[0], (char**) argv, environ);
  218151. exit (0);
  218152. }
  218153. return cpid >= 0;
  218154. }
  218155. void File::revealToUser() const
  218156. {
  218157. if (isDirectory())
  218158. startAsProcess();
  218159. else if (getParentDirectory().exists())
  218160. getParentDirectory().startAsProcess();
  218161. }
  218162. #endif
  218163. /*** End of inlined file: juce_linux_Files.cpp ***/
  218164. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  218165. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218166. // compiled on its own).
  218167. #if JUCE_INCLUDED_FILE
  218168. struct NamedPipeInternal
  218169. {
  218170. String pipeInName, pipeOutName;
  218171. int pipeIn, pipeOut;
  218172. bool volatile createdPipe, blocked, stopReadOperation;
  218173. static void signalHandler (int) {}
  218174. };
  218175. void NamedPipe::cancelPendingReads()
  218176. {
  218177. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  218178. {
  218179. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218180. intern->stopReadOperation = true;
  218181. char buffer [1] = { 0 };
  218182. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  218183. (void) bytesWritten;
  218184. int timeout = 2000;
  218185. while (intern->blocked && --timeout >= 0)
  218186. Thread::sleep (2);
  218187. intern->stopReadOperation = false;
  218188. }
  218189. }
  218190. void NamedPipe::close()
  218191. {
  218192. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218193. if (intern != 0)
  218194. {
  218195. internal = 0;
  218196. if (intern->pipeIn != -1)
  218197. ::close (intern->pipeIn);
  218198. if (intern->pipeOut != -1)
  218199. ::close (intern->pipeOut);
  218200. if (intern->createdPipe)
  218201. {
  218202. unlink (intern->pipeInName.toUTF8());
  218203. unlink (intern->pipeOutName.toUTF8());
  218204. }
  218205. delete intern;
  218206. }
  218207. }
  218208. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  218209. {
  218210. close();
  218211. NamedPipeInternal* const intern = new NamedPipeInternal();
  218212. internal = intern;
  218213. intern->createdPipe = createPipe;
  218214. intern->blocked = false;
  218215. intern->stopReadOperation = false;
  218216. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  218217. siginterrupt (SIGPIPE, 1);
  218218. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  218219. intern->pipeInName = pipePath + "_in";
  218220. intern->pipeOutName = pipePath + "_out";
  218221. intern->pipeIn = -1;
  218222. intern->pipeOut = -1;
  218223. if (createPipe)
  218224. {
  218225. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  218226. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  218227. {
  218228. delete intern;
  218229. internal = 0;
  218230. return false;
  218231. }
  218232. }
  218233. return true;
  218234. }
  218235. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  218236. {
  218237. int bytesRead = -1;
  218238. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218239. if (intern != 0)
  218240. {
  218241. intern->blocked = true;
  218242. if (intern->pipeIn == -1)
  218243. {
  218244. if (intern->createdPipe)
  218245. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  218246. else
  218247. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  218248. if (intern->pipeIn == -1)
  218249. {
  218250. intern->blocked = false;
  218251. return -1;
  218252. }
  218253. }
  218254. bytesRead = 0;
  218255. char* p = static_cast<char*> (destBuffer);
  218256. while (bytesRead < maxBytesToRead)
  218257. {
  218258. const int bytesThisTime = maxBytesToRead - bytesRead;
  218259. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  218260. if (numRead <= 0 || intern->stopReadOperation)
  218261. {
  218262. bytesRead = -1;
  218263. break;
  218264. }
  218265. bytesRead += numRead;
  218266. p += bytesRead;
  218267. }
  218268. intern->blocked = false;
  218269. }
  218270. return bytesRead;
  218271. }
  218272. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218273. {
  218274. int bytesWritten = -1;
  218275. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218276. if (intern != 0)
  218277. {
  218278. if (intern->pipeOut == -1)
  218279. {
  218280. if (intern->createdPipe)
  218281. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218282. else
  218283. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218284. if (intern->pipeOut == -1)
  218285. {
  218286. return -1;
  218287. }
  218288. }
  218289. const char* p = static_cast<const char*> (sourceBuffer);
  218290. bytesWritten = 0;
  218291. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218292. while (bytesWritten < numBytesToWrite
  218293. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218294. {
  218295. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218296. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218297. if (numWritten <= 0)
  218298. {
  218299. bytesWritten = -1;
  218300. break;
  218301. }
  218302. bytesWritten += numWritten;
  218303. p += bytesWritten;
  218304. }
  218305. }
  218306. return bytesWritten;
  218307. }
  218308. #endif
  218309. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218310. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218311. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218312. // compiled on its own).
  218313. #if JUCE_INCLUDED_FILE
  218314. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  218315. {
  218316. int numResults = 0;
  218317. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218318. if (s != -1)
  218319. {
  218320. char buf [1024];
  218321. struct ifconf ifc;
  218322. ifc.ifc_len = sizeof (buf);
  218323. ifc.ifc_buf = buf;
  218324. ioctl (s, SIOCGIFCONF, &ifc);
  218325. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218326. {
  218327. struct ifreq ifr;
  218328. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218329. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218330. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218331. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218332. && numResults < maxNum)
  218333. {
  218334. int64 a = 0;
  218335. for (int j = 6; --j >= 0;)
  218336. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218337. *addresses++ = a;
  218338. ++numResults;
  218339. }
  218340. }
  218341. close (s);
  218342. }
  218343. return numResults;
  218344. }
  218345. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218346. const String& emailSubject,
  218347. const String& bodyText,
  218348. const StringArray& filesToAttach)
  218349. {
  218350. jassertfalse; // xxx todo
  218351. return false;
  218352. }
  218353. /** A HTTP input stream that uses sockets.
  218354. */
  218355. class JUCE_HTTPSocketStream
  218356. {
  218357. public:
  218358. JUCE_HTTPSocketStream()
  218359. : readPosition (0),
  218360. socketHandle (-1),
  218361. levelsOfRedirection (0),
  218362. timeoutSeconds (15)
  218363. {
  218364. }
  218365. ~JUCE_HTTPSocketStream()
  218366. {
  218367. closeSocket();
  218368. }
  218369. bool open (const String& url,
  218370. const String& headers,
  218371. const MemoryBlock& postData,
  218372. const bool isPost,
  218373. URL::OpenStreamProgressCallback* callback,
  218374. void* callbackContext,
  218375. int timeOutMs)
  218376. {
  218377. closeSocket();
  218378. uint32 timeOutTime = Time::getMillisecondCounter();
  218379. if (timeOutMs == 0)
  218380. timeOutTime += 60000;
  218381. else if (timeOutMs < 0)
  218382. timeOutTime = 0xffffffff;
  218383. else
  218384. timeOutTime += timeOutMs;
  218385. String hostName, hostPath;
  218386. int hostPort;
  218387. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218388. return false;
  218389. const struct hostent* host = 0;
  218390. int port = 0;
  218391. String proxyName, proxyPath;
  218392. int proxyPort = 0;
  218393. String proxyURL (getenv ("http_proxy"));
  218394. if (proxyURL.startsWithIgnoreCase ("http://"))
  218395. {
  218396. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218397. return false;
  218398. host = gethostbyname (proxyName.toUTF8());
  218399. port = proxyPort;
  218400. }
  218401. else
  218402. {
  218403. host = gethostbyname (hostName.toUTF8());
  218404. port = hostPort;
  218405. }
  218406. if (host == 0)
  218407. return false;
  218408. struct sockaddr_in address;
  218409. zerostruct (address);
  218410. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218411. address.sin_family = host->h_addrtype;
  218412. address.sin_port = htons (port);
  218413. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218414. if (socketHandle == -1)
  218415. return false;
  218416. int receiveBufferSize = 16384;
  218417. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218418. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218419. #if JUCE_MAC
  218420. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218421. #endif
  218422. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218423. {
  218424. closeSocket();
  218425. return false;
  218426. }
  218427. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218428. proxyName, proxyPort,
  218429. hostPath, url,
  218430. headers, postData,
  218431. isPost));
  218432. size_t totalHeaderSent = 0;
  218433. while (totalHeaderSent < requestHeader.getSize())
  218434. {
  218435. if (Time::getMillisecondCounter() > timeOutTime)
  218436. {
  218437. closeSocket();
  218438. return false;
  218439. }
  218440. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218441. if (send (socketHandle,
  218442. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218443. numToSend, 0)
  218444. != numToSend)
  218445. {
  218446. closeSocket();
  218447. return false;
  218448. }
  218449. totalHeaderSent += numToSend;
  218450. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218451. {
  218452. closeSocket();
  218453. return false;
  218454. }
  218455. }
  218456. const String responseHeader (readResponse (timeOutTime));
  218457. if (responseHeader.isNotEmpty())
  218458. {
  218459. //DBG (responseHeader);
  218460. headerLines.clear();
  218461. headerLines.addLines (responseHeader);
  218462. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218463. .substring (0, 3).getIntValue();
  218464. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218465. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218466. String location (findHeaderItem (headerLines, "Location:"));
  218467. if (statusCode >= 300 && statusCode < 400
  218468. && location.isNotEmpty())
  218469. {
  218470. if (! location.startsWithIgnoreCase ("http://"))
  218471. location = "http://" + location;
  218472. if (levelsOfRedirection++ < 3)
  218473. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218474. }
  218475. else
  218476. {
  218477. levelsOfRedirection = 0;
  218478. return true;
  218479. }
  218480. }
  218481. closeSocket();
  218482. return false;
  218483. }
  218484. int read (void* buffer, int bytesToRead)
  218485. {
  218486. fd_set readbits;
  218487. FD_ZERO (&readbits);
  218488. FD_SET (socketHandle, &readbits);
  218489. struct timeval tv;
  218490. tv.tv_sec = timeoutSeconds;
  218491. tv.tv_usec = 0;
  218492. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218493. return 0; // (timeout)
  218494. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218495. readPosition += bytesRead;
  218496. return bytesRead;
  218497. }
  218498. int readPosition;
  218499. StringArray headerLines;
  218500. juce_UseDebuggingNewOperator
  218501. private:
  218502. int socketHandle, levelsOfRedirection;
  218503. const int timeoutSeconds;
  218504. void closeSocket()
  218505. {
  218506. if (socketHandle >= 0)
  218507. close (socketHandle);
  218508. socketHandle = -1;
  218509. }
  218510. const MemoryBlock createRequestHeader (const String& hostName,
  218511. const int hostPort,
  218512. const String& proxyName,
  218513. const int proxyPort,
  218514. const String& hostPath,
  218515. const String& originalURL,
  218516. const String& headers,
  218517. const MemoryBlock& postData,
  218518. const bool isPost)
  218519. {
  218520. String header (isPost ? "POST " : "GET ");
  218521. if (proxyName.isEmpty())
  218522. {
  218523. header << hostPath << " HTTP/1.0\r\nHost: "
  218524. << hostName << ':' << hostPort;
  218525. }
  218526. else
  218527. {
  218528. header << originalURL << " HTTP/1.0\r\nHost: "
  218529. << proxyName << ':' << proxyPort;
  218530. }
  218531. header << "\r\nUser-Agent: JUCE/"
  218532. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218533. << "\r\nConnection: Close\r\nContent-Length: "
  218534. << postData.getSize() << "\r\n"
  218535. << headers << "\r\n";
  218536. MemoryBlock mb;
  218537. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218538. mb.append (postData.getData(), postData.getSize());
  218539. return mb;
  218540. }
  218541. const String readResponse (const uint32 timeOutTime)
  218542. {
  218543. int bytesRead = 0, numConsecutiveLFs = 0;
  218544. MemoryBlock buffer (1024, true);
  218545. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218546. && Time::getMillisecondCounter() <= timeOutTime)
  218547. {
  218548. fd_set readbits;
  218549. FD_ZERO (&readbits);
  218550. FD_SET (socketHandle, &readbits);
  218551. struct timeval tv;
  218552. tv.tv_sec = timeoutSeconds;
  218553. tv.tv_usec = 0;
  218554. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218555. return String::empty; // (timeout)
  218556. buffer.ensureSize (bytesRead + 8, true);
  218557. char* const dest = (char*) buffer.getData() + bytesRead;
  218558. if (recv (socketHandle, dest, 1, 0) == -1)
  218559. return String::empty;
  218560. const char lastByte = *dest;
  218561. ++bytesRead;
  218562. if (lastByte == '\n')
  218563. ++numConsecutiveLFs;
  218564. else if (lastByte != '\r')
  218565. numConsecutiveLFs = 0;
  218566. }
  218567. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218568. if (header.startsWithIgnoreCase ("HTTP/"))
  218569. return header.trimEnd();
  218570. return String::empty;
  218571. }
  218572. static bool decomposeURL (const String& url,
  218573. String& host, String& path, int& port)
  218574. {
  218575. if (! url.startsWithIgnoreCase ("http://"))
  218576. return false;
  218577. const int nextSlash = url.indexOfChar (7, '/');
  218578. int nextColon = url.indexOfChar (7, ':');
  218579. if (nextColon > nextSlash && nextSlash > 0)
  218580. nextColon = -1;
  218581. if (nextColon >= 0)
  218582. {
  218583. host = url.substring (7, nextColon);
  218584. if (nextSlash >= 0)
  218585. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218586. else
  218587. port = url.substring (nextColon + 1).getIntValue();
  218588. }
  218589. else
  218590. {
  218591. port = 80;
  218592. if (nextSlash >= 0)
  218593. host = url.substring (7, nextSlash);
  218594. else
  218595. host = url.substring (7);
  218596. }
  218597. if (nextSlash >= 0)
  218598. path = url.substring (nextSlash);
  218599. else
  218600. path = "/";
  218601. return true;
  218602. }
  218603. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218604. {
  218605. for (int i = 0; i < lines.size(); ++i)
  218606. if (lines[i].startsWithIgnoreCase (itemName))
  218607. return lines[i].substring (itemName.length()).trim();
  218608. return String::empty;
  218609. }
  218610. };
  218611. void* juce_openInternetFile (const String& url,
  218612. const String& headers,
  218613. const MemoryBlock& postData,
  218614. const bool isPost,
  218615. URL::OpenStreamProgressCallback* callback,
  218616. void* callbackContext,
  218617. int timeOutMs)
  218618. {
  218619. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218620. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218621. return s.release();
  218622. return 0;
  218623. }
  218624. void juce_closeInternetFile (void* handle)
  218625. {
  218626. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218627. }
  218628. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218629. {
  218630. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218631. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218632. }
  218633. int64 juce_getInternetFileContentLength (void* handle)
  218634. {
  218635. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218636. if (s != 0)
  218637. {
  218638. //xxx todo
  218639. jassertfalse
  218640. }
  218641. return -1;
  218642. }
  218643. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218644. {
  218645. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218646. if (s != 0)
  218647. {
  218648. for (int i = 0; i < s->headerLines.size(); ++i)
  218649. {
  218650. const String& headersEntry = s->headerLines[i];
  218651. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218652. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218653. const String previousValue (headers [key]);
  218654. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218655. }
  218656. }
  218657. }
  218658. int juce_seekInInternetFile (void* handle, int newPosition)
  218659. {
  218660. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218661. return s != 0 ? s->readPosition : 0;
  218662. }
  218663. #endif
  218664. /*** End of inlined file: juce_linux_Network.cpp ***/
  218665. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218666. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218667. // compiled on its own).
  218668. #if JUCE_INCLUDED_FILE
  218669. void Logger::outputDebugString (const String& text)
  218670. {
  218671. std::cerr << text << std::endl;
  218672. }
  218673. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218674. {
  218675. return Linux;
  218676. }
  218677. const String SystemStats::getOperatingSystemName()
  218678. {
  218679. return "Linux";
  218680. }
  218681. bool SystemStats::isOperatingSystem64Bit()
  218682. {
  218683. #if JUCE_64BIT
  218684. return true;
  218685. #else
  218686. //xxx not sure how to find this out?..
  218687. return false;
  218688. #endif
  218689. }
  218690. static const String juce_getCpuInfo (const char* const key)
  218691. {
  218692. StringArray lines;
  218693. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218694. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218695. if (lines[i].startsWithIgnoreCase (key))
  218696. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218697. return String::empty;
  218698. }
  218699. const String SystemStats::getCpuVendor()
  218700. {
  218701. return juce_getCpuInfo ("vendor_id");
  218702. }
  218703. int SystemStats::getCpuSpeedInMegaherz()
  218704. {
  218705. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218706. }
  218707. int SystemStats::getMemorySizeInMegabytes()
  218708. {
  218709. struct sysinfo sysi;
  218710. if (sysinfo (&sysi) == 0)
  218711. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218712. return 0;
  218713. }
  218714. int SystemStats::getPageSize()
  218715. {
  218716. return sysconf (_SC_PAGESIZE);
  218717. }
  218718. const String SystemStats::getLogonName()
  218719. {
  218720. const char* user = getenv ("USER");
  218721. if (user == 0)
  218722. {
  218723. struct passwd* const pw = getpwuid (getuid());
  218724. if (pw != 0)
  218725. user = pw->pw_name;
  218726. }
  218727. return String::fromUTF8 (user);
  218728. }
  218729. const String SystemStats::getFullUserName()
  218730. {
  218731. return getLogonName();
  218732. }
  218733. void SystemStats::initialiseStats()
  218734. {
  218735. const String flags (juce_getCpuInfo ("flags"));
  218736. cpuFlags.hasMMX = flags.contains ("mmx");
  218737. cpuFlags.hasSSE = flags.contains ("sse");
  218738. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218739. cpuFlags.has3DNow = flags.contains ("3dnow");
  218740. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218741. }
  218742. void PlatformUtilities::fpuReset()
  218743. {
  218744. }
  218745. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218746. {
  218747. if (gettimeofday (t, 0) != 0)
  218748. return false;
  218749. static unsigned int calibrate = 0;
  218750. static bool calibrated = false;
  218751. if (! calibrated)
  218752. {
  218753. calibrated = true;
  218754. struct sysinfo sysi;
  218755. if (sysinfo (&sysi) == 0)
  218756. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218757. }
  218758. t->tv_sec -= calibrate;
  218759. return true;
  218760. }
  218761. uint32 juce_millisecondsSinceStartup() throw()
  218762. {
  218763. timeval t;
  218764. if (juce_getTimeSinceStartup (&t))
  218765. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218766. return 0;
  218767. }
  218768. int64 Time::getHighResolutionTicks() throw()
  218769. {
  218770. timeval t;
  218771. if (juce_getTimeSinceStartup (&t))
  218772. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218773. return 0;
  218774. }
  218775. int64 Time::getHighResolutionTicksPerSecond() throw()
  218776. {
  218777. return 1000000; // (microseconds)
  218778. }
  218779. double Time::getMillisecondCounterHiRes() throw()
  218780. {
  218781. return getHighResolutionTicks() * 0.001;
  218782. }
  218783. bool Time::setSystemTimeToThisTime() const
  218784. {
  218785. timeval t;
  218786. t.tv_sec = millisSinceEpoch % 1000000;
  218787. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218788. return settimeofday (&t, 0) ? false : true;
  218789. }
  218790. #endif
  218791. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218792. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218793. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218794. // compiled on its own).
  218795. #if JUCE_INCLUDED_FILE
  218796. /*
  218797. Note that a lot of methods that you'd expect to find in this file actually
  218798. live in juce_posix_SharedCode.h!
  218799. */
  218800. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218801. void Process::setPriority (ProcessPriority prior)
  218802. {
  218803. struct sched_param param;
  218804. int policy, maxp, minp;
  218805. const int p = (int) prior;
  218806. if (p <= 1)
  218807. policy = SCHED_OTHER;
  218808. else
  218809. policy = SCHED_RR;
  218810. minp = sched_get_priority_min (policy);
  218811. maxp = sched_get_priority_max (policy);
  218812. if (p < 2)
  218813. param.sched_priority = 0;
  218814. else if (p == 2 )
  218815. // Set to middle of lower realtime priority range
  218816. param.sched_priority = minp + (maxp - minp) / 4;
  218817. else
  218818. // Set to middle of higher realtime priority range
  218819. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218820. pthread_setschedparam (pthread_self(), policy, &param);
  218821. }
  218822. void Process::terminate()
  218823. {
  218824. exit (0);
  218825. }
  218826. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  218827. {
  218828. static char testResult = 0;
  218829. if (testResult == 0)
  218830. {
  218831. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218832. if (testResult >= 0)
  218833. {
  218834. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218835. testResult = 1;
  218836. }
  218837. }
  218838. return testResult < 0;
  218839. }
  218840. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218841. {
  218842. return juce_isRunningUnderDebugger();
  218843. }
  218844. void Process::raisePrivilege()
  218845. {
  218846. // If running suid root, change effective user
  218847. // to root
  218848. if (geteuid() != 0 && getuid() == 0)
  218849. {
  218850. setreuid (geteuid(), getuid());
  218851. setregid (getegid(), getgid());
  218852. }
  218853. }
  218854. void Process::lowerPrivilege()
  218855. {
  218856. // If runing suid root, change effective user
  218857. // back to real user
  218858. if (geteuid() == 0 && getuid() != 0)
  218859. {
  218860. setreuid (geteuid(), getuid());
  218861. setregid (getegid(), getgid());
  218862. }
  218863. }
  218864. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218865. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218866. {
  218867. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218868. }
  218869. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218870. {
  218871. dlclose(handle);
  218872. }
  218873. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218874. {
  218875. return dlsym (libraryHandle, procedureName.toCString());
  218876. }
  218877. #endif
  218878. #endif
  218879. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218880. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218881. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218882. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218883. // compiled on its own).
  218884. #if JUCE_INCLUDED_FILE
  218885. extern Display* display;
  218886. extern Window juce_messageWindowHandle;
  218887. namespace ClipboardHelpers
  218888. {
  218889. static String localClipboardContent;
  218890. static Atom atom_UTF8_STRING;
  218891. static Atom atom_CLIPBOARD;
  218892. static Atom atom_TARGETS;
  218893. static void initSelectionAtoms()
  218894. {
  218895. static bool isInitialised = false;
  218896. if (! isInitialised)
  218897. {
  218898. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218899. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218900. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218901. }
  218902. }
  218903. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218904. // works only for strings shorter than 1000000 bytes
  218905. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218906. {
  218907. String returnData;
  218908. char* clipData;
  218909. Atom actualType;
  218910. int actualFormat;
  218911. unsigned long numItems, bytesLeft;
  218912. if (XGetWindowProperty (display, window, prop,
  218913. 0L /* offset */, 1000000 /* length (max) */, False,
  218914. AnyPropertyType /* format */,
  218915. &actualType, &actualFormat, &numItems, &bytesLeft,
  218916. (unsigned char**) &clipData) == Success)
  218917. {
  218918. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218919. returnData = String::fromUTF8 (clipData, numItems);
  218920. else if (actualType == XA_STRING && actualFormat == 8)
  218921. returnData = String (clipData, numItems);
  218922. if (clipData != 0)
  218923. XFree (clipData);
  218924. jassert (bytesLeft == 0 || numItems == 1000000);
  218925. }
  218926. XDeleteProperty (display, window, prop);
  218927. return returnData;
  218928. }
  218929. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218930. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218931. {
  218932. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218933. // The selection owner will be asked to set the JUCE_SEL property on the
  218934. // juce_messageWindowHandle with the selection content
  218935. XConvertSelection (display, selection, requestedFormat, property_name,
  218936. juce_messageWindowHandle, CurrentTime);
  218937. int count = 50; // will wait at most for 200 ms
  218938. while (--count >= 0)
  218939. {
  218940. XEvent event;
  218941. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218942. {
  218943. if (event.xselection.property == property_name)
  218944. {
  218945. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218946. selectionContent = readWindowProperty (event.xselection.requestor,
  218947. event.xselection.property,
  218948. requestedFormat);
  218949. return true;
  218950. }
  218951. else
  218952. {
  218953. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218954. }
  218955. }
  218956. // not very elegant.. we could do a select() or something like that...
  218957. // however clipboard content requesting is inherently slow on x11, it
  218958. // often takes 50ms or more so...
  218959. Thread::sleep (4);
  218960. }
  218961. return false;
  218962. }
  218963. }
  218964. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218965. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218966. {
  218967. ClipboardHelpers::initSelectionAtoms();
  218968. // the selection content is sent to the target window as a window property
  218969. XSelectionEvent reply;
  218970. reply.type = SelectionNotify;
  218971. reply.display = evt.display;
  218972. reply.requestor = evt.requestor;
  218973. reply.selection = evt.selection;
  218974. reply.target = evt.target;
  218975. reply.property = None; // == "fail"
  218976. reply.time = evt.time;
  218977. HeapBlock <char> data;
  218978. int propertyFormat = 0, numDataItems = 0;
  218979. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218980. {
  218981. if (evt.target == XA_STRING)
  218982. {
  218983. // format data according to system locale
  218984. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218985. data.calloc (numDataItems + 1);
  218986. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218987. propertyFormat = 8; // bits/item
  218988. }
  218989. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218990. {
  218991. // translate to utf8
  218992. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218993. data.calloc (numDataItems + 1);
  218994. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218995. propertyFormat = 8; // bits/item
  218996. }
  218997. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218998. {
  218999. // another application wants to know what we are able to send
  219000. numDataItems = 2;
  219001. propertyFormat = 32; // atoms are 32-bit
  219002. data.calloc (numDataItems * 4);
  219003. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  219004. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  219005. atoms[1] = XA_STRING;
  219006. }
  219007. }
  219008. else
  219009. {
  219010. DBG ("requested unsupported clipboard");
  219011. }
  219012. if (data != 0)
  219013. {
  219014. const int maxReasonableSelectionSize = 1000000;
  219015. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  219016. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  219017. {
  219018. XChangeProperty (evt.display, evt.requestor,
  219019. evt.property, evt.target,
  219020. propertyFormat /* 8 or 32 */, PropModeReplace,
  219021. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  219022. reply.property = evt.property; // " == success"
  219023. }
  219024. }
  219025. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  219026. }
  219027. void SystemClipboard::copyTextToClipboard (const String& clipText)
  219028. {
  219029. ClipboardHelpers::initSelectionAtoms();
  219030. ClipboardHelpers::localClipboardContent = clipText;
  219031. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  219032. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  219033. }
  219034. const String SystemClipboard::getTextFromClipboard()
  219035. {
  219036. ClipboardHelpers::initSelectionAtoms();
  219037. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  219038. level" clipboard that is supposed to be filled by ctrl-C
  219039. etc). When a clipboard manager is running, the content of this
  219040. selection is preserved even when the original selection owner
  219041. exits.
  219042. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  219043. filled by good old x11 apps such as xterm)
  219044. */
  219045. String content;
  219046. Atom selection = XA_PRIMARY;
  219047. Window selectionOwner = None;
  219048. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  219049. {
  219050. selection = ClipboardHelpers::atom_CLIPBOARD;
  219051. selectionOwner = XGetSelectionOwner (display, selection);
  219052. }
  219053. if (selectionOwner != None)
  219054. {
  219055. if (selectionOwner == juce_messageWindowHandle)
  219056. {
  219057. content = ClipboardHelpers::localClipboardContent;
  219058. }
  219059. else
  219060. {
  219061. // first try: we want an utf8 string
  219062. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  219063. if (! ok)
  219064. {
  219065. // second chance, ask for a good old locale-dependent string ..
  219066. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  219067. }
  219068. }
  219069. }
  219070. return content;
  219071. }
  219072. #endif
  219073. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  219074. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  219075. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219076. // compiled on its own).
  219077. #if JUCE_INCLUDED_FILE
  219078. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  219079. #define JUCE_DEBUG_XERRORS 1
  219080. #endif
  219081. Display* display = 0;
  219082. Window juce_messageWindowHandle = None;
  219083. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  219084. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  219085. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  219086. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  219087. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  219088. class InternalMessageQueue
  219089. {
  219090. public:
  219091. InternalMessageQueue()
  219092. : bytesInSocket (0),
  219093. totalEventCount (0)
  219094. {
  219095. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  219096. (void) ret; jassert (ret == 0);
  219097. //setNonBlocking (fd[0]);
  219098. //setNonBlocking (fd[1]);
  219099. }
  219100. ~InternalMessageQueue()
  219101. {
  219102. close (fd[0]);
  219103. close (fd[1]);
  219104. clearSingletonInstance();
  219105. }
  219106. void postMessage (Message* msg)
  219107. {
  219108. const int maxBytesInSocketQueue = 128;
  219109. ScopedLock sl (lock);
  219110. queue.add (msg);
  219111. if (bytesInSocket < maxBytesInSocketQueue)
  219112. {
  219113. ++bytesInSocket;
  219114. ScopedUnlock ul (lock);
  219115. const unsigned char x = 0xff;
  219116. size_t bytesWritten = write (fd[0], &x, 1);
  219117. (void) bytesWritten;
  219118. }
  219119. }
  219120. bool isEmpty() const
  219121. {
  219122. ScopedLock sl (lock);
  219123. return queue.size() == 0;
  219124. }
  219125. bool dispatchNextEvent()
  219126. {
  219127. // This alternates between giving priority to XEvents or internal messages,
  219128. // to keep everything running smoothly..
  219129. if ((++totalEventCount & 1) != 0)
  219130. return dispatchNextXEvent() || dispatchNextInternalMessage();
  219131. else
  219132. return dispatchNextInternalMessage() || dispatchNextXEvent();
  219133. }
  219134. // Wait for an event (either XEvent, or an internal Message)
  219135. bool sleepUntilEvent (const int timeoutMs)
  219136. {
  219137. if (! isEmpty())
  219138. return true;
  219139. if (display != 0)
  219140. {
  219141. ScopedXLock xlock;
  219142. if (XPending (display))
  219143. return true;
  219144. }
  219145. struct timeval tv;
  219146. tv.tv_sec = 0;
  219147. tv.tv_usec = timeoutMs * 1000;
  219148. int fd0 = getWaitHandle();
  219149. int fdmax = fd0;
  219150. fd_set readset;
  219151. FD_ZERO (&readset);
  219152. FD_SET (fd0, &readset);
  219153. if (display != 0)
  219154. {
  219155. ScopedXLock xlock;
  219156. int fd1 = XConnectionNumber (display);
  219157. FD_SET (fd1, &readset);
  219158. fdmax = jmax (fd0, fd1);
  219159. }
  219160. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  219161. return (ret > 0); // ret <= 0 if error or timeout
  219162. }
  219163. struct MessageThreadFuncCall
  219164. {
  219165. enum { uniqueID = 0x73774623 };
  219166. MessageCallbackFunction* func;
  219167. void* parameter;
  219168. void* result;
  219169. CriticalSection lock;
  219170. WaitableEvent event;
  219171. };
  219172. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  219173. private:
  219174. CriticalSection lock;
  219175. OwnedArray <Message> queue;
  219176. int fd[2];
  219177. int bytesInSocket;
  219178. int totalEventCount;
  219179. int getWaitHandle() const throw() { return fd[1]; }
  219180. static bool setNonBlocking (int handle)
  219181. {
  219182. int socketFlags = fcntl (handle, F_GETFL, 0);
  219183. if (socketFlags == -1)
  219184. return false;
  219185. socketFlags |= O_NONBLOCK;
  219186. return fcntl (handle, F_SETFL, socketFlags) == 0;
  219187. }
  219188. static bool dispatchNextXEvent()
  219189. {
  219190. if (display == 0)
  219191. return false;
  219192. XEvent evt;
  219193. {
  219194. ScopedXLock xlock;
  219195. if (! XPending (display))
  219196. return false;
  219197. XNextEvent (display, &evt);
  219198. }
  219199. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  219200. juce_handleSelectionRequest (evt.xselectionrequest);
  219201. else if (evt.xany.window != juce_messageWindowHandle)
  219202. juce_windowMessageReceive (&evt);
  219203. return true;
  219204. }
  219205. Message* popNextMessage()
  219206. {
  219207. ScopedLock sl (lock);
  219208. if (bytesInSocket > 0)
  219209. {
  219210. --bytesInSocket;
  219211. ScopedUnlock ul (lock);
  219212. unsigned char x;
  219213. size_t numBytes = read (fd[1], &x, 1);
  219214. (void) numBytes;
  219215. }
  219216. return queue.removeAndReturn (0);
  219217. }
  219218. bool dispatchNextInternalMessage()
  219219. {
  219220. ScopedPointer <Message> msg (popNextMessage());
  219221. if (msg == 0)
  219222. return false;
  219223. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  219224. {
  219225. // Handle callback message
  219226. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  219227. call->result = (*(call->func)) (call->parameter);
  219228. call->event.signal();
  219229. }
  219230. else
  219231. {
  219232. // Handle "normal" messages
  219233. MessageManager::getInstance()->deliverMessage (msg.release());
  219234. }
  219235. return true;
  219236. }
  219237. };
  219238. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  219239. namespace LinuxErrorHandling
  219240. {
  219241. static bool errorOccurred = false;
  219242. static bool keyboardBreakOccurred = false;
  219243. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  219244. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  219245. // Usually happens when client-server connection is broken
  219246. static int ioErrorHandler (Display* display)
  219247. {
  219248. DBG ("ERROR: connection to X server broken.. terminating.");
  219249. if (JUCEApplication::isStandaloneApp())
  219250. MessageManager::getInstance()->stopDispatchLoop();
  219251. errorOccurred = true;
  219252. return 0;
  219253. }
  219254. // A protocol error has occurred
  219255. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  219256. {
  219257. #if JUCE_DEBUG_XERRORS
  219258. char errorStr[64] = { 0 };
  219259. char requestStr[64] = { 0 };
  219260. XGetErrorText (display, event->error_code, errorStr, 64);
  219261. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  219262. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  219263. #endif
  219264. return 0;
  219265. }
  219266. static void installXErrorHandlers()
  219267. {
  219268. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219269. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219270. }
  219271. static void removeXErrorHandlers()
  219272. {
  219273. XSetIOErrorHandler (oldIOErrorHandler);
  219274. oldIOErrorHandler = 0;
  219275. XSetErrorHandler (oldErrorHandler);
  219276. oldErrorHandler = 0;
  219277. }
  219278. static void keyboardBreakSignalHandler (int sig)
  219279. {
  219280. if (sig == SIGINT)
  219281. keyboardBreakOccurred = true;
  219282. }
  219283. static void installKeyboardBreakHandler()
  219284. {
  219285. struct sigaction saction;
  219286. sigset_t maskSet;
  219287. sigemptyset (&maskSet);
  219288. saction.sa_handler = keyboardBreakSignalHandler;
  219289. saction.sa_mask = maskSet;
  219290. saction.sa_flags = 0;
  219291. sigaction (SIGINT, &saction, 0);
  219292. }
  219293. }
  219294. void MessageManager::doPlatformSpecificInitialisation()
  219295. {
  219296. // Initialise xlib for multiple thread support
  219297. static bool initThreadCalled = false;
  219298. if (! initThreadCalled)
  219299. {
  219300. if (! XInitThreads())
  219301. {
  219302. // This is fatal! Print error and closedown
  219303. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219304. if (JUCEApplication::isStandaloneApp())
  219305. Process::terminate();
  219306. return;
  219307. }
  219308. initThreadCalled = true;
  219309. }
  219310. LinuxErrorHandling::installXErrorHandlers();
  219311. LinuxErrorHandling::installKeyboardBreakHandler();
  219312. // Create the internal message queue
  219313. InternalMessageQueue::getInstance();
  219314. // Try to connect to a display
  219315. String displayName (getenv ("DISPLAY"));
  219316. if (displayName.isEmpty())
  219317. displayName = ":0.0";
  219318. display = XOpenDisplay (displayName.toCString());
  219319. if (display != 0) // This is not fatal! we can run headless.
  219320. {
  219321. // Create a context to store user data associated with Windows we create in WindowDriver
  219322. windowHandleXContext = XUniqueContext();
  219323. // We're only interested in client messages for this window, which are always sent
  219324. XSetWindowAttributes swa;
  219325. swa.event_mask = NoEventMask;
  219326. // Create our message window (this will never be mapped)
  219327. const int screen = DefaultScreen (display);
  219328. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219329. 0, 0, 1, 1, 0, 0, InputOnly,
  219330. DefaultVisual (display, screen),
  219331. CWEventMask, &swa);
  219332. }
  219333. }
  219334. void MessageManager::doPlatformSpecificShutdown()
  219335. {
  219336. InternalMessageQueue::deleteInstance();
  219337. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219338. {
  219339. XDestroyWindow (display, juce_messageWindowHandle);
  219340. XCloseDisplay (display);
  219341. juce_messageWindowHandle = 0;
  219342. display = 0;
  219343. LinuxErrorHandling::removeXErrorHandlers();
  219344. }
  219345. }
  219346. bool juce_postMessageToSystemQueue (Message* message)
  219347. {
  219348. if (LinuxErrorHandling::errorOccurred)
  219349. return false;
  219350. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219351. return true;
  219352. }
  219353. void MessageManager::broadcastMessage (const String& value)
  219354. {
  219355. /* TODO */
  219356. }
  219357. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219358. {
  219359. if (LinuxErrorHandling::errorOccurred)
  219360. return 0;
  219361. if (isThisTheMessageThread())
  219362. return func (parameter);
  219363. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219364. messageCallContext.func = func;
  219365. messageCallContext.parameter = parameter;
  219366. InternalMessageQueue::getInstanceWithoutCreating()
  219367. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219368. 0, 0, &messageCallContext));
  219369. // Wait for it to complete before continuing
  219370. messageCallContext.event.wait();
  219371. return messageCallContext.result;
  219372. }
  219373. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219374. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219375. {
  219376. while (! LinuxErrorHandling::errorOccurred)
  219377. {
  219378. if (LinuxErrorHandling::keyboardBreakOccurred)
  219379. {
  219380. LinuxErrorHandling::errorOccurred = true;
  219381. if (JUCEApplication::isStandaloneApp())
  219382. Process::terminate();
  219383. break;
  219384. }
  219385. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219386. return true;
  219387. if (returnIfNoPendingMessages)
  219388. break;
  219389. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219390. }
  219391. return false;
  219392. }
  219393. #endif
  219394. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219395. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219396. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219397. // compiled on its own).
  219398. #if JUCE_INCLUDED_FILE
  219399. class FreeTypeFontFace
  219400. {
  219401. public:
  219402. enum FontStyle
  219403. {
  219404. Plain = 0,
  219405. Bold = 1,
  219406. Italic = 2
  219407. };
  219408. FreeTypeFontFace (const String& familyName)
  219409. : hasSerif (false),
  219410. monospaced (false)
  219411. {
  219412. family = familyName;
  219413. }
  219414. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219415. {
  219416. if (names [(int) style].fileName.isEmpty())
  219417. {
  219418. names [(int) style].fileName = name;
  219419. names [(int) style].faceIndex = faceIndex;
  219420. }
  219421. }
  219422. const String& getFamilyName() const throw() { return family; }
  219423. const String& getFileName (const int style, int& faceIndex) const throw()
  219424. {
  219425. faceIndex = names[style].faceIndex;
  219426. return names[style].fileName;
  219427. }
  219428. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219429. bool getMonospaced() const throw() { return monospaced; }
  219430. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219431. bool getSerif() const throw() { return hasSerif; }
  219432. private:
  219433. String family;
  219434. struct FontNameIndex
  219435. {
  219436. String fileName;
  219437. int faceIndex;
  219438. };
  219439. FontNameIndex names[4];
  219440. bool hasSerif, monospaced;
  219441. };
  219442. class FreeTypeInterface : public DeletedAtShutdown
  219443. {
  219444. public:
  219445. FreeTypeInterface()
  219446. : ftLib (0),
  219447. lastFace (0),
  219448. lastBold (false),
  219449. lastItalic (false)
  219450. {
  219451. if (FT_Init_FreeType (&ftLib) != 0)
  219452. {
  219453. ftLib = 0;
  219454. DBG ("Failed to initialize FreeType");
  219455. }
  219456. StringArray fontDirs;
  219457. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219458. fontDirs.removeEmptyStrings (true);
  219459. if (fontDirs.size() == 0)
  219460. {
  219461. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219462. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219463. if (fontsInfo != 0)
  219464. {
  219465. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219466. {
  219467. fontDirs.add (e->getAllSubText().trim());
  219468. }
  219469. }
  219470. }
  219471. if (fontDirs.size() == 0)
  219472. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219473. for (int i = 0; i < fontDirs.size(); ++i)
  219474. enumerateFaces (fontDirs[i]);
  219475. }
  219476. ~FreeTypeInterface()
  219477. {
  219478. if (lastFace != 0)
  219479. FT_Done_Face (lastFace);
  219480. if (ftLib != 0)
  219481. FT_Done_FreeType (ftLib);
  219482. clearSingletonInstance();
  219483. }
  219484. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219485. {
  219486. for (int i = 0; i < faces.size(); i++)
  219487. if (faces[i]->getFamilyName() == familyName)
  219488. return faces[i];
  219489. if (! create)
  219490. return 0;
  219491. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219492. faces.add (newFace);
  219493. return newFace;
  219494. }
  219495. // Enumerate all font faces available in a given directory
  219496. void enumerateFaces (const String& path)
  219497. {
  219498. File dirPath (path);
  219499. if (path.isEmpty() || ! dirPath.isDirectory())
  219500. return;
  219501. DirectoryIterator di (dirPath, true);
  219502. while (di.next())
  219503. {
  219504. File possible (di.getFile());
  219505. if (possible.hasFileExtension ("ttf")
  219506. || possible.hasFileExtension ("pfb")
  219507. || possible.hasFileExtension ("pcf"))
  219508. {
  219509. FT_Face face;
  219510. int faceIndex = 0;
  219511. int numFaces = 0;
  219512. do
  219513. {
  219514. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219515. faceIndex, &face) == 0)
  219516. {
  219517. if (faceIndex == 0)
  219518. numFaces = face->num_faces;
  219519. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219520. {
  219521. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219522. int style = (int) FreeTypeFontFace::Plain;
  219523. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219524. style |= (int) FreeTypeFontFace::Bold;
  219525. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219526. style |= (int) FreeTypeFontFace::Italic;
  219527. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219528. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219529. // Surely there must be a better way to do this?
  219530. const String name (face->family_name);
  219531. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219532. || name.containsIgnoreCase ("Verdana")
  219533. || name.containsIgnoreCase ("Arial")));
  219534. }
  219535. FT_Done_Face (face);
  219536. }
  219537. ++faceIndex;
  219538. }
  219539. while (faceIndex < numFaces);
  219540. }
  219541. }
  219542. }
  219543. // Create a FreeType face object for a given font
  219544. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219545. {
  219546. FT_Face face = 0;
  219547. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219548. {
  219549. face = lastFace;
  219550. }
  219551. else
  219552. {
  219553. if (lastFace != 0)
  219554. {
  219555. FT_Done_Face (lastFace);
  219556. lastFace = 0;
  219557. }
  219558. lastFontName = fontName;
  219559. lastBold = bold;
  219560. lastItalic = italic;
  219561. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219562. if (ftFace != 0)
  219563. {
  219564. int style = (int) FreeTypeFontFace::Plain;
  219565. if (bold)
  219566. style |= (int) FreeTypeFontFace::Bold;
  219567. if (italic)
  219568. style |= (int) FreeTypeFontFace::Italic;
  219569. int faceIndex;
  219570. String fileName (ftFace->getFileName (style, faceIndex));
  219571. if (fileName.isEmpty())
  219572. {
  219573. style ^= (int) FreeTypeFontFace::Bold;
  219574. fileName = ftFace->getFileName (style, faceIndex);
  219575. if (fileName.isEmpty())
  219576. {
  219577. style ^= (int) FreeTypeFontFace::Bold;
  219578. style ^= (int) FreeTypeFontFace::Italic;
  219579. fileName = ftFace->getFileName (style, faceIndex);
  219580. if (! fileName.length())
  219581. {
  219582. style ^= (int) FreeTypeFontFace::Bold;
  219583. fileName = ftFace->getFileName (style, faceIndex);
  219584. }
  219585. }
  219586. }
  219587. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219588. {
  219589. face = lastFace;
  219590. // If there isn't a unicode charmap then select the first one.
  219591. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219592. FT_Set_Charmap (face, face->charmaps[0]);
  219593. }
  219594. }
  219595. }
  219596. return face;
  219597. }
  219598. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219599. {
  219600. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219601. const float height = (float) (face->ascender - face->descender);
  219602. const float scaleX = 1.0f / height;
  219603. const float scaleY = -1.0f / height;
  219604. Path destShape;
  219605. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219606. || face->glyph->format != ft_glyph_format_outline)
  219607. {
  219608. return false;
  219609. }
  219610. const FT_Outline* const outline = &face->glyph->outline;
  219611. const short* const contours = outline->contours;
  219612. const char* const tags = outline->tags;
  219613. FT_Vector* const points = outline->points;
  219614. for (int c = 0; c < outline->n_contours; c++)
  219615. {
  219616. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219617. const int endPoint = contours[c];
  219618. for (int p = startPoint; p <= endPoint; p++)
  219619. {
  219620. const float x = scaleX * points[p].x;
  219621. const float y = scaleY * points[p].y;
  219622. if (p == startPoint)
  219623. {
  219624. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219625. {
  219626. float x2 = scaleX * points [endPoint].x;
  219627. float y2 = scaleY * points [endPoint].y;
  219628. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219629. {
  219630. x2 = (x + x2) * 0.5f;
  219631. y2 = (y + y2) * 0.5f;
  219632. }
  219633. destShape.startNewSubPath (x2, y2);
  219634. }
  219635. else
  219636. {
  219637. destShape.startNewSubPath (x, y);
  219638. }
  219639. }
  219640. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219641. {
  219642. if (p != startPoint)
  219643. destShape.lineTo (x, y);
  219644. }
  219645. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219646. {
  219647. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219648. float x2 = scaleX * points [nextIndex].x;
  219649. float y2 = scaleY * points [nextIndex].y;
  219650. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219651. {
  219652. x2 = (x + x2) * 0.5f;
  219653. y2 = (y + y2) * 0.5f;
  219654. }
  219655. else
  219656. {
  219657. ++p;
  219658. }
  219659. destShape.quadraticTo (x, y, x2, y2);
  219660. }
  219661. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219662. {
  219663. if (p >= endPoint)
  219664. return false;
  219665. const int next1 = p + 1;
  219666. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219667. const float x2 = scaleX * points [next1].x;
  219668. const float y2 = scaleY * points [next1].y;
  219669. const float x3 = scaleX * points [next2].x;
  219670. const float y3 = scaleY * points [next2].y;
  219671. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219672. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219673. return false;
  219674. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219675. p += 2;
  219676. }
  219677. }
  219678. destShape.closeSubPath();
  219679. }
  219680. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219681. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219682. addKerning (face, dest, character, glyphIndex);
  219683. return true;
  219684. }
  219685. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219686. {
  219687. const float height = (float) (face->ascender - face->descender);
  219688. uint32 rightGlyphIndex;
  219689. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219690. while (rightGlyphIndex != 0)
  219691. {
  219692. FT_Vector kerning;
  219693. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219694. {
  219695. if (kerning.x != 0)
  219696. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219697. }
  219698. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219699. }
  219700. }
  219701. // Add a glyph to a font
  219702. bool addGlyphToFont (const uint32 character, const String& fontName,
  219703. bool bold, bool italic, CustomTypeface& dest)
  219704. {
  219705. FT_Face face = createFT_Face (fontName, bold, italic);
  219706. return face != 0 && addGlyph (face, dest, character);
  219707. }
  219708. void getFamilyNames (StringArray& familyNames) const
  219709. {
  219710. for (int i = 0; i < faces.size(); i++)
  219711. familyNames.add (faces[i]->getFamilyName());
  219712. }
  219713. void getMonospacedNames (StringArray& monoSpaced) const
  219714. {
  219715. for (int i = 0; i < faces.size(); i++)
  219716. if (faces[i]->getMonospaced())
  219717. monoSpaced.add (faces[i]->getFamilyName());
  219718. }
  219719. void getSerifNames (StringArray& serif) const
  219720. {
  219721. for (int i = 0; i < faces.size(); i++)
  219722. if (faces[i]->getSerif())
  219723. serif.add (faces[i]->getFamilyName());
  219724. }
  219725. void getSansSerifNames (StringArray& sansSerif) const
  219726. {
  219727. for (int i = 0; i < faces.size(); i++)
  219728. if (! faces[i]->getSerif())
  219729. sansSerif.add (faces[i]->getFamilyName());
  219730. }
  219731. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219732. private:
  219733. FT_Library ftLib;
  219734. FT_Face lastFace;
  219735. String lastFontName;
  219736. bool lastBold, lastItalic;
  219737. OwnedArray<FreeTypeFontFace> faces;
  219738. };
  219739. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219740. class FreetypeTypeface : public CustomTypeface
  219741. {
  219742. public:
  219743. FreetypeTypeface (const Font& font)
  219744. {
  219745. FT_Face face = FreeTypeInterface::getInstance()
  219746. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219747. if (face == 0)
  219748. {
  219749. #if JUCE_DEBUG
  219750. String msg ("Failed to create typeface: ");
  219751. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219752. DBG (msg);
  219753. #endif
  219754. }
  219755. else
  219756. {
  219757. setCharacteristics (font.getTypefaceName(),
  219758. face->ascender / (float) (face->ascender - face->descender),
  219759. font.isBold(), font.isItalic(),
  219760. L' ');
  219761. }
  219762. }
  219763. bool loadGlyphIfPossible (juce_wchar character)
  219764. {
  219765. return FreeTypeInterface::getInstance()
  219766. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219767. }
  219768. };
  219769. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219770. {
  219771. return new FreetypeTypeface (font);
  219772. }
  219773. const StringArray Font::findAllTypefaceNames()
  219774. {
  219775. StringArray s;
  219776. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219777. s.sort (true);
  219778. return s;
  219779. }
  219780. static const String pickBestFont (const StringArray& names,
  219781. const char* const choicesString)
  219782. {
  219783. StringArray choices;
  219784. choices.addTokens (String (choicesString), ",", String::empty);
  219785. choices.trim();
  219786. choices.removeEmptyStrings();
  219787. int i, j;
  219788. for (j = 0; j < choices.size(); ++j)
  219789. if (names.contains (choices[j], true))
  219790. return choices[j];
  219791. for (j = 0; j < choices.size(); ++j)
  219792. for (i = 0; i < names.size(); i++)
  219793. if (names[i].startsWithIgnoreCase (choices[j]))
  219794. return names[i];
  219795. for (j = 0; j < choices.size(); ++j)
  219796. for (i = 0; i < names.size(); i++)
  219797. if (names[i].containsIgnoreCase (choices[j]))
  219798. return names[i];
  219799. return names[0];
  219800. }
  219801. static const String linux_getDefaultSansSerifFontName()
  219802. {
  219803. StringArray allFonts;
  219804. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219805. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219806. }
  219807. static const String linux_getDefaultSerifFontName()
  219808. {
  219809. StringArray allFonts;
  219810. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219811. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219812. }
  219813. static const String linux_getDefaultMonospacedFontName()
  219814. {
  219815. StringArray allFonts;
  219816. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219817. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219818. }
  219819. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219820. {
  219821. defaultSans = linux_getDefaultSansSerifFontName();
  219822. defaultSerif = linux_getDefaultSerifFontName();
  219823. defaultFixed = linux_getDefaultMonospacedFontName();
  219824. }
  219825. #endif
  219826. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219827. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219828. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219829. // compiled on its own).
  219830. #if JUCE_INCLUDED_FILE
  219831. // These are defined in juce_linux_Messaging.cpp
  219832. extern Display* display;
  219833. extern XContext windowHandleXContext;
  219834. namespace Atoms
  219835. {
  219836. enum ProtocolItems
  219837. {
  219838. TAKE_FOCUS = 0,
  219839. DELETE_WINDOW = 1,
  219840. PING = 2
  219841. };
  219842. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219843. ActiveWin, Pid, WindowType, WindowState,
  219844. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219845. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219846. XdndActionDescription, XdndActionCopy,
  219847. allowedActions[5],
  219848. allowedMimeTypes[2];
  219849. const unsigned long DndVersion = 3;
  219850. static void initialiseAtoms()
  219851. {
  219852. static bool atomsInitialised = false;
  219853. if (! atomsInitialised)
  219854. {
  219855. atomsInitialised = true;
  219856. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219857. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219858. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219859. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219860. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219861. State = XInternAtom (display, "WM_STATE", True);
  219862. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219863. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219864. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219865. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219866. XdndAware = XInternAtom (display, "XdndAware", False);
  219867. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219868. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219869. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219870. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219871. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219872. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219873. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219874. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219875. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219876. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219877. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219878. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219879. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219880. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219881. allowedActions[1] = XdndActionCopy;
  219882. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219883. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219884. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219885. }
  219886. }
  219887. }
  219888. namespace Keys
  219889. {
  219890. enum MouseButtons
  219891. {
  219892. NoButton = 0,
  219893. LeftButton = 1,
  219894. MiddleButton = 2,
  219895. RightButton = 3,
  219896. WheelUp = 4,
  219897. WheelDown = 5
  219898. };
  219899. static int AltMask = 0;
  219900. static int NumLockMask = 0;
  219901. static bool numLock = false;
  219902. static bool capsLock = false;
  219903. static char keyStates [32];
  219904. static const int extendedKeyModifier = 0x10000000;
  219905. }
  219906. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219907. {
  219908. int keysym;
  219909. if (keyCode & Keys::extendedKeyModifier)
  219910. {
  219911. keysym = 0xff00 | (keyCode & 0xff);
  219912. }
  219913. else
  219914. {
  219915. keysym = keyCode;
  219916. if (keysym == (XK_Tab & 0xff)
  219917. || keysym == (XK_Return & 0xff)
  219918. || keysym == (XK_Escape & 0xff)
  219919. || keysym == (XK_BackSpace & 0xff))
  219920. {
  219921. keysym |= 0xff00;
  219922. }
  219923. }
  219924. ScopedXLock xlock;
  219925. const int keycode = XKeysymToKeycode (display, keysym);
  219926. const int keybyte = keycode >> 3;
  219927. const int keybit = (1 << (keycode & 7));
  219928. return (Keys::keyStates [keybyte] & keybit) != 0;
  219929. }
  219930. #if JUCE_USE_XSHM
  219931. namespace XSHMHelpers
  219932. {
  219933. static int trappedErrorCode = 0;
  219934. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219935. {
  219936. trappedErrorCode = err->error_code;
  219937. return 0;
  219938. }
  219939. static bool isShmAvailable() throw()
  219940. {
  219941. static bool isChecked = false;
  219942. static bool isAvailable = false;
  219943. if (! isChecked)
  219944. {
  219945. isChecked = true;
  219946. int major, minor;
  219947. Bool pixmaps;
  219948. ScopedXLock xlock;
  219949. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219950. {
  219951. trappedErrorCode = 0;
  219952. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219953. XShmSegmentInfo segmentInfo;
  219954. zerostruct (segmentInfo);
  219955. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219956. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219957. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219958. xImage->bytes_per_line * xImage->height,
  219959. IPC_CREAT | 0777)) >= 0)
  219960. {
  219961. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219962. if (segmentInfo.shmaddr != (void*) -1)
  219963. {
  219964. segmentInfo.readOnly = False;
  219965. xImage->data = segmentInfo.shmaddr;
  219966. XSync (display, False);
  219967. if (XShmAttach (display, &segmentInfo) != 0)
  219968. {
  219969. XSync (display, False);
  219970. XShmDetach (display, &segmentInfo);
  219971. isAvailable = true;
  219972. }
  219973. }
  219974. XFlush (display);
  219975. XDestroyImage (xImage);
  219976. shmdt (segmentInfo.shmaddr);
  219977. }
  219978. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219979. XSetErrorHandler (oldHandler);
  219980. if (trappedErrorCode != 0)
  219981. isAvailable = false;
  219982. }
  219983. }
  219984. return isAvailable;
  219985. }
  219986. }
  219987. #endif
  219988. #if JUCE_USE_XRENDER
  219989. namespace XRender
  219990. {
  219991. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219992. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219993. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219994. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219995. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219996. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219997. static tXRenderFindFormat xRenderFindFormat = 0;
  219998. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219999. static bool isAvailable()
  220000. {
  220001. static bool hasLoaded = false;
  220002. if (! hasLoaded)
  220003. {
  220004. ScopedXLock xlock;
  220005. hasLoaded = true;
  220006. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  220007. if (h != 0)
  220008. {
  220009. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  220010. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  220011. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  220012. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  220013. }
  220014. if (xRenderQueryVersion != 0
  220015. && xRenderFindStandardFormat != 0
  220016. && xRenderFindFormat != 0
  220017. && xRenderFindVisualFormat != 0)
  220018. {
  220019. int major, minor;
  220020. if (xRenderQueryVersion (display, &major, &minor))
  220021. return true;
  220022. }
  220023. xRenderQueryVersion = 0;
  220024. }
  220025. return xRenderQueryVersion != 0;
  220026. }
  220027. static XRenderPictFormat* findPictureFormat()
  220028. {
  220029. ScopedXLock xlock;
  220030. XRenderPictFormat* pictFormat = 0;
  220031. if (isAvailable())
  220032. {
  220033. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  220034. if (pictFormat == 0)
  220035. {
  220036. XRenderPictFormat desiredFormat;
  220037. desiredFormat.type = PictTypeDirect;
  220038. desiredFormat.depth = 32;
  220039. desiredFormat.direct.alphaMask = 0xff;
  220040. desiredFormat.direct.redMask = 0xff;
  220041. desiredFormat.direct.greenMask = 0xff;
  220042. desiredFormat.direct.blueMask = 0xff;
  220043. desiredFormat.direct.alpha = 24;
  220044. desiredFormat.direct.red = 16;
  220045. desiredFormat.direct.green = 8;
  220046. desiredFormat.direct.blue = 0;
  220047. pictFormat = xRenderFindFormat (display,
  220048. PictFormatType | PictFormatDepth
  220049. | PictFormatRedMask | PictFormatRed
  220050. | PictFormatGreenMask | PictFormatGreen
  220051. | PictFormatBlueMask | PictFormatBlue
  220052. | PictFormatAlphaMask | PictFormatAlpha,
  220053. &desiredFormat,
  220054. 0);
  220055. }
  220056. }
  220057. return pictFormat;
  220058. }
  220059. }
  220060. #endif
  220061. namespace Visuals
  220062. {
  220063. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  220064. {
  220065. ScopedXLock xlock;
  220066. Visual* visual = 0;
  220067. int numVisuals = 0;
  220068. long desiredMask = VisualNoMask;
  220069. XVisualInfo desiredVisual;
  220070. desiredVisual.screen = DefaultScreen (display);
  220071. desiredVisual.depth = desiredDepth;
  220072. desiredMask = VisualScreenMask | VisualDepthMask;
  220073. if (desiredDepth == 32)
  220074. {
  220075. desiredVisual.c_class = TrueColor;
  220076. desiredVisual.red_mask = 0x00FF0000;
  220077. desiredVisual.green_mask = 0x0000FF00;
  220078. desiredVisual.blue_mask = 0x000000FF;
  220079. desiredVisual.bits_per_rgb = 8;
  220080. desiredMask |= VisualClassMask;
  220081. desiredMask |= VisualRedMaskMask;
  220082. desiredMask |= VisualGreenMaskMask;
  220083. desiredMask |= VisualBlueMaskMask;
  220084. desiredMask |= VisualBitsPerRGBMask;
  220085. }
  220086. XVisualInfo* xvinfos = XGetVisualInfo (display,
  220087. desiredMask,
  220088. &desiredVisual,
  220089. &numVisuals);
  220090. if (xvinfos != 0)
  220091. {
  220092. for (int i = 0; i < numVisuals; i++)
  220093. {
  220094. if (xvinfos[i].depth == desiredDepth)
  220095. {
  220096. visual = xvinfos[i].visual;
  220097. break;
  220098. }
  220099. }
  220100. XFree (xvinfos);
  220101. }
  220102. return visual;
  220103. }
  220104. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  220105. {
  220106. Visual* visual = 0;
  220107. if (desiredDepth == 32)
  220108. {
  220109. #if JUCE_USE_XSHM
  220110. if (XSHMHelpers::isShmAvailable())
  220111. {
  220112. #if JUCE_USE_XRENDER
  220113. if (XRender::isAvailable())
  220114. {
  220115. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  220116. if (pictFormat != 0)
  220117. {
  220118. int numVisuals = 0;
  220119. XVisualInfo desiredVisual;
  220120. desiredVisual.screen = DefaultScreen (display);
  220121. desiredVisual.depth = 32;
  220122. desiredVisual.bits_per_rgb = 8;
  220123. XVisualInfo* xvinfos = XGetVisualInfo (display,
  220124. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  220125. &desiredVisual, &numVisuals);
  220126. if (xvinfos != 0)
  220127. {
  220128. for (int i = 0; i < numVisuals; ++i)
  220129. {
  220130. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  220131. if (pictVisualFormat != 0
  220132. && pictVisualFormat->type == PictTypeDirect
  220133. && pictVisualFormat->direct.alphaMask)
  220134. {
  220135. visual = xvinfos[i].visual;
  220136. matchedDepth = 32;
  220137. break;
  220138. }
  220139. }
  220140. XFree (xvinfos);
  220141. }
  220142. }
  220143. }
  220144. #endif
  220145. if (visual == 0)
  220146. {
  220147. visual = findVisualWithDepth (32);
  220148. if (visual != 0)
  220149. matchedDepth = 32;
  220150. }
  220151. }
  220152. #endif
  220153. }
  220154. if (visual == 0 && desiredDepth >= 24)
  220155. {
  220156. visual = findVisualWithDepth (24);
  220157. if (visual != 0)
  220158. matchedDepth = 24;
  220159. }
  220160. if (visual == 0 && desiredDepth >= 16)
  220161. {
  220162. visual = findVisualWithDepth (16);
  220163. if (visual != 0)
  220164. matchedDepth = 16;
  220165. }
  220166. return visual;
  220167. }
  220168. }
  220169. class XBitmapImage : public Image::SharedImage
  220170. {
  220171. public:
  220172. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  220173. const bool clearImage, const int imageDepth_, Visual* visual)
  220174. : Image::SharedImage (format_, w, h),
  220175. imageDepth (imageDepth_),
  220176. gc (None)
  220177. {
  220178. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  220179. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  220180. lineStride = ((w * pixelStride + 3) & ~3);
  220181. ScopedXLock xlock;
  220182. #if JUCE_USE_XSHM
  220183. usingXShm = false;
  220184. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  220185. {
  220186. zerostruct (segmentInfo);
  220187. segmentInfo.shmid = -1;
  220188. segmentInfo.shmaddr = (char *) -1;
  220189. segmentInfo.readOnly = False;
  220190. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  220191. if (xImage != 0)
  220192. {
  220193. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  220194. xImage->bytes_per_line * xImage->height,
  220195. IPC_CREAT | 0777)) >= 0)
  220196. {
  220197. if (segmentInfo.shmid != -1)
  220198. {
  220199. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  220200. if (segmentInfo.shmaddr != (void*) -1)
  220201. {
  220202. segmentInfo.readOnly = False;
  220203. xImage->data = segmentInfo.shmaddr;
  220204. imageData = (uint8*) segmentInfo.shmaddr;
  220205. if (XShmAttach (display, &segmentInfo) != 0)
  220206. usingXShm = true;
  220207. else
  220208. jassertfalse;
  220209. }
  220210. else
  220211. {
  220212. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220213. }
  220214. }
  220215. }
  220216. }
  220217. }
  220218. if (! usingXShm)
  220219. #endif
  220220. {
  220221. imageDataAllocated.malloc (lineStride * h);
  220222. imageData = imageDataAllocated;
  220223. if (format_ == Image::ARGB && clearImage)
  220224. zeromem (imageData, h * lineStride);
  220225. xImage = (XImage*) juce_calloc (sizeof (XImage));
  220226. xImage->width = w;
  220227. xImage->height = h;
  220228. xImage->xoffset = 0;
  220229. xImage->format = ZPixmap;
  220230. xImage->data = (char*) imageData;
  220231. xImage->byte_order = ImageByteOrder (display);
  220232. xImage->bitmap_unit = BitmapUnit (display);
  220233. xImage->bitmap_bit_order = BitmapBitOrder (display);
  220234. xImage->bitmap_pad = 32;
  220235. xImage->depth = pixelStride * 8;
  220236. xImage->bytes_per_line = lineStride;
  220237. xImage->bits_per_pixel = pixelStride * 8;
  220238. xImage->red_mask = 0x00FF0000;
  220239. xImage->green_mask = 0x0000FF00;
  220240. xImage->blue_mask = 0x000000FF;
  220241. if (imageDepth == 16)
  220242. {
  220243. const int pixelStride = 2;
  220244. const int lineStride = ((w * pixelStride + 3) & ~3);
  220245. imageData16Bit.malloc (lineStride * h);
  220246. xImage->data = imageData16Bit;
  220247. xImage->bitmap_pad = 16;
  220248. xImage->depth = pixelStride * 8;
  220249. xImage->bytes_per_line = lineStride;
  220250. xImage->bits_per_pixel = pixelStride * 8;
  220251. xImage->red_mask = visual->red_mask;
  220252. xImage->green_mask = visual->green_mask;
  220253. xImage->blue_mask = visual->blue_mask;
  220254. }
  220255. if (! XInitImage (xImage))
  220256. jassertfalse;
  220257. }
  220258. }
  220259. ~XBitmapImage()
  220260. {
  220261. ScopedXLock xlock;
  220262. if (gc != None)
  220263. XFreeGC (display, gc);
  220264. #if JUCE_USE_XSHM
  220265. if (usingXShm)
  220266. {
  220267. XShmDetach (display, &segmentInfo);
  220268. XFlush (display);
  220269. XDestroyImage (xImage);
  220270. shmdt (segmentInfo.shmaddr);
  220271. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220272. }
  220273. else
  220274. #endif
  220275. {
  220276. xImage->data = 0;
  220277. XDestroyImage (xImage);
  220278. }
  220279. }
  220280. Image::ImageType getType() const { return Image::NativeImage; }
  220281. LowLevelGraphicsContext* createLowLevelContext()
  220282. {
  220283. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220284. }
  220285. SharedImage* clone()
  220286. {
  220287. jassertfalse;
  220288. return 0;
  220289. }
  220290. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220291. {
  220292. ScopedXLock xlock;
  220293. if (gc == None)
  220294. {
  220295. XGCValues gcvalues;
  220296. gcvalues.foreground = None;
  220297. gcvalues.background = None;
  220298. gcvalues.function = GXcopy;
  220299. gcvalues.plane_mask = AllPlanes;
  220300. gcvalues.clip_mask = None;
  220301. gcvalues.graphics_exposures = False;
  220302. gc = XCreateGC (display, window,
  220303. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220304. &gcvalues);
  220305. }
  220306. if (imageDepth == 16)
  220307. {
  220308. const uint32 rMask = xImage->red_mask;
  220309. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220310. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220311. const uint32 gMask = xImage->green_mask;
  220312. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220313. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220314. const uint32 bMask = xImage->blue_mask;
  220315. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220316. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220317. const Image::BitmapData srcData (Image (this), false);
  220318. for (int y = sy; y < sy + dh; ++y)
  220319. {
  220320. const uint8* p = srcData.getPixelPointer (sx, y);
  220321. for (int x = sx; x < sx + dw; ++x)
  220322. {
  220323. const PixelRGB* const pixel = (const PixelRGB*) p;
  220324. p += srcData.pixelStride;
  220325. XPutPixel (xImage, x, y,
  220326. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220327. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220328. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220329. }
  220330. }
  220331. }
  220332. // blit results to screen.
  220333. #if JUCE_USE_XSHM
  220334. if (usingXShm)
  220335. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220336. else
  220337. #endif
  220338. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220339. }
  220340. juce_UseDebuggingNewOperator
  220341. private:
  220342. XImage* xImage;
  220343. const int imageDepth;
  220344. HeapBlock <uint8> imageDataAllocated;
  220345. HeapBlock <char> imageData16Bit;
  220346. GC gc;
  220347. #if JUCE_USE_XSHM
  220348. XShmSegmentInfo segmentInfo;
  220349. bool usingXShm;
  220350. #endif
  220351. static int getShiftNeeded (const uint32 mask) throw()
  220352. {
  220353. for (int i = 32; --i >= 0;)
  220354. if (((mask >> i) & 1) != 0)
  220355. return i - 7;
  220356. jassertfalse;
  220357. return 0;
  220358. }
  220359. };
  220360. class LinuxComponentPeer : public ComponentPeer
  220361. {
  220362. public:
  220363. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220364. : ComponentPeer (component, windowStyleFlags),
  220365. windowH (0),
  220366. parentWindow (0),
  220367. wx (0),
  220368. wy (0),
  220369. ww (0),
  220370. wh (0),
  220371. fullScreen (false),
  220372. mapped (false),
  220373. visual (0),
  220374. depth (0)
  220375. {
  220376. // it's dangerous to create a window on a thread other than the message thread..
  220377. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220378. repainter = new LinuxRepaintManager (this);
  220379. createWindow();
  220380. setTitle (component->getName());
  220381. }
  220382. ~LinuxComponentPeer()
  220383. {
  220384. // it's dangerous to delete a window on a thread other than the message thread..
  220385. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220386. deleteIconPixmaps();
  220387. destroyWindow();
  220388. windowH = 0;
  220389. }
  220390. void* getNativeHandle() const
  220391. {
  220392. return (void*) windowH;
  220393. }
  220394. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220395. {
  220396. XPointer peer = 0;
  220397. ScopedXLock xlock;
  220398. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220399. {
  220400. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220401. peer = 0;
  220402. }
  220403. return (LinuxComponentPeer*) peer;
  220404. }
  220405. void setVisible (bool shouldBeVisible)
  220406. {
  220407. ScopedXLock xlock;
  220408. if (shouldBeVisible)
  220409. XMapWindow (display, windowH);
  220410. else
  220411. XUnmapWindow (display, windowH);
  220412. }
  220413. void setTitle (const String& title)
  220414. {
  220415. setWindowTitle (windowH, title);
  220416. }
  220417. void setPosition (int x, int y)
  220418. {
  220419. setBounds (x, y, ww, wh, false);
  220420. }
  220421. void setSize (int w, int h)
  220422. {
  220423. setBounds (wx, wy, w, h, false);
  220424. }
  220425. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220426. {
  220427. fullScreen = isNowFullScreen;
  220428. if (windowH != 0)
  220429. {
  220430. Component::SafePointer<Component> deletionChecker (component);
  220431. wx = x;
  220432. wy = y;
  220433. ww = jmax (1, w);
  220434. wh = jmax (1, h);
  220435. ScopedXLock xlock;
  220436. // Make sure the Window manager does what we want
  220437. XSizeHints* hints = XAllocSizeHints();
  220438. hints->flags = USSize | USPosition;
  220439. hints->width = ww;
  220440. hints->height = wh;
  220441. hints->x = wx;
  220442. hints->y = wy;
  220443. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220444. {
  220445. hints->min_width = hints->max_width = hints->width;
  220446. hints->min_height = hints->max_height = hints->height;
  220447. hints->flags |= PMinSize | PMaxSize;
  220448. }
  220449. XSetWMNormalHints (display, windowH, hints);
  220450. XFree (hints);
  220451. XMoveResizeWindow (display, windowH,
  220452. wx - windowBorder.getLeft(),
  220453. wy - windowBorder.getTop(), ww, wh);
  220454. if (deletionChecker != 0)
  220455. {
  220456. updateBorderSize();
  220457. handleMovedOrResized();
  220458. }
  220459. }
  220460. }
  220461. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220462. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220463. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220464. {
  220465. return relativePosition + getScreenPosition();
  220466. }
  220467. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220468. {
  220469. return screenPosition - getScreenPosition();
  220470. }
  220471. void setMinimised (bool shouldBeMinimised)
  220472. {
  220473. if (shouldBeMinimised)
  220474. {
  220475. Window root = RootWindow (display, DefaultScreen (display));
  220476. XClientMessageEvent clientMsg;
  220477. clientMsg.display = display;
  220478. clientMsg.window = windowH;
  220479. clientMsg.type = ClientMessage;
  220480. clientMsg.format = 32;
  220481. clientMsg.message_type = Atoms::ChangeState;
  220482. clientMsg.data.l[0] = IconicState;
  220483. ScopedXLock xlock;
  220484. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220485. }
  220486. else
  220487. {
  220488. setVisible (true);
  220489. }
  220490. }
  220491. bool isMinimised() const
  220492. {
  220493. bool minimised = false;
  220494. unsigned char* stateProp;
  220495. unsigned long nitems, bytesLeft;
  220496. Atom actualType;
  220497. int actualFormat;
  220498. ScopedXLock xlock;
  220499. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220500. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220501. &stateProp) == Success
  220502. && actualType == Atoms::State
  220503. && actualFormat == 32
  220504. && nitems > 0)
  220505. {
  220506. if (((unsigned long*) stateProp)[0] == IconicState)
  220507. minimised = true;
  220508. XFree (stateProp);
  220509. }
  220510. return minimised;
  220511. }
  220512. void setFullScreen (const bool shouldBeFullScreen)
  220513. {
  220514. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220515. setMinimised (false);
  220516. if (fullScreen != shouldBeFullScreen)
  220517. {
  220518. if (shouldBeFullScreen)
  220519. r = Desktop::getInstance().getMainMonitorArea();
  220520. if (! r.isEmpty())
  220521. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220522. getComponent()->repaint();
  220523. }
  220524. }
  220525. bool isFullScreen() const
  220526. {
  220527. return fullScreen;
  220528. }
  220529. bool isChildWindowOf (Window possibleParent) const
  220530. {
  220531. Window* windowList = 0;
  220532. uint32 windowListSize = 0;
  220533. Window parent, root;
  220534. ScopedXLock xlock;
  220535. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220536. {
  220537. if (windowList != 0)
  220538. XFree (windowList);
  220539. return parent == possibleParent;
  220540. }
  220541. return false;
  220542. }
  220543. bool isFrontWindow() const
  220544. {
  220545. Window* windowList = 0;
  220546. uint32 windowListSize = 0;
  220547. bool result = false;
  220548. ScopedXLock xlock;
  220549. Window parent, root = RootWindow (display, DefaultScreen (display));
  220550. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220551. {
  220552. for (int i = windowListSize; --i >= 0;)
  220553. {
  220554. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220555. if (peer != 0)
  220556. {
  220557. result = (peer == this);
  220558. break;
  220559. }
  220560. }
  220561. }
  220562. if (windowList != 0)
  220563. XFree (windowList);
  220564. return result;
  220565. }
  220566. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220567. {
  220568. int x = position.getX();
  220569. int y = position.getY();
  220570. if (((unsigned int) x) >= (unsigned int) ww
  220571. || ((unsigned int) y) >= (unsigned int) wh)
  220572. return false;
  220573. bool inFront = false;
  220574. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220575. {
  220576. Component* const c = Desktop::getInstance().getComponent (i);
  220577. if (inFront)
  220578. {
  220579. if (c->contains (x + wx - c->getScreenX(),
  220580. y + wy - c->getScreenY()))
  220581. {
  220582. return false;
  220583. }
  220584. }
  220585. else if (c == getComponent())
  220586. {
  220587. inFront = true;
  220588. }
  220589. }
  220590. if (trueIfInAChildWindow)
  220591. return true;
  220592. ::Window root, child;
  220593. unsigned int bw, depth;
  220594. int wx, wy, w, h;
  220595. ScopedXLock xlock;
  220596. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220597. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220598. &bw, &depth))
  220599. {
  220600. return false;
  220601. }
  220602. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220603. return false;
  220604. return child == None;
  220605. }
  220606. const BorderSize getFrameSize() const
  220607. {
  220608. return BorderSize();
  220609. }
  220610. bool setAlwaysOnTop (bool alwaysOnTop)
  220611. {
  220612. return false;
  220613. }
  220614. void toFront (bool makeActive)
  220615. {
  220616. if (makeActive)
  220617. {
  220618. setVisible (true);
  220619. grabFocus();
  220620. }
  220621. XEvent ev;
  220622. ev.xclient.type = ClientMessage;
  220623. ev.xclient.serial = 0;
  220624. ev.xclient.send_event = True;
  220625. ev.xclient.message_type = Atoms::ActiveWin;
  220626. ev.xclient.window = windowH;
  220627. ev.xclient.format = 32;
  220628. ev.xclient.data.l[0] = 2;
  220629. ev.xclient.data.l[1] = CurrentTime;
  220630. ev.xclient.data.l[2] = 0;
  220631. ev.xclient.data.l[3] = 0;
  220632. ev.xclient.data.l[4] = 0;
  220633. {
  220634. ScopedXLock xlock;
  220635. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220636. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220637. XWindowAttributes attr;
  220638. XGetWindowAttributes (display, windowH, &attr);
  220639. if (component->isAlwaysOnTop())
  220640. XRaiseWindow (display, windowH);
  220641. XSync (display, False);
  220642. }
  220643. handleBroughtToFront();
  220644. }
  220645. void toBehind (ComponentPeer* other)
  220646. {
  220647. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220648. jassert (otherPeer != 0); // wrong type of window?
  220649. if (otherPeer != 0)
  220650. {
  220651. setMinimised (false);
  220652. Window newStack[] = { otherPeer->windowH, windowH };
  220653. ScopedXLock xlock;
  220654. XRestackWindows (display, newStack, 2);
  220655. }
  220656. }
  220657. bool isFocused() const
  220658. {
  220659. int revert = 0;
  220660. Window focusedWindow = 0;
  220661. ScopedXLock xlock;
  220662. XGetInputFocus (display, &focusedWindow, &revert);
  220663. return focusedWindow == windowH;
  220664. }
  220665. void grabFocus()
  220666. {
  220667. XWindowAttributes atts;
  220668. ScopedXLock xlock;
  220669. if (windowH != 0
  220670. && XGetWindowAttributes (display, windowH, &atts)
  220671. && atts.map_state == IsViewable
  220672. && ! isFocused())
  220673. {
  220674. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220675. isActiveApplication = true;
  220676. }
  220677. }
  220678. void textInputRequired (const Point<int>&)
  220679. {
  220680. }
  220681. void repaint (const Rectangle<int>& area)
  220682. {
  220683. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220684. }
  220685. void performAnyPendingRepaintsNow()
  220686. {
  220687. repainter->performAnyPendingRepaintsNow();
  220688. }
  220689. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220690. {
  220691. ScopedXLock xlock;
  220692. const int width = image.getWidth();
  220693. const int height = image.getHeight();
  220694. HeapBlock <char> colour (width * height);
  220695. int index = 0;
  220696. for (int y = 0; y < height; ++y)
  220697. for (int x = 0; x < width; ++x)
  220698. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  220699. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220700. 0, colour.getData(),
  220701. width, height, 32, 0);
  220702. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220703. width, height, 24);
  220704. GC gc = XCreateGC (display, pixmap, 0, 0);
  220705. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220706. XFreeGC (display, gc);
  220707. return pixmap;
  220708. }
  220709. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220710. {
  220711. ScopedXLock xlock;
  220712. const int width = image.getWidth();
  220713. const int height = image.getHeight();
  220714. const int stride = (width + 7) >> 3;
  220715. HeapBlock <char> mask;
  220716. mask.calloc (stride * height);
  220717. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220718. for (int y = 0; y < height; ++y)
  220719. {
  220720. for (int x = 0; x < width; ++x)
  220721. {
  220722. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220723. const int offset = y * stride + (x >> 3);
  220724. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220725. mask[offset] |= bit;
  220726. }
  220727. }
  220728. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220729. mask.getData(), width, height, 1, 0, 1);
  220730. }
  220731. void setIcon (const Image& newIcon)
  220732. {
  220733. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220734. HeapBlock <unsigned long> data (dataSize);
  220735. int index = 0;
  220736. data[index++] = newIcon.getWidth();
  220737. data[index++] = newIcon.getHeight();
  220738. for (int y = 0; y < newIcon.getHeight(); ++y)
  220739. for (int x = 0; x < newIcon.getWidth(); ++x)
  220740. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220741. ScopedXLock xlock;
  220742. XChangeProperty (display, windowH,
  220743. XInternAtom (display, "_NET_WM_ICON", False),
  220744. XA_CARDINAL, 32, PropModeReplace,
  220745. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220746. deleteIconPixmaps();
  220747. XWMHints* wmHints = XGetWMHints (display, windowH);
  220748. if (wmHints == 0)
  220749. wmHints = XAllocWMHints();
  220750. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220751. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220752. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220753. XSetWMHints (display, windowH, wmHints);
  220754. XFree (wmHints);
  220755. XSync (display, False);
  220756. }
  220757. void deleteIconPixmaps()
  220758. {
  220759. ScopedXLock xlock;
  220760. XWMHints* wmHints = XGetWMHints (display, windowH);
  220761. if (wmHints != 0)
  220762. {
  220763. if ((wmHints->flags & IconPixmapHint) != 0)
  220764. {
  220765. wmHints->flags &= ~IconPixmapHint;
  220766. XFreePixmap (display, wmHints->icon_pixmap);
  220767. }
  220768. if ((wmHints->flags & IconMaskHint) != 0)
  220769. {
  220770. wmHints->flags &= ~IconMaskHint;
  220771. XFreePixmap (display, wmHints->icon_mask);
  220772. }
  220773. XSetWMHints (display, windowH, wmHints);
  220774. XFree (wmHints);
  220775. }
  220776. }
  220777. void handleWindowMessage (XEvent* event)
  220778. {
  220779. switch (event->xany.type)
  220780. {
  220781. case 2: // 'KeyPress'
  220782. {
  220783. ScopedXLock xlock;
  220784. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220785. updateKeyStates (keyEvent->keycode, true);
  220786. char utf8 [64];
  220787. zeromem (utf8, sizeof (utf8));
  220788. KeySym sym;
  220789. {
  220790. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220791. ::setlocale (LC_ALL, "");
  220792. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220793. ::setlocale (LC_ALL, oldLocale);
  220794. }
  220795. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220796. int keyCode = (int) unicodeChar;
  220797. if (keyCode < 0x20)
  220798. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220799. const ModifierKeys oldMods (currentModifiers);
  220800. bool keyPressed = false;
  220801. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220802. if ((sym & 0xff00) == 0xff00)
  220803. {
  220804. // Translate keypad
  220805. if (sym == XK_KP_Divide)
  220806. keyCode = XK_slash;
  220807. else if (sym == XK_KP_Multiply)
  220808. keyCode = XK_asterisk;
  220809. else if (sym == XK_KP_Subtract)
  220810. keyCode = XK_hyphen;
  220811. else if (sym == XK_KP_Add)
  220812. keyCode = XK_plus;
  220813. else if (sym == XK_KP_Enter)
  220814. keyCode = XK_Return;
  220815. else if (sym == XK_KP_Decimal)
  220816. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220817. else if (sym == XK_KP_0)
  220818. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220819. else if (sym == XK_KP_1)
  220820. keyCode = Keys::numLock ? XK_1 : XK_End;
  220821. else if (sym == XK_KP_2)
  220822. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220823. else if (sym == XK_KP_3)
  220824. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220825. else if (sym == XK_KP_4)
  220826. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220827. else if (sym == XK_KP_5)
  220828. keyCode = XK_5;
  220829. else if (sym == XK_KP_6)
  220830. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220831. else if (sym == XK_KP_7)
  220832. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220833. else if (sym == XK_KP_8)
  220834. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220835. else if (sym == XK_KP_9)
  220836. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220837. switch (sym)
  220838. {
  220839. case XK_Left:
  220840. case XK_Right:
  220841. case XK_Up:
  220842. case XK_Down:
  220843. case XK_Page_Up:
  220844. case XK_Page_Down:
  220845. case XK_End:
  220846. case XK_Home:
  220847. case XK_Delete:
  220848. case XK_Insert:
  220849. keyPressed = true;
  220850. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220851. break;
  220852. case XK_Tab:
  220853. case XK_Return:
  220854. case XK_Escape:
  220855. case XK_BackSpace:
  220856. keyPressed = true;
  220857. keyCode &= 0xff;
  220858. break;
  220859. default:
  220860. {
  220861. if (sym >= XK_F1 && sym <= XK_F16)
  220862. {
  220863. keyPressed = true;
  220864. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220865. }
  220866. break;
  220867. }
  220868. }
  220869. }
  220870. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220871. keyPressed = true;
  220872. if (oldMods != currentModifiers)
  220873. handleModifierKeysChange();
  220874. if (keyDownChange)
  220875. handleKeyUpOrDown (true);
  220876. if (keyPressed)
  220877. handleKeyPress (keyCode, unicodeChar);
  220878. break;
  220879. }
  220880. case KeyRelease:
  220881. {
  220882. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220883. updateKeyStates (keyEvent->keycode, false);
  220884. KeySym sym;
  220885. {
  220886. ScopedXLock xlock;
  220887. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220888. }
  220889. const ModifierKeys oldMods (currentModifiers);
  220890. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220891. if (oldMods != currentModifiers)
  220892. handleModifierKeysChange();
  220893. if (keyDownChange)
  220894. handleKeyUpOrDown (false);
  220895. break;
  220896. }
  220897. case ButtonPress:
  220898. {
  220899. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220900. updateKeyModifiers (buttonPressEvent->state);
  220901. bool buttonMsg = false;
  220902. const int map = pointerMap [buttonPressEvent->button - Button1];
  220903. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220904. {
  220905. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220906. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220907. }
  220908. if (map == Keys::LeftButton)
  220909. {
  220910. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220911. buttonMsg = true;
  220912. }
  220913. else if (map == Keys::RightButton)
  220914. {
  220915. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220916. buttonMsg = true;
  220917. }
  220918. else if (map == Keys::MiddleButton)
  220919. {
  220920. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220921. buttonMsg = true;
  220922. }
  220923. if (buttonMsg)
  220924. {
  220925. toFront (true);
  220926. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220927. getEventTime (buttonPressEvent->time));
  220928. }
  220929. clearLastMousePos();
  220930. break;
  220931. }
  220932. case ButtonRelease:
  220933. {
  220934. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220935. updateKeyModifiers (buttonRelEvent->state);
  220936. const int map = pointerMap [buttonRelEvent->button - Button1];
  220937. if (map == Keys::LeftButton)
  220938. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220939. else if (map == Keys::RightButton)
  220940. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220941. else if (map == Keys::MiddleButton)
  220942. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220943. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220944. getEventTime (buttonRelEvent->time));
  220945. clearLastMousePos();
  220946. break;
  220947. }
  220948. case MotionNotify:
  220949. {
  220950. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220951. updateKeyModifiers (movedEvent->state);
  220952. const Point<int> mousePos (Desktop::getMousePosition());
  220953. if (lastMousePos != mousePos)
  220954. {
  220955. lastMousePos = mousePos;
  220956. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220957. {
  220958. Window wRoot = 0, wParent = 0;
  220959. {
  220960. ScopedXLock xlock;
  220961. unsigned int numChildren;
  220962. Window* wChild = 0;
  220963. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220964. }
  220965. if (wParent != 0
  220966. && wParent != windowH
  220967. && wParent != wRoot)
  220968. {
  220969. parentWindow = wParent;
  220970. updateBounds();
  220971. }
  220972. else
  220973. {
  220974. parentWindow = 0;
  220975. }
  220976. }
  220977. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220978. }
  220979. break;
  220980. }
  220981. case EnterNotify:
  220982. {
  220983. clearLastMousePos();
  220984. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220985. if (! currentModifiers.isAnyMouseButtonDown())
  220986. {
  220987. updateKeyModifiers (enterEvent->state);
  220988. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220989. }
  220990. break;
  220991. }
  220992. case LeaveNotify:
  220993. {
  220994. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220995. // Suppress the normal leave if we've got a pointer grab, or if
  220996. // it's a bogus one caused by clicking a mouse button when running
  220997. // in a Window manager
  220998. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220999. || leaveEvent->mode == NotifyUngrab)
  221000. {
  221001. updateKeyModifiers (leaveEvent->state);
  221002. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  221003. }
  221004. break;
  221005. }
  221006. case FocusIn:
  221007. {
  221008. isActiveApplication = true;
  221009. if (isFocused())
  221010. handleFocusGain();
  221011. break;
  221012. }
  221013. case FocusOut:
  221014. {
  221015. isActiveApplication = false;
  221016. if (! isFocused())
  221017. handleFocusLoss();
  221018. break;
  221019. }
  221020. case Expose:
  221021. {
  221022. // Batch together all pending expose events
  221023. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  221024. XEvent nextEvent;
  221025. ScopedXLock xlock;
  221026. if (exposeEvent->window != windowH)
  221027. {
  221028. Window child;
  221029. XTranslateCoordinates (display, exposeEvent->window, windowH,
  221030. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  221031. &child);
  221032. }
  221033. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  221034. exposeEvent->width, exposeEvent->height));
  221035. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  221036. {
  221037. XPeekEvent (display, (XEvent*) &nextEvent);
  221038. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  221039. break;
  221040. XNextEvent (display, (XEvent*) &nextEvent);
  221041. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  221042. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  221043. nextExposeEvent->width, nextExposeEvent->height));
  221044. }
  221045. break;
  221046. }
  221047. case CirculateNotify:
  221048. case CreateNotify:
  221049. case DestroyNotify:
  221050. // Think we can ignore these
  221051. break;
  221052. case ConfigureNotify:
  221053. {
  221054. updateBounds();
  221055. updateBorderSize();
  221056. handleMovedOrResized();
  221057. // if the native title bar is dragged, need to tell any active menus, etc.
  221058. if ((styleFlags & windowHasTitleBar) != 0
  221059. && component->isCurrentlyBlockedByAnotherModalComponent())
  221060. {
  221061. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  221062. if (currentModalComp != 0)
  221063. currentModalComp->inputAttemptWhenModal();
  221064. }
  221065. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  221066. if (confEvent->window == windowH
  221067. && confEvent->above != 0
  221068. && isFrontWindow())
  221069. {
  221070. handleBroughtToFront();
  221071. }
  221072. break;
  221073. }
  221074. case ReparentNotify:
  221075. {
  221076. parentWindow = 0;
  221077. Window wRoot = 0;
  221078. Window* wChild = 0;
  221079. unsigned int numChildren;
  221080. {
  221081. ScopedXLock xlock;
  221082. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  221083. }
  221084. if (parentWindow == windowH || parentWindow == wRoot)
  221085. parentWindow = 0;
  221086. updateBounds();
  221087. updateBorderSize();
  221088. handleMovedOrResized();
  221089. break;
  221090. }
  221091. case GravityNotify:
  221092. {
  221093. updateBounds();
  221094. updateBorderSize();
  221095. handleMovedOrResized();
  221096. break;
  221097. }
  221098. case MapNotify:
  221099. mapped = true;
  221100. handleBroughtToFront();
  221101. break;
  221102. case UnmapNotify:
  221103. mapped = false;
  221104. break;
  221105. case MappingNotify:
  221106. {
  221107. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  221108. if (mappingEvent->request != MappingPointer)
  221109. {
  221110. // Deal with modifier/keyboard mapping
  221111. ScopedXLock xlock;
  221112. XRefreshKeyboardMapping (mappingEvent);
  221113. updateModifierMappings();
  221114. }
  221115. break;
  221116. }
  221117. case ClientMessage:
  221118. {
  221119. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  221120. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  221121. {
  221122. const Atom atom = (Atom) clientMsg->data.l[0];
  221123. if (atom == Atoms::ProtocolList [Atoms::PING])
  221124. {
  221125. Window root = RootWindow (display, DefaultScreen (display));
  221126. event->xclient.window = root;
  221127. XSendEvent (display, root, False, NoEventMask, event);
  221128. XFlush (display);
  221129. }
  221130. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  221131. {
  221132. XWindowAttributes atts;
  221133. ScopedXLock xlock;
  221134. if (clientMsg->window != 0
  221135. && XGetWindowAttributes (display, clientMsg->window, &atts))
  221136. {
  221137. if (atts.map_state == IsViewable)
  221138. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  221139. }
  221140. }
  221141. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  221142. {
  221143. handleUserClosingWindow();
  221144. }
  221145. }
  221146. else if (clientMsg->message_type == Atoms::XdndEnter)
  221147. {
  221148. handleDragAndDropEnter (clientMsg);
  221149. }
  221150. else if (clientMsg->message_type == Atoms::XdndLeave)
  221151. {
  221152. resetDragAndDrop();
  221153. }
  221154. else if (clientMsg->message_type == Atoms::XdndPosition)
  221155. {
  221156. handleDragAndDropPosition (clientMsg);
  221157. }
  221158. else if (clientMsg->message_type == Atoms::XdndDrop)
  221159. {
  221160. handleDragAndDropDrop (clientMsg);
  221161. }
  221162. else if (clientMsg->message_type == Atoms::XdndStatus)
  221163. {
  221164. handleDragAndDropStatus (clientMsg);
  221165. }
  221166. else if (clientMsg->message_type == Atoms::XdndFinished)
  221167. {
  221168. resetDragAndDrop();
  221169. }
  221170. break;
  221171. }
  221172. case SelectionNotify:
  221173. handleDragAndDropSelection (event);
  221174. break;
  221175. case SelectionClear:
  221176. case SelectionRequest:
  221177. break;
  221178. default:
  221179. #if JUCE_USE_XSHM
  221180. {
  221181. ScopedXLock xlock;
  221182. if (event->xany.type == XShmGetEventBase (display))
  221183. repainter->notifyPaintCompleted();
  221184. }
  221185. #endif
  221186. break;
  221187. }
  221188. }
  221189. void showMouseCursor (Cursor cursor) throw()
  221190. {
  221191. ScopedXLock xlock;
  221192. XDefineCursor (display, windowH, cursor);
  221193. }
  221194. void setTaskBarIcon (const Image& image)
  221195. {
  221196. ScopedXLock xlock;
  221197. taskbarImage = image;
  221198. Screen* const screen = XDefaultScreenOfDisplay (display);
  221199. const int screenNumber = XScreenNumberOfScreen (screen);
  221200. String screenAtom ("_NET_SYSTEM_TRAY_S");
  221201. screenAtom << screenNumber;
  221202. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  221203. XGrabServer (display);
  221204. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  221205. if (managerWin != None)
  221206. XSelectInput (display, managerWin, StructureNotifyMask);
  221207. XUngrabServer (display);
  221208. XFlush (display);
  221209. if (managerWin != None)
  221210. {
  221211. XEvent ev;
  221212. zerostruct (ev);
  221213. ev.xclient.type = ClientMessage;
  221214. ev.xclient.window = managerWin;
  221215. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  221216. ev.xclient.format = 32;
  221217. ev.xclient.data.l[0] = CurrentTime;
  221218. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  221219. ev.xclient.data.l[2] = windowH;
  221220. ev.xclient.data.l[3] = 0;
  221221. ev.xclient.data.l[4] = 0;
  221222. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  221223. XSync (display, False);
  221224. }
  221225. // For older KDE's ...
  221226. long atomData = 1;
  221227. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  221228. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  221229. // For more recent KDE's...
  221230. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  221231. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  221232. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  221233. XSizeHints* hints = XAllocSizeHints();
  221234. hints->flags = PMinSize;
  221235. hints->min_width = 22;
  221236. hints->min_height = 22;
  221237. XSetWMNormalHints (display, windowH, hints);
  221238. XFree (hints);
  221239. }
  221240. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  221241. juce_UseDebuggingNewOperator
  221242. bool dontRepaint;
  221243. static ModifierKeys currentModifiers;
  221244. static bool isActiveApplication;
  221245. private:
  221246. class LinuxRepaintManager : public Timer
  221247. {
  221248. public:
  221249. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  221250. : peer (peer_),
  221251. lastTimeImageUsed (0)
  221252. {
  221253. #if JUCE_USE_XSHM
  221254. shmCompletedDrawing = true;
  221255. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  221256. if (useARGBImagesForRendering)
  221257. {
  221258. ScopedXLock xlock;
  221259. XShmSegmentInfo segmentinfo;
  221260. XImage* const testImage
  221261. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  221262. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  221263. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221264. XDestroyImage (testImage);
  221265. }
  221266. #endif
  221267. }
  221268. ~LinuxRepaintManager()
  221269. {
  221270. }
  221271. void timerCallback()
  221272. {
  221273. #if JUCE_USE_XSHM
  221274. if (! shmCompletedDrawing)
  221275. return;
  221276. #endif
  221277. if (! regionsNeedingRepaint.isEmpty())
  221278. {
  221279. stopTimer();
  221280. performAnyPendingRepaintsNow();
  221281. }
  221282. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221283. {
  221284. stopTimer();
  221285. image = Image::null;
  221286. }
  221287. }
  221288. void repaint (const Rectangle<int>& area)
  221289. {
  221290. if (! isTimerRunning())
  221291. startTimer (repaintTimerPeriod);
  221292. regionsNeedingRepaint.add (area);
  221293. }
  221294. void performAnyPendingRepaintsNow()
  221295. {
  221296. #if JUCE_USE_XSHM
  221297. if (! shmCompletedDrawing)
  221298. {
  221299. startTimer (repaintTimerPeriod);
  221300. return;
  221301. }
  221302. #endif
  221303. peer->clearMaskedRegion();
  221304. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221305. regionsNeedingRepaint.clear();
  221306. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221307. if (! totalArea.isEmpty())
  221308. {
  221309. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221310. || image.getHeight() < totalArea.getHeight())
  221311. {
  221312. #if JUCE_USE_XSHM
  221313. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221314. : Image::RGB,
  221315. #else
  221316. image = Image (new XBitmapImage (Image::RGB,
  221317. #endif
  221318. (totalArea.getWidth() + 31) & ~31,
  221319. (totalArea.getHeight() + 31) & ~31,
  221320. false, peer->depth, peer->visual));
  221321. }
  221322. startTimer (repaintTimerPeriod);
  221323. RectangleList adjustedList (originalRepaintRegion);
  221324. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221325. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221326. if (peer->depth == 32)
  221327. {
  221328. RectangleList::Iterator i (originalRepaintRegion);
  221329. while (i.next())
  221330. image.clear (*i.getRectangle() - totalArea.getPosition());
  221331. }
  221332. peer->handlePaint (context);
  221333. if (! peer->maskedRegion.isEmpty())
  221334. originalRepaintRegion.subtract (peer->maskedRegion);
  221335. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221336. {
  221337. #if JUCE_USE_XSHM
  221338. shmCompletedDrawing = false;
  221339. #endif
  221340. const Rectangle<int>& r = *i.getRectangle();
  221341. static_cast<XBitmapImage*> (image.getSharedImage())
  221342. ->blitToWindow (peer->windowH,
  221343. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221344. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221345. }
  221346. }
  221347. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221348. startTimer (repaintTimerPeriod);
  221349. }
  221350. #if JUCE_USE_XSHM
  221351. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221352. #endif
  221353. private:
  221354. enum { repaintTimerPeriod = 1000 / 100 };
  221355. LinuxComponentPeer* const peer;
  221356. Image image;
  221357. uint32 lastTimeImageUsed;
  221358. RectangleList regionsNeedingRepaint;
  221359. #if JUCE_USE_XSHM
  221360. bool useARGBImagesForRendering, shmCompletedDrawing;
  221361. #endif
  221362. LinuxRepaintManager (const LinuxRepaintManager&);
  221363. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221364. };
  221365. ScopedPointer <LinuxRepaintManager> repainter;
  221366. friend class LinuxRepaintManager;
  221367. Window windowH, parentWindow;
  221368. int wx, wy, ww, wh;
  221369. Image taskbarImage;
  221370. bool fullScreen, mapped;
  221371. Visual* visual;
  221372. int depth;
  221373. BorderSize windowBorder;
  221374. struct MotifWmHints
  221375. {
  221376. unsigned long flags;
  221377. unsigned long functions;
  221378. unsigned long decorations;
  221379. long input_mode;
  221380. unsigned long status;
  221381. };
  221382. static void updateKeyStates (const int keycode, const bool press) throw()
  221383. {
  221384. const int keybyte = keycode >> 3;
  221385. const int keybit = (1 << (keycode & 7));
  221386. if (press)
  221387. Keys::keyStates [keybyte] |= keybit;
  221388. else
  221389. Keys::keyStates [keybyte] &= ~keybit;
  221390. }
  221391. static void updateKeyModifiers (const int status) throw()
  221392. {
  221393. int keyMods = 0;
  221394. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221395. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221396. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221397. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221398. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221399. Keys::capsLock = ((status & LockMask) != 0);
  221400. }
  221401. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221402. {
  221403. int modifier = 0;
  221404. bool isModifier = true;
  221405. switch (sym)
  221406. {
  221407. case XK_Shift_L:
  221408. case XK_Shift_R:
  221409. modifier = ModifierKeys::shiftModifier;
  221410. break;
  221411. case XK_Control_L:
  221412. case XK_Control_R:
  221413. modifier = ModifierKeys::ctrlModifier;
  221414. break;
  221415. case XK_Alt_L:
  221416. case XK_Alt_R:
  221417. modifier = ModifierKeys::altModifier;
  221418. break;
  221419. case XK_Num_Lock:
  221420. if (press)
  221421. Keys::numLock = ! Keys::numLock;
  221422. break;
  221423. case XK_Caps_Lock:
  221424. if (press)
  221425. Keys::capsLock = ! Keys::capsLock;
  221426. break;
  221427. case XK_Scroll_Lock:
  221428. break;
  221429. default:
  221430. isModifier = false;
  221431. break;
  221432. }
  221433. if (modifier != 0)
  221434. {
  221435. if (press)
  221436. currentModifiers = currentModifiers.withFlags (modifier);
  221437. else
  221438. currentModifiers = currentModifiers.withoutFlags (modifier);
  221439. }
  221440. return isModifier;
  221441. }
  221442. // Alt and Num lock are not defined by standard X
  221443. // modifier constants: check what they're mapped to
  221444. static void updateModifierMappings() throw()
  221445. {
  221446. ScopedXLock xlock;
  221447. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221448. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221449. Keys::AltMask = 0;
  221450. Keys::NumLockMask = 0;
  221451. XModifierKeymap* mapping = XGetModifierMapping (display);
  221452. if (mapping)
  221453. {
  221454. for (int i = 0; i < 8; i++)
  221455. {
  221456. if (mapping->modifiermap [i << 1] == altLeftCode)
  221457. Keys::AltMask = 1 << i;
  221458. else if (mapping->modifiermap [i << 1] == numLockCode)
  221459. Keys::NumLockMask = 1 << i;
  221460. }
  221461. XFreeModifiermap (mapping);
  221462. }
  221463. }
  221464. void removeWindowDecorations (Window wndH)
  221465. {
  221466. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221467. if (hints != None)
  221468. {
  221469. MotifWmHints motifHints;
  221470. zerostruct (motifHints);
  221471. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221472. motifHints.decorations = 0;
  221473. ScopedXLock xlock;
  221474. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221475. (unsigned char*) &motifHints, 4);
  221476. }
  221477. hints = XInternAtom (display, "_WIN_HINTS", True);
  221478. if (hints != None)
  221479. {
  221480. long gnomeHints = 0;
  221481. ScopedXLock xlock;
  221482. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221483. (unsigned char*) &gnomeHints, 1);
  221484. }
  221485. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221486. if (hints != None)
  221487. {
  221488. long kwmHints = 2; /*KDE_tinyDecoration*/
  221489. ScopedXLock xlock;
  221490. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221491. (unsigned char*) &kwmHints, 1);
  221492. }
  221493. }
  221494. void addWindowButtons (Window wndH)
  221495. {
  221496. ScopedXLock xlock;
  221497. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221498. if (hints != None)
  221499. {
  221500. MotifWmHints motifHints;
  221501. zerostruct (motifHints);
  221502. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221503. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221504. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221505. if ((styleFlags & windowHasCloseButton) != 0)
  221506. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221507. if ((styleFlags & windowHasMinimiseButton) != 0)
  221508. {
  221509. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221510. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221511. }
  221512. if ((styleFlags & windowHasMaximiseButton) != 0)
  221513. {
  221514. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221515. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221516. }
  221517. if ((styleFlags & windowIsResizable) != 0)
  221518. {
  221519. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221520. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221521. }
  221522. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221523. }
  221524. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221525. if (hints != None)
  221526. {
  221527. int netHints [6];
  221528. int num = 0;
  221529. if ((styleFlags & windowIsResizable) != 0)
  221530. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221531. if ((styleFlags & windowHasMaximiseButton) != 0)
  221532. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221533. if ((styleFlags & windowHasMinimiseButton) != 0)
  221534. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221535. if ((styleFlags & windowHasCloseButton) != 0)
  221536. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221537. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221538. }
  221539. }
  221540. void setWindowType()
  221541. {
  221542. int netHints [2];
  221543. int numHints = 0;
  221544. if ((styleFlags & windowIsTemporary) != 0
  221545. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221546. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221547. else
  221548. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221549. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221550. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221551. (unsigned char*) &netHints, numHints);
  221552. numHints = 0;
  221553. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221554. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221555. if (component->isAlwaysOnTop())
  221556. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221557. if (numHints > 0)
  221558. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221559. (unsigned char*) &netHints, numHints);
  221560. }
  221561. void createWindow()
  221562. {
  221563. ScopedXLock xlock;
  221564. Atoms::initialiseAtoms();
  221565. resetDragAndDrop();
  221566. // Get defaults for various properties
  221567. const int screen = DefaultScreen (display);
  221568. Window root = RootWindow (display, screen);
  221569. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221570. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221571. if (visual == 0)
  221572. {
  221573. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221574. Process::terminate();
  221575. }
  221576. // Create and install a colormap suitable fr our visual
  221577. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221578. XInstallColormap (display, colormap);
  221579. // Set up the window attributes
  221580. XSetWindowAttributes swa;
  221581. swa.border_pixel = 0;
  221582. swa.background_pixmap = None;
  221583. swa.colormap = colormap;
  221584. swa.event_mask = getAllEventsMask();
  221585. windowH = XCreateWindow (display, root,
  221586. 0, 0, 1, 1,
  221587. 0, depth, InputOutput, visual,
  221588. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221589. &swa);
  221590. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221591. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221592. GrabModeAsync, GrabModeAsync, None, None);
  221593. // Set the window context to identify the window handle object
  221594. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221595. {
  221596. // Failed
  221597. jassertfalse;
  221598. Logger::outputDebugString ("Failed to create context information for window.\n");
  221599. XDestroyWindow (display, windowH);
  221600. windowH = 0;
  221601. return;
  221602. }
  221603. // Set window manager hints
  221604. XWMHints* wmHints = XAllocWMHints();
  221605. wmHints->flags = InputHint | StateHint;
  221606. wmHints->input = True; // Locally active input model
  221607. wmHints->initial_state = NormalState;
  221608. XSetWMHints (display, windowH, wmHints);
  221609. XFree (wmHints);
  221610. // Set the window type
  221611. setWindowType();
  221612. // Define decoration
  221613. if ((styleFlags & windowHasTitleBar) == 0)
  221614. removeWindowDecorations (windowH);
  221615. else
  221616. addWindowButtons (windowH);
  221617. // Set window name
  221618. setWindowTitle (windowH, getComponent()->getName());
  221619. // Associate the PID, allowing to be shut down when something goes wrong
  221620. unsigned long pid = getpid();
  221621. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221622. (unsigned char*) &pid, 1);
  221623. // Set window manager protocols
  221624. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221625. (unsigned char*) Atoms::ProtocolList, 2);
  221626. // Set drag and drop flags
  221627. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221628. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221629. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221630. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221631. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221632. (const unsigned char*) "", 0);
  221633. unsigned long dndVersion = Atoms::DndVersion;
  221634. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221635. (const unsigned char*) &dndVersion, 1);
  221636. // Initialise the pointer and keyboard mapping
  221637. // This is not the same as the logical pointer mapping the X server uses:
  221638. // we don't mess with this.
  221639. static bool mappingInitialised = false;
  221640. if (! mappingInitialised)
  221641. {
  221642. mappingInitialised = true;
  221643. const int numButtons = XGetPointerMapping (display, 0, 0);
  221644. if (numButtons == 2)
  221645. {
  221646. pointerMap[0] = Keys::LeftButton;
  221647. pointerMap[1] = Keys::RightButton;
  221648. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221649. }
  221650. else if (numButtons >= 3)
  221651. {
  221652. pointerMap[0] = Keys::LeftButton;
  221653. pointerMap[1] = Keys::MiddleButton;
  221654. pointerMap[2] = Keys::RightButton;
  221655. if (numButtons >= 5)
  221656. {
  221657. pointerMap[3] = Keys::WheelUp;
  221658. pointerMap[4] = Keys::WheelDown;
  221659. }
  221660. }
  221661. updateModifierMappings();
  221662. }
  221663. }
  221664. void destroyWindow()
  221665. {
  221666. ScopedXLock xlock;
  221667. XPointer handlePointer;
  221668. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221669. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221670. XDestroyWindow (display, windowH);
  221671. // Wait for it to complete and then remove any events for this
  221672. // window from the event queue.
  221673. XSync (display, false);
  221674. XEvent event;
  221675. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221676. {}
  221677. }
  221678. static int getAllEventsMask() throw()
  221679. {
  221680. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221681. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221682. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221683. }
  221684. static int64 getEventTime (::Time t)
  221685. {
  221686. static int64 eventTimeOffset = 0x12345678;
  221687. const int64 thisMessageTime = t;
  221688. if (eventTimeOffset == 0x12345678)
  221689. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221690. return eventTimeOffset + thisMessageTime;
  221691. }
  221692. static void setWindowTitle (Window xwin, const String& title)
  221693. {
  221694. XTextProperty nameProperty;
  221695. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221696. ScopedXLock xlock;
  221697. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221698. {
  221699. XSetWMName (display, xwin, &nameProperty);
  221700. XSetWMIconName (display, xwin, &nameProperty);
  221701. XFree (nameProperty.value);
  221702. }
  221703. }
  221704. void updateBorderSize()
  221705. {
  221706. if ((styleFlags & windowHasTitleBar) == 0)
  221707. {
  221708. windowBorder = BorderSize (0);
  221709. }
  221710. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221711. {
  221712. ScopedXLock xlock;
  221713. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221714. if (hints != None)
  221715. {
  221716. unsigned char* data = 0;
  221717. unsigned long nitems, bytesLeft;
  221718. Atom actualType;
  221719. int actualFormat;
  221720. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221721. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221722. &data) == Success)
  221723. {
  221724. const unsigned long* const sizes = (const unsigned long*) data;
  221725. if (actualFormat == 32)
  221726. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221727. (int) sizes[3], (int) sizes[1]);
  221728. XFree (data);
  221729. }
  221730. }
  221731. }
  221732. }
  221733. void updateBounds()
  221734. {
  221735. jassert (windowH != 0);
  221736. if (windowH != 0)
  221737. {
  221738. Window root, child;
  221739. unsigned int bw, depth;
  221740. ScopedXLock xlock;
  221741. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221742. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221743. &bw, &depth))
  221744. {
  221745. wx = wy = ww = wh = 0;
  221746. }
  221747. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221748. {
  221749. wx = wy = 0;
  221750. }
  221751. }
  221752. }
  221753. void resetDragAndDrop()
  221754. {
  221755. dragAndDropFiles.clear();
  221756. lastDropPos = Point<int> (-1, -1);
  221757. dragAndDropCurrentMimeType = 0;
  221758. dragAndDropSourceWindow = 0;
  221759. srcMimeTypeAtomList.clear();
  221760. }
  221761. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221762. {
  221763. msg.type = ClientMessage;
  221764. msg.display = display;
  221765. msg.window = dragAndDropSourceWindow;
  221766. msg.format = 32;
  221767. msg.data.l[0] = windowH;
  221768. ScopedXLock xlock;
  221769. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221770. }
  221771. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221772. {
  221773. XClientMessageEvent msg;
  221774. zerostruct (msg);
  221775. msg.message_type = Atoms::XdndStatus;
  221776. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221777. msg.data.l[4] = dropAction;
  221778. sendDragAndDropMessage (msg);
  221779. }
  221780. void sendDragAndDropLeave()
  221781. {
  221782. XClientMessageEvent msg;
  221783. zerostruct (msg);
  221784. msg.message_type = Atoms::XdndLeave;
  221785. sendDragAndDropMessage (msg);
  221786. }
  221787. void sendDragAndDropFinish()
  221788. {
  221789. XClientMessageEvent msg;
  221790. zerostruct (msg);
  221791. msg.message_type = Atoms::XdndFinished;
  221792. sendDragAndDropMessage (msg);
  221793. }
  221794. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221795. {
  221796. if ((clientMsg->data.l[1] & 1) == 0)
  221797. {
  221798. sendDragAndDropLeave();
  221799. if (dragAndDropFiles.size() > 0)
  221800. handleFileDragExit (dragAndDropFiles);
  221801. dragAndDropFiles.clear();
  221802. }
  221803. }
  221804. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221805. {
  221806. if (dragAndDropSourceWindow == 0)
  221807. return;
  221808. dragAndDropSourceWindow = clientMsg->data.l[0];
  221809. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221810. (int) clientMsg->data.l[2] & 0xffff);
  221811. dropPos -= getScreenPosition();
  221812. if (lastDropPos != dropPos)
  221813. {
  221814. lastDropPos = dropPos;
  221815. dragAndDropTimestamp = clientMsg->data.l[3];
  221816. Atom targetAction = Atoms::XdndActionCopy;
  221817. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221818. {
  221819. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221820. {
  221821. targetAction = Atoms::allowedActions[i];
  221822. break;
  221823. }
  221824. }
  221825. sendDragAndDropStatus (true, targetAction);
  221826. if (dragAndDropFiles.size() == 0)
  221827. updateDraggedFileList (clientMsg);
  221828. if (dragAndDropFiles.size() > 0)
  221829. handleFileDragMove (dragAndDropFiles, dropPos);
  221830. }
  221831. }
  221832. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221833. {
  221834. if (dragAndDropFiles.size() == 0)
  221835. updateDraggedFileList (clientMsg);
  221836. const StringArray files (dragAndDropFiles);
  221837. const Point<int> lastPos (lastDropPos);
  221838. sendDragAndDropFinish();
  221839. resetDragAndDrop();
  221840. if (files.size() > 0)
  221841. handleFileDragDrop (files, lastPos);
  221842. }
  221843. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221844. {
  221845. dragAndDropFiles.clear();
  221846. srcMimeTypeAtomList.clear();
  221847. dragAndDropCurrentMimeType = 0;
  221848. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221849. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221850. {
  221851. dragAndDropSourceWindow = 0;
  221852. return;
  221853. }
  221854. dragAndDropSourceWindow = clientMsg->data.l[0];
  221855. if ((clientMsg->data.l[1] & 1) != 0)
  221856. {
  221857. Atom actual;
  221858. int format;
  221859. unsigned long count = 0, remaining = 0;
  221860. unsigned char* data = 0;
  221861. ScopedXLock xlock;
  221862. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221863. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221864. &count, &remaining, &data);
  221865. if (data != 0)
  221866. {
  221867. if (actual == XA_ATOM && format == 32 && count != 0)
  221868. {
  221869. const unsigned long* const types = (const unsigned long*) data;
  221870. for (unsigned int i = 0; i < count; ++i)
  221871. if (types[i] != None)
  221872. srcMimeTypeAtomList.add (types[i]);
  221873. }
  221874. XFree (data);
  221875. }
  221876. }
  221877. if (srcMimeTypeAtomList.size() == 0)
  221878. {
  221879. for (int i = 2; i < 5; ++i)
  221880. if (clientMsg->data.l[i] != None)
  221881. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221882. if (srcMimeTypeAtomList.size() == 0)
  221883. {
  221884. dragAndDropSourceWindow = 0;
  221885. return;
  221886. }
  221887. }
  221888. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221889. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221890. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221891. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221892. handleDragAndDropPosition (clientMsg);
  221893. }
  221894. void handleDragAndDropSelection (const XEvent* const evt)
  221895. {
  221896. dragAndDropFiles.clear();
  221897. if (evt->xselection.property != 0)
  221898. {
  221899. StringArray lines;
  221900. {
  221901. MemoryBlock dropData;
  221902. for (;;)
  221903. {
  221904. Atom actual;
  221905. uint8* data = 0;
  221906. unsigned long count = 0, remaining = 0;
  221907. int format = 0;
  221908. ScopedXLock xlock;
  221909. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221910. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221911. &format, &count, &remaining, &data) == Success)
  221912. {
  221913. dropData.append (data, count * format / 8);
  221914. XFree (data);
  221915. if (remaining == 0)
  221916. break;
  221917. }
  221918. else
  221919. {
  221920. XFree (data);
  221921. break;
  221922. }
  221923. }
  221924. lines.addLines (dropData.toString());
  221925. }
  221926. for (int i = 0; i < lines.size(); ++i)
  221927. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221928. dragAndDropFiles.trim();
  221929. dragAndDropFiles.removeEmptyStrings();
  221930. }
  221931. }
  221932. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221933. {
  221934. dragAndDropFiles.clear();
  221935. if (dragAndDropSourceWindow != None
  221936. && dragAndDropCurrentMimeType != 0)
  221937. {
  221938. dragAndDropTimestamp = clientMsg->data.l[2];
  221939. ScopedXLock xlock;
  221940. XConvertSelection (display,
  221941. Atoms::XdndSelection,
  221942. dragAndDropCurrentMimeType,
  221943. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221944. windowH,
  221945. dragAndDropTimestamp);
  221946. }
  221947. }
  221948. StringArray dragAndDropFiles;
  221949. int dragAndDropTimestamp;
  221950. Point<int> lastDropPos;
  221951. Atom dragAndDropCurrentMimeType;
  221952. Window dragAndDropSourceWindow;
  221953. Array <Atom> srcMimeTypeAtomList;
  221954. static int pointerMap[5];
  221955. static Point<int> lastMousePos;
  221956. static void clearLastMousePos() throw()
  221957. {
  221958. lastMousePos = Point<int> (0x100000, 0x100000);
  221959. }
  221960. };
  221961. ModifierKeys LinuxComponentPeer::currentModifiers;
  221962. bool LinuxComponentPeer::isActiveApplication = false;
  221963. int LinuxComponentPeer::pointerMap[5];
  221964. Point<int> LinuxComponentPeer::lastMousePos;
  221965. bool Process::isForegroundProcess()
  221966. {
  221967. return LinuxComponentPeer::isActiveApplication;
  221968. }
  221969. void ModifierKeys::updateCurrentModifiers() throw()
  221970. {
  221971. currentModifiers = LinuxComponentPeer::currentModifiers;
  221972. }
  221973. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221974. {
  221975. Window root, child;
  221976. int x, y, winx, winy;
  221977. unsigned int mask;
  221978. int mouseMods = 0;
  221979. ScopedXLock xlock;
  221980. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221981. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221982. {
  221983. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221984. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221985. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221986. }
  221987. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221988. return LinuxComponentPeer::currentModifiers;
  221989. }
  221990. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221991. {
  221992. if (enableOrDisable)
  221993. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221994. }
  221995. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221996. {
  221997. return new LinuxComponentPeer (this, styleFlags);
  221998. }
  221999. // (this callback is hooked up in the messaging code)
  222000. void juce_windowMessageReceive (XEvent* event)
  222001. {
  222002. if (event->xany.window != None)
  222003. {
  222004. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  222005. if (ComponentPeer::isValidPeer (peer))
  222006. peer->handleWindowMessage (event);
  222007. }
  222008. else
  222009. {
  222010. switch (event->xany.type)
  222011. {
  222012. case KeymapNotify:
  222013. {
  222014. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  222015. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  222016. break;
  222017. }
  222018. default:
  222019. break;
  222020. }
  222021. }
  222022. }
  222023. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  222024. {
  222025. if (display == 0)
  222026. return;
  222027. #if JUCE_USE_XINERAMA
  222028. int major_opcode, first_event, first_error;
  222029. ScopedXLock xlock;
  222030. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  222031. {
  222032. typedef Bool (*tXineramaIsActive) (Display*);
  222033. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  222034. static tXineramaIsActive xXineramaIsActive = 0;
  222035. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  222036. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  222037. {
  222038. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  222039. if (h == 0)
  222040. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  222041. if (h != 0)
  222042. {
  222043. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  222044. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  222045. }
  222046. }
  222047. if (xXineramaIsActive != 0
  222048. && xXineramaQueryScreens != 0
  222049. && xXineramaIsActive (display))
  222050. {
  222051. int numMonitors = 0;
  222052. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  222053. if (screens != 0)
  222054. {
  222055. for (int i = numMonitors; --i >= 0;)
  222056. {
  222057. int index = screens[i].screen_number;
  222058. if (index >= 0)
  222059. {
  222060. while (monitorCoords.size() < index)
  222061. monitorCoords.add (Rectangle<int>());
  222062. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  222063. screens[i].y_org,
  222064. screens[i].width,
  222065. screens[i].height));
  222066. }
  222067. }
  222068. XFree (screens);
  222069. }
  222070. }
  222071. }
  222072. if (monitorCoords.size() == 0)
  222073. #endif
  222074. {
  222075. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  222076. if (hints != None)
  222077. {
  222078. const int numMonitors = ScreenCount (display);
  222079. for (int i = 0; i < numMonitors; ++i)
  222080. {
  222081. Window root = RootWindow (display, i);
  222082. unsigned long nitems, bytesLeft;
  222083. Atom actualType;
  222084. int actualFormat;
  222085. unsigned char* data = 0;
  222086. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  222087. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  222088. &data) == Success)
  222089. {
  222090. const long* const position = (const long*) data;
  222091. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  222092. monitorCoords.add (Rectangle<int> (position[0], position[1],
  222093. position[2], position[3]));
  222094. XFree (data);
  222095. }
  222096. }
  222097. }
  222098. if (monitorCoords.size() == 0)
  222099. {
  222100. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  222101. DisplayHeight (display, DefaultScreen (display))));
  222102. }
  222103. }
  222104. }
  222105. void Desktop::createMouseInputSources()
  222106. {
  222107. mouseSources.add (new MouseInputSource (0, true));
  222108. }
  222109. bool Desktop::canUseSemiTransparentWindows() throw()
  222110. {
  222111. int matchedDepth = 0;
  222112. const int desiredDepth = 32;
  222113. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  222114. && (matchedDepth == desiredDepth);
  222115. }
  222116. const Point<int> Desktop::getMousePosition()
  222117. {
  222118. Window root, child;
  222119. int x, y, winx, winy;
  222120. unsigned int mask;
  222121. ScopedXLock xlock;
  222122. if (XQueryPointer (display,
  222123. RootWindow (display, DefaultScreen (display)),
  222124. &root, &child,
  222125. &x, &y, &winx, &winy, &mask) == False)
  222126. {
  222127. // Pointer not on the default screen
  222128. x = y = -1;
  222129. }
  222130. return Point<int> (x, y);
  222131. }
  222132. void Desktop::setMousePosition (const Point<int>& newPosition)
  222133. {
  222134. ScopedXLock xlock;
  222135. Window root = RootWindow (display, DefaultScreen (display));
  222136. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  222137. }
  222138. static bool screenSaverAllowed = true;
  222139. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  222140. {
  222141. if (screenSaverAllowed != isEnabled)
  222142. {
  222143. screenSaverAllowed = isEnabled;
  222144. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  222145. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  222146. if (xScreenSaverSuspend == 0)
  222147. {
  222148. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  222149. if (h != 0)
  222150. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  222151. }
  222152. ScopedXLock xlock;
  222153. if (xScreenSaverSuspend != 0)
  222154. xScreenSaverSuspend (display, ! isEnabled);
  222155. }
  222156. }
  222157. bool Desktop::isScreenSaverEnabled()
  222158. {
  222159. return screenSaverAllowed;
  222160. }
  222161. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  222162. {
  222163. ScopedXLock xlock;
  222164. const unsigned int imageW = image.getWidth();
  222165. const unsigned int imageH = image.getHeight();
  222166. #if JUCE_USE_XCURSOR
  222167. {
  222168. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  222169. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  222170. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  222171. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  222172. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  222173. static tXcursorImageCreate xXcursorImageCreate = 0;
  222174. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  222175. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  222176. static bool hasBeenLoaded = false;
  222177. if (! hasBeenLoaded)
  222178. {
  222179. hasBeenLoaded = true;
  222180. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  222181. if (h != 0)
  222182. {
  222183. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  222184. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  222185. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  222186. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  222187. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  222188. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  222189. || ! xXcursorSupportsARGB (display))
  222190. xXcursorSupportsARGB = 0;
  222191. }
  222192. }
  222193. if (xXcursorSupportsARGB != 0)
  222194. {
  222195. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  222196. if (xcImage != 0)
  222197. {
  222198. xcImage->xhot = hotspotX;
  222199. xcImage->yhot = hotspotY;
  222200. XcursorPixel* dest = xcImage->pixels;
  222201. for (int y = 0; y < (int) imageH; ++y)
  222202. for (int x = 0; x < (int) imageW; ++x)
  222203. *dest++ = image.getPixelAt (x, y).getARGB();
  222204. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  222205. xXcursorImageDestroy (xcImage);
  222206. if (result != 0)
  222207. return result;
  222208. }
  222209. }
  222210. }
  222211. #endif
  222212. Window root = RootWindow (display, DefaultScreen (display));
  222213. unsigned int cursorW, cursorH;
  222214. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  222215. return 0;
  222216. Image im (Image::ARGB, cursorW, cursorH, true);
  222217. {
  222218. Graphics g (im);
  222219. if (imageW > cursorW || imageH > cursorH)
  222220. {
  222221. hotspotX = (hotspotX * cursorW) / imageW;
  222222. hotspotY = (hotspotY * cursorH) / imageH;
  222223. g.drawImageWithin (image, 0, 0, imageW, imageH,
  222224. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222225. false);
  222226. }
  222227. else
  222228. {
  222229. g.drawImageAt (image, 0, 0);
  222230. }
  222231. }
  222232. const int stride = (cursorW + 7) >> 3;
  222233. HeapBlock <char> maskPlane, sourcePlane;
  222234. maskPlane.calloc (stride * cursorH);
  222235. sourcePlane.calloc (stride * cursorH);
  222236. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  222237. for (int y = cursorH; --y >= 0;)
  222238. {
  222239. for (int x = cursorW; --x >= 0;)
  222240. {
  222241. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  222242. const int offset = y * stride + (x >> 3);
  222243. const Colour c (im.getPixelAt (x, y));
  222244. if (c.getAlpha() >= 128)
  222245. maskPlane[offset] |= mask;
  222246. if (c.getBrightness() >= 0.5f)
  222247. sourcePlane[offset] |= mask;
  222248. }
  222249. }
  222250. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222251. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222252. XColor white, black;
  222253. black.red = black.green = black.blue = 0;
  222254. white.red = white.green = white.blue = 0xffff;
  222255. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  222256. XFreePixmap (display, sourcePixmap);
  222257. XFreePixmap (display, maskPixmap);
  222258. return result;
  222259. }
  222260. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  222261. {
  222262. ScopedXLock xlock;
  222263. if (cursorHandle != 0)
  222264. XFreeCursor (display, (Cursor) cursorHandle);
  222265. }
  222266. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222267. {
  222268. unsigned int shape;
  222269. switch (type)
  222270. {
  222271. case NormalCursor: return None; // Use parent cursor
  222272. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222273. case WaitCursor: shape = XC_watch; break;
  222274. case IBeamCursor: shape = XC_xterm; break;
  222275. case PointingHandCursor: shape = XC_hand2; break;
  222276. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222277. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222278. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222279. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222280. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222281. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222282. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222283. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222284. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222285. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222286. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222287. case CrosshairCursor: shape = XC_crosshair; break;
  222288. case DraggingHandCursor:
  222289. {
  222290. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222291. 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,
  222292. 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 };
  222293. const int dragHandDataSize = 99;
  222294. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222295. }
  222296. case CopyingCursor:
  222297. {
  222298. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222299. 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,
  222300. 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,
  222301. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222302. const int copyCursorSize = 119;
  222303. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222304. }
  222305. default:
  222306. jassertfalse;
  222307. return None;
  222308. }
  222309. ScopedXLock xlock;
  222310. return (void*) XCreateFontCursor (display, shape);
  222311. }
  222312. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222313. {
  222314. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222315. if (lp != 0)
  222316. lp->showMouseCursor ((Cursor) getHandle());
  222317. }
  222318. void MouseCursor::showInAllWindows() const
  222319. {
  222320. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222321. showInWindow (ComponentPeer::getPeer (i));
  222322. }
  222323. const Image juce_createIconForFile (const File& file)
  222324. {
  222325. return Image::null;
  222326. }
  222327. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222328. {
  222329. return createSoftwareImage (format, width, height, clearImage);
  222330. }
  222331. #if JUCE_OPENGL
  222332. class WindowedGLContext : public OpenGLContext
  222333. {
  222334. public:
  222335. WindowedGLContext (Component* const component,
  222336. const OpenGLPixelFormat& pixelFormat_,
  222337. GLXContext sharedContext)
  222338. : renderContext (0),
  222339. embeddedWindow (0),
  222340. pixelFormat (pixelFormat_),
  222341. swapInterval (0)
  222342. {
  222343. jassert (component != 0);
  222344. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222345. if (peer == 0)
  222346. return;
  222347. ScopedXLock xlock;
  222348. XSync (display, False);
  222349. GLint attribs [64];
  222350. int n = 0;
  222351. attribs[n++] = GLX_RGBA;
  222352. attribs[n++] = GLX_DOUBLEBUFFER;
  222353. attribs[n++] = GLX_RED_SIZE;
  222354. attribs[n++] = pixelFormat.redBits;
  222355. attribs[n++] = GLX_GREEN_SIZE;
  222356. attribs[n++] = pixelFormat.greenBits;
  222357. attribs[n++] = GLX_BLUE_SIZE;
  222358. attribs[n++] = pixelFormat.blueBits;
  222359. attribs[n++] = GLX_ALPHA_SIZE;
  222360. attribs[n++] = pixelFormat.alphaBits;
  222361. attribs[n++] = GLX_DEPTH_SIZE;
  222362. attribs[n++] = pixelFormat.depthBufferBits;
  222363. attribs[n++] = GLX_STENCIL_SIZE;
  222364. attribs[n++] = pixelFormat.stencilBufferBits;
  222365. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222366. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222367. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222368. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222369. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222370. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222371. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222372. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222373. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222374. attribs[n++] = None;
  222375. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222376. if (bestVisual == 0)
  222377. return;
  222378. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222379. Window windowH = (Window) peer->getNativeHandle();
  222380. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222381. XSetWindowAttributes swa;
  222382. swa.colormap = colourMap;
  222383. swa.border_pixel = 0;
  222384. swa.event_mask = ExposureMask | StructureNotifyMask;
  222385. embeddedWindow = XCreateWindow (display, windowH,
  222386. 0, 0, 1, 1, 0,
  222387. bestVisual->depth,
  222388. InputOutput,
  222389. bestVisual->visual,
  222390. CWBorderPixel | CWColormap | CWEventMask,
  222391. &swa);
  222392. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222393. XMapWindow (display, embeddedWindow);
  222394. XFreeColormap (display, colourMap);
  222395. XFree (bestVisual);
  222396. XSync (display, False);
  222397. }
  222398. ~WindowedGLContext()
  222399. {
  222400. ScopedXLock xlock;
  222401. deleteContext();
  222402. XUnmapWindow (display, embeddedWindow);
  222403. XDestroyWindow (display, embeddedWindow);
  222404. }
  222405. void deleteContext()
  222406. {
  222407. makeInactive();
  222408. if (renderContext != 0)
  222409. {
  222410. ScopedXLock xlock;
  222411. glXDestroyContext (display, renderContext);
  222412. renderContext = 0;
  222413. }
  222414. }
  222415. bool makeActive() const throw()
  222416. {
  222417. jassert (renderContext != 0);
  222418. ScopedXLock xlock;
  222419. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222420. && XSync (display, False);
  222421. }
  222422. bool makeInactive() const throw()
  222423. {
  222424. ScopedXLock xlock;
  222425. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222426. }
  222427. bool isActive() const throw()
  222428. {
  222429. ScopedXLock xlock;
  222430. return glXGetCurrentContext() == renderContext;
  222431. }
  222432. const OpenGLPixelFormat getPixelFormat() const
  222433. {
  222434. return pixelFormat;
  222435. }
  222436. void* getRawContext() const throw()
  222437. {
  222438. return renderContext;
  222439. }
  222440. void updateWindowPosition (int x, int y, int w, int h, int)
  222441. {
  222442. ScopedXLock xlock;
  222443. XMoveResizeWindow (display, embeddedWindow,
  222444. x, y, jmax (1, w), jmax (1, h));
  222445. }
  222446. void swapBuffers()
  222447. {
  222448. ScopedXLock xlock;
  222449. glXSwapBuffers (display, embeddedWindow);
  222450. }
  222451. bool setSwapInterval (const int numFramesPerSwap)
  222452. {
  222453. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222454. if (GLXSwapIntervalSGI != 0)
  222455. {
  222456. swapInterval = numFramesPerSwap;
  222457. GLXSwapIntervalSGI (numFramesPerSwap);
  222458. return true;
  222459. }
  222460. return false;
  222461. }
  222462. int getSwapInterval() const
  222463. {
  222464. return swapInterval;
  222465. }
  222466. void repaint()
  222467. {
  222468. }
  222469. juce_UseDebuggingNewOperator
  222470. GLXContext renderContext;
  222471. private:
  222472. Window embeddedWindow;
  222473. OpenGLPixelFormat pixelFormat;
  222474. int swapInterval;
  222475. WindowedGLContext (const WindowedGLContext&);
  222476. WindowedGLContext& operator= (const WindowedGLContext&);
  222477. };
  222478. OpenGLContext* OpenGLComponent::createContext()
  222479. {
  222480. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222481. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222482. return (c->renderContext != 0) ? c.release() : 0;
  222483. }
  222484. void juce_glViewport (const int w, const int h)
  222485. {
  222486. glViewport (0, 0, w, h);
  222487. }
  222488. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222489. OwnedArray <OpenGLPixelFormat>& results)
  222490. {
  222491. results.add (new OpenGLPixelFormat()); // xxx
  222492. }
  222493. #endif
  222494. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222495. {
  222496. jassertfalse; // not implemented!
  222497. return false;
  222498. }
  222499. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222500. {
  222501. jassertfalse; // not implemented!
  222502. return false;
  222503. }
  222504. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222505. {
  222506. if (! isOnDesktop ())
  222507. addToDesktop (0);
  222508. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222509. if (wp != 0)
  222510. {
  222511. wp->setTaskBarIcon (newImage);
  222512. setVisible (true);
  222513. toFront (false);
  222514. repaint();
  222515. }
  222516. }
  222517. void SystemTrayIconComponent::paint (Graphics& g)
  222518. {
  222519. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222520. if (wp != 0)
  222521. {
  222522. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222523. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222524. false);
  222525. }
  222526. }
  222527. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222528. {
  222529. // xxx not yet implemented!
  222530. }
  222531. void PlatformUtilities::beep()
  222532. {
  222533. std::cout << "\a" << std::flush;
  222534. }
  222535. bool AlertWindow::showNativeDialogBox (const String& title,
  222536. const String& bodyText,
  222537. bool isOkCancel)
  222538. {
  222539. // use a non-native one for the time being..
  222540. if (isOkCancel)
  222541. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222542. else
  222543. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222544. return true;
  222545. }
  222546. const int KeyPress::spaceKey = XK_space & 0xff;
  222547. const int KeyPress::returnKey = XK_Return & 0xff;
  222548. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222549. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222550. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222551. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222552. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222553. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222554. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222555. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222556. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222557. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222558. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222559. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222560. const int KeyPress::tabKey = XK_Tab & 0xff;
  222561. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222562. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222563. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222564. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222565. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222566. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222567. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222568. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222569. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222570. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222571. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222572. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222573. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222574. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222575. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222576. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222577. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222578. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222579. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222580. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222581. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222582. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222583. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222584. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222585. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222586. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222587. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222588. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222589. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222590. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222591. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222592. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222593. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222594. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222595. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222596. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222597. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222598. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222599. #endif
  222600. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222601. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222602. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222603. // compiled on its own).
  222604. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222605. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222606. {
  222607. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222608. snd_pcm_hw_params_t* hwParams;
  222609. snd_pcm_hw_params_alloca (&hwParams);
  222610. for (int i = 0; ratesToTry[i] != 0; ++i)
  222611. {
  222612. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222613. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222614. {
  222615. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222616. }
  222617. }
  222618. }
  222619. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222620. {
  222621. snd_pcm_hw_params_t *params;
  222622. snd_pcm_hw_params_alloca (&params);
  222623. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222624. {
  222625. snd_pcm_hw_params_get_channels_min (params, minChans);
  222626. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222627. }
  222628. }
  222629. static void getDeviceProperties (const String& deviceID,
  222630. unsigned int& minChansOut,
  222631. unsigned int& maxChansOut,
  222632. unsigned int& minChansIn,
  222633. unsigned int& maxChansIn,
  222634. Array <int>& rates)
  222635. {
  222636. if (deviceID.isEmpty())
  222637. return;
  222638. snd_ctl_t* handle;
  222639. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222640. {
  222641. snd_pcm_info_t* info;
  222642. snd_pcm_info_alloca (&info);
  222643. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222644. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222645. snd_pcm_info_set_subdevice (info, 0);
  222646. if (snd_ctl_pcm_info (handle, info) >= 0)
  222647. {
  222648. snd_pcm_t* pcmHandle;
  222649. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  222650. {
  222651. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222652. getDeviceSampleRates (pcmHandle, rates);
  222653. snd_pcm_close (pcmHandle);
  222654. }
  222655. }
  222656. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222657. if (snd_ctl_pcm_info (handle, info) >= 0)
  222658. {
  222659. snd_pcm_t* pcmHandle;
  222660. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  222661. {
  222662. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222663. if (rates.size() == 0)
  222664. getDeviceSampleRates (pcmHandle, rates);
  222665. snd_pcm_close (pcmHandle);
  222666. }
  222667. }
  222668. snd_ctl_close (handle);
  222669. }
  222670. }
  222671. class ALSADevice
  222672. {
  222673. public:
  222674. ALSADevice (const String& deviceID,
  222675. const bool forInput)
  222676. : handle (0),
  222677. bitDepth (16),
  222678. numChannelsRunning (0),
  222679. latency (0),
  222680. isInput (forInput),
  222681. sampleFormat (AudioDataConverters::int16LE)
  222682. {
  222683. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222684. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222685. SND_PCM_ASYNC));
  222686. }
  222687. ~ALSADevice()
  222688. {
  222689. if (handle != 0)
  222690. snd_pcm_close (handle);
  222691. }
  222692. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222693. {
  222694. if (handle == 0)
  222695. return false;
  222696. snd_pcm_hw_params_t* hwParams;
  222697. snd_pcm_hw_params_alloca (&hwParams);
  222698. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222699. return false;
  222700. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222701. isInterleaved = false;
  222702. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222703. isInterleaved = true;
  222704. else
  222705. {
  222706. jassertfalse;
  222707. return false;
  222708. }
  222709. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  222710. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  222711. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  222712. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  222713. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  222714. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  222715. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  222716. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  222717. bitDepth = 0;
  222718. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  222719. {
  222720. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222721. {
  222722. bitDepth = formatsToTry [i + 1];
  222723. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  222724. break;
  222725. }
  222726. }
  222727. if (bitDepth == 0)
  222728. {
  222729. error = "device doesn't support a compatible PCM format";
  222730. DBG ("ALSA error: " + error + "\n");
  222731. return false;
  222732. }
  222733. int dir = 0;
  222734. unsigned int periods = 4;
  222735. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222736. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222737. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222738. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222739. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222740. || failed (snd_pcm_hw_params (handle, hwParams)))
  222741. {
  222742. return false;
  222743. }
  222744. snd_pcm_uframes_t frames = 0;
  222745. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222746. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222747. latency = 0;
  222748. else
  222749. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222750. snd_pcm_sw_params_t* swParams;
  222751. snd_pcm_sw_params_alloca (&swParams);
  222752. snd_pcm_uframes_t boundary;
  222753. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222754. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222755. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222756. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222757. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222758. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222759. || failed (snd_pcm_sw_params (handle, swParams)))
  222760. {
  222761. return false;
  222762. }
  222763. /*
  222764. #if JUCE_DEBUG
  222765. // enable this to dump the config of the devices that get opened
  222766. snd_output_t* out;
  222767. snd_output_stdio_attach (&out, stderr, 0);
  222768. snd_pcm_hw_params_dump (hwParams, out);
  222769. snd_pcm_sw_params_dump (swParams, out);
  222770. #endif
  222771. */
  222772. numChannelsRunning = numChannels;
  222773. return true;
  222774. }
  222775. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222776. {
  222777. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222778. float** const data = outputChannelBuffer.getArrayOfChannels();
  222779. if (isInterleaved)
  222780. {
  222781. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222782. float* interleaved = static_cast <float*> (scratch.getData());
  222783. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  222784. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  222785. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  222786. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222787. return false;
  222788. }
  222789. else
  222790. {
  222791. for (int i = 0; i < numChannelsRunning; ++i)
  222792. if (data[i] != 0)
  222793. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  222794. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  222795. if (failed (num))
  222796. {
  222797. if (num == -EPIPE)
  222798. {
  222799. if (failed (snd_pcm_prepare (handle)))
  222800. return false;
  222801. }
  222802. else if (num != -ESTRPIPE)
  222803. return false;
  222804. }
  222805. }
  222806. return true;
  222807. }
  222808. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222809. {
  222810. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222811. float** const data = inputChannelBuffer.getArrayOfChannels();
  222812. if (isInterleaved)
  222813. {
  222814. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222815. float* interleaved = static_cast <float*> (scratch.getData());
  222816. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  222817. if (failed (num))
  222818. {
  222819. if (num == -EPIPE)
  222820. {
  222821. if (failed (snd_pcm_prepare (handle)))
  222822. return false;
  222823. }
  222824. else if (num != -ESTRPIPE)
  222825. return false;
  222826. }
  222827. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  222828. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  222829. }
  222830. else
  222831. {
  222832. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222833. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222834. return false;
  222835. for (int i = 0; i < numChannelsRunning; ++i)
  222836. if (data[i] != 0)
  222837. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  222838. }
  222839. return true;
  222840. }
  222841. juce_UseDebuggingNewOperator
  222842. snd_pcm_t* handle;
  222843. String error;
  222844. int bitDepth, numChannelsRunning, latency;
  222845. private:
  222846. const bool isInput;
  222847. bool isInterleaved;
  222848. MemoryBlock scratch;
  222849. AudioDataConverters::DataFormat sampleFormat;
  222850. bool failed (const int errorNum)
  222851. {
  222852. if (errorNum >= 0)
  222853. return false;
  222854. error = snd_strerror (errorNum);
  222855. DBG ("ALSA error: " + error + "\n");
  222856. return true;
  222857. }
  222858. };
  222859. class ALSAThread : public Thread
  222860. {
  222861. public:
  222862. ALSAThread (const String& inputId_,
  222863. const String& outputId_)
  222864. : Thread ("Juce ALSA"),
  222865. sampleRate (0),
  222866. bufferSize (0),
  222867. outputLatency (0),
  222868. inputLatency (0),
  222869. callback (0),
  222870. inputId (inputId_),
  222871. outputId (outputId_),
  222872. numCallbacks (0),
  222873. inputChannelBuffer (1, 1),
  222874. outputChannelBuffer (1, 1)
  222875. {
  222876. initialiseRatesAndChannels();
  222877. }
  222878. ~ALSAThread()
  222879. {
  222880. close();
  222881. }
  222882. void open (BigInteger inputChannels,
  222883. BigInteger outputChannels,
  222884. const double sampleRate_,
  222885. const int bufferSize_)
  222886. {
  222887. close();
  222888. error = String::empty;
  222889. sampleRate = sampleRate_;
  222890. bufferSize = bufferSize_;
  222891. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222892. inputChannelBuffer.clear();
  222893. inputChannelDataForCallback.clear();
  222894. currentInputChans.clear();
  222895. if (inputChannels.getHighestBit() >= 0)
  222896. {
  222897. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222898. {
  222899. if (inputChannels[i])
  222900. {
  222901. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222902. currentInputChans.setBit (i);
  222903. }
  222904. }
  222905. }
  222906. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222907. outputChannelBuffer.clear();
  222908. outputChannelDataForCallback.clear();
  222909. currentOutputChans.clear();
  222910. if (outputChannels.getHighestBit() >= 0)
  222911. {
  222912. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222913. {
  222914. if (outputChannels[i])
  222915. {
  222916. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222917. currentOutputChans.setBit (i);
  222918. }
  222919. }
  222920. }
  222921. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222922. {
  222923. outputDevice = new ALSADevice (outputId, false);
  222924. if (outputDevice->error.isNotEmpty())
  222925. {
  222926. error = outputDevice->error;
  222927. outputDevice = 0;
  222928. return;
  222929. }
  222930. currentOutputChans.setRange (0, minChansOut, true);
  222931. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222932. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222933. bufferSize))
  222934. {
  222935. error = outputDevice->error;
  222936. outputDevice = 0;
  222937. return;
  222938. }
  222939. outputLatency = outputDevice->latency;
  222940. }
  222941. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222942. {
  222943. inputDevice = new ALSADevice (inputId, true);
  222944. if (inputDevice->error.isNotEmpty())
  222945. {
  222946. error = inputDevice->error;
  222947. inputDevice = 0;
  222948. return;
  222949. }
  222950. currentInputChans.setRange (0, minChansIn, true);
  222951. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222952. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222953. bufferSize))
  222954. {
  222955. error = inputDevice->error;
  222956. inputDevice = 0;
  222957. return;
  222958. }
  222959. inputLatency = inputDevice->latency;
  222960. }
  222961. if (outputDevice == 0 && inputDevice == 0)
  222962. {
  222963. error = "no channels";
  222964. return;
  222965. }
  222966. if (outputDevice != 0 && inputDevice != 0)
  222967. {
  222968. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222969. }
  222970. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222971. return;
  222972. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222973. return;
  222974. startThread (9);
  222975. int count = 1000;
  222976. while (numCallbacks == 0)
  222977. {
  222978. sleep (5);
  222979. if (--count < 0 || ! isThreadRunning())
  222980. {
  222981. error = "device didn't start";
  222982. break;
  222983. }
  222984. }
  222985. }
  222986. void close()
  222987. {
  222988. stopThread (6000);
  222989. inputDevice = 0;
  222990. outputDevice = 0;
  222991. inputChannelBuffer.setSize (1, 1);
  222992. outputChannelBuffer.setSize (1, 1);
  222993. numCallbacks = 0;
  222994. }
  222995. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222996. {
  222997. const ScopedLock sl (callbackLock);
  222998. callback = newCallback;
  222999. }
  223000. void run()
  223001. {
  223002. while (! threadShouldExit())
  223003. {
  223004. if (inputDevice != 0)
  223005. {
  223006. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  223007. {
  223008. DBG ("ALSA: read failure");
  223009. break;
  223010. }
  223011. }
  223012. if (threadShouldExit())
  223013. break;
  223014. {
  223015. const ScopedLock sl (callbackLock);
  223016. ++numCallbacks;
  223017. if (callback != 0)
  223018. {
  223019. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  223020. inputChannelDataForCallback.size(),
  223021. outputChannelDataForCallback.getRawDataPointer(),
  223022. outputChannelDataForCallback.size(),
  223023. bufferSize);
  223024. }
  223025. else
  223026. {
  223027. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  223028. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  223029. }
  223030. }
  223031. if (outputDevice != 0)
  223032. {
  223033. failed (snd_pcm_wait (outputDevice->handle, 2000));
  223034. if (threadShouldExit())
  223035. break;
  223036. failed (snd_pcm_avail_update (outputDevice->handle));
  223037. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  223038. {
  223039. DBG ("ALSA: write failure");
  223040. break;
  223041. }
  223042. }
  223043. }
  223044. }
  223045. int getBitDepth() const throw()
  223046. {
  223047. if (outputDevice != 0)
  223048. return outputDevice->bitDepth;
  223049. if (inputDevice != 0)
  223050. return inputDevice->bitDepth;
  223051. return 16;
  223052. }
  223053. juce_UseDebuggingNewOperator
  223054. String error;
  223055. double sampleRate;
  223056. int bufferSize, outputLatency, inputLatency;
  223057. BigInteger currentInputChans, currentOutputChans;
  223058. Array <int> sampleRates;
  223059. StringArray channelNamesOut, channelNamesIn;
  223060. AudioIODeviceCallback* callback;
  223061. private:
  223062. const String inputId, outputId;
  223063. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  223064. int numCallbacks;
  223065. CriticalSection callbackLock;
  223066. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  223067. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  223068. unsigned int minChansOut, maxChansOut;
  223069. unsigned int minChansIn, maxChansIn;
  223070. bool failed (const int errorNum)
  223071. {
  223072. if (errorNum >= 0)
  223073. return false;
  223074. error = snd_strerror (errorNum);
  223075. DBG ("ALSA error: " + error + "\n");
  223076. return true;
  223077. }
  223078. void initialiseRatesAndChannels()
  223079. {
  223080. sampleRates.clear();
  223081. channelNamesOut.clear();
  223082. channelNamesIn.clear();
  223083. minChansOut = 0;
  223084. maxChansOut = 0;
  223085. minChansIn = 0;
  223086. maxChansIn = 0;
  223087. unsigned int dummy = 0;
  223088. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  223089. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  223090. unsigned int i;
  223091. for (i = 0; i < maxChansOut; ++i)
  223092. channelNamesOut.add ("channel " + String ((int) i + 1));
  223093. for (i = 0; i < maxChansIn; ++i)
  223094. channelNamesIn.add ("channel " + String ((int) i + 1));
  223095. }
  223096. };
  223097. class ALSAAudioIODevice : public AudioIODevice
  223098. {
  223099. public:
  223100. ALSAAudioIODevice (const String& deviceName,
  223101. const String& inputId_,
  223102. const String& outputId_)
  223103. : AudioIODevice (deviceName, "ALSA"),
  223104. inputId (inputId_),
  223105. outputId (outputId_),
  223106. isOpen_ (false),
  223107. isStarted (false),
  223108. internal (inputId_, outputId_)
  223109. {
  223110. }
  223111. ~ALSAAudioIODevice()
  223112. {
  223113. }
  223114. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  223115. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  223116. int getNumSampleRates() { return internal.sampleRates.size(); }
  223117. double getSampleRate (int index) { return internal.sampleRates [index]; }
  223118. int getDefaultBufferSize() { return 512; }
  223119. int getNumBufferSizesAvailable() { return 50; }
  223120. int getBufferSizeSamples (int index)
  223121. {
  223122. int n = 16;
  223123. for (int i = 0; i < index; ++i)
  223124. n += n < 64 ? 16
  223125. : (n < 512 ? 32
  223126. : (n < 1024 ? 64
  223127. : (n < 2048 ? 128 : 256)));
  223128. return n;
  223129. }
  223130. const String open (const BigInteger& inputChannels,
  223131. const BigInteger& outputChannels,
  223132. double sampleRate,
  223133. int bufferSizeSamples)
  223134. {
  223135. close();
  223136. if (bufferSizeSamples <= 0)
  223137. bufferSizeSamples = getDefaultBufferSize();
  223138. if (sampleRate <= 0)
  223139. {
  223140. for (int i = 0; i < getNumSampleRates(); ++i)
  223141. {
  223142. if (getSampleRate (i) >= 44100)
  223143. {
  223144. sampleRate = getSampleRate (i);
  223145. break;
  223146. }
  223147. }
  223148. }
  223149. internal.open (inputChannels, outputChannels,
  223150. sampleRate, bufferSizeSamples);
  223151. isOpen_ = internal.error.isEmpty();
  223152. return internal.error;
  223153. }
  223154. void close()
  223155. {
  223156. stop();
  223157. internal.close();
  223158. isOpen_ = false;
  223159. }
  223160. bool isOpen() { return isOpen_; }
  223161. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  223162. const String getLastError() { return internal.error; }
  223163. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  223164. double getCurrentSampleRate() { return internal.sampleRate; }
  223165. int getCurrentBitDepth() { return internal.getBitDepth(); }
  223166. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  223167. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  223168. int getOutputLatencyInSamples() { return internal.outputLatency; }
  223169. int getInputLatencyInSamples() { return internal.inputLatency; }
  223170. void start (AudioIODeviceCallback* callback)
  223171. {
  223172. if (! isOpen_)
  223173. callback = 0;
  223174. if (callback != 0)
  223175. callback->audioDeviceAboutToStart (this);
  223176. internal.setCallback (callback);
  223177. isStarted = (callback != 0);
  223178. }
  223179. void stop()
  223180. {
  223181. AudioIODeviceCallback* const oldCallback = internal.callback;
  223182. start (0);
  223183. if (oldCallback != 0)
  223184. oldCallback->audioDeviceStopped();
  223185. }
  223186. String inputId, outputId;
  223187. private:
  223188. bool isOpen_, isStarted;
  223189. ALSAThread internal;
  223190. };
  223191. class ALSAAudioIODeviceType : public AudioIODeviceType
  223192. {
  223193. public:
  223194. ALSAAudioIODeviceType()
  223195. : AudioIODeviceType ("ALSA"),
  223196. hasScanned (false)
  223197. {
  223198. }
  223199. ~ALSAAudioIODeviceType()
  223200. {
  223201. }
  223202. void scanForDevices()
  223203. {
  223204. if (hasScanned)
  223205. return;
  223206. hasScanned = true;
  223207. inputNames.clear();
  223208. inputIds.clear();
  223209. outputNames.clear();
  223210. outputIds.clear();
  223211. /* void** hints = 0;
  223212. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  223213. {
  223214. for (void** hint = hints; *hint != 0; ++hint)
  223215. {
  223216. const String name (getHint (*hint, "NAME"));
  223217. if (name.isNotEmpty())
  223218. {
  223219. const String ioid (getHint (*hint, "IOID"));
  223220. String desc (getHint (*hint, "DESC"));
  223221. if (desc.isEmpty())
  223222. desc = name;
  223223. desc = desc.replaceCharacters ("\n\r", " ");
  223224. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  223225. if (ioid.isEmpty() || ioid == "Input")
  223226. {
  223227. inputNames.add (desc);
  223228. inputIds.add (name);
  223229. }
  223230. if (ioid.isEmpty() || ioid == "Output")
  223231. {
  223232. outputNames.add (desc);
  223233. outputIds.add (name);
  223234. }
  223235. }
  223236. }
  223237. snd_device_name_free_hint (hints);
  223238. }
  223239. */
  223240. snd_ctl_t* handle = 0;
  223241. snd_ctl_card_info_t* info = 0;
  223242. snd_ctl_card_info_alloca (&info);
  223243. int cardNum = -1;
  223244. while (outputIds.size() + inputIds.size() <= 32)
  223245. {
  223246. snd_card_next (&cardNum);
  223247. if (cardNum < 0)
  223248. break;
  223249. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223250. {
  223251. if (snd_ctl_card_info (handle, info) >= 0)
  223252. {
  223253. String cardId (snd_ctl_card_info_get_id (info));
  223254. if (cardId.removeCharacters ("0123456789").isEmpty())
  223255. cardId = String (cardNum);
  223256. int device = -1;
  223257. for (;;)
  223258. {
  223259. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223260. break;
  223261. String id, name;
  223262. id << "hw:" << cardId << ',' << device;
  223263. bool isInput, isOutput;
  223264. if (testDevice (id, isInput, isOutput))
  223265. {
  223266. name << snd_ctl_card_info_get_name (info);
  223267. if (name.isEmpty())
  223268. name = id;
  223269. if (isInput)
  223270. {
  223271. inputNames.add (name);
  223272. inputIds.add (id);
  223273. }
  223274. if (isOutput)
  223275. {
  223276. outputNames.add (name);
  223277. outputIds.add (id);
  223278. }
  223279. }
  223280. }
  223281. }
  223282. snd_ctl_close (handle);
  223283. }
  223284. }
  223285. inputNames.appendNumbersToDuplicates (false, true);
  223286. outputNames.appendNumbersToDuplicates (false, true);
  223287. }
  223288. const StringArray getDeviceNames (bool wantInputNames) const
  223289. {
  223290. jassert (hasScanned); // need to call scanForDevices() before doing this
  223291. return wantInputNames ? inputNames : outputNames;
  223292. }
  223293. int getDefaultDeviceIndex (bool forInput) const
  223294. {
  223295. jassert (hasScanned); // need to call scanForDevices() before doing this
  223296. return 0;
  223297. }
  223298. bool hasSeparateInputsAndOutputs() const { return true; }
  223299. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223300. {
  223301. jassert (hasScanned); // need to call scanForDevices() before doing this
  223302. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223303. if (d == 0)
  223304. return -1;
  223305. return asInput ? inputIds.indexOf (d->inputId)
  223306. : outputIds.indexOf (d->outputId);
  223307. }
  223308. AudioIODevice* createDevice (const String& outputDeviceName,
  223309. const String& inputDeviceName)
  223310. {
  223311. jassert (hasScanned); // need to call scanForDevices() before doing this
  223312. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223313. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223314. String deviceName (outputIndex >= 0 ? outputDeviceName
  223315. : inputDeviceName);
  223316. if (inputIndex >= 0 || outputIndex >= 0)
  223317. return new ALSAAudioIODevice (deviceName,
  223318. inputIds [inputIndex],
  223319. outputIds [outputIndex]);
  223320. return 0;
  223321. }
  223322. juce_UseDebuggingNewOperator
  223323. private:
  223324. StringArray inputNames, outputNames, inputIds, outputIds;
  223325. bool hasScanned;
  223326. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223327. {
  223328. unsigned int minChansOut = 0, maxChansOut = 0;
  223329. unsigned int minChansIn = 0, maxChansIn = 0;
  223330. Array <int> rates;
  223331. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223332. DBG ("ALSA device: " + id
  223333. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223334. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223335. + " rates=" + String (rates.size()));
  223336. isInput = maxChansIn > 0;
  223337. isOutput = maxChansOut > 0;
  223338. return (isInput || isOutput) && rates.size() > 0;
  223339. }
  223340. /*static const String getHint (void* hint, const char* type)
  223341. {
  223342. char* const n = snd_device_name_get_hint (hint, type);
  223343. const String s ((const char*) n);
  223344. free (n);
  223345. return s;
  223346. }*/
  223347. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223348. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223349. };
  223350. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223351. {
  223352. return new ALSAAudioIODeviceType();
  223353. }
  223354. #endif
  223355. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223356. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223357. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223358. // compiled on its own).
  223359. #ifdef JUCE_INCLUDED_FILE
  223360. #if JUCE_JACK
  223361. static void* juce_libjack_handle = 0;
  223362. void* juce_load_jack_function (const char* const name)
  223363. {
  223364. if (juce_libjack_handle == 0)
  223365. return 0;
  223366. return dlsym (juce_libjack_handle, name);
  223367. }
  223368. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223369. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223370. return_type fn_name argument_types { \
  223371. static fn_name##_ptr_t fn = 0; \
  223372. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223373. if (fn) return (*fn)arguments; \
  223374. else return 0; \
  223375. }
  223376. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223377. typedef void (*fn_name##_ptr_t)argument_types; \
  223378. void fn_name argument_types { \
  223379. static fn_name##_ptr_t fn = 0; \
  223380. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223381. if (fn) (*fn)arguments; \
  223382. }
  223383. 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));
  223384. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223385. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223386. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223387. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223388. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223389. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223390. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223391. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223392. 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));
  223393. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223394. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223395. 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));
  223396. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223397. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223398. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223399. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223400. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223401. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223402. #if JUCE_DEBUG
  223403. #define JACK_LOGGING_ENABLED 1
  223404. #endif
  223405. #if JACK_LOGGING_ENABLED
  223406. static void jack_Log (const String& s)
  223407. {
  223408. std::cerr << s << std::endl;
  223409. }
  223410. static void dumpJackErrorMessage (const jack_status_t status)
  223411. {
  223412. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223413. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223414. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223415. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223416. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223417. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223418. }
  223419. #else
  223420. #define dumpJackErrorMessage(a) {}
  223421. #define jack_Log(...) {}
  223422. #endif
  223423. #ifndef JUCE_JACK_CLIENT_NAME
  223424. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223425. #endif
  223426. class JackAudioIODevice : public AudioIODevice
  223427. {
  223428. public:
  223429. JackAudioIODevice (const String& deviceName,
  223430. const String& inputId_,
  223431. const String& outputId_)
  223432. : AudioIODevice (deviceName, "JACK"),
  223433. inputId (inputId_),
  223434. outputId (outputId_),
  223435. isOpen_ (false),
  223436. callback (0),
  223437. totalNumberOfInputChannels (0),
  223438. totalNumberOfOutputChannels (0)
  223439. {
  223440. jassert (deviceName.isNotEmpty());
  223441. jack_status_t status;
  223442. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223443. if (client == 0)
  223444. {
  223445. dumpJackErrorMessage (status);
  223446. }
  223447. else
  223448. {
  223449. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223450. // open input ports
  223451. const StringArray inputChannels (getInputChannelNames());
  223452. for (int i = 0; i < inputChannels.size(); i++)
  223453. {
  223454. String inputName;
  223455. inputName << "in_" << ++totalNumberOfInputChannels;
  223456. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223457. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223458. }
  223459. // open output ports
  223460. const StringArray outputChannels (getOutputChannelNames());
  223461. for (int i = 0; i < outputChannels.size (); i++)
  223462. {
  223463. String outputName;
  223464. outputName << "out_" << ++totalNumberOfOutputChannels;
  223465. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223466. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223467. }
  223468. inChans.calloc (totalNumberOfInputChannels + 2);
  223469. outChans.calloc (totalNumberOfOutputChannels + 2);
  223470. }
  223471. }
  223472. ~JackAudioIODevice()
  223473. {
  223474. close();
  223475. if (client != 0)
  223476. {
  223477. JUCE_NAMESPACE::jack_client_close (client);
  223478. client = 0;
  223479. }
  223480. }
  223481. const StringArray getChannelNames (bool forInput) const
  223482. {
  223483. StringArray names;
  223484. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223485. forInput ? JackPortIsInput : JackPortIsOutput);
  223486. if (ports != 0)
  223487. {
  223488. int j = 0;
  223489. while (ports[j] != 0)
  223490. {
  223491. const String portName (ports [j++]);
  223492. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223493. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223494. }
  223495. free (ports);
  223496. }
  223497. return names;
  223498. }
  223499. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223500. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223501. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223502. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223503. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223504. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223505. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223506. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223507. double sampleRate, int bufferSizeSamples)
  223508. {
  223509. if (client == 0)
  223510. {
  223511. lastError = "No JACK client running";
  223512. return lastError;
  223513. }
  223514. lastError = String::empty;
  223515. close();
  223516. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223517. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223518. JUCE_NAMESPACE::jack_activate (client);
  223519. isOpen_ = true;
  223520. if (! inputChannels.isZero())
  223521. {
  223522. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223523. if (ports != 0)
  223524. {
  223525. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223526. for (int i = 0; i < numInputChannels; ++i)
  223527. {
  223528. const String portName (ports[i]);
  223529. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223530. {
  223531. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223532. if (error != 0)
  223533. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223534. }
  223535. }
  223536. free (ports);
  223537. }
  223538. }
  223539. if (! outputChannels.isZero())
  223540. {
  223541. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223542. if (ports != 0)
  223543. {
  223544. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223545. for (int i = 0; i < numOutputChannels; ++i)
  223546. {
  223547. const String portName (ports[i]);
  223548. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223549. {
  223550. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223551. if (error != 0)
  223552. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223553. }
  223554. }
  223555. free (ports);
  223556. }
  223557. }
  223558. return lastError;
  223559. }
  223560. void close()
  223561. {
  223562. stop();
  223563. if (client != 0)
  223564. {
  223565. JUCE_NAMESPACE::jack_deactivate (client);
  223566. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223567. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223568. }
  223569. isOpen_ = false;
  223570. }
  223571. void start (AudioIODeviceCallback* newCallback)
  223572. {
  223573. if (isOpen_ && newCallback != callback)
  223574. {
  223575. if (newCallback != 0)
  223576. newCallback->audioDeviceAboutToStart (this);
  223577. AudioIODeviceCallback* const oldCallback = callback;
  223578. {
  223579. const ScopedLock sl (callbackLock);
  223580. callback = newCallback;
  223581. }
  223582. if (oldCallback != 0)
  223583. oldCallback->audioDeviceStopped();
  223584. }
  223585. }
  223586. void stop()
  223587. {
  223588. start (0);
  223589. }
  223590. bool isOpen() { return isOpen_; }
  223591. bool isPlaying() { return callback != 0; }
  223592. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223593. double getCurrentSampleRate() { return getSampleRate (0); }
  223594. int getCurrentBitDepth() { return 32; }
  223595. const String getLastError() { return lastError; }
  223596. const BigInteger getActiveOutputChannels() const
  223597. {
  223598. BigInteger outputBits;
  223599. for (int i = 0; i < outputPorts.size(); i++)
  223600. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223601. outputBits.setBit (i);
  223602. return outputBits;
  223603. }
  223604. const BigInteger getActiveInputChannels() const
  223605. {
  223606. BigInteger inputBits;
  223607. for (int i = 0; i < inputPorts.size(); i++)
  223608. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223609. inputBits.setBit (i);
  223610. return inputBits;
  223611. }
  223612. int getOutputLatencyInSamples()
  223613. {
  223614. int latency = 0;
  223615. for (int i = 0; i < outputPorts.size(); i++)
  223616. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223617. return latency;
  223618. }
  223619. int getInputLatencyInSamples()
  223620. {
  223621. int latency = 0;
  223622. for (int i = 0; i < inputPorts.size(); i++)
  223623. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223624. return latency;
  223625. }
  223626. String inputId, outputId;
  223627. private:
  223628. void process (const int numSamples)
  223629. {
  223630. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223631. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223632. {
  223633. jack_default_audio_sample_t* in
  223634. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223635. if (in != 0)
  223636. inChans [numActiveInChans++] = (float*) in;
  223637. }
  223638. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223639. {
  223640. jack_default_audio_sample_t* out
  223641. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223642. if (out != 0)
  223643. outChans [numActiveOutChans++] = (float*) out;
  223644. }
  223645. const ScopedLock sl (callbackLock);
  223646. if (callback != 0)
  223647. {
  223648. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223649. outChans, numActiveOutChans, numSamples);
  223650. }
  223651. else
  223652. {
  223653. for (i = 0; i < numActiveOutChans; ++i)
  223654. zeromem (outChans[i], sizeof (float) * numSamples);
  223655. }
  223656. }
  223657. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223658. {
  223659. if (callbackArgument != 0)
  223660. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223661. return 0;
  223662. }
  223663. static void threadInitCallback (void* callbackArgument)
  223664. {
  223665. jack_Log ("JackAudioIODevice::initialise");
  223666. }
  223667. static void shutdownCallback (void* callbackArgument)
  223668. {
  223669. jack_Log ("JackAudioIODevice::shutdown");
  223670. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223671. if (device != 0)
  223672. {
  223673. device->client = 0;
  223674. device->close();
  223675. }
  223676. }
  223677. static void errorCallback (const char* msg)
  223678. {
  223679. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223680. }
  223681. bool isOpen_;
  223682. jack_client_t* client;
  223683. String lastError;
  223684. AudioIODeviceCallback* callback;
  223685. CriticalSection callbackLock;
  223686. HeapBlock <float*> inChans, outChans;
  223687. int totalNumberOfInputChannels;
  223688. int totalNumberOfOutputChannels;
  223689. Array<void*> inputPorts, outputPorts;
  223690. };
  223691. class JackAudioIODeviceType : public AudioIODeviceType
  223692. {
  223693. public:
  223694. JackAudioIODeviceType()
  223695. : AudioIODeviceType ("JACK"),
  223696. hasScanned (false)
  223697. {
  223698. }
  223699. ~JackAudioIODeviceType()
  223700. {
  223701. }
  223702. void scanForDevices()
  223703. {
  223704. hasScanned = true;
  223705. inputNames.clear();
  223706. inputIds.clear();
  223707. outputNames.clear();
  223708. outputIds.clear();
  223709. if (juce_libjack_handle == 0)
  223710. {
  223711. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223712. if (juce_libjack_handle == 0)
  223713. return;
  223714. }
  223715. // open a dummy client
  223716. jack_status_t status;
  223717. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223718. if (client == 0)
  223719. {
  223720. dumpJackErrorMessage (status);
  223721. }
  223722. else
  223723. {
  223724. // scan for output devices
  223725. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223726. if (ports != 0)
  223727. {
  223728. int j = 0;
  223729. while (ports[j] != 0)
  223730. {
  223731. String clientName (ports[j]);
  223732. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223733. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223734. && ! inputNames.contains (clientName))
  223735. {
  223736. inputNames.add (clientName);
  223737. inputIds.add (ports [j]);
  223738. }
  223739. ++j;
  223740. }
  223741. free (ports);
  223742. }
  223743. // scan for input devices
  223744. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223745. if (ports != 0)
  223746. {
  223747. int j = 0;
  223748. while (ports[j] != 0)
  223749. {
  223750. String clientName (ports[j]);
  223751. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223752. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223753. && ! outputNames.contains (clientName))
  223754. {
  223755. outputNames.add (clientName);
  223756. outputIds.add (ports [j]);
  223757. }
  223758. ++j;
  223759. }
  223760. free (ports);
  223761. }
  223762. JUCE_NAMESPACE::jack_client_close (client);
  223763. }
  223764. }
  223765. const StringArray getDeviceNames (bool wantInputNames) const
  223766. {
  223767. jassert (hasScanned); // need to call scanForDevices() before doing this
  223768. return wantInputNames ? inputNames : outputNames;
  223769. }
  223770. int getDefaultDeviceIndex (bool forInput) const
  223771. {
  223772. jassert (hasScanned); // need to call scanForDevices() before doing this
  223773. return 0;
  223774. }
  223775. bool hasSeparateInputsAndOutputs() const { return true; }
  223776. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223777. {
  223778. jassert (hasScanned); // need to call scanForDevices() before doing this
  223779. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223780. if (d == 0)
  223781. return -1;
  223782. return asInput ? inputIds.indexOf (d->inputId)
  223783. : outputIds.indexOf (d->outputId);
  223784. }
  223785. AudioIODevice* createDevice (const String& outputDeviceName,
  223786. const String& inputDeviceName)
  223787. {
  223788. jassert (hasScanned); // need to call scanForDevices() before doing this
  223789. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223790. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223791. if (inputIndex >= 0 || outputIndex >= 0)
  223792. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223793. : inputDeviceName,
  223794. inputIds [inputIndex],
  223795. outputIds [outputIndex]);
  223796. return 0;
  223797. }
  223798. juce_UseDebuggingNewOperator
  223799. private:
  223800. StringArray inputNames, outputNames, inputIds, outputIds;
  223801. bool hasScanned;
  223802. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223803. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223804. };
  223805. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223806. {
  223807. return new JackAudioIODeviceType();
  223808. }
  223809. #else // if JACK is turned off..
  223810. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223811. #endif
  223812. #endif
  223813. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223814. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223815. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223816. // compiled on its own).
  223817. #if JUCE_INCLUDED_FILE
  223818. #if JUCE_ALSA
  223819. static snd_seq_t* iterateMidiDevices (const bool forInput,
  223820. StringArray& deviceNamesFound,
  223821. const int deviceIndexToOpen)
  223822. {
  223823. snd_seq_t* returnedHandle = 0;
  223824. snd_seq_t* seqHandle;
  223825. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223826. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223827. {
  223828. snd_seq_system_info_t* systemInfo;
  223829. snd_seq_client_info_t* clientInfo;
  223830. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223831. {
  223832. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223833. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223834. {
  223835. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223836. while (--numClients >= 0 && returnedHandle == 0)
  223837. {
  223838. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223839. {
  223840. snd_seq_port_info_t* portInfo;
  223841. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223842. {
  223843. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223844. const int client = snd_seq_client_info_get_client (clientInfo);
  223845. snd_seq_port_info_set_client (portInfo, client);
  223846. snd_seq_port_info_set_port (portInfo, -1);
  223847. while (--numPorts >= 0)
  223848. {
  223849. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223850. && (snd_seq_port_info_get_capability (portInfo)
  223851. & (forInput ? SND_SEQ_PORT_CAP_READ
  223852. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223853. {
  223854. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223855. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223856. {
  223857. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223858. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223859. if (sourcePort != -1)
  223860. {
  223861. snd_seq_set_client_name (seqHandle,
  223862. forInput ? "Juce Midi Input"
  223863. : "Juce Midi Output");
  223864. const int portId
  223865. = snd_seq_create_simple_port (seqHandle,
  223866. forInput ? "Juce Midi In Port"
  223867. : "Juce Midi Out Port",
  223868. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223869. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223870. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223871. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223872. returnedHandle = seqHandle;
  223873. }
  223874. }
  223875. }
  223876. }
  223877. snd_seq_port_info_free (portInfo);
  223878. }
  223879. }
  223880. }
  223881. snd_seq_client_info_free (clientInfo);
  223882. }
  223883. snd_seq_system_info_free (systemInfo);
  223884. }
  223885. if (returnedHandle == 0)
  223886. snd_seq_close (seqHandle);
  223887. }
  223888. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223889. return returnedHandle;
  223890. }
  223891. static snd_seq_t* createMidiDevice (const bool forInput,
  223892. const String& deviceNameToOpen)
  223893. {
  223894. snd_seq_t* seqHandle = 0;
  223895. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223896. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223897. {
  223898. snd_seq_set_client_name (seqHandle,
  223899. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223900. const int portId
  223901. = snd_seq_create_simple_port (seqHandle,
  223902. forInput ? "in"
  223903. : "out",
  223904. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223905. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223906. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223907. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223908. if (portId < 0)
  223909. {
  223910. snd_seq_close (seqHandle);
  223911. seqHandle = 0;
  223912. }
  223913. }
  223914. return seqHandle;
  223915. }
  223916. class MidiOutputDevice
  223917. {
  223918. public:
  223919. MidiOutputDevice (MidiOutput* const midiOutput_,
  223920. snd_seq_t* const seqHandle_)
  223921. :
  223922. midiOutput (midiOutput_),
  223923. seqHandle (seqHandle_),
  223924. maxEventSize (16 * 1024)
  223925. {
  223926. jassert (seqHandle != 0 && midiOutput != 0);
  223927. snd_midi_event_new (maxEventSize, &midiParser);
  223928. }
  223929. ~MidiOutputDevice()
  223930. {
  223931. snd_midi_event_free (midiParser);
  223932. snd_seq_close (seqHandle);
  223933. }
  223934. void sendMessageNow (const MidiMessage& message)
  223935. {
  223936. if (message.getRawDataSize() > maxEventSize)
  223937. {
  223938. maxEventSize = message.getRawDataSize();
  223939. snd_midi_event_free (midiParser);
  223940. snd_midi_event_new (maxEventSize, &midiParser);
  223941. }
  223942. snd_seq_event_t event;
  223943. snd_seq_ev_clear (&event);
  223944. snd_midi_event_encode (midiParser,
  223945. message.getRawData(),
  223946. message.getRawDataSize(),
  223947. &event);
  223948. snd_midi_event_reset_encode (midiParser);
  223949. snd_seq_ev_set_source (&event, 0);
  223950. snd_seq_ev_set_subs (&event);
  223951. snd_seq_ev_set_direct (&event);
  223952. snd_seq_event_output (seqHandle, &event);
  223953. snd_seq_drain_output (seqHandle);
  223954. }
  223955. juce_UseDebuggingNewOperator
  223956. private:
  223957. MidiOutput* const midiOutput;
  223958. snd_seq_t* const seqHandle;
  223959. snd_midi_event_t* midiParser;
  223960. int maxEventSize;
  223961. };
  223962. const StringArray MidiOutput::getDevices()
  223963. {
  223964. StringArray devices;
  223965. iterateMidiDevices (false, devices, -1);
  223966. return devices;
  223967. }
  223968. int MidiOutput::getDefaultDeviceIndex()
  223969. {
  223970. return 0;
  223971. }
  223972. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223973. {
  223974. MidiOutput* newDevice = 0;
  223975. StringArray devices;
  223976. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223977. if (handle != 0)
  223978. {
  223979. newDevice = new MidiOutput();
  223980. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223981. }
  223982. return newDevice;
  223983. }
  223984. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223985. {
  223986. MidiOutput* newDevice = 0;
  223987. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223988. if (handle != 0)
  223989. {
  223990. newDevice = new MidiOutput();
  223991. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223992. }
  223993. return newDevice;
  223994. }
  223995. MidiOutput::~MidiOutput()
  223996. {
  223997. delete static_cast <MidiOutputDevice*> (internal);
  223998. }
  223999. void MidiOutput::reset()
  224000. {
  224001. }
  224002. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  224003. {
  224004. return false;
  224005. }
  224006. void MidiOutput::setVolume (float leftVol, float rightVol)
  224007. {
  224008. }
  224009. void MidiOutput::sendMessageNow (const MidiMessage& message)
  224010. {
  224011. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  224012. }
  224013. class MidiInputThread : public Thread
  224014. {
  224015. public:
  224016. MidiInputThread (MidiInput* const midiInput_,
  224017. snd_seq_t* const seqHandle_,
  224018. MidiInputCallback* const callback_)
  224019. : Thread ("Juce MIDI Input"),
  224020. midiInput (midiInput_),
  224021. seqHandle (seqHandle_),
  224022. callback (callback_)
  224023. {
  224024. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  224025. }
  224026. ~MidiInputThread()
  224027. {
  224028. snd_seq_close (seqHandle);
  224029. }
  224030. void run()
  224031. {
  224032. const int maxEventSize = 16 * 1024;
  224033. snd_midi_event_t* midiParser;
  224034. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  224035. {
  224036. HeapBlock <uint8> buffer (maxEventSize);
  224037. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  224038. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  224039. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  224040. while (! threadShouldExit())
  224041. {
  224042. if (poll (pfd, numPfds, 500) > 0)
  224043. {
  224044. snd_seq_event_t* inputEvent = 0;
  224045. snd_seq_nonblock (seqHandle, 1);
  224046. do
  224047. {
  224048. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  224049. {
  224050. // xxx what about SYSEXes that are too big for the buffer?
  224051. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  224052. snd_midi_event_reset_decode (midiParser);
  224053. if (numBytes > 0)
  224054. {
  224055. const MidiMessage message ((const uint8*) buffer,
  224056. numBytes,
  224057. Time::getMillisecondCounter() * 0.001);
  224058. callback->handleIncomingMidiMessage (midiInput, message);
  224059. }
  224060. snd_seq_free_event (inputEvent);
  224061. }
  224062. }
  224063. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  224064. snd_seq_free_event (inputEvent);
  224065. }
  224066. }
  224067. snd_midi_event_free (midiParser);
  224068. }
  224069. };
  224070. juce_UseDebuggingNewOperator
  224071. private:
  224072. MidiInput* const midiInput;
  224073. snd_seq_t* const seqHandle;
  224074. MidiInputCallback* const callback;
  224075. };
  224076. MidiInput::MidiInput (const String& name_)
  224077. : name (name_),
  224078. internal (0)
  224079. {
  224080. }
  224081. MidiInput::~MidiInput()
  224082. {
  224083. stop();
  224084. delete static_cast <MidiInputThread*> (internal);
  224085. }
  224086. void MidiInput::start()
  224087. {
  224088. static_cast <MidiInputThread*> (internal)->startThread();
  224089. }
  224090. void MidiInput::stop()
  224091. {
  224092. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  224093. }
  224094. int MidiInput::getDefaultDeviceIndex()
  224095. {
  224096. return 0;
  224097. }
  224098. const StringArray MidiInput::getDevices()
  224099. {
  224100. StringArray devices;
  224101. iterateMidiDevices (true, devices, -1);
  224102. return devices;
  224103. }
  224104. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  224105. {
  224106. MidiInput* newDevice = 0;
  224107. StringArray devices;
  224108. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  224109. if (handle != 0)
  224110. {
  224111. newDevice = new MidiInput (devices [deviceIndex]);
  224112. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224113. }
  224114. return newDevice;
  224115. }
  224116. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  224117. {
  224118. MidiInput* newDevice = 0;
  224119. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  224120. if (handle != 0)
  224121. {
  224122. newDevice = new MidiInput (deviceName);
  224123. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224124. }
  224125. return newDevice;
  224126. }
  224127. #else
  224128. // (These are just stub functions if ALSA is unavailable...)
  224129. const StringArray MidiOutput::getDevices() { return StringArray(); }
  224130. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  224131. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  224132. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  224133. MidiOutput::~MidiOutput() {}
  224134. void MidiOutput::reset() {}
  224135. bool MidiOutput::getVolume (float&, float&) { return false; }
  224136. void MidiOutput::setVolume (float, float) {}
  224137. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  224138. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  224139. MidiInput::~MidiInput() {}
  224140. void MidiInput::start() {}
  224141. void MidiInput::stop() {}
  224142. int MidiInput::getDefaultDeviceIndex() { return 0; }
  224143. const StringArray MidiInput::getDevices() { return StringArray(); }
  224144. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  224145. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  224146. #endif
  224147. #endif
  224148. /*** End of inlined file: juce_linux_Midi.cpp ***/
  224149. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  224150. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224151. // compiled on its own).
  224152. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  224153. AudioCDReader::AudioCDReader()
  224154. : AudioFormatReader (0, "CD Audio")
  224155. {
  224156. }
  224157. const StringArray AudioCDReader::getAvailableCDNames()
  224158. {
  224159. StringArray names;
  224160. return names;
  224161. }
  224162. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  224163. {
  224164. return 0;
  224165. }
  224166. AudioCDReader::~AudioCDReader()
  224167. {
  224168. }
  224169. void AudioCDReader::refreshTrackLengths()
  224170. {
  224171. }
  224172. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  224173. int64 startSampleInFile, int numSamples)
  224174. {
  224175. return false;
  224176. }
  224177. bool AudioCDReader::isCDStillPresent() const
  224178. {
  224179. return false;
  224180. }
  224181. bool AudioCDReader::isTrackAudio (int trackNum) const
  224182. {
  224183. return false;
  224184. }
  224185. void AudioCDReader::enableIndexScanning (bool b)
  224186. {
  224187. }
  224188. int AudioCDReader::getLastIndex() const
  224189. {
  224190. return 0;
  224191. }
  224192. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  224193. {
  224194. return Array<int>();
  224195. }
  224196. #endif
  224197. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  224198. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  224199. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224200. // compiled on its own).
  224201. #if JUCE_INCLUDED_FILE
  224202. void FileChooser::showPlatformDialog (Array<File>& results,
  224203. const String& title,
  224204. const File& file,
  224205. const String& filters,
  224206. bool isDirectory,
  224207. bool selectsFiles,
  224208. bool isSave,
  224209. bool warnAboutOverwritingExistingFiles,
  224210. bool selectMultipleFiles,
  224211. FilePreviewComponent* previewComponent)
  224212. {
  224213. const String separator (":");
  224214. String command ("zenity --file-selection");
  224215. if (title.isNotEmpty())
  224216. command << " --title=\"" << title << "\"";
  224217. if (file != File::nonexistent)
  224218. command << " --filename=\"" << file.getFullPathName () << "\"";
  224219. if (isDirectory)
  224220. command << " --directory";
  224221. if (isSave)
  224222. command << " --save";
  224223. if (selectMultipleFiles)
  224224. command << " --multiple --separator=\"" << separator << "\"";
  224225. command << " 2>&1";
  224226. MemoryOutputStream result;
  224227. int status = -1;
  224228. FILE* stream = popen (command.toUTF8(), "r");
  224229. if (stream != 0)
  224230. {
  224231. for (;;)
  224232. {
  224233. char buffer [1024];
  224234. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224235. if (bytesRead <= 0)
  224236. break;
  224237. result.write (buffer, bytesRead);
  224238. }
  224239. status = pclose (stream);
  224240. }
  224241. if (status == 0)
  224242. {
  224243. StringArray tokens;
  224244. if (selectMultipleFiles)
  224245. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224246. else
  224247. tokens.add (result.toUTF8());
  224248. for (int i = 0; i < tokens.size(); i++)
  224249. results.add (File (tokens[i]));
  224250. return;
  224251. }
  224252. //xxx ain't got one!
  224253. jassertfalse;
  224254. }
  224255. #endif
  224256. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224257. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224258. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224259. // compiled on its own).
  224260. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224261. /*
  224262. Sorry.. This class isn't implemented on Linux!
  224263. */
  224264. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224265. : browser (0),
  224266. blankPageShown (false),
  224267. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224268. {
  224269. setOpaque (true);
  224270. }
  224271. WebBrowserComponent::~WebBrowserComponent()
  224272. {
  224273. }
  224274. void WebBrowserComponent::goToURL (const String& url,
  224275. const StringArray* headers,
  224276. const MemoryBlock* postData)
  224277. {
  224278. lastURL = url;
  224279. lastHeaders.clear();
  224280. if (headers != 0)
  224281. lastHeaders = *headers;
  224282. lastPostData.setSize (0);
  224283. if (postData != 0)
  224284. lastPostData = *postData;
  224285. blankPageShown = false;
  224286. }
  224287. void WebBrowserComponent::stop()
  224288. {
  224289. }
  224290. void WebBrowserComponent::goBack()
  224291. {
  224292. lastURL = String::empty;
  224293. blankPageShown = false;
  224294. }
  224295. void WebBrowserComponent::goForward()
  224296. {
  224297. lastURL = String::empty;
  224298. }
  224299. void WebBrowserComponent::refresh()
  224300. {
  224301. }
  224302. void WebBrowserComponent::paint (Graphics& g)
  224303. {
  224304. g.fillAll (Colours::white);
  224305. }
  224306. void WebBrowserComponent::checkWindowAssociation()
  224307. {
  224308. }
  224309. void WebBrowserComponent::reloadLastURL()
  224310. {
  224311. if (lastURL.isNotEmpty())
  224312. {
  224313. goToURL (lastURL, &lastHeaders, &lastPostData);
  224314. lastURL = String::empty;
  224315. }
  224316. }
  224317. void WebBrowserComponent::parentHierarchyChanged()
  224318. {
  224319. checkWindowAssociation();
  224320. }
  224321. void WebBrowserComponent::resized()
  224322. {
  224323. }
  224324. void WebBrowserComponent::visibilityChanged()
  224325. {
  224326. checkWindowAssociation();
  224327. }
  224328. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224329. {
  224330. return true;
  224331. }
  224332. #endif
  224333. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224334. #endif
  224335. END_JUCE_NAMESPACE
  224336. #endif
  224337. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224338. #endif
  224339. #if JUCE_MAC || JUCE_IPHONE
  224340. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224341. /*
  224342. This file wraps together all the mac-specific code, so that
  224343. we can include all the native headers just once, and compile all our
  224344. platform-specific stuff in one big lump, keeping it out of the way of
  224345. the rest of the codebase.
  224346. */
  224347. #if JUCE_MAC || JUCE_IOS
  224348. BEGIN_JUCE_NAMESPACE
  224349. #undef Point
  224350. #define JUCE_INCLUDED_FILE 1
  224351. // Now include the actual code files..
  224352. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224353. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224354. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224355. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224356. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224357. actually calling into a similarly named class in the other module's address space.
  224358. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224359. have unique names, and should avoid this problem.
  224360. If you're using the amalgamated version, you can just set this macro to something unique before
  224361. you include juce_amalgamated.cpp.
  224362. */
  224363. #ifndef JUCE_ObjCExtraSuffix
  224364. #define JUCE_ObjCExtraSuffix 3
  224365. #endif
  224366. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224367. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224368. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224369. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224370. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224371. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224372. // compiled on its own).
  224373. #if JUCE_INCLUDED_FILE
  224374. static const String nsStringToJuce (NSString* s)
  224375. {
  224376. return String::fromUTF8 ([s UTF8String]);
  224377. }
  224378. static NSString* juceStringToNS (const String& s)
  224379. {
  224380. return [NSString stringWithUTF8String: s.toUTF8()];
  224381. }
  224382. static const String convertUTF16ToString (const UniChar* utf16)
  224383. {
  224384. String s;
  224385. while (*utf16 != 0)
  224386. s += (juce_wchar) *utf16++;
  224387. return s;
  224388. }
  224389. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224390. {
  224391. String result;
  224392. if (cfString != 0)
  224393. {
  224394. CFRange range = { 0, CFStringGetLength (cfString) };
  224395. HeapBlock <UniChar> u (range.length + 1);
  224396. CFStringGetCharacters (cfString, range, u);
  224397. u[range.length] = 0;
  224398. result = convertUTF16ToString (u);
  224399. }
  224400. return result;
  224401. }
  224402. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224403. {
  224404. const int len = s.length();
  224405. HeapBlock <UniChar> temp (len + 2);
  224406. for (int i = 0; i <= len; ++i)
  224407. temp[i] = s[i];
  224408. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224409. }
  224410. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224411. {
  224412. #if JUCE_IOS
  224413. const ScopedAutoReleasePool pool;
  224414. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224415. #else
  224416. UnicodeMapping map;
  224417. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224418. kUnicodeNoSubset,
  224419. kTextEncodingDefaultFormat);
  224420. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224421. kUnicodeCanonicalCompVariant,
  224422. kTextEncodingDefaultFormat);
  224423. map.mappingVersion = kUnicodeUseLatestMapping;
  224424. UnicodeToTextInfo conversionInfo = 0;
  224425. String result;
  224426. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224427. {
  224428. const int len = s.length();
  224429. HeapBlock <UniChar> tempIn, tempOut;
  224430. tempIn.calloc (len + 2);
  224431. tempOut.calloc (len + 2);
  224432. for (int i = 0; i <= len; ++i)
  224433. tempIn[i] = s[i];
  224434. ByteCount bytesRead = 0;
  224435. ByteCount outputBufferSize = 0;
  224436. if (ConvertFromUnicodeToText (conversionInfo,
  224437. len * sizeof (UniChar), tempIn,
  224438. kUnicodeDefaultDirectionMask,
  224439. 0, 0, 0, 0,
  224440. len * sizeof (UniChar), &bytesRead,
  224441. &outputBufferSize, tempOut) == noErr)
  224442. {
  224443. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224444. juce_wchar* t = result;
  224445. unsigned int i;
  224446. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224447. t[i] = (juce_wchar) tempOut[i];
  224448. t[i] = 0;
  224449. }
  224450. DisposeUnicodeToTextInfo (&conversionInfo);
  224451. }
  224452. return result;
  224453. #endif
  224454. }
  224455. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224456. void SystemClipboard::copyTextToClipboard (const String& text)
  224457. {
  224458. #if JUCE_IOS
  224459. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224460. forPasteboardType: @"public.text"];
  224461. #else
  224462. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224463. owner: nil];
  224464. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224465. forType: NSStringPboardType];
  224466. #endif
  224467. }
  224468. const String SystemClipboard::getTextFromClipboard()
  224469. {
  224470. #if JUCE_IOS
  224471. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224472. #else
  224473. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224474. #endif
  224475. return text == 0 ? String::empty
  224476. : nsStringToJuce (text);
  224477. }
  224478. #endif
  224479. #endif
  224480. /*** End of inlined file: juce_mac_Strings.mm ***/
  224481. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224482. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224483. // compiled on its own).
  224484. #if JUCE_INCLUDED_FILE
  224485. namespace SystemStatsHelpers
  224486. {
  224487. static int64 highResTimerFrequency = 0;
  224488. static double highResTimerToMillisecRatio = 0;
  224489. #if JUCE_INTEL
  224490. static void juce_getCpuVendor (char* const v) throw()
  224491. {
  224492. int vendor[4];
  224493. zerostruct (vendor);
  224494. int dummy = 0;
  224495. asm ("mov %%ebx, %%esi \n\t"
  224496. "cpuid \n\t"
  224497. "xchg %%esi, %%ebx"
  224498. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224499. memcpy (v, vendor, 16);
  224500. }
  224501. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224502. {
  224503. unsigned int cpu = 0;
  224504. unsigned int ext = 0;
  224505. unsigned int family = 0;
  224506. unsigned int dummy = 0;
  224507. asm ("mov %%ebx, %%esi \n\t"
  224508. "cpuid \n\t"
  224509. "xchg %%esi, %%ebx"
  224510. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224511. familyModel = family;
  224512. extFeatures = ext;
  224513. return cpu;
  224514. }
  224515. #endif
  224516. }
  224517. void SystemStats::initialiseStats()
  224518. {
  224519. using namespace SystemStatsHelpers;
  224520. static bool initialised = false;
  224521. if (! initialised)
  224522. {
  224523. initialised = true;
  224524. #if JUCE_MAC
  224525. [NSApplication sharedApplication];
  224526. #endif
  224527. #if JUCE_INTEL
  224528. unsigned int familyModel, extFeatures;
  224529. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224530. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224531. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224532. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224533. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224534. #else
  224535. cpuFlags.hasMMX = false;
  224536. cpuFlags.hasSSE = false;
  224537. cpuFlags.hasSSE2 = false;
  224538. cpuFlags.has3DNow = false;
  224539. #endif
  224540. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224541. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224542. #else
  224543. cpuFlags.numCpus = (int) MPProcessors();
  224544. #endif
  224545. mach_timebase_info_data_t timebase;
  224546. (void) mach_timebase_info (&timebase);
  224547. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224548. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224549. String s (SystemStats::getJUCEVersion());
  224550. rlimit lim;
  224551. getrlimit (RLIMIT_NOFILE, &lim);
  224552. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224553. setrlimit (RLIMIT_NOFILE, &lim);
  224554. }
  224555. }
  224556. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224557. {
  224558. return MacOSX;
  224559. }
  224560. const String SystemStats::getOperatingSystemName()
  224561. {
  224562. return "Mac OS X";
  224563. }
  224564. #if ! JUCE_IOS
  224565. int PlatformUtilities::getOSXMinorVersionNumber()
  224566. {
  224567. SInt32 versionMinor = 0;
  224568. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224569. (void) err;
  224570. jassert (err == noErr);
  224571. return (int) versionMinor;
  224572. }
  224573. #endif
  224574. bool SystemStats::isOperatingSystem64Bit()
  224575. {
  224576. #if JUCE_IOS
  224577. return false;
  224578. #elif JUCE_64BIT
  224579. return true;
  224580. #else
  224581. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224582. #endif
  224583. }
  224584. int SystemStats::getMemorySizeInMegabytes()
  224585. {
  224586. uint64 mem = 0;
  224587. size_t memSize = sizeof (mem);
  224588. int mib[] = { CTL_HW, HW_MEMSIZE };
  224589. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224590. return (int) (mem / (1024 * 1024));
  224591. }
  224592. const String SystemStats::getCpuVendor()
  224593. {
  224594. #if JUCE_INTEL
  224595. char v [16];
  224596. SystemStatsHelpers::juce_getCpuVendor (v);
  224597. return String (v, 16);
  224598. #else
  224599. return String::empty;
  224600. #endif
  224601. }
  224602. int SystemStats::getCpuSpeedInMegaherz()
  224603. {
  224604. uint64 speedHz = 0;
  224605. size_t speedSize = sizeof (speedHz);
  224606. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224607. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224608. #if JUCE_BIG_ENDIAN
  224609. if (speedSize == 4)
  224610. speedHz >>= 32;
  224611. #endif
  224612. return (int) (speedHz / 1000000);
  224613. }
  224614. const String SystemStats::getLogonName()
  224615. {
  224616. return nsStringToJuce (NSUserName());
  224617. }
  224618. const String SystemStats::getFullUserName()
  224619. {
  224620. return nsStringToJuce (NSFullUserName());
  224621. }
  224622. uint32 juce_millisecondsSinceStartup() throw()
  224623. {
  224624. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224625. }
  224626. double Time::getMillisecondCounterHiRes() throw()
  224627. {
  224628. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224629. }
  224630. int64 Time::getHighResolutionTicks() throw()
  224631. {
  224632. return (int64) mach_absolute_time();
  224633. }
  224634. int64 Time::getHighResolutionTicksPerSecond() throw()
  224635. {
  224636. return SystemStatsHelpers::highResTimerFrequency;
  224637. }
  224638. bool Time::setSystemTimeToThisTime() const
  224639. {
  224640. jassertfalse;
  224641. return false;
  224642. }
  224643. int SystemStats::getPageSize()
  224644. {
  224645. return (int) NSPageSize();
  224646. }
  224647. void PlatformUtilities::fpuReset()
  224648. {
  224649. }
  224650. #endif
  224651. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224652. /*** Start of inlined file: juce_mac_Network.mm ***/
  224653. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224654. // compiled on its own).
  224655. #if JUCE_INCLUDED_FILE
  224656. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224657. {
  224658. #ifndef IFT_ETHER
  224659. #define IFT_ETHER 6
  224660. #endif
  224661. ifaddrs* addrs = 0;
  224662. int numResults = 0;
  224663. if (getifaddrs (&addrs) == 0)
  224664. {
  224665. const ifaddrs* cursor = addrs;
  224666. while (cursor != 0 && numResults < maxNum)
  224667. {
  224668. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224669. if (sto->ss_family == AF_LINK)
  224670. {
  224671. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224672. if (sadd->sdl_type == IFT_ETHER)
  224673. {
  224674. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224675. uint64 a = 0;
  224676. for (int i = 6; --i >= 0;)
  224677. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224678. *addresses++ = (int64) a;
  224679. ++numResults;
  224680. }
  224681. }
  224682. cursor = cursor->ifa_next;
  224683. }
  224684. freeifaddrs (addrs);
  224685. }
  224686. return numResults;
  224687. }
  224688. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224689. const String& emailSubject,
  224690. const String& bodyText,
  224691. const StringArray& filesToAttach)
  224692. {
  224693. #if JUCE_IOS
  224694. //xxx probably need to use MFMailComposeViewController
  224695. jassertfalse;
  224696. return false;
  224697. #else
  224698. const ScopedAutoReleasePool pool;
  224699. String script;
  224700. script << "tell application \"Mail\"\r\n"
  224701. "set newMessage to make new outgoing message with properties {subject:\""
  224702. << emailSubject.replace ("\"", "\\\"")
  224703. << "\", content:\""
  224704. << bodyText.replace ("\"", "\\\"")
  224705. << "\" & return & return}\r\n"
  224706. "tell newMessage\r\n"
  224707. "set visible to true\r\n"
  224708. "set sender to \"sdfsdfsdfewf\"\r\n"
  224709. "make new to recipient at end of to recipients with properties {address:\""
  224710. << targetEmailAddress
  224711. << "\"}\r\n";
  224712. for (int i = 0; i < filesToAttach.size(); ++i)
  224713. {
  224714. script << "tell content\r\n"
  224715. "make new attachment with properties {file name:\""
  224716. << filesToAttach[i].replace ("\"", "\\\"")
  224717. << "\"} at after the last paragraph\r\n"
  224718. "end tell\r\n";
  224719. }
  224720. script << "end tell\r\n"
  224721. "end tell\r\n";
  224722. NSAppleScript* s = [[NSAppleScript alloc]
  224723. initWithSource: juceStringToNS (script)];
  224724. NSDictionary* error = 0;
  224725. const bool ok = [s executeAndReturnError: &error] != nil;
  224726. [s release];
  224727. return ok;
  224728. #endif
  224729. }
  224730. END_JUCE_NAMESPACE
  224731. using namespace JUCE_NAMESPACE;
  224732. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224733. @interface JuceURLConnection : NSObject
  224734. {
  224735. @public
  224736. NSURLRequest* request;
  224737. NSURLConnection* connection;
  224738. NSMutableData* data;
  224739. Thread* runLoopThread;
  224740. bool initialised, hasFailed, hasFinished;
  224741. int position;
  224742. int64 contentLength;
  224743. NSDictionary* headers;
  224744. NSLock* dataLock;
  224745. }
  224746. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224747. - (void) dealloc;
  224748. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224749. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224750. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224751. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224752. - (BOOL) isOpen;
  224753. - (int) read: (char*) dest numBytes: (int) num;
  224754. - (int) readPosition;
  224755. - (void) stop;
  224756. - (void) createConnection;
  224757. @end
  224758. class JuceURLConnectionMessageThread : public Thread
  224759. {
  224760. JuceURLConnection* owner;
  224761. public:
  224762. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224763. : Thread ("http connection"),
  224764. owner (owner_)
  224765. {
  224766. }
  224767. ~JuceURLConnectionMessageThread()
  224768. {
  224769. stopThread (10000);
  224770. }
  224771. void run()
  224772. {
  224773. [owner createConnection];
  224774. while (! threadShouldExit())
  224775. {
  224776. const ScopedAutoReleasePool pool;
  224777. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224778. }
  224779. }
  224780. };
  224781. @implementation JuceURLConnection
  224782. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224783. withCallback: (URL::OpenStreamProgressCallback*) callback
  224784. withContext: (void*) context;
  224785. {
  224786. [super init];
  224787. request = req;
  224788. [request retain];
  224789. data = [[NSMutableData data] retain];
  224790. dataLock = [[NSLock alloc] init];
  224791. connection = 0;
  224792. initialised = false;
  224793. hasFailed = false;
  224794. hasFinished = false;
  224795. contentLength = -1;
  224796. headers = 0;
  224797. runLoopThread = new JuceURLConnectionMessageThread (self);
  224798. runLoopThread->startThread();
  224799. while (runLoopThread->isThreadRunning() && ! initialised)
  224800. {
  224801. if (callback != 0)
  224802. callback (context, -1, (int) [[request HTTPBody] length]);
  224803. Thread::sleep (1);
  224804. }
  224805. return self;
  224806. }
  224807. - (void) dealloc
  224808. {
  224809. [self stop];
  224810. deleteAndZero (runLoopThread);
  224811. [connection release];
  224812. [data release];
  224813. [dataLock release];
  224814. [request release];
  224815. [headers release];
  224816. [super dealloc];
  224817. }
  224818. - (void) createConnection
  224819. {
  224820. NSUInteger oldRetainCount = [self retainCount];
  224821. connection = [[NSURLConnection alloc] initWithRequest: request
  224822. delegate: self];
  224823. if (oldRetainCount == [self retainCount])
  224824. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224825. if (connection == nil)
  224826. runLoopThread->signalThreadShouldExit();
  224827. }
  224828. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224829. {
  224830. (void) conn;
  224831. [dataLock lock];
  224832. [data setLength: 0];
  224833. [dataLock unlock];
  224834. initialised = true;
  224835. contentLength = [response expectedContentLength];
  224836. [headers release];
  224837. headers = 0;
  224838. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224839. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224840. }
  224841. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224842. {
  224843. (void) conn;
  224844. DBG (nsStringToJuce ([error description]));
  224845. hasFailed = true;
  224846. initialised = true;
  224847. if (runLoopThread != 0)
  224848. runLoopThread->signalThreadShouldExit();
  224849. }
  224850. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224851. {
  224852. (void) conn;
  224853. [dataLock lock];
  224854. [data appendData: newData];
  224855. [dataLock unlock];
  224856. initialised = true;
  224857. }
  224858. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224859. {
  224860. (void) conn;
  224861. hasFinished = true;
  224862. initialised = true;
  224863. if (runLoopThread != 0)
  224864. runLoopThread->signalThreadShouldExit();
  224865. }
  224866. - (BOOL) isOpen
  224867. {
  224868. return connection != 0 && ! hasFailed;
  224869. }
  224870. - (int) readPosition
  224871. {
  224872. return position;
  224873. }
  224874. - (int) read: (char*) dest numBytes: (int) numNeeded
  224875. {
  224876. int numDone = 0;
  224877. while (numNeeded > 0)
  224878. {
  224879. int available = jmin (numNeeded, (int) [data length]);
  224880. if (available > 0)
  224881. {
  224882. [dataLock lock];
  224883. [data getBytes: dest length: available];
  224884. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224885. [dataLock unlock];
  224886. numDone += available;
  224887. numNeeded -= available;
  224888. dest += available;
  224889. }
  224890. else
  224891. {
  224892. if (hasFailed || hasFinished)
  224893. break;
  224894. Thread::sleep (1);
  224895. }
  224896. }
  224897. position += numDone;
  224898. return numDone;
  224899. }
  224900. - (void) stop
  224901. {
  224902. [connection cancel];
  224903. if (runLoopThread != 0)
  224904. runLoopThread->stopThread (10000);
  224905. }
  224906. @end
  224907. BEGIN_JUCE_NAMESPACE
  224908. void* juce_openInternetFile (const String& url,
  224909. const String& headers,
  224910. const MemoryBlock& postData,
  224911. const bool isPost,
  224912. URL::OpenStreamProgressCallback* callback,
  224913. void* callbackContext,
  224914. int timeOutMs)
  224915. {
  224916. const ScopedAutoReleasePool pool;
  224917. NSMutableURLRequest* req = [NSMutableURLRequest
  224918. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224919. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224920. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224921. if (req == nil)
  224922. return 0;
  224923. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224924. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224925. StringArray headerLines;
  224926. headerLines.addLines (headers);
  224927. headerLines.removeEmptyStrings (true);
  224928. for (int i = 0; i < headerLines.size(); ++i)
  224929. {
  224930. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224931. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224932. if (key.isNotEmpty() && value.isNotEmpty())
  224933. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224934. }
  224935. if (isPost && postData.getSize() > 0)
  224936. {
  224937. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224938. length: postData.getSize()]];
  224939. }
  224940. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224941. withCallback: callback
  224942. withContext: callbackContext];
  224943. if ([s isOpen])
  224944. return s;
  224945. [s release];
  224946. return 0;
  224947. }
  224948. void juce_closeInternetFile (void* handle)
  224949. {
  224950. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224951. if (s != 0)
  224952. {
  224953. const ScopedAutoReleasePool pool;
  224954. [s stop];
  224955. [s release];
  224956. }
  224957. }
  224958. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224959. {
  224960. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224961. if (s != 0)
  224962. {
  224963. const ScopedAutoReleasePool pool;
  224964. return [s read: (char*) buffer numBytes: bytesToRead];
  224965. }
  224966. return 0;
  224967. }
  224968. int64 juce_getInternetFileContentLength (void* handle)
  224969. {
  224970. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224971. if (s != 0)
  224972. return s->contentLength;
  224973. return -1;
  224974. }
  224975. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224976. {
  224977. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224978. if (s != 0 && s->headers != 0)
  224979. {
  224980. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224981. NSString* key;
  224982. while ((key = [enumerator nextObject]) != nil)
  224983. headers.set (nsStringToJuce (key),
  224984. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224985. }
  224986. }
  224987. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224988. {
  224989. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224990. if (s != 0)
  224991. return [s readPosition];
  224992. return 0;
  224993. }
  224994. #endif
  224995. /*** End of inlined file: juce_mac_Network.mm ***/
  224996. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224997. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224998. // compiled on its own).
  224999. #if JUCE_INCLUDED_FILE
  225000. struct NamedPipeInternal
  225001. {
  225002. String pipeInName, pipeOutName;
  225003. int pipeIn, pipeOut;
  225004. bool volatile createdPipe, blocked, stopReadOperation;
  225005. static void signalHandler (int) {}
  225006. };
  225007. void NamedPipe::cancelPendingReads()
  225008. {
  225009. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  225010. {
  225011. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225012. intern->stopReadOperation = true;
  225013. char buffer [1] = { 0 };
  225014. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  225015. (void) bytesWritten;
  225016. int timeout = 2000;
  225017. while (intern->blocked && --timeout >= 0)
  225018. Thread::sleep (2);
  225019. intern->stopReadOperation = false;
  225020. }
  225021. }
  225022. void NamedPipe::close()
  225023. {
  225024. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225025. if (intern != 0)
  225026. {
  225027. internal = 0;
  225028. if (intern->pipeIn != -1)
  225029. ::close (intern->pipeIn);
  225030. if (intern->pipeOut != -1)
  225031. ::close (intern->pipeOut);
  225032. if (intern->createdPipe)
  225033. {
  225034. unlink (intern->pipeInName.toUTF8());
  225035. unlink (intern->pipeOutName.toUTF8());
  225036. }
  225037. delete intern;
  225038. }
  225039. }
  225040. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  225041. {
  225042. close();
  225043. NamedPipeInternal* const intern = new NamedPipeInternal();
  225044. internal = intern;
  225045. intern->createdPipe = createPipe;
  225046. intern->blocked = false;
  225047. intern->stopReadOperation = false;
  225048. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  225049. siginterrupt (SIGPIPE, 1);
  225050. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  225051. intern->pipeInName = pipePath + "_in";
  225052. intern->pipeOutName = pipePath + "_out";
  225053. intern->pipeIn = -1;
  225054. intern->pipeOut = -1;
  225055. if (createPipe)
  225056. {
  225057. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  225058. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  225059. {
  225060. delete intern;
  225061. internal = 0;
  225062. return false;
  225063. }
  225064. }
  225065. return true;
  225066. }
  225067. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  225068. {
  225069. int bytesRead = -1;
  225070. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225071. if (intern != 0)
  225072. {
  225073. intern->blocked = true;
  225074. if (intern->pipeIn == -1)
  225075. {
  225076. if (intern->createdPipe)
  225077. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  225078. else
  225079. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  225080. if (intern->pipeIn == -1)
  225081. {
  225082. intern->blocked = false;
  225083. return -1;
  225084. }
  225085. }
  225086. bytesRead = 0;
  225087. char* p = static_cast<char*> (destBuffer);
  225088. while (bytesRead < maxBytesToRead)
  225089. {
  225090. const int bytesThisTime = maxBytesToRead - bytesRead;
  225091. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  225092. if (numRead <= 0 || intern->stopReadOperation)
  225093. {
  225094. bytesRead = -1;
  225095. break;
  225096. }
  225097. bytesRead += numRead;
  225098. p += bytesRead;
  225099. }
  225100. intern->blocked = false;
  225101. }
  225102. return bytesRead;
  225103. }
  225104. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  225105. {
  225106. int bytesWritten = -1;
  225107. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225108. if (intern != 0)
  225109. {
  225110. if (intern->pipeOut == -1)
  225111. {
  225112. if (intern->createdPipe)
  225113. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  225114. else
  225115. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  225116. if (intern->pipeOut == -1)
  225117. {
  225118. return -1;
  225119. }
  225120. }
  225121. const char* p = static_cast<const char*> (sourceBuffer);
  225122. bytesWritten = 0;
  225123. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  225124. while (bytesWritten < numBytesToWrite
  225125. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  225126. {
  225127. const int bytesThisTime = numBytesToWrite - bytesWritten;
  225128. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  225129. if (numWritten <= 0)
  225130. {
  225131. bytesWritten = -1;
  225132. break;
  225133. }
  225134. bytesWritten += numWritten;
  225135. p += bytesWritten;
  225136. }
  225137. }
  225138. return bytesWritten;
  225139. }
  225140. #endif
  225141. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  225142. /*** Start of inlined file: juce_mac_Threads.mm ***/
  225143. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225144. // compiled on its own).
  225145. #if JUCE_INCLUDED_FILE
  225146. /*
  225147. Note that a lot of methods that you'd expect to find in this file actually
  225148. live in juce_posix_SharedCode.h!
  225149. */
  225150. bool Process::isForegroundProcess()
  225151. {
  225152. #if JUCE_MAC
  225153. return [NSApp isActive];
  225154. #else
  225155. return true; // xxx change this if more than one app is ever possible on the iPhone!
  225156. #endif
  225157. }
  225158. void Process::raisePrivilege()
  225159. {
  225160. jassertfalse;
  225161. }
  225162. void Process::lowerPrivilege()
  225163. {
  225164. jassertfalse;
  225165. }
  225166. void Process::terminate()
  225167. {
  225168. exit (0);
  225169. }
  225170. void Process::setPriority (ProcessPriority)
  225171. {
  225172. // xxx
  225173. }
  225174. #endif
  225175. /*** End of inlined file: juce_mac_Threads.mm ***/
  225176. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  225177. /*
  225178. This file contains posix routines that are common to both the Linux and Mac builds.
  225179. It gets included directly in the cpp files for these platforms.
  225180. */
  225181. CriticalSection::CriticalSection() throw()
  225182. {
  225183. pthread_mutexattr_t atts;
  225184. pthread_mutexattr_init (&atts);
  225185. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  225186. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225187. pthread_mutex_init (&internal, &atts);
  225188. }
  225189. CriticalSection::~CriticalSection() throw()
  225190. {
  225191. pthread_mutex_destroy (&internal);
  225192. }
  225193. void CriticalSection::enter() const throw()
  225194. {
  225195. pthread_mutex_lock (&internal);
  225196. }
  225197. bool CriticalSection::tryEnter() const throw()
  225198. {
  225199. return pthread_mutex_trylock (&internal) == 0;
  225200. }
  225201. void CriticalSection::exit() const throw()
  225202. {
  225203. pthread_mutex_unlock (&internal);
  225204. }
  225205. class WaitableEventImpl
  225206. {
  225207. public:
  225208. WaitableEventImpl (const bool manualReset_)
  225209. : triggered (false),
  225210. manualReset (manualReset_)
  225211. {
  225212. pthread_cond_init (&condition, 0);
  225213. pthread_mutexattr_t atts;
  225214. pthread_mutexattr_init (&atts);
  225215. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225216. pthread_mutex_init (&mutex, &atts);
  225217. }
  225218. ~WaitableEventImpl()
  225219. {
  225220. pthread_cond_destroy (&condition);
  225221. pthread_mutex_destroy (&mutex);
  225222. }
  225223. bool wait (const int timeOutMillisecs) throw()
  225224. {
  225225. pthread_mutex_lock (&mutex);
  225226. if (! triggered)
  225227. {
  225228. if (timeOutMillisecs < 0)
  225229. {
  225230. do
  225231. {
  225232. pthread_cond_wait (&condition, &mutex);
  225233. }
  225234. while (! triggered);
  225235. }
  225236. else
  225237. {
  225238. struct timeval now;
  225239. gettimeofday (&now, 0);
  225240. struct timespec time;
  225241. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225242. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225243. if (time.tv_nsec >= 1000000000)
  225244. {
  225245. time.tv_nsec -= 1000000000;
  225246. time.tv_sec++;
  225247. }
  225248. do
  225249. {
  225250. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225251. {
  225252. pthread_mutex_unlock (&mutex);
  225253. return false;
  225254. }
  225255. }
  225256. while (! triggered);
  225257. }
  225258. }
  225259. if (! manualReset)
  225260. triggered = false;
  225261. pthread_mutex_unlock (&mutex);
  225262. return true;
  225263. }
  225264. void signal() throw()
  225265. {
  225266. pthread_mutex_lock (&mutex);
  225267. triggered = true;
  225268. pthread_cond_broadcast (&condition);
  225269. pthread_mutex_unlock (&mutex);
  225270. }
  225271. void reset() throw()
  225272. {
  225273. pthread_mutex_lock (&mutex);
  225274. triggered = false;
  225275. pthread_mutex_unlock (&mutex);
  225276. }
  225277. private:
  225278. pthread_cond_t condition;
  225279. pthread_mutex_t mutex;
  225280. bool triggered;
  225281. const bool manualReset;
  225282. WaitableEventImpl (const WaitableEventImpl&);
  225283. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225284. };
  225285. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225286. : internal (new WaitableEventImpl (manualReset))
  225287. {
  225288. }
  225289. WaitableEvent::~WaitableEvent() throw()
  225290. {
  225291. delete static_cast <WaitableEventImpl*> (internal);
  225292. }
  225293. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225294. {
  225295. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225296. }
  225297. void WaitableEvent::signal() const throw()
  225298. {
  225299. static_cast <WaitableEventImpl*> (internal)->signal();
  225300. }
  225301. void WaitableEvent::reset() const throw()
  225302. {
  225303. static_cast <WaitableEventImpl*> (internal)->reset();
  225304. }
  225305. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225306. {
  225307. struct timespec time;
  225308. time.tv_sec = millisecs / 1000;
  225309. time.tv_nsec = (millisecs % 1000) * 1000000;
  225310. nanosleep (&time, 0);
  225311. }
  225312. const juce_wchar File::separator = '/';
  225313. const String File::separatorString ("/");
  225314. const File File::getCurrentWorkingDirectory()
  225315. {
  225316. HeapBlock<char> heapBuffer;
  225317. char localBuffer [1024];
  225318. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225319. int bufferSize = 4096;
  225320. while (cwd == 0 && errno == ERANGE)
  225321. {
  225322. heapBuffer.malloc (bufferSize);
  225323. cwd = getcwd (heapBuffer, bufferSize - 1);
  225324. bufferSize += 1024;
  225325. }
  225326. return File (String::fromUTF8 (cwd));
  225327. }
  225328. bool File::setAsCurrentWorkingDirectory() const
  225329. {
  225330. return chdir (getFullPathName().toUTF8()) == 0;
  225331. }
  225332. static bool juce_stat (const String& fileName, struct stat& info)
  225333. {
  225334. return fileName.isNotEmpty()
  225335. && (stat (fileName.toUTF8(), &info) == 0);
  225336. }
  225337. bool File::isDirectory() const
  225338. {
  225339. struct stat info;
  225340. return fullPath.isEmpty()
  225341. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225342. }
  225343. bool File::exists() const
  225344. {
  225345. return fullPath.isNotEmpty()
  225346. && access (fullPath.toUTF8(), F_OK) == 0;
  225347. }
  225348. bool File::existsAsFile() const
  225349. {
  225350. return exists() && ! isDirectory();
  225351. }
  225352. int64 File::getSize() const
  225353. {
  225354. struct stat info;
  225355. return juce_stat (fullPath, info) ? info.st_size : 0;
  225356. }
  225357. bool File::hasWriteAccess() const
  225358. {
  225359. if (exists())
  225360. return access (fullPath.toUTF8(), W_OK) == 0;
  225361. if ((! isDirectory()) && fullPath.containsChar (separator))
  225362. return getParentDirectory().hasWriteAccess();
  225363. return false;
  225364. }
  225365. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225366. {
  225367. struct stat info;
  225368. const int res = stat (fullPath.toUTF8(), &info);
  225369. if (res != 0)
  225370. return false;
  225371. info.st_mode &= 0777; // Just permissions
  225372. if (shouldBeReadOnly)
  225373. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225374. else
  225375. // Give everybody write permission?
  225376. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225377. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225378. }
  225379. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225380. {
  225381. modificationTime = 0;
  225382. accessTime = 0;
  225383. creationTime = 0;
  225384. struct stat info;
  225385. const int res = stat (fullPath.toUTF8(), &info);
  225386. if (res == 0)
  225387. {
  225388. modificationTime = (int64) info.st_mtime * 1000;
  225389. accessTime = (int64) info.st_atime * 1000;
  225390. creationTime = (int64) info.st_ctime * 1000;
  225391. }
  225392. }
  225393. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225394. {
  225395. struct utimbuf times;
  225396. times.actime = (time_t) (accessTime / 1000);
  225397. times.modtime = (time_t) (modificationTime / 1000);
  225398. return utime (fullPath.toUTF8(), &times) == 0;
  225399. }
  225400. bool File::deleteFile() const
  225401. {
  225402. if (! exists())
  225403. return true;
  225404. else if (isDirectory())
  225405. return rmdir (fullPath.toUTF8()) == 0;
  225406. else
  225407. return remove (fullPath.toUTF8()) == 0;
  225408. }
  225409. bool File::moveInternal (const File& dest) const
  225410. {
  225411. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225412. return true;
  225413. if (hasWriteAccess() && copyInternal (dest))
  225414. {
  225415. if (deleteFile())
  225416. return true;
  225417. dest.deleteFile();
  225418. }
  225419. return false;
  225420. }
  225421. void File::createDirectoryInternal (const String& fileName) const
  225422. {
  225423. mkdir (fileName.toUTF8(), 0777);
  225424. }
  225425. int64 juce_fileSetPosition (void* handle, int64 pos)
  225426. {
  225427. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225428. return pos;
  225429. return -1;
  225430. }
  225431. void FileInputStream::openHandle()
  225432. {
  225433. totalSize = file.getSize();
  225434. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225435. if (f != -1)
  225436. fileHandle = (void*) f;
  225437. }
  225438. void FileInputStream::closeHandle()
  225439. {
  225440. if (fileHandle != 0)
  225441. {
  225442. close ((int) (pointer_sized_int) fileHandle);
  225443. fileHandle = 0;
  225444. }
  225445. }
  225446. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225447. {
  225448. if (fileHandle != 0)
  225449. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225450. return 0;
  225451. }
  225452. void FileOutputStream::openHandle()
  225453. {
  225454. if (file.exists())
  225455. {
  225456. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225457. if (f != -1)
  225458. {
  225459. currentPosition = lseek (f, 0, SEEK_END);
  225460. if (currentPosition >= 0)
  225461. fileHandle = (void*) f;
  225462. else
  225463. close (f);
  225464. }
  225465. }
  225466. else
  225467. {
  225468. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225469. if (f != -1)
  225470. fileHandle = (void*) f;
  225471. }
  225472. }
  225473. void FileOutputStream::closeHandle()
  225474. {
  225475. if (fileHandle != 0)
  225476. {
  225477. close ((int) (pointer_sized_int) fileHandle);
  225478. fileHandle = 0;
  225479. }
  225480. }
  225481. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225482. {
  225483. if (fileHandle != 0)
  225484. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225485. return 0;
  225486. }
  225487. void FileOutputStream::flushInternal()
  225488. {
  225489. if (fileHandle != 0)
  225490. fsync ((int) (pointer_sized_int) fileHandle);
  225491. }
  225492. const File juce_getExecutableFile()
  225493. {
  225494. Dl_info exeInfo;
  225495. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225496. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225497. }
  225498. // if this file doesn't exist, find a parent of it that does..
  225499. static bool juce_doStatFS (File f, struct statfs& result)
  225500. {
  225501. for (int i = 5; --i >= 0;)
  225502. {
  225503. if (f.exists())
  225504. break;
  225505. f = f.getParentDirectory();
  225506. }
  225507. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225508. }
  225509. int64 File::getBytesFreeOnVolume() const
  225510. {
  225511. struct statfs buf;
  225512. if (juce_doStatFS (*this, buf))
  225513. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225514. return 0;
  225515. }
  225516. int64 File::getVolumeTotalSize() const
  225517. {
  225518. struct statfs buf;
  225519. if (juce_doStatFS (*this, buf))
  225520. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225521. return 0;
  225522. }
  225523. const String File::getVolumeLabel() const
  225524. {
  225525. #if JUCE_MAC
  225526. struct VolAttrBuf
  225527. {
  225528. u_int32_t length;
  225529. attrreference_t mountPointRef;
  225530. char mountPointSpace [MAXPATHLEN];
  225531. } attrBuf;
  225532. struct attrlist attrList;
  225533. zerostruct (attrList);
  225534. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225535. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225536. File f (*this);
  225537. for (;;)
  225538. {
  225539. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225540. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225541. (int) attrBuf.mountPointRef.attr_length);
  225542. const File parent (f.getParentDirectory());
  225543. if (f == parent)
  225544. break;
  225545. f = parent;
  225546. }
  225547. #endif
  225548. return String::empty;
  225549. }
  225550. int File::getVolumeSerialNumber() const
  225551. {
  225552. return 0; // xxx
  225553. }
  225554. void juce_runSystemCommand (const String& command)
  225555. {
  225556. int result = system (command.toUTF8());
  225557. (void) result;
  225558. }
  225559. const String juce_getOutputFromCommand (const String& command)
  225560. {
  225561. // slight bodge here, as we just pipe the output into a temp file and read it...
  225562. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225563. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225564. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225565. String result (tempFile.loadFileAsString());
  225566. tempFile.deleteFile();
  225567. return result;
  225568. }
  225569. class InterProcessLock::Pimpl
  225570. {
  225571. public:
  225572. Pimpl (const String& name, const int timeOutMillisecs)
  225573. : handle (0), refCount (1)
  225574. {
  225575. #if JUCE_MAC
  225576. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225577. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225578. #else
  225579. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225580. #endif
  225581. temp.create();
  225582. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225583. if (handle != 0)
  225584. {
  225585. struct flock fl;
  225586. zerostruct (fl);
  225587. fl.l_whence = SEEK_SET;
  225588. fl.l_type = F_WRLCK;
  225589. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225590. for (;;)
  225591. {
  225592. const int result = fcntl (handle, F_SETLK, &fl);
  225593. if (result >= 0)
  225594. return;
  225595. if (errno != EINTR)
  225596. {
  225597. if (timeOutMillisecs == 0
  225598. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225599. break;
  225600. Thread::sleep (10);
  225601. }
  225602. }
  225603. }
  225604. closeFile();
  225605. }
  225606. ~Pimpl()
  225607. {
  225608. closeFile();
  225609. }
  225610. void closeFile()
  225611. {
  225612. if (handle != 0)
  225613. {
  225614. struct flock fl;
  225615. zerostruct (fl);
  225616. fl.l_whence = SEEK_SET;
  225617. fl.l_type = F_UNLCK;
  225618. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225619. {}
  225620. close (handle);
  225621. handle = 0;
  225622. }
  225623. }
  225624. int handle, refCount;
  225625. };
  225626. InterProcessLock::InterProcessLock (const String& name_)
  225627. : name (name_)
  225628. {
  225629. }
  225630. InterProcessLock::~InterProcessLock()
  225631. {
  225632. }
  225633. bool InterProcessLock::enter (const int timeOutMillisecs)
  225634. {
  225635. const ScopedLock sl (lock);
  225636. if (pimpl == 0)
  225637. {
  225638. pimpl = new Pimpl (name, timeOutMillisecs);
  225639. if (pimpl->handle == 0)
  225640. pimpl = 0;
  225641. }
  225642. else
  225643. {
  225644. pimpl->refCount++;
  225645. }
  225646. return pimpl != 0;
  225647. }
  225648. void InterProcessLock::exit()
  225649. {
  225650. const ScopedLock sl (lock);
  225651. // Trying to release the lock too many times!
  225652. jassert (pimpl != 0);
  225653. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225654. pimpl = 0;
  225655. }
  225656. void JUCE_API juce_threadEntryPoint (void*);
  225657. void* threadEntryProc (void* userData)
  225658. {
  225659. JUCE_AUTORELEASEPOOL
  225660. juce_threadEntryPoint (userData);
  225661. return 0;
  225662. }
  225663. void* juce_createThread (void* userData)
  225664. {
  225665. pthread_t handle = 0;
  225666. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225667. {
  225668. pthread_detach (handle);
  225669. return (void*) handle;
  225670. }
  225671. return 0;
  225672. }
  225673. void juce_killThread (void* handle)
  225674. {
  225675. if (handle != 0)
  225676. pthread_cancel ((pthread_t) handle);
  225677. }
  225678. void juce_setCurrentThreadName (const String& /*name*/)
  225679. {
  225680. }
  225681. bool juce_setThreadPriority (void* handle, int priority)
  225682. {
  225683. struct sched_param param;
  225684. int policy;
  225685. priority = jlimit (0, 10, priority);
  225686. if (handle == 0)
  225687. handle = (void*) pthread_self();
  225688. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225689. return false;
  225690. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225691. const int minPriority = sched_get_priority_min (policy);
  225692. const int maxPriority = sched_get_priority_max (policy);
  225693. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225694. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225695. }
  225696. Thread::ThreadID Thread::getCurrentThreadId()
  225697. {
  225698. return (ThreadID) pthread_self();
  225699. }
  225700. void Thread::yield()
  225701. {
  225702. sched_yield();
  225703. }
  225704. /* Remove this macro if you're having problems compiling the cpu affinity
  225705. calls (the API for these has changed about quite a bit in various Linux
  225706. versions, and a lot of distros seem to ship with obsolete versions)
  225707. */
  225708. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225709. #define SUPPORT_AFFINITIES 1
  225710. #endif
  225711. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225712. {
  225713. #if SUPPORT_AFFINITIES
  225714. cpu_set_t affinity;
  225715. CPU_ZERO (&affinity);
  225716. for (int i = 0; i < 32; ++i)
  225717. if ((affinityMask & (1 << i)) != 0)
  225718. CPU_SET (i, &affinity);
  225719. /*
  225720. N.B. If this line causes a compile error, then you've probably not got the latest
  225721. version of glibc installed.
  225722. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225723. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225724. */
  225725. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225726. sched_yield();
  225727. #else
  225728. /* affinities aren't supported because either the appropriate header files weren't found,
  225729. or the SUPPORT_AFFINITIES macro was turned off
  225730. */
  225731. jassertfalse;
  225732. #endif
  225733. }
  225734. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225735. /*** Start of inlined file: juce_mac_Files.mm ***/
  225736. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225737. // compiled on its own).
  225738. #if JUCE_INCLUDED_FILE
  225739. /*
  225740. Note that a lot of methods that you'd expect to find in this file actually
  225741. live in juce_posix_SharedCode.h!
  225742. */
  225743. bool File::copyInternal (const File& dest) const
  225744. {
  225745. const ScopedAutoReleasePool pool;
  225746. NSFileManager* fm = [NSFileManager defaultManager];
  225747. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225748. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225749. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225750. toPath: juceStringToNS (dest.getFullPathName())
  225751. error: nil];
  225752. #else
  225753. && [fm copyPath: juceStringToNS (fullPath)
  225754. toPath: juceStringToNS (dest.getFullPathName())
  225755. handler: nil];
  225756. #endif
  225757. }
  225758. void File::findFileSystemRoots (Array<File>& destArray)
  225759. {
  225760. destArray.add (File ("/"));
  225761. }
  225762. static bool isFileOnDriveType (const File& f, const char* const* types)
  225763. {
  225764. struct statfs buf;
  225765. if (juce_doStatFS (f, buf))
  225766. {
  225767. const String type (buf.f_fstypename);
  225768. while (*types != 0)
  225769. if (type.equalsIgnoreCase (*types++))
  225770. return true;
  225771. }
  225772. return false;
  225773. }
  225774. bool File::isOnCDRomDrive() const
  225775. {
  225776. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225777. return isFileOnDriveType (*this, cdTypes);
  225778. }
  225779. bool File::isOnHardDisk() const
  225780. {
  225781. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225782. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225783. }
  225784. bool File::isOnRemovableDrive() const
  225785. {
  225786. #if JUCE_IOS
  225787. return false; // xxx is this possible?
  225788. #else
  225789. const ScopedAutoReleasePool pool;
  225790. BOOL removable = false;
  225791. [[NSWorkspace sharedWorkspace]
  225792. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225793. isRemovable: &removable
  225794. isWritable: nil
  225795. isUnmountable: nil
  225796. description: nil
  225797. type: nil];
  225798. return removable;
  225799. #endif
  225800. }
  225801. static bool juce_isHiddenFile (const String& path)
  225802. {
  225803. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225804. const ScopedAutoReleasePool pool;
  225805. NSNumber* hidden = nil;
  225806. NSError* err = nil;
  225807. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225808. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225809. && [hidden boolValue];
  225810. #else
  225811. #if JUCE_IOS
  225812. return File (path).getFileName().startsWithChar ('.');
  225813. #else
  225814. FSRef ref;
  225815. LSItemInfoRecord info;
  225816. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225817. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225818. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225819. #endif
  225820. #endif
  225821. }
  225822. bool File::isHidden() const
  225823. {
  225824. return juce_isHiddenFile (getFullPathName());
  225825. }
  225826. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225827. const File File::getSpecialLocation (const SpecialLocationType type)
  225828. {
  225829. const ScopedAutoReleasePool pool;
  225830. String resultPath;
  225831. switch (type)
  225832. {
  225833. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225834. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225835. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225836. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225837. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225838. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225839. case userMusicDirectory: resultPath = "~/Music"; break;
  225840. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225841. case tempDirectory:
  225842. {
  225843. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225844. tmp.createDirectory();
  225845. return tmp.getFullPathName();
  225846. }
  225847. case invokedExecutableFile:
  225848. if (juce_Argv0 != 0)
  225849. return File (String::fromUTF8 (juce_Argv0));
  225850. // deliberate fall-through...
  225851. case currentExecutableFile:
  225852. return juce_getExecutableFile();
  225853. case currentApplicationFile:
  225854. {
  225855. const File exe (juce_getExecutableFile());
  225856. const File parent (exe.getParentDirectory());
  225857. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225858. ? parent.getParentDirectory().getParentDirectory()
  225859. : exe;
  225860. }
  225861. case hostApplicationPath:
  225862. {
  225863. unsigned int size = 8192;
  225864. HeapBlock<char> buffer;
  225865. buffer.calloc (size + 8);
  225866. _NSGetExecutablePath (buffer.getData(), &size);
  225867. return String::fromUTF8 (buffer, size);
  225868. }
  225869. default:
  225870. jassertfalse; // unknown type?
  225871. break;
  225872. }
  225873. if (resultPath.isNotEmpty())
  225874. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225875. return File::nonexistent;
  225876. }
  225877. const String File::getVersion() const
  225878. {
  225879. const ScopedAutoReleasePool pool;
  225880. String result;
  225881. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225882. if (bundle != 0)
  225883. {
  225884. NSDictionary* info = [bundle infoDictionary];
  225885. if (info != 0)
  225886. {
  225887. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225888. if (name != nil)
  225889. result = nsStringToJuce (name);
  225890. }
  225891. }
  225892. return result;
  225893. }
  225894. const File File::getLinkedTarget() const
  225895. {
  225896. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225897. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225898. #else
  225899. // (the cast here avoids a deprecation warning)
  225900. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225901. #endif
  225902. if (dest != nil)
  225903. return File (nsStringToJuce (dest));
  225904. return *this;
  225905. }
  225906. bool File::moveToTrash() const
  225907. {
  225908. if (! exists())
  225909. return true;
  225910. #if JUCE_IOS
  225911. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225912. #else
  225913. const ScopedAutoReleasePool pool;
  225914. NSString* p = juceStringToNS (getFullPathName());
  225915. return [[NSWorkspace sharedWorkspace]
  225916. performFileOperation: NSWorkspaceRecycleOperation
  225917. source: [p stringByDeletingLastPathComponent]
  225918. destination: @""
  225919. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225920. tag: nil ];
  225921. #endif
  225922. }
  225923. class DirectoryIterator::NativeIterator::Pimpl
  225924. {
  225925. public:
  225926. Pimpl (const File& directory, const String& wildCard_)
  225927. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225928. wildCard (wildCard_),
  225929. enumerator (0)
  225930. {
  225931. const ScopedAutoReleasePool pool;
  225932. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225933. wildcardUTF8 = wildCard.toUTF8();
  225934. }
  225935. ~Pimpl()
  225936. {
  225937. [enumerator release];
  225938. }
  225939. bool next (String& filenameFound,
  225940. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225941. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225942. {
  225943. const ScopedAutoReleasePool pool;
  225944. for (;;)
  225945. {
  225946. NSString* file;
  225947. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225948. return false;
  225949. [enumerator skipDescendents];
  225950. filenameFound = nsStringToJuce (file);
  225951. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225952. continue;
  225953. const String path (parentDir + filenameFound);
  225954. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225955. {
  225956. struct stat info;
  225957. const bool statOk = juce_stat (path, info);
  225958. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225959. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225960. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225961. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225962. }
  225963. if (isHidden != 0)
  225964. *isHidden = juce_isHiddenFile (path);
  225965. if (isReadOnly != 0)
  225966. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225967. return true;
  225968. }
  225969. }
  225970. private:
  225971. String parentDir, wildCard;
  225972. const char* wildcardUTF8;
  225973. NSDirectoryEnumerator* enumerator;
  225974. Pimpl (const Pimpl&);
  225975. Pimpl& operator= (const Pimpl&);
  225976. };
  225977. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225978. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225979. {
  225980. }
  225981. DirectoryIterator::NativeIterator::~NativeIterator()
  225982. {
  225983. }
  225984. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225985. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225986. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225987. {
  225988. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225989. }
  225990. bool juce_launchExecutable (const String& pathAndArguments)
  225991. {
  225992. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225993. const int cpid = fork();
  225994. if (cpid == 0)
  225995. {
  225996. // Child process
  225997. if (execve (argv[0], (char**) argv, 0) < 0)
  225998. exit (0);
  225999. }
  226000. else
  226001. {
  226002. if (cpid < 0)
  226003. return false;
  226004. }
  226005. return true;
  226006. }
  226007. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  226008. {
  226009. #if JUCE_IOS
  226010. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  226011. #else
  226012. const ScopedAutoReleasePool pool;
  226013. if (parameters.isEmpty())
  226014. {
  226015. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  226016. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  226017. }
  226018. bool ok = false;
  226019. if (PlatformUtilities::isBundle (fileName))
  226020. {
  226021. NSMutableArray* urls = [NSMutableArray array];
  226022. StringArray docs;
  226023. docs.addTokens (parameters, true);
  226024. for (int i = 0; i < docs.size(); ++i)
  226025. [urls addObject: juceStringToNS (docs[i])];
  226026. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  226027. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  226028. options: 0
  226029. additionalEventParamDescriptor: nil
  226030. launchIdentifiers: nil];
  226031. }
  226032. else if (File (fileName).exists())
  226033. {
  226034. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  226035. }
  226036. return ok;
  226037. #endif
  226038. }
  226039. void File::revealToUser() const
  226040. {
  226041. #if ! JUCE_IOS
  226042. if (exists())
  226043. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  226044. else if (getParentDirectory().exists())
  226045. getParentDirectory().revealToUser();
  226046. #endif
  226047. }
  226048. #if ! JUCE_IOS
  226049. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  226050. {
  226051. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  226052. }
  226053. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  226054. {
  226055. char path [2048];
  226056. zerostruct (path);
  226057. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  226058. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  226059. return String::empty;
  226060. }
  226061. #endif
  226062. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  226063. {
  226064. const ScopedAutoReleasePool pool;
  226065. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  226066. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  226067. #else
  226068. // (the cast here avoids a deprecation warning)
  226069. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  226070. #endif
  226071. return [fileDict fileHFSTypeCode];
  226072. }
  226073. bool PlatformUtilities::isBundle (const String& filename)
  226074. {
  226075. #if JUCE_IOS
  226076. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  226077. #else
  226078. const ScopedAutoReleasePool pool;
  226079. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  226080. #endif
  226081. }
  226082. #endif
  226083. /*** End of inlined file: juce_mac_Files.mm ***/
  226084. #if JUCE_IOS
  226085. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  226086. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226087. // compiled on its own).
  226088. #if JUCE_INCLUDED_FILE
  226089. END_JUCE_NAMESPACE
  226090. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  226091. {
  226092. }
  226093. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  226094. - (void) applicationWillTerminate: (UIApplication*) application;
  226095. @end
  226096. @implementation JuceAppStartupDelegate
  226097. - (void) applicationDidFinishLaunching: (UIApplication*) application
  226098. {
  226099. initialiseJuce_GUI();
  226100. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  226101. exit (0);
  226102. }
  226103. - (void) applicationWillTerminate: (UIApplication*) application
  226104. {
  226105. jassert (JUCEApplication::getInstance() != 0);
  226106. JUCEApplication::getInstance()->shutdownApp();
  226107. delete JUCEApplication::getInstance();
  226108. shutdownJuce_GUI();
  226109. }
  226110. @end
  226111. BEGIN_JUCE_NAMESPACE
  226112. int juce_iOSMain (int argc, const char* argv[])
  226113. {
  226114. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  226115. }
  226116. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226117. {
  226118. pool = [[NSAutoreleasePool alloc] init];
  226119. }
  226120. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226121. {
  226122. [((NSAutoreleasePool*) pool) release];
  226123. }
  226124. void PlatformUtilities::beep()
  226125. {
  226126. //xxx
  226127. //AudioServicesPlaySystemSound ();
  226128. }
  226129. void PlatformUtilities::addItemToDock (const File& file)
  226130. {
  226131. }
  226132. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226133. END_JUCE_NAMESPACE
  226134. @interface JuceAlertBoxDelegate : NSObject
  226135. {
  226136. @public
  226137. bool clickedOk;
  226138. }
  226139. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  226140. @end
  226141. @implementation JuceAlertBoxDelegate
  226142. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  226143. {
  226144. clickedOk = (buttonIndex == 0);
  226145. alertView.hidden = true;
  226146. }
  226147. @end
  226148. BEGIN_JUCE_NAMESPACE
  226149. // (This function is used directly by other bits of code)
  226150. bool juce_iPhoneShowModalAlert (const String& title,
  226151. const String& bodyText,
  226152. NSString* okButtonText,
  226153. NSString* cancelButtonText)
  226154. {
  226155. const ScopedAutoReleasePool pool;
  226156. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  226157. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  226158. message: juceStringToNS (bodyText)
  226159. delegate: callback
  226160. cancelButtonTitle: okButtonText
  226161. otherButtonTitles: cancelButtonText, nil];
  226162. [alert retain];
  226163. [alert show];
  226164. while (! alert.hidden && alert.superview != nil)
  226165. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  226166. const bool result = callback->clickedOk;
  226167. [alert release];
  226168. [callback release];
  226169. return result;
  226170. }
  226171. bool AlertWindow::showNativeDialogBox (const String& title,
  226172. const String& bodyText,
  226173. bool isOkCancel)
  226174. {
  226175. return juce_iPhoneShowModalAlert (title, bodyText,
  226176. @"OK",
  226177. isOkCancel ? @"Cancel" : nil);
  226178. }
  226179. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  226180. {
  226181. jassertfalse; // no such thing on the iphone!
  226182. return false;
  226183. }
  226184. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  226185. {
  226186. jassertfalse; // no such thing on the iphone!
  226187. return false;
  226188. }
  226189. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226190. {
  226191. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  226192. }
  226193. bool Desktop::isScreenSaverEnabled()
  226194. {
  226195. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  226196. }
  226197. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  226198. {
  226199. const ScopedAutoReleasePool pool;
  226200. monitorCoords.clear();
  226201. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  226202. : [[UIScreen mainScreen] bounds];
  226203. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226204. (int) r.origin.y,
  226205. (int) r.size.width,
  226206. (int) r.size.height));
  226207. }
  226208. #endif
  226209. #endif
  226210. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  226211. #else
  226212. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  226213. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226214. // compiled on its own).
  226215. #if JUCE_INCLUDED_FILE
  226216. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226217. {
  226218. pool = [[NSAutoreleasePool alloc] init];
  226219. }
  226220. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226221. {
  226222. [((NSAutoreleasePool*) pool) release];
  226223. }
  226224. void PlatformUtilities::beep()
  226225. {
  226226. NSBeep();
  226227. }
  226228. void PlatformUtilities::addItemToDock (const File& file)
  226229. {
  226230. // check that it's not already there...
  226231. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226232. .containsIgnoreCase (file.getFullPathName()))
  226233. {
  226234. 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>"
  226235. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226236. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226237. }
  226238. }
  226239. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226240. bool AlertWindow::showNativeDialogBox (const String& title,
  226241. const String& bodyText,
  226242. bool isOkCancel)
  226243. {
  226244. const ScopedAutoReleasePool pool;
  226245. return NSRunAlertPanel (juceStringToNS (title),
  226246. juceStringToNS (bodyText),
  226247. @"Ok",
  226248. isOkCancel ? @"Cancel" : nil,
  226249. nil) == NSAlertDefaultReturn;
  226250. }
  226251. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226252. {
  226253. if (files.size() == 0)
  226254. return false;
  226255. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226256. if (draggingSource == 0)
  226257. {
  226258. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226259. return false;
  226260. }
  226261. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226262. if (sourceComp == 0)
  226263. {
  226264. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226265. return false;
  226266. }
  226267. const ScopedAutoReleasePool pool;
  226268. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226269. if (view == 0)
  226270. return false;
  226271. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226272. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226273. owner: nil];
  226274. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226275. for (int i = 0; i < files.size(); ++i)
  226276. [filesArray addObject: juceStringToNS (files[i])];
  226277. [pboard setPropertyList: filesArray
  226278. forType: NSFilenamesPboardType];
  226279. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226280. fromView: nil];
  226281. dragPosition.x -= 16;
  226282. dragPosition.y -= 16;
  226283. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226284. at: dragPosition
  226285. offset: NSMakeSize (0, 0)
  226286. event: [[view window] currentEvent]
  226287. pasteboard: pboard
  226288. source: view
  226289. slideBack: YES];
  226290. return true;
  226291. }
  226292. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226293. {
  226294. jassertfalse; // not implemented!
  226295. return false;
  226296. }
  226297. bool Desktop::canUseSemiTransparentWindows() throw()
  226298. {
  226299. return true;
  226300. }
  226301. const Point<int> Desktop::getMousePosition()
  226302. {
  226303. const ScopedAutoReleasePool pool;
  226304. const NSPoint p ([NSEvent mouseLocation]);
  226305. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226306. }
  226307. void Desktop::setMousePosition (const Point<int>& newPosition)
  226308. {
  226309. // this rubbish needs to be done around the warp call, to avoid causing a
  226310. // bizarre glitch..
  226311. CGAssociateMouseAndMouseCursorPosition (false);
  226312. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226313. CGAssociateMouseAndMouseCursorPosition (true);
  226314. }
  226315. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226316. class ScreenSaverDefeater : public Timer,
  226317. public DeletedAtShutdown
  226318. {
  226319. public:
  226320. ScreenSaverDefeater()
  226321. {
  226322. startTimer (10000);
  226323. timerCallback();
  226324. }
  226325. ~ScreenSaverDefeater() {}
  226326. void timerCallback()
  226327. {
  226328. if (Process::isForegroundProcess())
  226329. UpdateSystemActivity (UsrActivity);
  226330. }
  226331. };
  226332. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226333. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226334. {
  226335. if (isEnabled)
  226336. deleteAndZero (screenSaverDefeater);
  226337. else if (screenSaverDefeater == 0)
  226338. screenSaverDefeater = new ScreenSaverDefeater();
  226339. }
  226340. bool Desktop::isScreenSaverEnabled()
  226341. {
  226342. return screenSaverDefeater == 0;
  226343. }
  226344. #else
  226345. static IOPMAssertionID screenSaverDisablerID = 0;
  226346. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226347. {
  226348. if (isEnabled)
  226349. {
  226350. if (screenSaverDisablerID != 0)
  226351. {
  226352. IOPMAssertionRelease (screenSaverDisablerID);
  226353. screenSaverDisablerID = 0;
  226354. }
  226355. }
  226356. else
  226357. {
  226358. if (screenSaverDisablerID == 0)
  226359. {
  226360. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226361. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226362. CFSTR ("Juce"), &screenSaverDisablerID);
  226363. #else
  226364. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226365. &screenSaverDisablerID);
  226366. #endif
  226367. }
  226368. }
  226369. }
  226370. bool Desktop::isScreenSaverEnabled()
  226371. {
  226372. return screenSaverDisablerID == 0;
  226373. }
  226374. #endif
  226375. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226376. {
  226377. const ScopedAutoReleasePool pool;
  226378. monitorCoords.clear();
  226379. NSArray* screens = [NSScreen screens];
  226380. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226381. for (unsigned int i = 0; i < [screens count]; ++i)
  226382. {
  226383. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226384. NSRect r = clipToWorkArea ? [s visibleFrame]
  226385. : [s frame];
  226386. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226387. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  226388. (int) r.size.width,
  226389. (int) r.size.height));
  226390. }
  226391. jassert (monitorCoords.size() > 0);
  226392. }
  226393. #endif
  226394. #endif
  226395. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226396. #endif
  226397. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226398. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226399. // compiled on its own).
  226400. #if JUCE_INCLUDED_FILE
  226401. void Logger::outputDebugString (const String& text)
  226402. {
  226403. std::cerr << text << std::endl;
  226404. }
  226405. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  226406. {
  226407. static char testResult = 0;
  226408. if (testResult == 0)
  226409. {
  226410. struct kinfo_proc info;
  226411. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226412. size_t sz = sizeof (info);
  226413. sysctl (m, 4, &info, &sz, 0, 0);
  226414. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226415. }
  226416. return testResult > 0;
  226417. }
  226418. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226419. {
  226420. return juce_isRunningUnderDebugger();
  226421. }
  226422. #endif
  226423. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226424. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226425. #if JUCE_IOS
  226426. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226427. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226428. // compiled on its own).
  226429. #if JUCE_INCLUDED_FILE
  226430. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226431. #define SUPPORT_10_4_FONTS 1
  226432. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226433. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226434. #define SUPPORT_ONLY_10_4_FONTS 1
  226435. #endif
  226436. END_JUCE_NAMESPACE
  226437. @interface NSFont (PrivateHack)
  226438. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226439. @end
  226440. BEGIN_JUCE_NAMESPACE
  226441. #endif
  226442. class MacTypeface : public Typeface
  226443. {
  226444. public:
  226445. MacTypeface (const Font& font)
  226446. : Typeface (font.getTypefaceName())
  226447. {
  226448. const ScopedAutoReleasePool pool;
  226449. renderingTransform = CGAffineTransformIdentity;
  226450. bool needsItalicTransform = false;
  226451. #if JUCE_IOS
  226452. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226453. if (font.isItalic() || font.isBold())
  226454. {
  226455. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226456. for (NSString* i in familyFonts)
  226457. {
  226458. const String fn (nsStringToJuce (i));
  226459. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226460. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226461. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226462. || afterDash.containsIgnoreCase ("italic")
  226463. || fn.endsWithIgnoreCase ("oblique")
  226464. || fn.endsWithIgnoreCase ("italic");
  226465. if (probablyBold == font.isBold()
  226466. && probablyItalic == font.isItalic())
  226467. {
  226468. fontName = i;
  226469. needsItalicTransform = false;
  226470. break;
  226471. }
  226472. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226473. {
  226474. fontName = i;
  226475. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226476. }
  226477. }
  226478. if (needsItalicTransform)
  226479. renderingTransform.c = 0.15f;
  226480. }
  226481. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226482. const int ascender = abs (CGFontGetAscent (fontRef));
  226483. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226484. ascent = ascender / totalHeight;
  226485. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226486. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226487. #else
  226488. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226489. if (font.isItalic())
  226490. {
  226491. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226492. toHaveTrait: NSItalicFontMask];
  226493. if (newFont == nsFont)
  226494. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226495. nsFont = newFont;
  226496. }
  226497. if (font.isBold())
  226498. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226499. [nsFont retain];
  226500. ascent = std::abs ((float) [nsFont ascender]);
  226501. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226502. ascent /= totalSize;
  226503. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226504. if (needsItalicTransform)
  226505. {
  226506. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226507. renderingTransform.c = 0.15f;
  226508. }
  226509. #if SUPPORT_ONLY_10_4_FONTS
  226510. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226511. if (atsFont == 0)
  226512. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226513. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226514. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226515. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226516. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226517. #else
  226518. #if SUPPORT_10_4_FONTS
  226519. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226520. {
  226521. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226522. if (atsFont == 0)
  226523. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226524. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226525. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226526. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226527. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226528. }
  226529. else
  226530. #endif
  226531. {
  226532. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226533. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226534. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226535. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226536. }
  226537. #endif
  226538. #endif
  226539. }
  226540. ~MacTypeface()
  226541. {
  226542. #if ! JUCE_IOS
  226543. [nsFont release];
  226544. #endif
  226545. if (fontRef != 0)
  226546. CGFontRelease (fontRef);
  226547. }
  226548. float getAscent() const
  226549. {
  226550. return ascent;
  226551. }
  226552. float getDescent() const
  226553. {
  226554. return 1.0f - ascent;
  226555. }
  226556. float getStringWidth (const String& text)
  226557. {
  226558. if (fontRef == 0 || text.isEmpty())
  226559. return 0;
  226560. const int length = text.length();
  226561. HeapBlock <CGGlyph> glyphs;
  226562. createGlyphsForString (text, length, glyphs);
  226563. float x = 0;
  226564. #if SUPPORT_ONLY_10_4_FONTS
  226565. HeapBlock <NSSize> advances (length);
  226566. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226567. for (int i = 0; i < length; ++i)
  226568. x += advances[i].width;
  226569. #else
  226570. #if SUPPORT_10_4_FONTS
  226571. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226572. {
  226573. HeapBlock <NSSize> advances (length);
  226574. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226575. for (int i = 0; i < length; ++i)
  226576. x += advances[i].width;
  226577. }
  226578. else
  226579. #endif
  226580. {
  226581. HeapBlock <int> advances (length);
  226582. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226583. for (int i = 0; i < length; ++i)
  226584. x += advances[i];
  226585. }
  226586. #endif
  226587. return x * unitsToHeightScaleFactor;
  226588. }
  226589. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226590. {
  226591. xOffsets.add (0);
  226592. if (fontRef == 0 || text.isEmpty())
  226593. return;
  226594. const int length = text.length();
  226595. HeapBlock <CGGlyph> glyphs;
  226596. createGlyphsForString (text, length, glyphs);
  226597. #if SUPPORT_ONLY_10_4_FONTS
  226598. HeapBlock <NSSize> advances (length);
  226599. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226600. int x = 0;
  226601. for (int i = 0; i < length; ++i)
  226602. {
  226603. x += advances[i].width;
  226604. xOffsets.add (x * unitsToHeightScaleFactor);
  226605. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226606. }
  226607. #else
  226608. #if SUPPORT_10_4_FONTS
  226609. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226610. {
  226611. HeapBlock <NSSize> advances (length);
  226612. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226613. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226614. float x = 0;
  226615. for (int i = 0; i < length; ++i)
  226616. {
  226617. x += advances[i].width;
  226618. xOffsets.add (x * unitsToHeightScaleFactor);
  226619. resultGlyphs.add (nsGlyphs[i]);
  226620. }
  226621. }
  226622. else
  226623. #endif
  226624. {
  226625. HeapBlock <int> advances (length);
  226626. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226627. {
  226628. int x = 0;
  226629. for (int i = 0; i < length; ++i)
  226630. {
  226631. x += advances [i];
  226632. xOffsets.add (x * unitsToHeightScaleFactor);
  226633. resultGlyphs.add (glyphs[i]);
  226634. }
  226635. }
  226636. }
  226637. #endif
  226638. }
  226639. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226640. {
  226641. #if JUCE_IOS
  226642. return false;
  226643. #else
  226644. if (nsFont == 0)
  226645. return false;
  226646. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226647. jassert (path.isEmpty());
  226648. const ScopedAutoReleasePool pool;
  226649. NSBezierPath* bez = [NSBezierPath bezierPath];
  226650. [bez moveToPoint: NSMakePoint (0, 0)];
  226651. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226652. inFont: nsFont];
  226653. for (int i = 0; i < [bez elementCount]; ++i)
  226654. {
  226655. NSPoint p[3];
  226656. switch ([bez elementAtIndex: i associatedPoints: p])
  226657. {
  226658. case NSMoveToBezierPathElement:
  226659. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226660. break;
  226661. case NSLineToBezierPathElement:
  226662. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226663. break;
  226664. case NSCurveToBezierPathElement:
  226665. 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);
  226666. break;
  226667. case NSClosePathBezierPathElement:
  226668. path.closeSubPath();
  226669. break;
  226670. default:
  226671. jassertfalse;
  226672. break;
  226673. }
  226674. }
  226675. path.applyTransform (pathTransform);
  226676. return true;
  226677. #endif
  226678. }
  226679. juce_UseDebuggingNewOperator
  226680. CGFontRef fontRef;
  226681. float fontHeightToCGSizeFactor;
  226682. CGAffineTransform renderingTransform;
  226683. private:
  226684. float ascent, unitsToHeightScaleFactor;
  226685. #if JUCE_IOS
  226686. #else
  226687. NSFont* nsFont;
  226688. AffineTransform pathTransform;
  226689. #endif
  226690. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226691. {
  226692. #if SUPPORT_10_4_FONTS
  226693. #if ! SUPPORT_ONLY_10_4_FONTS
  226694. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226695. #endif
  226696. {
  226697. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226698. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226699. for (int i = 0; i < length; ++i)
  226700. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226701. return;
  226702. }
  226703. #endif
  226704. #if ! SUPPORT_ONLY_10_4_FONTS
  226705. if (charToGlyphMapper == 0)
  226706. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226707. glyphs.malloc (length);
  226708. for (int i = 0; i < length; ++i)
  226709. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226710. #endif
  226711. }
  226712. #if ! SUPPORT_ONLY_10_4_FONTS
  226713. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226714. class CharToGlyphMapper
  226715. {
  226716. public:
  226717. CharToGlyphMapper (CGFontRef fontRef)
  226718. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226719. idRangeOffset (0), glyphIndexes (0)
  226720. {
  226721. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226722. if (cmapTable != 0)
  226723. {
  226724. const int numSubtables = getValue16 (cmapTable, 2);
  226725. for (int i = 0; i < numSubtables; ++i)
  226726. {
  226727. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226728. {
  226729. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226730. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226731. {
  226732. const int length = getValue16 (cmapTable, offset + 2);
  226733. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226734. segCount = segCountX2 / 2;
  226735. const int endCodeOffset = offset + 14;
  226736. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226737. const int idDeltaOffset = startCodeOffset + segCountX2;
  226738. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226739. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226740. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226741. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226742. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226743. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226744. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226745. }
  226746. break;
  226747. }
  226748. }
  226749. CFRelease (cmapTable);
  226750. }
  226751. }
  226752. ~CharToGlyphMapper()
  226753. {
  226754. if (endCode != 0)
  226755. {
  226756. CFRelease (endCode);
  226757. CFRelease (startCode);
  226758. CFRelease (idDelta);
  226759. CFRelease (idRangeOffset);
  226760. CFRelease (glyphIndexes);
  226761. }
  226762. }
  226763. int getGlyphForCharacter (const juce_wchar c) const
  226764. {
  226765. for (int i = 0; i < segCount; ++i)
  226766. {
  226767. if (getValue16 (endCode, i * 2) >= c)
  226768. {
  226769. const int start = getValue16 (startCode, i * 2);
  226770. if (start > c)
  226771. break;
  226772. const int delta = getValue16 (idDelta, i * 2);
  226773. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226774. if (rangeOffset == 0)
  226775. return delta + c;
  226776. else
  226777. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226778. }
  226779. }
  226780. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226781. return jmax (-1, c - 29);
  226782. }
  226783. private:
  226784. int segCount;
  226785. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226786. static uint16 getValue16 (CFDataRef data, const int index)
  226787. {
  226788. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226789. }
  226790. static uint32 getValue32 (CFDataRef data, const int index)
  226791. {
  226792. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226793. }
  226794. };
  226795. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226796. #endif
  226797. MacTypeface (const MacTypeface&);
  226798. MacTypeface& operator= (const MacTypeface&);
  226799. };
  226800. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226801. {
  226802. return new MacTypeface (font);
  226803. }
  226804. const StringArray Font::findAllTypefaceNames()
  226805. {
  226806. StringArray names;
  226807. const ScopedAutoReleasePool pool;
  226808. #if JUCE_IOS
  226809. NSArray* fonts = [UIFont familyNames];
  226810. #else
  226811. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226812. #endif
  226813. for (unsigned int i = 0; i < [fonts count]; ++i)
  226814. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226815. names.sort (true);
  226816. return names;
  226817. }
  226818. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226819. {
  226820. #if JUCE_IOS
  226821. defaultSans = "Helvetica";
  226822. defaultSerif = "Times New Roman";
  226823. defaultFixed = "Courier New";
  226824. #else
  226825. defaultSans = "Lucida Grande";
  226826. defaultSerif = "Times New Roman";
  226827. defaultFixed = "Monaco";
  226828. #endif
  226829. }
  226830. #endif
  226831. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226832. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226833. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226834. // compiled on its own).
  226835. #if JUCE_INCLUDED_FILE
  226836. class CoreGraphicsImage : public Image::SharedImage
  226837. {
  226838. public:
  226839. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226840. : Image::SharedImage (format_, width_, height_)
  226841. {
  226842. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226843. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226844. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226845. imageData = imageDataAllocated;
  226846. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226847. : CGColorSpaceCreateDeviceRGB();
  226848. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226849. colourSpace, getCGImageFlags (format_));
  226850. CGColorSpaceRelease (colourSpace);
  226851. }
  226852. ~CoreGraphicsImage()
  226853. {
  226854. CGContextRelease (context);
  226855. }
  226856. Image::ImageType getType() const { return Image::NativeImage; }
  226857. LowLevelGraphicsContext* createLowLevelContext();
  226858. SharedImage* clone()
  226859. {
  226860. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226861. memcpy (im->imageData, imageData, lineStride * height);
  226862. return im;
  226863. }
  226864. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226865. {
  226866. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226867. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226868. {
  226869. return CGBitmapContextCreateImage (nativeImage->context);
  226870. }
  226871. else
  226872. {
  226873. const Image::BitmapData srcData (juceImage, false);
  226874. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226875. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226876. 8, srcData.pixelStride * 8, srcData.lineStride,
  226877. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226878. 0, true, kCGRenderingIntentDefault);
  226879. CGDataProviderRelease (provider);
  226880. return imageRef;
  226881. }
  226882. }
  226883. #if JUCE_MAC
  226884. static NSImage* createNSImage (const Image& image)
  226885. {
  226886. const ScopedAutoReleasePool pool;
  226887. NSImage* im = [[NSImage alloc] init];
  226888. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226889. [im lockFocus];
  226890. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226891. CGImageRef imageRef = createImage (image, false, colourSpace);
  226892. CGColorSpaceRelease (colourSpace);
  226893. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226894. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226895. CGImageRelease (imageRef);
  226896. [im unlockFocus];
  226897. return im;
  226898. }
  226899. #endif
  226900. CGContextRef context;
  226901. HeapBlock<uint8> imageDataAllocated;
  226902. private:
  226903. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226904. {
  226905. #if JUCE_BIG_ENDIAN
  226906. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226907. #else
  226908. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226909. #endif
  226910. }
  226911. };
  226912. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226913. {
  226914. #if USE_COREGRAPHICS_RENDERING
  226915. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226916. #else
  226917. return createSoftwareImage (format, width, height, clearImage);
  226918. #endif
  226919. }
  226920. class CoreGraphicsContext : public LowLevelGraphicsContext
  226921. {
  226922. public:
  226923. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226924. : context (context_),
  226925. flipHeight (flipHeight_),
  226926. state (new SavedState()),
  226927. numGradientLookupEntries (0),
  226928. lastClipRectIsValid (false)
  226929. {
  226930. CGContextRetain (context);
  226931. CGContextSaveGState(context);
  226932. CGContextSetShouldSmoothFonts (context, true);
  226933. CGContextSetShouldAntialias (context, true);
  226934. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226935. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226936. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226937. gradientCallbacks.version = 0;
  226938. gradientCallbacks.evaluate = gradientCallback;
  226939. gradientCallbacks.releaseInfo = 0;
  226940. setFont (Font());
  226941. }
  226942. ~CoreGraphicsContext()
  226943. {
  226944. CGContextRestoreGState (context);
  226945. CGContextRelease (context);
  226946. CGColorSpaceRelease (rgbColourSpace);
  226947. CGColorSpaceRelease (greyColourSpace);
  226948. }
  226949. bool isVectorDevice() const { return false; }
  226950. void setOrigin (int x, int y)
  226951. {
  226952. CGContextTranslateCTM (context, x, -y);
  226953. if (lastClipRectIsValid)
  226954. lastClipRect.translate (-x, -y);
  226955. }
  226956. bool clipToRectangle (const Rectangle<int>& r)
  226957. {
  226958. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226959. if (lastClipRectIsValid)
  226960. {
  226961. // This is actually incorrect, because the actual clip region may be complex, and
  226962. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226963. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226964. // when calculating the resultant clip bounds, and makes the same mistake!
  226965. lastClipRect = lastClipRect.getIntersection (r);
  226966. return ! lastClipRect.isEmpty();
  226967. }
  226968. return ! isClipEmpty();
  226969. }
  226970. bool clipToRectangleList (const RectangleList& clipRegion)
  226971. {
  226972. if (clipRegion.isEmpty())
  226973. {
  226974. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226975. lastClipRectIsValid = true;
  226976. lastClipRect = Rectangle<int>();
  226977. return false;
  226978. }
  226979. else
  226980. {
  226981. const int numRects = clipRegion.getNumRectangles();
  226982. HeapBlock <CGRect> rects (numRects);
  226983. for (int i = 0; i < numRects; ++i)
  226984. {
  226985. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226986. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226987. }
  226988. CGContextClipToRects (context, rects, numRects);
  226989. lastClipRectIsValid = false;
  226990. return ! isClipEmpty();
  226991. }
  226992. }
  226993. void excludeClipRectangle (const Rectangle<int>& r)
  226994. {
  226995. RectangleList remaining (getClipBounds());
  226996. remaining.subtract (r);
  226997. clipToRectangleList (remaining);
  226998. lastClipRectIsValid = false;
  226999. }
  227000. void clipToPath (const Path& path, const AffineTransform& transform)
  227001. {
  227002. createPath (path, transform);
  227003. CGContextClip (context);
  227004. lastClipRectIsValid = false;
  227005. }
  227006. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  227007. {
  227008. if (! transform.isSingularity())
  227009. {
  227010. Image singleChannelImage (sourceImage);
  227011. if (sourceImage.getFormat() != Image::SingleChannel)
  227012. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  227013. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  227014. flip();
  227015. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  227016. applyTransform (t);
  227017. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  227018. CGContextClipToMask (context, r, image);
  227019. applyTransform (t.inverted());
  227020. flip();
  227021. CGImageRelease (image);
  227022. lastClipRectIsValid = false;
  227023. }
  227024. }
  227025. bool clipRegionIntersects (const Rectangle<int>& r)
  227026. {
  227027. return getClipBounds().intersects (r);
  227028. }
  227029. const Rectangle<int> getClipBounds() const
  227030. {
  227031. if (! lastClipRectIsValid)
  227032. {
  227033. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227034. lastClipRectIsValid = true;
  227035. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  227036. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  227037. roundToInt (bounds.size.width),
  227038. roundToInt (bounds.size.height));
  227039. }
  227040. return lastClipRect;
  227041. }
  227042. bool isClipEmpty() const
  227043. {
  227044. return getClipBounds().isEmpty();
  227045. }
  227046. void saveState()
  227047. {
  227048. CGContextSaveGState (context);
  227049. stateStack.add (new SavedState (*state));
  227050. }
  227051. void restoreState()
  227052. {
  227053. CGContextRestoreGState (context);
  227054. SavedState* const top = stateStack.getLast();
  227055. if (top != 0)
  227056. {
  227057. state = top;
  227058. stateStack.removeLast (1, false);
  227059. lastClipRectIsValid = false;
  227060. }
  227061. else
  227062. {
  227063. jassertfalse; // trying to pop with an empty stack!
  227064. }
  227065. }
  227066. void setFill (const FillType& fillType)
  227067. {
  227068. state->fillType = fillType;
  227069. if (fillType.isColour())
  227070. {
  227071. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  227072. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  227073. CGContextSetAlpha (context, 1.0f);
  227074. }
  227075. }
  227076. void setOpacity (float newOpacity)
  227077. {
  227078. state->fillType.setOpacity (newOpacity);
  227079. setFill (state->fillType);
  227080. }
  227081. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  227082. {
  227083. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  227084. ? kCGInterpolationLow
  227085. : kCGInterpolationHigh);
  227086. }
  227087. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  227088. {
  227089. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  227090. }
  227091. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  227092. {
  227093. if (replaceExistingContents)
  227094. {
  227095. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  227096. CGContextClearRect (context, cgRect);
  227097. #else
  227098. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227099. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  227100. CGContextClearRect (context, cgRect);
  227101. else
  227102. #endif
  227103. CGContextSetBlendMode (context, kCGBlendModeCopy);
  227104. #endif
  227105. fillCGRect (cgRect, false);
  227106. CGContextSetBlendMode (context, kCGBlendModeNormal);
  227107. }
  227108. else
  227109. {
  227110. if (state->fillType.isColour())
  227111. {
  227112. CGContextFillRect (context, cgRect);
  227113. }
  227114. else if (state->fillType.isGradient())
  227115. {
  227116. CGContextSaveGState (context);
  227117. CGContextClipToRect (context, cgRect);
  227118. drawGradient();
  227119. CGContextRestoreGState (context);
  227120. }
  227121. else
  227122. {
  227123. CGContextSaveGState (context);
  227124. CGContextClipToRect (context, cgRect);
  227125. drawImage (state->fillType.image, state->fillType.transform, true);
  227126. CGContextRestoreGState (context);
  227127. }
  227128. }
  227129. }
  227130. void fillPath (const Path& path, const AffineTransform& transform)
  227131. {
  227132. CGContextSaveGState (context);
  227133. if (state->fillType.isColour())
  227134. {
  227135. flip();
  227136. applyTransform (transform);
  227137. createPath (path);
  227138. if (path.isUsingNonZeroWinding())
  227139. CGContextFillPath (context);
  227140. else
  227141. CGContextEOFillPath (context);
  227142. }
  227143. else
  227144. {
  227145. createPath (path, transform);
  227146. if (path.isUsingNonZeroWinding())
  227147. CGContextClip (context);
  227148. else
  227149. CGContextEOClip (context);
  227150. if (state->fillType.isGradient())
  227151. drawGradient();
  227152. else
  227153. drawImage (state->fillType.image, state->fillType.transform, true);
  227154. }
  227155. CGContextRestoreGState (context);
  227156. }
  227157. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  227158. {
  227159. const int iw = sourceImage.getWidth();
  227160. const int ih = sourceImage.getHeight();
  227161. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  227162. CGContextSaveGState (context);
  227163. CGContextSetAlpha (context, state->fillType.getOpacity());
  227164. flip();
  227165. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  227166. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  227167. if (fillEntireClipAsTiles)
  227168. {
  227169. #if JUCE_IOS
  227170. CGContextDrawTiledImage (context, imageRect, image);
  227171. #else
  227172. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  227173. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  227174. // if it's doing a transformation - it's quicker to just draw lots of images manually
  227175. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  227176. CGContextDrawTiledImage (context, imageRect, image);
  227177. else
  227178. #endif
  227179. {
  227180. // Fallback to manually doing a tiled fill on 10.4
  227181. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227182. int x = 0, y = 0;
  227183. while (x > clip.origin.x) x -= iw;
  227184. while (y > clip.origin.y) y -= ih;
  227185. const int right = (int) (clip.origin.x + clip.size.width);
  227186. const int bottom = (int) (clip.origin.y + clip.size.height);
  227187. while (y < bottom)
  227188. {
  227189. for (int x2 = x; x2 < right; x2 += iw)
  227190. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227191. y += ih;
  227192. }
  227193. }
  227194. #endif
  227195. }
  227196. else
  227197. {
  227198. CGContextDrawImage (context, imageRect, image);
  227199. }
  227200. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227201. CGContextRestoreGState (context);
  227202. }
  227203. void drawLine (const Line<float>& line)
  227204. {
  227205. if (state->fillType.isColour())
  227206. {
  227207. CGContextSetLineCap (context, kCGLineCapSquare);
  227208. CGContextSetLineWidth (context, 1.0f);
  227209. CGContextSetRGBStrokeColor (context,
  227210. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227211. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227212. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  227213. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  227214. CGContextStrokeLineSegments (context, cgLine, 1);
  227215. }
  227216. else
  227217. {
  227218. Path p;
  227219. p.addLineSegment (line, 1.0f);
  227220. fillPath (p, AffineTransform::identity);
  227221. }
  227222. }
  227223. void drawVerticalLine (const int x, float top, float bottom)
  227224. {
  227225. if (state->fillType.isColour())
  227226. {
  227227. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227228. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227229. #else
  227230. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227231. // the x co-ord slightly to trick it..
  227232. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227233. #endif
  227234. }
  227235. else
  227236. {
  227237. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227238. }
  227239. }
  227240. void drawHorizontalLine (const int y, float left, float right)
  227241. {
  227242. if (state->fillType.isColour())
  227243. {
  227244. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227245. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227246. #else
  227247. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227248. // the x co-ord slightly to trick it..
  227249. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227250. #endif
  227251. }
  227252. else
  227253. {
  227254. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227255. }
  227256. }
  227257. void setFont (const Font& newFont)
  227258. {
  227259. if (state->font != newFont)
  227260. {
  227261. state->fontRef = 0;
  227262. state->font = newFont;
  227263. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227264. if (mf != 0)
  227265. {
  227266. state->fontRef = mf->fontRef;
  227267. CGContextSetFont (context, state->fontRef);
  227268. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227269. state->fontTransform = mf->renderingTransform;
  227270. state->fontTransform.a *= state->font.getHorizontalScale();
  227271. CGContextSetTextMatrix (context, state->fontTransform);
  227272. }
  227273. }
  227274. }
  227275. const Font getFont()
  227276. {
  227277. return state->font;
  227278. }
  227279. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227280. {
  227281. if (state->fontRef != 0 && state->fillType.isColour())
  227282. {
  227283. if (transform.isOnlyTranslation())
  227284. {
  227285. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227286. CGGlyph g = glyphNumber;
  227287. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227288. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227289. }
  227290. else
  227291. {
  227292. CGContextSaveGState (context);
  227293. flip();
  227294. applyTransform (transform);
  227295. CGAffineTransform t = state->fontTransform;
  227296. t.d = -t.d;
  227297. CGContextSetTextMatrix (context, t);
  227298. CGGlyph g = glyphNumber;
  227299. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227300. CGContextRestoreGState (context);
  227301. }
  227302. }
  227303. else
  227304. {
  227305. Path p;
  227306. Font& f = state->font;
  227307. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227308. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227309. .followedBy (transform));
  227310. }
  227311. }
  227312. private:
  227313. CGContextRef context;
  227314. const CGFloat flipHeight;
  227315. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227316. CGFunctionCallbacks gradientCallbacks;
  227317. mutable Rectangle<int> lastClipRect;
  227318. mutable bool lastClipRectIsValid;
  227319. struct SavedState
  227320. {
  227321. SavedState()
  227322. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227323. {
  227324. }
  227325. SavedState (const SavedState& other)
  227326. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227327. fontTransform (other.fontTransform)
  227328. {
  227329. }
  227330. ~SavedState()
  227331. {
  227332. }
  227333. FillType fillType;
  227334. Font font;
  227335. CGFontRef fontRef;
  227336. CGAffineTransform fontTransform;
  227337. };
  227338. ScopedPointer <SavedState> state;
  227339. OwnedArray <SavedState> stateStack;
  227340. HeapBlock <PixelARGB> gradientLookupTable;
  227341. int numGradientLookupEntries;
  227342. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227343. {
  227344. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227345. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227346. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227347. colour.unpremultiply();
  227348. outData[0] = colour.getRed() / 255.0f;
  227349. outData[1] = colour.getGreen() / 255.0f;
  227350. outData[2] = colour.getBlue() / 255.0f;
  227351. outData[3] = colour.getAlpha() / 255.0f;
  227352. }
  227353. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227354. {
  227355. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227356. --numGradientLookupEntries;
  227357. CGShadingRef result = 0;
  227358. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227359. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227360. if (gradient.isRadial)
  227361. {
  227362. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227363. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227364. function, true, true);
  227365. }
  227366. else
  227367. {
  227368. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227369. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227370. function, true, true);
  227371. }
  227372. CGFunctionRelease (function);
  227373. return result;
  227374. }
  227375. void drawGradient()
  227376. {
  227377. flip();
  227378. applyTransform (state->fillType.transform);
  227379. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227380. // you draw a gradient with high quality interp enabled).
  227381. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227382. CGContextSetAlpha (context, state->fillType.getOpacity());
  227383. CGContextDrawShading (context, shading);
  227384. CGShadingRelease (shading);
  227385. }
  227386. void createPath (const Path& path) const
  227387. {
  227388. CGContextBeginPath (context);
  227389. Path::Iterator i (path);
  227390. while (i.next())
  227391. {
  227392. switch (i.elementType)
  227393. {
  227394. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227395. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227396. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227397. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227398. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227399. default: jassertfalse; break;
  227400. }
  227401. }
  227402. }
  227403. void createPath (const Path& path, const AffineTransform& transform) const
  227404. {
  227405. CGContextBeginPath (context);
  227406. Path::Iterator i (path);
  227407. while (i.next())
  227408. {
  227409. switch (i.elementType)
  227410. {
  227411. case Path::Iterator::startNewSubPath:
  227412. transform.transformPoint (i.x1, i.y1);
  227413. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227414. break;
  227415. case Path::Iterator::lineTo:
  227416. transform.transformPoint (i.x1, i.y1);
  227417. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227418. break;
  227419. case Path::Iterator::quadraticTo:
  227420. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227421. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227422. break;
  227423. case Path::Iterator::cubicTo:
  227424. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227425. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227426. break;
  227427. case Path::Iterator::closePath:
  227428. CGContextClosePath (context); break;
  227429. default:
  227430. jassertfalse;
  227431. break;
  227432. }
  227433. }
  227434. }
  227435. void flip() const
  227436. {
  227437. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227438. }
  227439. void applyTransform (const AffineTransform& transform) const
  227440. {
  227441. CGAffineTransform t;
  227442. t.a = transform.mat00;
  227443. t.b = transform.mat10;
  227444. t.c = transform.mat01;
  227445. t.d = transform.mat11;
  227446. t.tx = transform.mat02;
  227447. t.ty = transform.mat12;
  227448. CGContextConcatCTM (context, t);
  227449. }
  227450. CoreGraphicsContext (const CoreGraphicsContext&);
  227451. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227452. };
  227453. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227454. {
  227455. return new CoreGraphicsContext (context, height);
  227456. }
  227457. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227458. const Image juce_loadWithCoreImage (InputStream& input)
  227459. {
  227460. MemoryBlock data;
  227461. input.readIntoMemoryBlock (data, -1);
  227462. #if JUCE_IOS
  227463. JUCE_AUTORELEASEPOOL
  227464. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData() length: data.getSize()]];
  227465. if (image != nil)
  227466. {
  227467. CGImageRef loadedImage = image.CGImage;
  227468. #else
  227469. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227470. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227471. CGDataProviderRelease (provider);
  227472. if (imageSource != 0)
  227473. {
  227474. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227475. CFRelease (imageSource);
  227476. #endif
  227477. if (loadedImage != 0)
  227478. {
  227479. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  227480. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  227481. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227482. hasAlphaChan, Image::NativeImage);
  227483. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227484. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227485. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227486. CGContextFlush (cgImage->context);
  227487. #if ! JUCE_IOS
  227488. CFRelease (loadedImage);
  227489. #endif
  227490. return image;
  227491. }
  227492. }
  227493. return Image::null;
  227494. }
  227495. #endif
  227496. #endif
  227497. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227498. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227499. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227500. // compiled on its own).
  227501. #if JUCE_INCLUDED_FILE
  227502. class UIViewComponentPeer;
  227503. END_JUCE_NAMESPACE
  227504. #define JuceUIView MakeObjCClassName(JuceUIView)
  227505. @interface JuceUIView : UIView <UITextViewDelegate>
  227506. {
  227507. @public
  227508. UIViewComponentPeer* owner;
  227509. UITextView* hiddenTextView;
  227510. }
  227511. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227512. - (void) dealloc;
  227513. - (void) drawRect: (CGRect) r;
  227514. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227515. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227516. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227517. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227518. - (BOOL) becomeFirstResponder;
  227519. - (BOOL) resignFirstResponder;
  227520. - (BOOL) canBecomeFirstResponder;
  227521. - (void) asyncRepaint: (id) rect;
  227522. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227523. @end
  227524. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227525. @interface JuceUIWindow : UIWindow
  227526. {
  227527. @private
  227528. UIViewComponentPeer* owner;
  227529. bool isZooming;
  227530. }
  227531. - (void) setOwner: (UIViewComponentPeer*) owner;
  227532. - (void) becomeKeyWindow;
  227533. @end
  227534. BEGIN_JUCE_NAMESPACE
  227535. class UIViewComponentPeer : public ComponentPeer,
  227536. public FocusChangeListener
  227537. {
  227538. public:
  227539. UIViewComponentPeer (Component* const component,
  227540. const int windowStyleFlags,
  227541. UIView* viewToAttachTo);
  227542. ~UIViewComponentPeer();
  227543. void* getNativeHandle() const;
  227544. void setVisible (bool shouldBeVisible);
  227545. void setTitle (const String& title);
  227546. void setPosition (int x, int y);
  227547. void setSize (int w, int h);
  227548. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227549. const Rectangle<int> getBounds() const;
  227550. const Rectangle<int> getBounds (const bool global) const;
  227551. const Point<int> getScreenPosition() const;
  227552. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227553. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227554. void setMinimised (bool shouldBeMinimised);
  227555. bool isMinimised() const;
  227556. void setFullScreen (bool shouldBeFullScreen);
  227557. bool isFullScreen() const;
  227558. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227559. const BorderSize getFrameSize() const;
  227560. bool setAlwaysOnTop (bool alwaysOnTop);
  227561. void toFront (bool makeActiveWindow);
  227562. void toBehind (ComponentPeer* other);
  227563. void setIcon (const Image& newIcon);
  227564. virtual void drawRect (CGRect r);
  227565. virtual bool canBecomeKeyWindow();
  227566. virtual bool windowShouldClose();
  227567. virtual void redirectMovedOrResized();
  227568. virtual CGRect constrainRect (CGRect r);
  227569. virtual void viewFocusGain();
  227570. virtual void viewFocusLoss();
  227571. bool isFocused() const;
  227572. void grabFocus();
  227573. void textInputRequired (const Point<int>& position);
  227574. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227575. void updateHiddenTextContent (TextInputTarget* target);
  227576. void globalFocusChanged (Component*);
  227577. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227578. void repaint (const Rectangle<int>& area);
  227579. void performAnyPendingRepaintsNow();
  227580. juce_UseDebuggingNewOperator
  227581. UIWindow* window;
  227582. JuceUIView* view;
  227583. bool isSharedWindow, fullScreen, insideDrawRect;
  227584. static ModifierKeys currentModifiers;
  227585. static int64 getMouseTime (UIEvent* e)
  227586. {
  227587. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227588. + (int64) ([e timestamp] * 1000.0);
  227589. }
  227590. Array <UITouch*> currentTouches;
  227591. };
  227592. END_JUCE_NAMESPACE
  227593. @implementation JuceUIView
  227594. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227595. withFrame: (CGRect) frame
  227596. {
  227597. [super initWithFrame: frame];
  227598. owner = owner_;
  227599. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227600. [self addSubview: hiddenTextView];
  227601. hiddenTextView.delegate = self;
  227602. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227603. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227604. return self;
  227605. }
  227606. - (void) dealloc
  227607. {
  227608. [hiddenTextView removeFromSuperview];
  227609. [hiddenTextView release];
  227610. [super dealloc];
  227611. }
  227612. - (void) drawRect: (CGRect) r
  227613. {
  227614. if (owner != 0)
  227615. owner->drawRect (r);
  227616. }
  227617. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227618. {
  227619. return false;
  227620. }
  227621. ModifierKeys UIViewComponentPeer::currentModifiers;
  227622. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227623. {
  227624. return UIViewComponentPeer::currentModifiers;
  227625. }
  227626. void ModifierKeys::updateCurrentModifiers() throw()
  227627. {
  227628. currentModifiers = UIViewComponentPeer::currentModifiers;
  227629. }
  227630. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227631. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227632. {
  227633. if (owner != 0)
  227634. owner->handleTouches (event, true, false, false);
  227635. }
  227636. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227637. {
  227638. if (owner != 0)
  227639. owner->handleTouches (event, false, false, false);
  227640. }
  227641. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227642. {
  227643. if (owner != 0)
  227644. owner->handleTouches (event, false, true, false);
  227645. }
  227646. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227647. {
  227648. if (owner != 0)
  227649. owner->handleTouches (event, false, true, true);
  227650. [self touchesEnded: touches withEvent: event];
  227651. }
  227652. - (BOOL) becomeFirstResponder
  227653. {
  227654. if (owner != 0)
  227655. owner->viewFocusGain();
  227656. return true;
  227657. }
  227658. - (BOOL) resignFirstResponder
  227659. {
  227660. if (owner != 0)
  227661. owner->viewFocusLoss();
  227662. return true;
  227663. }
  227664. - (BOOL) canBecomeFirstResponder
  227665. {
  227666. return owner != 0 && owner->canBecomeKeyWindow();
  227667. }
  227668. - (void) asyncRepaint: (id) rect
  227669. {
  227670. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227671. [self setNeedsDisplayInRect: *r];
  227672. }
  227673. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227674. {
  227675. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227676. nsStringToJuce (text));
  227677. }
  227678. @end
  227679. @implementation JuceUIWindow
  227680. - (void) setOwner: (UIViewComponentPeer*) owner_
  227681. {
  227682. owner = owner_;
  227683. isZooming = false;
  227684. }
  227685. - (void) becomeKeyWindow
  227686. {
  227687. [super becomeKeyWindow];
  227688. if (owner != 0)
  227689. owner->grabFocus();
  227690. }
  227691. @end
  227692. BEGIN_JUCE_NAMESPACE
  227693. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227694. const int windowStyleFlags,
  227695. UIView* viewToAttachTo)
  227696. : ComponentPeer (component, windowStyleFlags),
  227697. window (0),
  227698. view (0),
  227699. isSharedWindow (viewToAttachTo != 0),
  227700. fullScreen (false),
  227701. insideDrawRect (false)
  227702. {
  227703. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  227704. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227705. if (isSharedWindow)
  227706. {
  227707. window = [viewToAttachTo window];
  227708. [viewToAttachTo addSubview: view];
  227709. setVisible (component->isVisible());
  227710. }
  227711. else
  227712. {
  227713. r.origin.x = (float) component->getX();
  227714. r.origin.y = (float) component->getY();
  227715. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227716. window = [[JuceUIWindow alloc] init];
  227717. window.frame = r;
  227718. window.opaque = component->isOpaque();
  227719. view.opaque = component->isOpaque();
  227720. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227721. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227722. [((JuceUIWindow*) window) setOwner: this];
  227723. if (component->isAlwaysOnTop())
  227724. window.windowLevel = UIWindowLevelAlert;
  227725. [window addSubview: view];
  227726. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227727. view.hidden = ! component->isVisible();
  227728. window.hidden = ! component->isVisible();
  227729. view.multipleTouchEnabled = YES;
  227730. }
  227731. setTitle (component->getName());
  227732. Desktop::getInstance().addFocusChangeListener (this);
  227733. }
  227734. UIViewComponentPeer::~UIViewComponentPeer()
  227735. {
  227736. Desktop::getInstance().removeFocusChangeListener (this);
  227737. view->owner = 0;
  227738. [view removeFromSuperview];
  227739. [view release];
  227740. if (! isSharedWindow)
  227741. {
  227742. [((JuceUIWindow*) window) setOwner: 0];
  227743. [window release];
  227744. }
  227745. }
  227746. void* UIViewComponentPeer::getNativeHandle() const
  227747. {
  227748. return view;
  227749. }
  227750. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227751. {
  227752. view.hidden = ! shouldBeVisible;
  227753. if (! isSharedWindow)
  227754. window.hidden = ! shouldBeVisible;
  227755. }
  227756. void UIViewComponentPeer::setTitle (const String& title)
  227757. {
  227758. // xxx is this possible?
  227759. }
  227760. void UIViewComponentPeer::setPosition (int x, int y)
  227761. {
  227762. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227763. }
  227764. void UIViewComponentPeer::setSize (int w, int h)
  227765. {
  227766. setBounds (component->getX(), component->getY(), w, h, false);
  227767. }
  227768. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227769. {
  227770. fullScreen = isNowFullScreen;
  227771. w = jmax (0, w);
  227772. h = jmax (0, h);
  227773. CGRect r;
  227774. r.origin.x = (float) x;
  227775. r.origin.y = (float) y;
  227776. r.size.width = (float) w;
  227777. r.size.height = (float) h;
  227778. if (isSharedWindow)
  227779. {
  227780. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227781. if ([view frame].size.width != r.size.width
  227782. || [view frame].size.height != r.size.height)
  227783. [view setNeedsDisplay];
  227784. view.frame = r;
  227785. }
  227786. else
  227787. {
  227788. window.frame = r;
  227789. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227790. }
  227791. }
  227792. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227793. {
  227794. CGRect r = [view frame];
  227795. if (global && [view window] != 0)
  227796. {
  227797. r = [view convertRect: r toView: nil];
  227798. CGRect wr = [[view window] frame];
  227799. r.origin.x += wr.origin.x;
  227800. r.origin.y += wr.origin.y;
  227801. }
  227802. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  227803. (int) r.size.width, (int) r.size.height);
  227804. }
  227805. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227806. {
  227807. return getBounds (! isSharedWindow);
  227808. }
  227809. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227810. {
  227811. return getBounds (true).getPosition();
  227812. }
  227813. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227814. {
  227815. return relativePosition + getScreenPosition();
  227816. }
  227817. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227818. {
  227819. return screenPosition - getScreenPosition();
  227820. }
  227821. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227822. {
  227823. if (constrainer != 0)
  227824. {
  227825. CGRect current = [window frame];
  227826. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227827. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227828. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227829. (int) r.size.width, (int) r.size.height);
  227830. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227831. (int) current.size.width, (int) current.size.height);
  227832. constrainer->checkBounds (pos, original,
  227833. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227834. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227835. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227836. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227837. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227838. r.origin.x = pos.getX();
  227839. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227840. r.size.width = pos.getWidth();
  227841. r.size.height = pos.getHeight();
  227842. }
  227843. return r;
  227844. }
  227845. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227846. {
  227847. // xxx
  227848. }
  227849. bool UIViewComponentPeer::isMinimised() const
  227850. {
  227851. return false;
  227852. }
  227853. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227854. {
  227855. if (! isSharedWindow)
  227856. {
  227857. Rectangle<int> r (lastNonFullscreenBounds);
  227858. setMinimised (false);
  227859. if (fullScreen != shouldBeFullScreen)
  227860. {
  227861. if (shouldBeFullScreen)
  227862. r = Desktop::getInstance().getMainMonitorArea();
  227863. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227864. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227865. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227866. }
  227867. }
  227868. }
  227869. bool UIViewComponentPeer::isFullScreen() const
  227870. {
  227871. return fullScreen;
  227872. }
  227873. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227874. {
  227875. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227876. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227877. return false;
  227878. CGPoint p;
  227879. p.x = (float) position.getX();
  227880. p.y = (float) position.getY();
  227881. UIView* v = [view hitTest: p withEvent: nil];
  227882. if (trueIfInAChildWindow)
  227883. return v != nil;
  227884. return v == view;
  227885. }
  227886. const BorderSize UIViewComponentPeer::getFrameSize() const
  227887. {
  227888. BorderSize b;
  227889. if (! isSharedWindow)
  227890. {
  227891. CGRect v = [view convertRect: [view frame] toView: nil];
  227892. CGRect w = [window frame];
  227893. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227894. b.setBottom ((int) v.origin.y);
  227895. b.setLeft ((int) v.origin.x);
  227896. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227897. }
  227898. return b;
  227899. }
  227900. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227901. {
  227902. if (! isSharedWindow)
  227903. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227904. return true;
  227905. }
  227906. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227907. {
  227908. if (isSharedWindow)
  227909. [[view superview] bringSubviewToFront: view];
  227910. if (window != 0 && component->isVisible())
  227911. [window makeKeyAndVisible];
  227912. }
  227913. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227914. {
  227915. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227916. jassert (otherPeer != 0); // wrong type of window?
  227917. if (otherPeer != 0)
  227918. {
  227919. if (isSharedWindow)
  227920. {
  227921. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227922. }
  227923. else
  227924. {
  227925. jassertfalse; // don't know how to do this
  227926. }
  227927. }
  227928. }
  227929. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227930. {
  227931. // to do..
  227932. }
  227933. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227934. {
  227935. NSArray* touches = [[event touchesForView: view] allObjects];
  227936. for (unsigned int i = 0; i < [touches count]; ++i)
  227937. {
  227938. UITouch* touch = [touches objectAtIndex: i];
  227939. CGPoint p = [touch locationInView: view];
  227940. const Point<int> pos ((int) p.x, (int) p.y);
  227941. juce_lastMousePos = pos + getScreenPosition();
  227942. const int64 time = getMouseTime (event);
  227943. int touchIndex = currentTouches.indexOf (touch);
  227944. if (touchIndex < 0)
  227945. {
  227946. touchIndex = currentTouches.size();
  227947. currentTouches.add (touch);
  227948. }
  227949. if (isDown)
  227950. {
  227951. currentModifiers = currentModifiers.withoutMouseButtons();
  227952. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227953. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227954. }
  227955. else if (isUp)
  227956. {
  227957. currentModifiers = currentModifiers.withoutMouseButtons();
  227958. currentTouches.remove (touchIndex);
  227959. }
  227960. if (isCancel)
  227961. currentTouches.clear();
  227962. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227963. }
  227964. }
  227965. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227966. void UIViewComponentPeer::viewFocusGain()
  227967. {
  227968. if (currentlyFocusedPeer != this)
  227969. {
  227970. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227971. currentlyFocusedPeer->handleFocusLoss();
  227972. currentlyFocusedPeer = this;
  227973. handleFocusGain();
  227974. }
  227975. }
  227976. void UIViewComponentPeer::viewFocusLoss()
  227977. {
  227978. if (currentlyFocusedPeer == this)
  227979. {
  227980. currentlyFocusedPeer = 0;
  227981. handleFocusLoss();
  227982. }
  227983. }
  227984. void juce_HandleProcessFocusChange()
  227985. {
  227986. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227987. {
  227988. if (Process::isForegroundProcess())
  227989. {
  227990. currentlyFocusedPeer->handleFocusGain();
  227991. ComponentPeer::bringModalComponentToFront();
  227992. }
  227993. else
  227994. {
  227995. currentlyFocusedPeer->handleFocusLoss();
  227996. // turn kiosk mode off if we lose focus..
  227997. Desktop::getInstance().setKioskModeComponent (0);
  227998. }
  227999. }
  228000. }
  228001. bool UIViewComponentPeer::isFocused() const
  228002. {
  228003. return isSharedWindow ? this == currentlyFocusedPeer
  228004. : (window != 0 && [window isKeyWindow]);
  228005. }
  228006. void UIViewComponentPeer::grabFocus()
  228007. {
  228008. if (window != 0)
  228009. {
  228010. [window makeKeyWindow];
  228011. viewFocusGain();
  228012. }
  228013. }
  228014. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  228015. {
  228016. }
  228017. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  228018. {
  228019. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  228020. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  228021. }
  228022. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  228023. {
  228024. TextInputTarget* const target = findCurrentTextInputTarget();
  228025. if (target != 0)
  228026. {
  228027. const Range<int> currentSelection (target->getHighlightedRegion());
  228028. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  228029. if (currentSelection.isEmpty())
  228030. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  228031. target->insertTextAtCaret (text);
  228032. updateHiddenTextContent (target);
  228033. }
  228034. return NO;
  228035. }
  228036. void UIViewComponentPeer::globalFocusChanged (Component*)
  228037. {
  228038. TextInputTarget* const target = findCurrentTextInputTarget();
  228039. if (target != 0)
  228040. {
  228041. Component* comp = dynamic_cast<Component*> (target);
  228042. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  228043. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  228044. updateHiddenTextContent (target);
  228045. [view->hiddenTextView becomeFirstResponder];
  228046. }
  228047. else
  228048. {
  228049. [view->hiddenTextView resignFirstResponder];
  228050. }
  228051. }
  228052. void UIViewComponentPeer::drawRect (CGRect r)
  228053. {
  228054. if (r.size.width < 1.0f || r.size.height < 1.0f)
  228055. return;
  228056. CGContextRef cg = UIGraphicsGetCurrentContext();
  228057. if (! component->isOpaque())
  228058. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  228059. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  228060. CoreGraphicsContext g (cg, view.bounds.size.height);
  228061. insideDrawRect = true;
  228062. handlePaint (g);
  228063. insideDrawRect = false;
  228064. }
  228065. bool UIViewComponentPeer::canBecomeKeyWindow()
  228066. {
  228067. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228068. }
  228069. bool UIViewComponentPeer::windowShouldClose()
  228070. {
  228071. if (! isValidPeer (this))
  228072. return YES;
  228073. handleUserClosingWindow();
  228074. return NO;
  228075. }
  228076. void UIViewComponentPeer::redirectMovedOrResized()
  228077. {
  228078. handleMovedOrResized();
  228079. }
  228080. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228081. {
  228082. }
  228083. class AsyncRepaintMessage : public CallbackMessage
  228084. {
  228085. public:
  228086. UIViewComponentPeer* const peer;
  228087. const Rectangle<int> rect;
  228088. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228089. : peer (peer_), rect (rect_)
  228090. {
  228091. }
  228092. void messageCallback()
  228093. {
  228094. if (ComponentPeer::isValidPeer (peer))
  228095. peer->repaint (rect);
  228096. }
  228097. };
  228098. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  228099. {
  228100. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  228101. {
  228102. (new AsyncRepaintMessage (this, area))->post();
  228103. }
  228104. else
  228105. {
  228106. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  228107. (float) area.getWidth(), (float) area.getHeight())];
  228108. }
  228109. }
  228110. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  228111. {
  228112. }
  228113. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228114. {
  228115. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  228116. }
  228117. const Image juce_createIconForFile (const File& file)
  228118. {
  228119. return Image::null;
  228120. }
  228121. void Desktop::createMouseInputSources()
  228122. {
  228123. for (int i = 0; i < 10; ++i)
  228124. mouseSources.add (new MouseInputSource (i, false));
  228125. }
  228126. bool Desktop::canUseSemiTransparentWindows() throw()
  228127. {
  228128. return true;
  228129. }
  228130. const Point<int> Desktop::getMousePosition()
  228131. {
  228132. return juce_lastMousePos;
  228133. }
  228134. void Desktop::setMousePosition (const Point<int>&)
  228135. {
  228136. }
  228137. const int KeyPress::spaceKey = ' ';
  228138. const int KeyPress::returnKey = 0x0d;
  228139. const int KeyPress::escapeKey = 0x1b;
  228140. const int KeyPress::backspaceKey = 0x7f;
  228141. const int KeyPress::leftKey = 0x1000;
  228142. const int KeyPress::rightKey = 0x1001;
  228143. const int KeyPress::upKey = 0x1002;
  228144. const int KeyPress::downKey = 0x1003;
  228145. const int KeyPress::pageUpKey = 0x1004;
  228146. const int KeyPress::pageDownKey = 0x1005;
  228147. const int KeyPress::endKey = 0x1006;
  228148. const int KeyPress::homeKey = 0x1007;
  228149. const int KeyPress::deleteKey = 0x1008;
  228150. const int KeyPress::insertKey = -1;
  228151. const int KeyPress::tabKey = 9;
  228152. const int KeyPress::F1Key = 0x2001;
  228153. const int KeyPress::F2Key = 0x2002;
  228154. const int KeyPress::F3Key = 0x2003;
  228155. const int KeyPress::F4Key = 0x2004;
  228156. const int KeyPress::F5Key = 0x2005;
  228157. const int KeyPress::F6Key = 0x2006;
  228158. const int KeyPress::F7Key = 0x2007;
  228159. const int KeyPress::F8Key = 0x2008;
  228160. const int KeyPress::F9Key = 0x2009;
  228161. const int KeyPress::F10Key = 0x200a;
  228162. const int KeyPress::F11Key = 0x200b;
  228163. const int KeyPress::F12Key = 0x200c;
  228164. const int KeyPress::F13Key = 0x200d;
  228165. const int KeyPress::F14Key = 0x200e;
  228166. const int KeyPress::F15Key = 0x200f;
  228167. const int KeyPress::F16Key = 0x2010;
  228168. const int KeyPress::numberPad0 = 0x30020;
  228169. const int KeyPress::numberPad1 = 0x30021;
  228170. const int KeyPress::numberPad2 = 0x30022;
  228171. const int KeyPress::numberPad3 = 0x30023;
  228172. const int KeyPress::numberPad4 = 0x30024;
  228173. const int KeyPress::numberPad5 = 0x30025;
  228174. const int KeyPress::numberPad6 = 0x30026;
  228175. const int KeyPress::numberPad7 = 0x30027;
  228176. const int KeyPress::numberPad8 = 0x30028;
  228177. const int KeyPress::numberPad9 = 0x30029;
  228178. const int KeyPress::numberPadAdd = 0x3002a;
  228179. const int KeyPress::numberPadSubtract = 0x3002b;
  228180. const int KeyPress::numberPadMultiply = 0x3002c;
  228181. const int KeyPress::numberPadDivide = 0x3002d;
  228182. const int KeyPress::numberPadSeparator = 0x3002e;
  228183. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228184. const int KeyPress::numberPadEquals = 0x30030;
  228185. const int KeyPress::numberPadDelete = 0x30031;
  228186. const int KeyPress::playKey = 0x30000;
  228187. const int KeyPress::stopKey = 0x30001;
  228188. const int KeyPress::fastForwardKey = 0x30002;
  228189. const int KeyPress::rewindKey = 0x30003;
  228190. #endif
  228191. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  228192. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  228193. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228194. // compiled on its own).
  228195. #if JUCE_INCLUDED_FILE
  228196. struct CallbackMessagePayload
  228197. {
  228198. MessageCallbackFunction* function;
  228199. void* parameter;
  228200. void* volatile result;
  228201. bool volatile hasBeenExecuted;
  228202. };
  228203. END_JUCE_NAMESPACE
  228204. @interface JuceCustomMessageHandler : NSObject
  228205. {
  228206. }
  228207. - (void) performCallback: (id) info;
  228208. @end
  228209. @implementation JuceCustomMessageHandler
  228210. - (void) performCallback: (id) info
  228211. {
  228212. if ([info isKindOfClass: [NSData class]])
  228213. {
  228214. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  228215. if (pl != 0)
  228216. {
  228217. pl->result = (*pl->function) (pl->parameter);
  228218. pl->hasBeenExecuted = true;
  228219. }
  228220. }
  228221. else
  228222. {
  228223. jassertfalse; // should never get here!
  228224. }
  228225. }
  228226. @end
  228227. BEGIN_JUCE_NAMESPACE
  228228. void MessageManager::runDispatchLoop()
  228229. {
  228230. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228231. runDispatchLoopUntil (-1);
  228232. }
  228233. void MessageManager::stopDispatchLoop()
  228234. {
  228235. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228236. exit (0); // iPhone apps get no mercy..
  228237. }
  228238. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228239. {
  228240. const ScopedAutoReleasePool pool;
  228241. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228242. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228243. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228244. while (! quitMessagePosted)
  228245. {
  228246. const ScopedAutoReleasePool pool;
  228247. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228248. beforeDate: endDate];
  228249. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228250. break;
  228251. }
  228252. return ! quitMessagePosted;
  228253. }
  228254. static CFRunLoopRef runLoop = 0;
  228255. static CFRunLoopSourceRef runLoopSource = 0;
  228256. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228257. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228258. static void runLoopSourceCallback (void*)
  228259. {
  228260. if (pendingMessages != 0)
  228261. {
  228262. int numDispatched = 0;
  228263. do
  228264. {
  228265. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228266. if (nextMessage == 0)
  228267. return;
  228268. const ScopedAutoReleasePool pool;
  228269. MessageManager::getInstance()->deliverMessage (nextMessage);
  228270. } while (++numDispatched <= 4);
  228271. CFRunLoopSourceSignal (runLoopSource);
  228272. CFRunLoopWakeUp (runLoop);
  228273. }
  228274. }
  228275. void MessageManager::doPlatformSpecificInitialisation()
  228276. {
  228277. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228278. runLoop = CFRunLoopGetCurrent();
  228279. CFRunLoopSourceContext sourceContext;
  228280. zerostruct (sourceContext);
  228281. sourceContext.perform = runLoopSourceCallback;
  228282. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228283. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228284. if (juceCustomMessageHandler == 0)
  228285. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228286. }
  228287. void MessageManager::doPlatformSpecificShutdown()
  228288. {
  228289. CFRunLoopSourceInvalidate (runLoopSource);
  228290. CFRelease (runLoopSource);
  228291. runLoopSource = 0;
  228292. deleteAndZero (pendingMessages);
  228293. if (juceCustomMessageHandler != 0)
  228294. {
  228295. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228296. [juceCustomMessageHandler release];
  228297. juceCustomMessageHandler = 0;
  228298. }
  228299. }
  228300. bool juce_postMessageToSystemQueue (Message* message)
  228301. {
  228302. if (pendingMessages != 0)
  228303. {
  228304. pendingMessages->add (message);
  228305. CFRunLoopSourceSignal (runLoopSource);
  228306. CFRunLoopWakeUp (runLoop);
  228307. }
  228308. return true;
  228309. }
  228310. void MessageManager::broadcastMessage (const String& value)
  228311. {
  228312. }
  228313. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228314. {
  228315. if (isThisTheMessageThread())
  228316. {
  228317. return (*callback) (data);
  228318. }
  228319. else
  228320. {
  228321. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228322. // deadlock because the message manager is blocked from running, so can never
  228323. // call your function..
  228324. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228325. const ScopedAutoReleasePool pool;
  228326. CallbackMessagePayload cmp;
  228327. cmp.function = callback;
  228328. cmp.parameter = data;
  228329. cmp.result = 0;
  228330. cmp.hasBeenExecuted = false;
  228331. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228332. withObject: [NSData dataWithBytesNoCopy: &cmp
  228333. length: sizeof (cmp)
  228334. freeWhenDone: NO]
  228335. waitUntilDone: YES];
  228336. return cmp.result;
  228337. }
  228338. }
  228339. #endif
  228340. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228341. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228342. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228343. // compiled on its own).
  228344. #if JUCE_INCLUDED_FILE
  228345. #if JUCE_MAC
  228346. END_JUCE_NAMESPACE
  228347. using namespace JUCE_NAMESPACE;
  228348. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228349. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228350. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228351. #else
  228352. @interface JuceFileChooserDelegate : NSObject
  228353. #endif
  228354. {
  228355. StringArray* filters;
  228356. }
  228357. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228358. - (void) dealloc;
  228359. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228360. @end
  228361. @implementation JuceFileChooserDelegate
  228362. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228363. {
  228364. [super init];
  228365. filters = filters_;
  228366. return self;
  228367. }
  228368. - (void) dealloc
  228369. {
  228370. delete filters;
  228371. [super dealloc];
  228372. }
  228373. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228374. {
  228375. (void) sender;
  228376. const File f (nsStringToJuce (filename));
  228377. for (int i = filters->size(); --i >= 0;)
  228378. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228379. return true;
  228380. return f.isDirectory();
  228381. }
  228382. @end
  228383. BEGIN_JUCE_NAMESPACE
  228384. void FileChooser::showPlatformDialog (Array<File>& results,
  228385. const String& title,
  228386. const File& currentFileOrDirectory,
  228387. const String& filter,
  228388. bool selectsDirectory,
  228389. bool selectsFiles,
  228390. bool isSaveDialogue,
  228391. bool warnAboutOverwritingExistingFiles,
  228392. bool selectMultipleFiles,
  228393. FilePreviewComponent* extraInfoComponent)
  228394. {
  228395. const ScopedAutoReleasePool pool;
  228396. StringArray* filters = new StringArray();
  228397. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228398. filters->trim();
  228399. filters->removeEmptyStrings();
  228400. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228401. [delegate autorelease];
  228402. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228403. : [NSOpenPanel openPanel];
  228404. [panel setTitle: juceStringToNS (title)];
  228405. if (! isSaveDialogue)
  228406. {
  228407. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228408. [openPanel setCanChooseDirectories: selectsDirectory];
  228409. [openPanel setCanChooseFiles: selectsFiles];
  228410. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228411. }
  228412. [panel setDelegate: delegate];
  228413. if (isSaveDialogue || selectsDirectory)
  228414. [panel setCanCreateDirectories: YES];
  228415. String directory, filename;
  228416. if (currentFileOrDirectory.isDirectory())
  228417. {
  228418. directory = currentFileOrDirectory.getFullPathName();
  228419. }
  228420. else
  228421. {
  228422. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228423. filename = currentFileOrDirectory.getFileName();
  228424. }
  228425. if ([panel runModalForDirectory: juceStringToNS (directory)
  228426. file: juceStringToNS (filename)]
  228427. == NSOKButton)
  228428. {
  228429. if (isSaveDialogue)
  228430. {
  228431. results.add (File (nsStringToJuce ([panel filename])));
  228432. }
  228433. else
  228434. {
  228435. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228436. NSArray* urls = [openPanel filenames];
  228437. for (unsigned int i = 0; i < [urls count]; ++i)
  228438. {
  228439. NSString* f = [urls objectAtIndex: i];
  228440. results.add (File (nsStringToJuce (f)));
  228441. }
  228442. }
  228443. }
  228444. [panel setDelegate: nil];
  228445. }
  228446. #else
  228447. void FileChooser::showPlatformDialog (Array<File>& results,
  228448. const String& title,
  228449. const File& currentFileOrDirectory,
  228450. const String& filter,
  228451. bool selectsDirectory,
  228452. bool selectsFiles,
  228453. bool isSaveDialogue,
  228454. bool warnAboutOverwritingExistingFiles,
  228455. bool selectMultipleFiles,
  228456. FilePreviewComponent* extraInfoComponent)
  228457. {
  228458. const ScopedAutoReleasePool pool;
  228459. jassertfalse; //xxx to do
  228460. }
  228461. #endif
  228462. #endif
  228463. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228464. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228465. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228466. // compiled on its own).
  228467. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228468. #if JUCE_MAC
  228469. END_JUCE_NAMESPACE
  228470. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228471. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228472. {
  228473. CriticalSection* contextLock;
  228474. bool needsUpdate;
  228475. }
  228476. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228477. - (bool) makeActive;
  228478. - (void) makeInactive;
  228479. - (void) reshape;
  228480. @end
  228481. @implementation ThreadSafeNSOpenGLView
  228482. - (id) initWithFrame: (NSRect) frameRect
  228483. pixelFormat: (NSOpenGLPixelFormat*) format
  228484. {
  228485. contextLock = new CriticalSection();
  228486. self = [super initWithFrame: frameRect pixelFormat: format];
  228487. if (self != nil)
  228488. [[NSNotificationCenter defaultCenter] addObserver: self
  228489. selector: @selector (_surfaceNeedsUpdate:)
  228490. name: NSViewGlobalFrameDidChangeNotification
  228491. object: self];
  228492. return self;
  228493. }
  228494. - (void) dealloc
  228495. {
  228496. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228497. delete contextLock;
  228498. [super dealloc];
  228499. }
  228500. - (bool) makeActive
  228501. {
  228502. const ScopedLock sl (*contextLock);
  228503. if ([self openGLContext] == 0)
  228504. return false;
  228505. [[self openGLContext] makeCurrentContext];
  228506. if (needsUpdate)
  228507. {
  228508. [super update];
  228509. needsUpdate = false;
  228510. }
  228511. return true;
  228512. }
  228513. - (void) makeInactive
  228514. {
  228515. const ScopedLock sl (*contextLock);
  228516. [NSOpenGLContext clearCurrentContext];
  228517. }
  228518. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228519. {
  228520. const ScopedLock sl (*contextLock);
  228521. needsUpdate = true;
  228522. }
  228523. - (void) update
  228524. {
  228525. const ScopedLock sl (*contextLock);
  228526. needsUpdate = true;
  228527. }
  228528. - (void) reshape
  228529. {
  228530. const ScopedLock sl (*contextLock);
  228531. needsUpdate = true;
  228532. }
  228533. @end
  228534. BEGIN_JUCE_NAMESPACE
  228535. class WindowedGLContext : public OpenGLContext
  228536. {
  228537. public:
  228538. WindowedGLContext (Component* const component,
  228539. const OpenGLPixelFormat& pixelFormat_,
  228540. NSOpenGLContext* sharedContext)
  228541. : renderContext (0),
  228542. pixelFormat (pixelFormat_)
  228543. {
  228544. jassert (component != 0);
  228545. NSOpenGLPixelFormatAttribute attribs [64];
  228546. int n = 0;
  228547. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228548. attribs[n++] = NSOpenGLPFAAccelerated;
  228549. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228550. attribs[n++] = NSOpenGLPFAColorSize;
  228551. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228552. pixelFormat.greenBits,
  228553. pixelFormat.blueBits);
  228554. attribs[n++] = NSOpenGLPFAAlphaSize;
  228555. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228556. attribs[n++] = NSOpenGLPFADepthSize;
  228557. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228558. attribs[n++] = NSOpenGLPFAStencilSize;
  228559. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228560. attribs[n++] = NSOpenGLPFAAccumSize;
  228561. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228562. pixelFormat.accumulationBufferGreenBits,
  228563. pixelFormat.accumulationBufferBlueBits,
  228564. pixelFormat.accumulationBufferAlphaBits);
  228565. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228566. attribs[n++] = NSOpenGLPFASampleBuffers;
  228567. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228568. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228569. attribs[n++] = NSOpenGLPFANoRecovery;
  228570. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228571. NSOpenGLPixelFormat* format
  228572. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228573. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228574. pixelFormat: format];
  228575. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228576. shareContext: sharedContext] autorelease];
  228577. const GLint swapInterval = 1;
  228578. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228579. [view setOpenGLContext: renderContext];
  228580. [format release];
  228581. viewHolder = new NSViewComponentInternal (view, component);
  228582. }
  228583. ~WindowedGLContext()
  228584. {
  228585. deleteContext();
  228586. viewHolder = 0;
  228587. }
  228588. void deleteContext()
  228589. {
  228590. makeInactive();
  228591. [renderContext clearDrawable];
  228592. [renderContext setView: nil];
  228593. [view setOpenGLContext: nil];
  228594. renderContext = nil;
  228595. }
  228596. bool makeActive() const throw()
  228597. {
  228598. jassert (renderContext != 0);
  228599. if ([renderContext view] != view)
  228600. [renderContext setView: view];
  228601. [view makeActive];
  228602. return isActive();
  228603. }
  228604. bool makeInactive() const throw()
  228605. {
  228606. [view makeInactive];
  228607. return true;
  228608. }
  228609. bool isActive() const throw()
  228610. {
  228611. return [NSOpenGLContext currentContext] == renderContext;
  228612. }
  228613. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228614. void* getRawContext() const throw() { return renderContext; }
  228615. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228616. {
  228617. }
  228618. void swapBuffers()
  228619. {
  228620. [renderContext flushBuffer];
  228621. }
  228622. bool setSwapInterval (const int numFramesPerSwap)
  228623. {
  228624. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228625. forParameter: NSOpenGLCPSwapInterval];
  228626. return true;
  228627. }
  228628. int getSwapInterval() const
  228629. {
  228630. GLint numFrames = 0;
  228631. [renderContext getValues: &numFrames
  228632. forParameter: NSOpenGLCPSwapInterval];
  228633. return numFrames;
  228634. }
  228635. void repaint()
  228636. {
  228637. // we need to invalidate the juce view that holds this gl view, to make it
  228638. // cause a repaint callback
  228639. NSView* v = (NSView*) viewHolder->view;
  228640. NSRect r = [v frame];
  228641. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228642. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228643. // repaint message, thus never causing our paint() callback, and never repainting
  228644. // the comp. So invalidating just a little bit around the edge helps..
  228645. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228646. }
  228647. void* getNativeWindowHandle() const { return viewHolder->view; }
  228648. juce_UseDebuggingNewOperator
  228649. NSOpenGLContext* renderContext;
  228650. ThreadSafeNSOpenGLView* view;
  228651. private:
  228652. OpenGLPixelFormat pixelFormat;
  228653. ScopedPointer <NSViewComponentInternal> viewHolder;
  228654. WindowedGLContext (const WindowedGLContext&);
  228655. WindowedGLContext& operator= (const WindowedGLContext&);
  228656. };
  228657. OpenGLContext* OpenGLComponent::createContext()
  228658. {
  228659. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228660. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228661. return (c->renderContext != 0) ? c.release() : 0;
  228662. }
  228663. void* OpenGLComponent::getNativeWindowHandle() const
  228664. {
  228665. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228666. : 0;
  228667. }
  228668. void juce_glViewport (const int w, const int h)
  228669. {
  228670. glViewport (0, 0, w, h);
  228671. }
  228672. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228673. OwnedArray <OpenGLPixelFormat>& results)
  228674. {
  228675. /* GLint attribs [64];
  228676. int n = 0;
  228677. attribs[n++] = AGL_RGBA;
  228678. attribs[n++] = AGL_DOUBLEBUFFER;
  228679. attribs[n++] = AGL_ACCELERATED;
  228680. attribs[n++] = AGL_NO_RECOVERY;
  228681. attribs[n++] = AGL_NONE;
  228682. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228683. while (p != 0)
  228684. {
  228685. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228686. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228687. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228688. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228689. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228690. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228691. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228692. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228693. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228694. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228695. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228696. results.add (pf);
  228697. p = aglNextPixelFormat (p);
  228698. }*/
  228699. //jassertfalse // can't see how you do this in cocoa!
  228700. }
  228701. #else
  228702. END_JUCE_NAMESPACE
  228703. @interface JuceGLView : UIView
  228704. {
  228705. }
  228706. + (Class) layerClass;
  228707. @end
  228708. @implementation JuceGLView
  228709. + (Class) layerClass
  228710. {
  228711. return [CAEAGLLayer class];
  228712. }
  228713. @end
  228714. BEGIN_JUCE_NAMESPACE
  228715. class GLESContext : public OpenGLContext
  228716. {
  228717. public:
  228718. GLESContext (UIViewComponentPeer* peer,
  228719. Component* const component_,
  228720. const OpenGLPixelFormat& pixelFormat_,
  228721. const GLESContext* const sharedContext,
  228722. NSUInteger apiType)
  228723. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228724. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228725. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228726. {
  228727. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228728. view.opaque = YES;
  228729. view.hidden = NO;
  228730. view.backgroundColor = [UIColor blackColor];
  228731. view.userInteractionEnabled = NO;
  228732. glLayer = (CAEAGLLayer*) [view layer];
  228733. [peer->view addSubview: view];
  228734. if (sharedContext != 0)
  228735. context = [[EAGLContext alloc] initWithAPI: apiType
  228736. sharegroup: [sharedContext->context sharegroup]];
  228737. else
  228738. context = [[EAGLContext alloc] initWithAPI: apiType];
  228739. createGLBuffers();
  228740. }
  228741. ~GLESContext()
  228742. {
  228743. deleteContext();
  228744. [view removeFromSuperview];
  228745. [view release];
  228746. freeGLBuffers();
  228747. }
  228748. void deleteContext()
  228749. {
  228750. makeInactive();
  228751. [context release];
  228752. context = nil;
  228753. }
  228754. bool makeActive() const throw()
  228755. {
  228756. jassert (context != 0);
  228757. [EAGLContext setCurrentContext: context];
  228758. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228759. return true;
  228760. }
  228761. void swapBuffers()
  228762. {
  228763. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228764. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228765. }
  228766. bool makeInactive() const throw()
  228767. {
  228768. return [EAGLContext setCurrentContext: nil];
  228769. }
  228770. bool isActive() const throw()
  228771. {
  228772. return [EAGLContext currentContext] == context;
  228773. }
  228774. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228775. void* getRawContext() const throw() { return glLayer; }
  228776. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228777. {
  228778. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228779. if (lastWidth != w || lastHeight != h)
  228780. {
  228781. lastWidth = w;
  228782. lastHeight = h;
  228783. freeGLBuffers();
  228784. createGLBuffers();
  228785. }
  228786. }
  228787. bool setSwapInterval (const int numFramesPerSwap)
  228788. {
  228789. numFrames = numFramesPerSwap;
  228790. return true;
  228791. }
  228792. int getSwapInterval() const
  228793. {
  228794. return numFrames;
  228795. }
  228796. void repaint()
  228797. {
  228798. }
  228799. void createGLBuffers()
  228800. {
  228801. makeActive();
  228802. glGenFramebuffersOES (1, &frameBufferHandle);
  228803. glGenRenderbuffersOES (1, &colorBufferHandle);
  228804. glGenRenderbuffersOES (1, &depthBufferHandle);
  228805. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228806. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228807. GLint width, height;
  228808. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228809. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228810. if (useDepthBuffer)
  228811. {
  228812. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228813. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228814. }
  228815. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228816. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228817. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228818. if (useDepthBuffer)
  228819. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228820. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228821. }
  228822. void freeGLBuffers()
  228823. {
  228824. if (frameBufferHandle != 0)
  228825. {
  228826. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228827. frameBufferHandle = 0;
  228828. }
  228829. if (colorBufferHandle != 0)
  228830. {
  228831. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228832. colorBufferHandle = 0;
  228833. }
  228834. if (depthBufferHandle != 0)
  228835. {
  228836. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228837. depthBufferHandle = 0;
  228838. }
  228839. }
  228840. juce_UseDebuggingNewOperator
  228841. private:
  228842. Component::SafePointer<Component> component;
  228843. OpenGLPixelFormat pixelFormat;
  228844. JuceGLView* view;
  228845. CAEAGLLayer* glLayer;
  228846. EAGLContext* context;
  228847. bool useDepthBuffer;
  228848. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228849. int numFrames;
  228850. int lastWidth, lastHeight;
  228851. GLESContext (const GLESContext&);
  228852. GLESContext& operator= (const GLESContext&);
  228853. };
  228854. OpenGLContext* OpenGLComponent::createContext()
  228855. {
  228856. ScopedAutoReleasePool pool;
  228857. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228858. if (peer != 0)
  228859. return new GLESContext (peer, this, preferredPixelFormat,
  228860. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228861. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228862. return 0;
  228863. }
  228864. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228865. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228866. {
  228867. }
  228868. void juce_glViewport (const int w, const int h)
  228869. {
  228870. glViewport (0, 0, w, h);
  228871. }
  228872. #endif
  228873. #endif
  228874. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228875. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228876. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228877. // compiled on its own).
  228878. #if JUCE_INCLUDED_FILE
  228879. #if JUCE_MAC
  228880. namespace MouseCursorHelpers
  228881. {
  228882. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228883. {
  228884. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228885. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228886. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228887. [im release];
  228888. return c;
  228889. }
  228890. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228891. {
  228892. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228893. BufferedInputStream buf (&fileStream, 4096, false);
  228894. PNGImageFormat pngFormat;
  228895. Image im (pngFormat.decodeImage (buf));
  228896. if (im.isValid())
  228897. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228898. jassertfalse;
  228899. return 0;
  228900. }
  228901. }
  228902. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228903. {
  228904. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228905. }
  228906. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228907. {
  228908. const ScopedAutoReleasePool pool;
  228909. NSCursor* c = 0;
  228910. switch (type)
  228911. {
  228912. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228913. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228914. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228915. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228916. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228917. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228918. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228919. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228920. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228921. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228922. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228923. case UpDownResizeCursor:
  228924. case TopEdgeResizeCursor:
  228925. case BottomEdgeResizeCursor:
  228926. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228927. case TopLeftCornerResizeCursor:
  228928. case BottomRightCornerResizeCursor:
  228929. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228930. case TopRightCornerResizeCursor:
  228931. case BottomLeftCornerResizeCursor:
  228932. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228933. case UpDownLeftRightResizeCursor:
  228934. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228935. default:
  228936. jassertfalse;
  228937. break;
  228938. }
  228939. [c retain];
  228940. return c;
  228941. }
  228942. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228943. {
  228944. [((NSCursor*) cursorHandle) release];
  228945. }
  228946. void MouseCursor::showInAllWindows() const
  228947. {
  228948. showInWindow (0);
  228949. }
  228950. void MouseCursor::showInWindow (ComponentPeer*) const
  228951. {
  228952. [((NSCursor*) getHandle()) set];
  228953. }
  228954. #else
  228955. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228956. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228957. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228958. void MouseCursor::showInAllWindows() const {}
  228959. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228960. #endif
  228961. #endif
  228962. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228963. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228964. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228965. // compiled on its own).
  228966. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228967. #if JUCE_MAC
  228968. END_JUCE_NAMESPACE
  228969. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228970. @interface DownloadClickDetector : NSObject
  228971. {
  228972. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228973. }
  228974. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228975. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228976. request: (NSURLRequest*) request
  228977. frame: (WebFrame*) frame
  228978. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228979. @end
  228980. @implementation DownloadClickDetector
  228981. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228982. {
  228983. [super init];
  228984. ownerComponent = ownerComponent_;
  228985. return self;
  228986. }
  228987. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228988. request: (NSURLRequest*) request
  228989. frame: (WebFrame*) frame
  228990. decisionListener: (id <WebPolicyDecisionListener>) listener
  228991. {
  228992. (void) sender;
  228993. (void) request;
  228994. (void) frame;
  228995. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228996. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228997. [listener use];
  228998. else
  228999. [listener ignore];
  229000. }
  229001. @end
  229002. BEGIN_JUCE_NAMESPACE
  229003. class WebBrowserComponentInternal : public NSViewComponent
  229004. {
  229005. public:
  229006. WebBrowserComponentInternal (WebBrowserComponent* owner)
  229007. {
  229008. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  229009. frameName: @""
  229010. groupName: @""];
  229011. setView (webView);
  229012. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  229013. [webView setPolicyDelegate: clickListener];
  229014. }
  229015. ~WebBrowserComponentInternal()
  229016. {
  229017. [webView setPolicyDelegate: nil];
  229018. [clickListener release];
  229019. setView (0);
  229020. }
  229021. void goToURL (const String& url,
  229022. const StringArray* headers,
  229023. const MemoryBlock* postData)
  229024. {
  229025. NSMutableURLRequest* r
  229026. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  229027. cachePolicy: NSURLRequestUseProtocolCachePolicy
  229028. timeoutInterval: 30.0];
  229029. if (postData != 0 && postData->getSize() > 0)
  229030. {
  229031. [r setHTTPMethod: @"POST"];
  229032. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  229033. length: postData->getSize()]];
  229034. }
  229035. if (headers != 0)
  229036. {
  229037. for (int i = 0; i < headers->size(); ++i)
  229038. {
  229039. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  229040. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  229041. [r setValue: juceStringToNS (headerValue)
  229042. forHTTPHeaderField: juceStringToNS (headerName)];
  229043. }
  229044. }
  229045. stop();
  229046. [[webView mainFrame] loadRequest: r];
  229047. }
  229048. void goBack()
  229049. {
  229050. [webView goBack];
  229051. }
  229052. void goForward()
  229053. {
  229054. [webView goForward];
  229055. }
  229056. void stop()
  229057. {
  229058. [webView stopLoading: nil];
  229059. }
  229060. void refresh()
  229061. {
  229062. [webView reload: nil];
  229063. }
  229064. private:
  229065. WebView* webView;
  229066. DownloadClickDetector* clickListener;
  229067. };
  229068. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229069. : browser (0),
  229070. blankPageShown (false),
  229071. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  229072. {
  229073. setOpaque (true);
  229074. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  229075. }
  229076. WebBrowserComponent::~WebBrowserComponent()
  229077. {
  229078. deleteAndZero (browser);
  229079. }
  229080. void WebBrowserComponent::goToURL (const String& url,
  229081. const StringArray* headers,
  229082. const MemoryBlock* postData)
  229083. {
  229084. lastURL = url;
  229085. lastHeaders.clear();
  229086. if (headers != 0)
  229087. lastHeaders = *headers;
  229088. lastPostData.setSize (0);
  229089. if (postData != 0)
  229090. lastPostData = *postData;
  229091. blankPageShown = false;
  229092. browser->goToURL (url, headers, postData);
  229093. }
  229094. void WebBrowserComponent::stop()
  229095. {
  229096. browser->stop();
  229097. }
  229098. void WebBrowserComponent::goBack()
  229099. {
  229100. lastURL = String::empty;
  229101. blankPageShown = false;
  229102. browser->goBack();
  229103. }
  229104. void WebBrowserComponent::goForward()
  229105. {
  229106. lastURL = String::empty;
  229107. browser->goForward();
  229108. }
  229109. void WebBrowserComponent::refresh()
  229110. {
  229111. browser->refresh();
  229112. }
  229113. void WebBrowserComponent::paint (Graphics&)
  229114. {
  229115. }
  229116. void WebBrowserComponent::checkWindowAssociation()
  229117. {
  229118. if (isShowing())
  229119. {
  229120. if (blankPageShown)
  229121. goBack();
  229122. }
  229123. else
  229124. {
  229125. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  229126. {
  229127. // when the component becomes invisible, some stuff like flash
  229128. // carries on playing audio, so we need to force it onto a blank
  229129. // page to avoid this, (and send it back when it's made visible again).
  229130. blankPageShown = true;
  229131. browser->goToURL ("about:blank", 0, 0);
  229132. }
  229133. }
  229134. }
  229135. void WebBrowserComponent::reloadLastURL()
  229136. {
  229137. if (lastURL.isNotEmpty())
  229138. {
  229139. goToURL (lastURL, &lastHeaders, &lastPostData);
  229140. lastURL = String::empty;
  229141. }
  229142. }
  229143. void WebBrowserComponent::parentHierarchyChanged()
  229144. {
  229145. checkWindowAssociation();
  229146. }
  229147. void WebBrowserComponent::resized()
  229148. {
  229149. browser->setSize (getWidth(), getHeight());
  229150. }
  229151. void WebBrowserComponent::visibilityChanged()
  229152. {
  229153. checkWindowAssociation();
  229154. }
  229155. bool WebBrowserComponent::pageAboutToLoad (const String&)
  229156. {
  229157. return true;
  229158. }
  229159. #else
  229160. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229161. {
  229162. }
  229163. WebBrowserComponent::~WebBrowserComponent()
  229164. {
  229165. }
  229166. void WebBrowserComponent::goToURL (const String& url,
  229167. const StringArray* headers,
  229168. const MemoryBlock* postData)
  229169. {
  229170. }
  229171. void WebBrowserComponent::stop()
  229172. {
  229173. }
  229174. void WebBrowserComponent::goBack()
  229175. {
  229176. }
  229177. void WebBrowserComponent::goForward()
  229178. {
  229179. }
  229180. void WebBrowserComponent::refresh()
  229181. {
  229182. }
  229183. void WebBrowserComponent::paint (Graphics& g)
  229184. {
  229185. }
  229186. void WebBrowserComponent::checkWindowAssociation()
  229187. {
  229188. }
  229189. void WebBrowserComponent::reloadLastURL()
  229190. {
  229191. }
  229192. void WebBrowserComponent::parentHierarchyChanged()
  229193. {
  229194. }
  229195. void WebBrowserComponent::resized()
  229196. {
  229197. }
  229198. void WebBrowserComponent::visibilityChanged()
  229199. {
  229200. }
  229201. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  229202. {
  229203. return true;
  229204. }
  229205. #endif
  229206. #endif
  229207. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229208. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  229209. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229210. // compiled on its own).
  229211. #if JUCE_INCLUDED_FILE
  229212. class IPhoneAudioIODevice : public AudioIODevice
  229213. {
  229214. public:
  229215. IPhoneAudioIODevice (const String& deviceName)
  229216. : AudioIODevice (deviceName, "Audio"),
  229217. audioUnit (0),
  229218. isRunning (false),
  229219. callback (0),
  229220. actualBufferSize (0),
  229221. floatData (1, 2)
  229222. {
  229223. numInputChannels = 2;
  229224. numOutputChannels = 2;
  229225. preferredBufferSize = 0;
  229226. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229227. updateDeviceInfo();
  229228. }
  229229. ~IPhoneAudioIODevice()
  229230. {
  229231. close();
  229232. }
  229233. const StringArray getOutputChannelNames()
  229234. {
  229235. StringArray s;
  229236. s.add ("Left");
  229237. s.add ("Right");
  229238. return s;
  229239. }
  229240. const StringArray getInputChannelNames()
  229241. {
  229242. StringArray s;
  229243. if (audioInputIsAvailable)
  229244. {
  229245. s.add ("Left");
  229246. s.add ("Right");
  229247. }
  229248. return s;
  229249. }
  229250. int getNumSampleRates()
  229251. {
  229252. return 1;
  229253. }
  229254. double getSampleRate (int index)
  229255. {
  229256. return sampleRate;
  229257. }
  229258. int getNumBufferSizesAvailable()
  229259. {
  229260. return 1;
  229261. }
  229262. int getBufferSizeSamples (int index)
  229263. {
  229264. return getDefaultBufferSize();
  229265. }
  229266. int getDefaultBufferSize()
  229267. {
  229268. return 1024;
  229269. }
  229270. const String open (const BigInteger& inputChannels,
  229271. const BigInteger& outputChannels,
  229272. double sampleRate,
  229273. int bufferSize)
  229274. {
  229275. close();
  229276. lastError = String::empty;
  229277. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229278. // xxx set up channel mapping
  229279. activeOutputChans = outputChannels;
  229280. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229281. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229282. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229283. activeInputChans = inputChannels;
  229284. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229285. numInputChannels = activeInputChans.countNumberOfSetBits();
  229286. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229287. AudioSessionSetActive (true);
  229288. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229289. : kAudioSessionCategory_MediaPlayback;
  229290. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229291. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229292. fixAudioRouteIfSetToReceiver();
  229293. updateDeviceInfo();
  229294. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229295. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229296. actualBufferSize = preferredBufferSize;
  229297. prepareFloatBuffers();
  229298. isRunning = true;
  229299. propertyChanged (0, 0, 0); // creates and starts the AU
  229300. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229301. return lastError;
  229302. }
  229303. void close()
  229304. {
  229305. if (isRunning)
  229306. {
  229307. isRunning = false;
  229308. AudioSessionSetActive (false);
  229309. if (audioUnit != 0)
  229310. {
  229311. AudioComponentInstanceDispose (audioUnit);
  229312. audioUnit = 0;
  229313. }
  229314. }
  229315. }
  229316. bool isOpen()
  229317. {
  229318. return isRunning;
  229319. }
  229320. int getCurrentBufferSizeSamples()
  229321. {
  229322. return actualBufferSize;
  229323. }
  229324. double getCurrentSampleRate()
  229325. {
  229326. return sampleRate;
  229327. }
  229328. int getCurrentBitDepth()
  229329. {
  229330. return 16;
  229331. }
  229332. const BigInteger getActiveOutputChannels() const
  229333. {
  229334. return activeOutputChans;
  229335. }
  229336. const BigInteger getActiveInputChannels() const
  229337. {
  229338. return activeInputChans;
  229339. }
  229340. int getOutputLatencyInSamples()
  229341. {
  229342. return 0; //xxx
  229343. }
  229344. int getInputLatencyInSamples()
  229345. {
  229346. return 0; //xxx
  229347. }
  229348. void start (AudioIODeviceCallback* callback_)
  229349. {
  229350. if (isRunning && callback != callback_)
  229351. {
  229352. if (callback_ != 0)
  229353. callback_->audioDeviceAboutToStart (this);
  229354. const ScopedLock sl (callbackLock);
  229355. callback = callback_;
  229356. }
  229357. }
  229358. void stop()
  229359. {
  229360. if (isRunning)
  229361. {
  229362. AudioIODeviceCallback* lastCallback;
  229363. {
  229364. const ScopedLock sl (callbackLock);
  229365. lastCallback = callback;
  229366. callback = 0;
  229367. }
  229368. if (lastCallback != 0)
  229369. lastCallback->audioDeviceStopped();
  229370. }
  229371. }
  229372. bool isPlaying()
  229373. {
  229374. return isRunning && callback != 0;
  229375. }
  229376. const String getLastError()
  229377. {
  229378. return lastError;
  229379. }
  229380. private:
  229381. CriticalSection callbackLock;
  229382. Float64 sampleRate;
  229383. int numInputChannels, numOutputChannels;
  229384. int preferredBufferSize;
  229385. int actualBufferSize;
  229386. bool isRunning;
  229387. String lastError;
  229388. AudioStreamBasicDescription format;
  229389. AudioUnit audioUnit;
  229390. UInt32 audioInputIsAvailable;
  229391. AudioIODeviceCallback* callback;
  229392. BigInteger activeOutputChans, activeInputChans;
  229393. AudioSampleBuffer floatData;
  229394. float* inputChannels[3];
  229395. float* outputChannels[3];
  229396. bool monoInputChannelNumber, monoOutputChannelNumber;
  229397. void prepareFloatBuffers()
  229398. {
  229399. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229400. zerostruct (inputChannels);
  229401. zerostruct (outputChannels);
  229402. for (int i = 0; i < numInputChannels; ++i)
  229403. inputChannels[i] = floatData.getSampleData (i);
  229404. for (int i = 0; i < numOutputChannels; ++i)
  229405. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229406. }
  229407. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229408. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229409. {
  229410. OSStatus err = noErr;
  229411. if (audioInputIsAvailable)
  229412. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229413. const ScopedLock sl (callbackLock);
  229414. if (callback != 0)
  229415. {
  229416. if (audioInputIsAvailable && numInputChannels > 0)
  229417. {
  229418. short* shortData = (short*) ioData->mBuffers[0].mData;
  229419. if (numInputChannels >= 2)
  229420. {
  229421. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229422. {
  229423. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229424. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229425. }
  229426. }
  229427. else
  229428. {
  229429. if (monoInputChannelNumber > 0)
  229430. ++shortData;
  229431. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229432. {
  229433. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229434. ++shortData;
  229435. }
  229436. }
  229437. }
  229438. else
  229439. {
  229440. for (int i = numInputChannels; --i >= 0;)
  229441. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229442. }
  229443. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229444. outputChannels, numOutputChannels,
  229445. (int) inNumberFrames);
  229446. short* shortData = (short*) ioData->mBuffers[0].mData;
  229447. int n = 0;
  229448. if (numOutputChannels >= 2)
  229449. {
  229450. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229451. {
  229452. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229453. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229454. }
  229455. }
  229456. else if (numOutputChannels == 1)
  229457. {
  229458. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229459. {
  229460. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229461. shortData [n++] = s;
  229462. shortData [n++] = s;
  229463. }
  229464. }
  229465. else
  229466. {
  229467. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229468. }
  229469. }
  229470. else
  229471. {
  229472. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229473. }
  229474. return err;
  229475. }
  229476. void updateDeviceInfo()
  229477. {
  229478. UInt32 size = sizeof (sampleRate);
  229479. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229480. size = sizeof (audioInputIsAvailable);
  229481. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229482. }
  229483. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229484. {
  229485. if (! isRunning)
  229486. return;
  229487. if (inPropertyValue != 0)
  229488. {
  229489. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229490. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229491. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229492. SInt32 routeChangeReason;
  229493. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229494. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229495. fixAudioRouteIfSetToReceiver();
  229496. }
  229497. updateDeviceInfo();
  229498. createAudioUnit();
  229499. AudioSessionSetActive (true);
  229500. if (audioUnit != 0)
  229501. {
  229502. UInt32 formatSize = sizeof (format);
  229503. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229504. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229505. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229506. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229507. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229508. AudioOutputUnitStart (audioUnit);
  229509. }
  229510. }
  229511. void interruptionListener (UInt32 inInterruption)
  229512. {
  229513. /*if (inInterruption == kAudioSessionBeginInterruption)
  229514. {
  229515. isRunning = false;
  229516. AudioOutputUnitStop (audioUnit);
  229517. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229518. "This could have been interrupted by another application or by unplugging a headset",
  229519. @"Resume",
  229520. @"Cancel"))
  229521. {
  229522. isRunning = true;
  229523. propertyChanged (0, 0, 0);
  229524. }
  229525. }*/
  229526. if (inInterruption == kAudioSessionEndInterruption)
  229527. {
  229528. isRunning = true;
  229529. AudioSessionSetActive (true);
  229530. AudioOutputUnitStart (audioUnit);
  229531. }
  229532. }
  229533. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229534. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229535. {
  229536. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229537. }
  229538. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229539. {
  229540. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229541. }
  229542. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229543. {
  229544. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229545. }
  229546. void resetFormat (const int numChannels)
  229547. {
  229548. memset (&format, 0, sizeof (format));
  229549. format.mFormatID = kAudioFormatLinearPCM;
  229550. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229551. format.mBitsPerChannel = 8 * sizeof (short);
  229552. format.mChannelsPerFrame = 2;
  229553. format.mFramesPerPacket = 1;
  229554. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229555. }
  229556. bool createAudioUnit()
  229557. {
  229558. if (audioUnit != 0)
  229559. {
  229560. AudioComponentInstanceDispose (audioUnit);
  229561. audioUnit = 0;
  229562. }
  229563. resetFormat (2);
  229564. AudioComponentDescription desc;
  229565. desc.componentType = kAudioUnitType_Output;
  229566. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229567. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229568. desc.componentFlags = 0;
  229569. desc.componentFlagsMask = 0;
  229570. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229571. AudioComponentInstanceNew (comp, &audioUnit);
  229572. if (audioUnit == 0)
  229573. return false;
  229574. const UInt32 one = 1;
  229575. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229576. AudioChannelLayout layout;
  229577. layout.mChannelBitmap = 0;
  229578. layout.mNumberChannelDescriptions = 0;
  229579. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229580. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229581. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229582. AURenderCallbackStruct inputProc;
  229583. inputProc.inputProc = processStatic;
  229584. inputProc.inputProcRefCon = this;
  229585. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229586. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229587. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229588. AudioUnitInitialize (audioUnit);
  229589. return true;
  229590. }
  229591. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229592. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229593. static void fixAudioRouteIfSetToReceiver()
  229594. {
  229595. CFStringRef audioRoute = 0;
  229596. UInt32 propertySize = sizeof (audioRoute);
  229597. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229598. {
  229599. NSString* route = (NSString*) audioRoute;
  229600. //DBG ("audio route: " + nsStringToJuce (route));
  229601. if ([route hasPrefix: @"Receiver"])
  229602. {
  229603. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229604. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229605. }
  229606. CFRelease (audioRoute);
  229607. }
  229608. }
  229609. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229610. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229611. };
  229612. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229613. {
  229614. public:
  229615. IPhoneAudioIODeviceType()
  229616. : AudioIODeviceType ("iPhone Audio")
  229617. {
  229618. }
  229619. ~IPhoneAudioIODeviceType()
  229620. {
  229621. }
  229622. void scanForDevices()
  229623. {
  229624. }
  229625. const StringArray getDeviceNames (bool wantInputNames) const
  229626. {
  229627. StringArray s;
  229628. s.add ("iPhone Audio");
  229629. return s;
  229630. }
  229631. int getDefaultDeviceIndex (bool forInput) const
  229632. {
  229633. return 0;
  229634. }
  229635. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229636. {
  229637. return device != 0 ? 0 : -1;
  229638. }
  229639. bool hasSeparateInputsAndOutputs() const { return false; }
  229640. AudioIODevice* createDevice (const String& outputDeviceName,
  229641. const String& inputDeviceName)
  229642. {
  229643. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229644. {
  229645. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229646. : inputDeviceName);
  229647. }
  229648. return 0;
  229649. }
  229650. juce_UseDebuggingNewOperator
  229651. private:
  229652. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229653. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229654. };
  229655. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229656. {
  229657. return new IPhoneAudioIODeviceType();
  229658. }
  229659. #endif
  229660. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229661. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229662. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229663. // compiled on its own).
  229664. #if JUCE_INCLUDED_FILE
  229665. #if JUCE_MAC
  229666. #undef log
  229667. #define log(a) Logger::writeToLog(a)
  229668. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  229669. {
  229670. if (err == noErr)
  229671. return true;
  229672. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229673. jassertfalse;
  229674. return false;
  229675. }
  229676. #undef OK
  229677. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  229678. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229679. {
  229680. String result;
  229681. CFStringRef str = 0;
  229682. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229683. if (str != 0)
  229684. {
  229685. result = PlatformUtilities::cfStringToJuceString (str);
  229686. CFRelease (str);
  229687. str = 0;
  229688. }
  229689. MIDIEntityRef entity = 0;
  229690. MIDIEndpointGetEntity (endpoint, &entity);
  229691. if (entity == 0)
  229692. return result; // probably virtual
  229693. if (result.isEmpty())
  229694. {
  229695. // endpoint name has zero length - try the entity
  229696. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229697. if (str != 0)
  229698. {
  229699. result += PlatformUtilities::cfStringToJuceString (str);
  229700. CFRelease (str);
  229701. str = 0;
  229702. }
  229703. }
  229704. // now consider the device's name
  229705. MIDIDeviceRef device = 0;
  229706. MIDIEntityGetDevice (entity, &device);
  229707. if (device == 0)
  229708. return result;
  229709. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229710. if (str != 0)
  229711. {
  229712. const String s (PlatformUtilities::cfStringToJuceString (str));
  229713. CFRelease (str);
  229714. // if an external device has only one entity, throw away
  229715. // the endpoint name and just use the device name
  229716. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229717. {
  229718. result = s;
  229719. }
  229720. else if (! result.startsWithIgnoreCase (s))
  229721. {
  229722. // prepend the device name to the entity name
  229723. result = (s + " " + result).trimEnd();
  229724. }
  229725. }
  229726. return result;
  229727. }
  229728. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229729. {
  229730. String result;
  229731. // Does the endpoint have connections?
  229732. CFDataRef connections = 0;
  229733. int numConnections = 0;
  229734. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229735. if (connections != 0)
  229736. {
  229737. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229738. if (numConnections > 0)
  229739. {
  229740. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229741. for (int i = 0; i < numConnections; ++i, ++pid)
  229742. {
  229743. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229744. MIDIObjectRef connObject;
  229745. MIDIObjectType connObjectType;
  229746. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229747. if (err == noErr)
  229748. {
  229749. String s;
  229750. if (connObjectType == kMIDIObjectType_ExternalSource
  229751. || connObjectType == kMIDIObjectType_ExternalDestination)
  229752. {
  229753. // Connected to an external device's endpoint (10.3 and later).
  229754. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229755. }
  229756. else
  229757. {
  229758. // Connected to an external device (10.2) (or something else, catch-all)
  229759. CFStringRef str = 0;
  229760. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229761. if (str != 0)
  229762. {
  229763. s = PlatformUtilities::cfStringToJuceString (str);
  229764. CFRelease (str);
  229765. }
  229766. }
  229767. if (s.isNotEmpty())
  229768. {
  229769. if (result.isNotEmpty())
  229770. result += ", ";
  229771. result += s;
  229772. }
  229773. }
  229774. }
  229775. }
  229776. CFRelease (connections);
  229777. }
  229778. if (result.isNotEmpty())
  229779. return result;
  229780. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229781. return getEndpointName (endpoint, false);
  229782. }
  229783. const StringArray MidiOutput::getDevices()
  229784. {
  229785. StringArray s;
  229786. const ItemCount num = MIDIGetNumberOfDestinations();
  229787. for (ItemCount i = 0; i < num; ++i)
  229788. {
  229789. MIDIEndpointRef dest = MIDIGetDestination (i);
  229790. if (dest != 0)
  229791. {
  229792. String name (getConnectedEndpointName (dest));
  229793. if (name.isEmpty())
  229794. name = "<error>";
  229795. s.add (name);
  229796. }
  229797. else
  229798. {
  229799. s.add ("<error>");
  229800. }
  229801. }
  229802. return s;
  229803. }
  229804. int MidiOutput::getDefaultDeviceIndex()
  229805. {
  229806. return 0;
  229807. }
  229808. static MIDIClientRef globalMidiClient;
  229809. static bool hasGlobalClientBeenCreated = false;
  229810. static bool makeSureClientExists()
  229811. {
  229812. if (! hasGlobalClientBeenCreated)
  229813. {
  229814. String name ("JUCE");
  229815. if (JUCEApplication::getInstance() != 0)
  229816. name = JUCEApplication::getInstance()->getApplicationName();
  229817. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229818. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229819. CFRelease (appName);
  229820. }
  229821. return hasGlobalClientBeenCreated;
  229822. }
  229823. class MidiPortAndEndpoint
  229824. {
  229825. public:
  229826. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229827. : port (port_), endPoint (endPoint_)
  229828. {
  229829. }
  229830. ~MidiPortAndEndpoint()
  229831. {
  229832. if (port != 0)
  229833. MIDIPortDispose (port);
  229834. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229835. MIDIEndpointDispose (endPoint);
  229836. }
  229837. MIDIPortRef port;
  229838. MIDIEndpointRef endPoint;
  229839. };
  229840. MidiOutput* MidiOutput::openDevice (int index)
  229841. {
  229842. MidiOutput* mo = 0;
  229843. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229844. {
  229845. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229846. CFStringRef pname;
  229847. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229848. {
  229849. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  229850. if (makeSureClientExists())
  229851. {
  229852. MIDIPortRef port;
  229853. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  229854. {
  229855. mo = new MidiOutput();
  229856. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  229857. }
  229858. }
  229859. CFRelease (pname);
  229860. }
  229861. }
  229862. return mo;
  229863. }
  229864. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229865. {
  229866. MidiOutput* mo = 0;
  229867. if (makeSureClientExists())
  229868. {
  229869. MIDIEndpointRef endPoint;
  229870. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229871. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  229872. {
  229873. mo = new MidiOutput();
  229874. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  229875. }
  229876. CFRelease (name);
  229877. }
  229878. return mo;
  229879. }
  229880. MidiOutput::~MidiOutput()
  229881. {
  229882. delete static_cast<MidiPortAndEndpoint*> (internal);
  229883. }
  229884. void MidiOutput::reset()
  229885. {
  229886. }
  229887. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229888. {
  229889. return false;
  229890. }
  229891. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229892. {
  229893. }
  229894. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229895. {
  229896. MidiPortAndEndpoint* const mpe = static_cast<MidiPortAndEndpoint*> (internal);
  229897. if (message.isSysEx())
  229898. {
  229899. const int maxPacketSize = 256;
  229900. int pos = 0, bytesLeft = message.getRawDataSize();
  229901. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229902. HeapBlock <MIDIPacketList> packets;
  229903. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229904. packets->numPackets = numPackets;
  229905. MIDIPacket* p = packets->packet;
  229906. for (int i = 0; i < numPackets; ++i)
  229907. {
  229908. p->timeStamp = 0;
  229909. p->length = jmin (maxPacketSize, bytesLeft);
  229910. memcpy (p->data, message.getRawData() + pos, p->length);
  229911. pos += p->length;
  229912. bytesLeft -= p->length;
  229913. p = MIDIPacketNext (p);
  229914. }
  229915. if (mpe->port != 0)
  229916. MIDISend (mpe->port, mpe->endPoint, packets);
  229917. else
  229918. MIDIReceived (mpe->endPoint, packets);
  229919. }
  229920. else
  229921. {
  229922. MIDIPacketList packets;
  229923. packets.numPackets = 1;
  229924. packets.packet[0].timeStamp = 0;
  229925. packets.packet[0].length = message.getRawDataSize();
  229926. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229927. if (mpe->port != 0)
  229928. MIDISend (mpe->port, mpe->endPoint, &packets);
  229929. else
  229930. MIDIReceived (mpe->endPoint, &packets);
  229931. }
  229932. }
  229933. const StringArray MidiInput::getDevices()
  229934. {
  229935. StringArray s;
  229936. const ItemCount num = MIDIGetNumberOfSources();
  229937. for (ItemCount i = 0; i < num; ++i)
  229938. {
  229939. MIDIEndpointRef source = MIDIGetSource (i);
  229940. if (source != 0)
  229941. {
  229942. String name (getConnectedEndpointName (source));
  229943. if (name.isEmpty())
  229944. name = "<error>";
  229945. s.add (name);
  229946. }
  229947. else
  229948. {
  229949. s.add ("<error>");
  229950. }
  229951. }
  229952. return s;
  229953. }
  229954. int MidiInput::getDefaultDeviceIndex()
  229955. {
  229956. return 0;
  229957. }
  229958. struct MidiPortAndCallback
  229959. {
  229960. MidiInput* input;
  229961. MidiPortAndEndpoint* portAndEndpoint;
  229962. MidiInputCallback* callback;
  229963. MemoryBlock pendingData;
  229964. int pendingBytes;
  229965. double pendingDataTime;
  229966. bool active;
  229967. void processSysex (const uint8*& d, int& size, const double time)
  229968. {
  229969. if (*d == 0xf0)
  229970. {
  229971. pendingBytes = 0;
  229972. pendingDataTime = time;
  229973. }
  229974. pendingData.ensureSize (pendingBytes + size, false);
  229975. uint8* totalMessage = (uint8*) pendingData.getData();
  229976. uint8* dest = totalMessage + pendingBytes;
  229977. while (size > 0)
  229978. {
  229979. if (pendingBytes > 0 && *d >= 0x80)
  229980. {
  229981. if (*d >= 0xfa || *d == 0xf8)
  229982. {
  229983. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  229984. ++d;
  229985. --size;
  229986. }
  229987. else
  229988. {
  229989. if (*d == 0xf7)
  229990. {
  229991. *dest++ = *d++;
  229992. pendingBytes++;
  229993. --size;
  229994. }
  229995. break;
  229996. }
  229997. }
  229998. else
  229999. {
  230000. *dest++ = *d++;
  230001. pendingBytes++;
  230002. --size;
  230003. }
  230004. }
  230005. if (totalMessage [pendingBytes - 1] == 0xf7)
  230006. {
  230007. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  230008. pendingBytes = 0;
  230009. }
  230010. else
  230011. {
  230012. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  230013. }
  230014. }
  230015. };
  230016. namespace CoreMidiCallbacks
  230017. {
  230018. static CriticalSection callbackLock;
  230019. static Array<void*> activeCallbacks;
  230020. }
  230021. static void midiInputProc (const MIDIPacketList* pktlist,
  230022. void* readProcRefCon,
  230023. void* /*srcConnRefCon*/)
  230024. {
  230025. double time = Time::getMillisecondCounterHiRes() * 0.001;
  230026. const double originalTime = time;
  230027. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  230028. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230029. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  230030. {
  230031. const MIDIPacket* packet = &pktlist->packet[0];
  230032. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  230033. {
  230034. const uint8* d = (const uint8*) (packet->data);
  230035. int size = packet->length;
  230036. while (size > 0)
  230037. {
  230038. time = originalTime;
  230039. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  230040. {
  230041. mpc->processSysex (d, size, time);
  230042. }
  230043. else
  230044. {
  230045. int used = 0;
  230046. const MidiMessage m (d, size, used, 0, time);
  230047. if (used <= 0)
  230048. {
  230049. jassertfalse; // malformed midi message
  230050. break;
  230051. }
  230052. else
  230053. {
  230054. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  230055. }
  230056. size -= used;
  230057. d += used;
  230058. }
  230059. }
  230060. packet = MIDIPacketNext (packet);
  230061. }
  230062. }
  230063. }
  230064. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  230065. {
  230066. MidiInput* mi = 0;
  230067. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  230068. {
  230069. MIDIEndpointRef endPoint = MIDIGetSource (index);
  230070. if (endPoint != 0)
  230071. {
  230072. CFStringRef pname;
  230073. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  230074. {
  230075. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  230076. if (makeSureClientExists())
  230077. {
  230078. MIDIPortRef port;
  230079. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  230080. mpc->active = false;
  230081. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  230082. {
  230083. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  230084. {
  230085. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  230086. mpc->callback = callback;
  230087. mpc->pendingBytes = 0;
  230088. mpc->pendingData.ensureSize (128);
  230089. mi = new MidiInput (getDevices() [index]);
  230090. mpc->input = mi;
  230091. mi->internal = mpc;
  230092. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230093. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  230094. }
  230095. else
  230096. {
  230097. OK (MIDIPortDispose (port));
  230098. }
  230099. }
  230100. }
  230101. }
  230102. CFRelease (pname);
  230103. }
  230104. }
  230105. return mi;
  230106. }
  230107. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  230108. {
  230109. MidiInput* mi = 0;
  230110. if (makeSureClientExists())
  230111. {
  230112. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  230113. mpc->active = false;
  230114. MIDIEndpointRef endPoint;
  230115. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  230116. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  230117. {
  230118. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  230119. mpc->callback = callback;
  230120. mpc->pendingBytes = 0;
  230121. mpc->pendingData.ensureSize (128);
  230122. mi = new MidiInput (deviceName);
  230123. mpc->input = mi;
  230124. mi->internal = mpc;
  230125. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230126. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  230127. }
  230128. CFRelease (name);
  230129. }
  230130. return mi;
  230131. }
  230132. MidiInput::MidiInput (const String& name_)
  230133. : name (name_)
  230134. {
  230135. }
  230136. MidiInput::~MidiInput()
  230137. {
  230138. MidiPortAndCallback* const mpc = static_cast<MidiPortAndCallback*> (internal);
  230139. mpc->active = false;
  230140. {
  230141. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230142. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  230143. }
  230144. if (mpc->portAndEndpoint->port != 0)
  230145. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  230146. delete mpc->portAndEndpoint;
  230147. delete mpc;
  230148. }
  230149. void MidiInput::start()
  230150. {
  230151. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230152. static_cast<MidiPortAndCallback*> (internal)->active = true;
  230153. }
  230154. void MidiInput::stop()
  230155. {
  230156. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  230157. static_cast<MidiPortAndCallback*> (internal)->active = false;
  230158. }
  230159. #undef log
  230160. #else
  230161. MidiOutput::~MidiOutput()
  230162. {
  230163. }
  230164. void MidiOutput::reset()
  230165. {
  230166. }
  230167. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  230168. {
  230169. return false;
  230170. }
  230171. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  230172. {
  230173. }
  230174. void MidiOutput::sendMessageNow (const MidiMessage& message)
  230175. {
  230176. }
  230177. const StringArray MidiOutput::getDevices()
  230178. {
  230179. return StringArray();
  230180. }
  230181. MidiOutput* MidiOutput::openDevice (int index)
  230182. {
  230183. return 0;
  230184. }
  230185. const StringArray MidiInput::getDevices()
  230186. {
  230187. return StringArray();
  230188. }
  230189. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  230190. {
  230191. return 0;
  230192. }
  230193. #endif
  230194. #endif
  230195. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  230196. #else
  230197. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  230198. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230199. // compiled on its own).
  230200. #if JUCE_INCLUDED_FILE
  230201. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230202. #define SUPPORT_10_4_FONTS 1
  230203. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  230204. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230205. #define SUPPORT_ONLY_10_4_FONTS 1
  230206. #endif
  230207. END_JUCE_NAMESPACE
  230208. @interface NSFont (PrivateHack)
  230209. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  230210. @end
  230211. BEGIN_JUCE_NAMESPACE
  230212. #endif
  230213. class MacTypeface : public Typeface
  230214. {
  230215. public:
  230216. MacTypeface (const Font& font)
  230217. : Typeface (font.getTypefaceName())
  230218. {
  230219. const ScopedAutoReleasePool pool;
  230220. renderingTransform = CGAffineTransformIdentity;
  230221. bool needsItalicTransform = false;
  230222. #if JUCE_IOS
  230223. NSString* fontName = juceStringToNS (font.getTypefaceName());
  230224. if (font.isItalic() || font.isBold())
  230225. {
  230226. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  230227. for (NSString* i in familyFonts)
  230228. {
  230229. const String fn (nsStringToJuce (i));
  230230. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  230231. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  230232. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  230233. || afterDash.containsIgnoreCase ("italic")
  230234. || fn.endsWithIgnoreCase ("oblique")
  230235. || fn.endsWithIgnoreCase ("italic");
  230236. if (probablyBold == font.isBold()
  230237. && probablyItalic == font.isItalic())
  230238. {
  230239. fontName = i;
  230240. needsItalicTransform = false;
  230241. break;
  230242. }
  230243. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  230244. {
  230245. fontName = i;
  230246. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  230247. }
  230248. }
  230249. if (needsItalicTransform)
  230250. renderingTransform.c = 0.15f;
  230251. }
  230252. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  230253. const int ascender = abs (CGFontGetAscent (fontRef));
  230254. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  230255. ascent = ascender / totalHeight;
  230256. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230257. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  230258. #else
  230259. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  230260. if (font.isItalic())
  230261. {
  230262. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  230263. toHaveTrait: NSItalicFontMask];
  230264. if (newFont == nsFont)
  230265. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  230266. nsFont = newFont;
  230267. }
  230268. if (font.isBold())
  230269. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  230270. [nsFont retain];
  230271. ascent = std::abs ((float) [nsFont ascender]);
  230272. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  230273. ascent /= totalSize;
  230274. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  230275. if (needsItalicTransform)
  230276. {
  230277. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  230278. renderingTransform.c = 0.15f;
  230279. }
  230280. #if SUPPORT_ONLY_10_4_FONTS
  230281. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230282. if (atsFont == 0)
  230283. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230284. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230285. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230286. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230287. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230288. #else
  230289. #if SUPPORT_10_4_FONTS
  230290. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230291. {
  230292. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230293. if (atsFont == 0)
  230294. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230295. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230296. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230297. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230298. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230299. }
  230300. else
  230301. #endif
  230302. {
  230303. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  230304. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  230305. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230306. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  230307. }
  230308. #endif
  230309. #endif
  230310. }
  230311. ~MacTypeface()
  230312. {
  230313. #if ! JUCE_IOS
  230314. [nsFont release];
  230315. #endif
  230316. if (fontRef != 0)
  230317. CGFontRelease (fontRef);
  230318. }
  230319. float getAscent() const
  230320. {
  230321. return ascent;
  230322. }
  230323. float getDescent() const
  230324. {
  230325. return 1.0f - ascent;
  230326. }
  230327. float getStringWidth (const String& text)
  230328. {
  230329. if (fontRef == 0 || text.isEmpty())
  230330. return 0;
  230331. const int length = text.length();
  230332. HeapBlock <CGGlyph> glyphs;
  230333. createGlyphsForString (text, length, glyphs);
  230334. float x = 0;
  230335. #if SUPPORT_ONLY_10_4_FONTS
  230336. HeapBlock <NSSize> advances (length);
  230337. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230338. for (int i = 0; i < length; ++i)
  230339. x += advances[i].width;
  230340. #else
  230341. #if SUPPORT_10_4_FONTS
  230342. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230343. {
  230344. HeapBlock <NSSize> advances (length);
  230345. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230346. for (int i = 0; i < length; ++i)
  230347. x += advances[i].width;
  230348. }
  230349. else
  230350. #endif
  230351. {
  230352. HeapBlock <int> advances (length);
  230353. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230354. for (int i = 0; i < length; ++i)
  230355. x += advances[i];
  230356. }
  230357. #endif
  230358. return x * unitsToHeightScaleFactor;
  230359. }
  230360. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230361. {
  230362. xOffsets.add (0);
  230363. if (fontRef == 0 || text.isEmpty())
  230364. return;
  230365. const int length = text.length();
  230366. HeapBlock <CGGlyph> glyphs;
  230367. createGlyphsForString (text, length, glyphs);
  230368. #if SUPPORT_ONLY_10_4_FONTS
  230369. HeapBlock <NSSize> advances (length);
  230370. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230371. int x = 0;
  230372. for (int i = 0; i < length; ++i)
  230373. {
  230374. x += advances[i].width;
  230375. xOffsets.add (x * unitsToHeightScaleFactor);
  230376. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230377. }
  230378. #else
  230379. #if SUPPORT_10_4_FONTS
  230380. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230381. {
  230382. HeapBlock <NSSize> advances (length);
  230383. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230384. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230385. float x = 0;
  230386. for (int i = 0; i < length; ++i)
  230387. {
  230388. x += advances[i].width;
  230389. xOffsets.add (x * unitsToHeightScaleFactor);
  230390. resultGlyphs.add (nsGlyphs[i]);
  230391. }
  230392. }
  230393. else
  230394. #endif
  230395. {
  230396. HeapBlock <int> advances (length);
  230397. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230398. {
  230399. int x = 0;
  230400. for (int i = 0; i < length; ++i)
  230401. {
  230402. x += advances [i];
  230403. xOffsets.add (x * unitsToHeightScaleFactor);
  230404. resultGlyphs.add (glyphs[i]);
  230405. }
  230406. }
  230407. }
  230408. #endif
  230409. }
  230410. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230411. {
  230412. #if JUCE_IOS
  230413. return false;
  230414. #else
  230415. if (nsFont == 0)
  230416. return false;
  230417. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230418. jassert (path.isEmpty());
  230419. const ScopedAutoReleasePool pool;
  230420. NSBezierPath* bez = [NSBezierPath bezierPath];
  230421. [bez moveToPoint: NSMakePoint (0, 0)];
  230422. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230423. inFont: nsFont];
  230424. for (int i = 0; i < [bez elementCount]; ++i)
  230425. {
  230426. NSPoint p[3];
  230427. switch ([bez elementAtIndex: i associatedPoints: p])
  230428. {
  230429. case NSMoveToBezierPathElement:
  230430. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230431. break;
  230432. case NSLineToBezierPathElement:
  230433. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230434. break;
  230435. case NSCurveToBezierPathElement:
  230436. 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);
  230437. break;
  230438. case NSClosePathBezierPathElement:
  230439. path.closeSubPath();
  230440. break;
  230441. default:
  230442. jassertfalse;
  230443. break;
  230444. }
  230445. }
  230446. path.applyTransform (pathTransform);
  230447. return true;
  230448. #endif
  230449. }
  230450. juce_UseDebuggingNewOperator
  230451. CGFontRef fontRef;
  230452. float fontHeightToCGSizeFactor;
  230453. CGAffineTransform renderingTransform;
  230454. private:
  230455. float ascent, unitsToHeightScaleFactor;
  230456. #if JUCE_IOS
  230457. #else
  230458. NSFont* nsFont;
  230459. AffineTransform pathTransform;
  230460. #endif
  230461. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230462. {
  230463. #if SUPPORT_10_4_FONTS
  230464. #if ! SUPPORT_ONLY_10_4_FONTS
  230465. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230466. #endif
  230467. {
  230468. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230469. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230470. for (int i = 0; i < length; ++i)
  230471. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230472. return;
  230473. }
  230474. #endif
  230475. #if ! SUPPORT_ONLY_10_4_FONTS
  230476. if (charToGlyphMapper == 0)
  230477. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230478. glyphs.malloc (length);
  230479. for (int i = 0; i < length; ++i)
  230480. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230481. #endif
  230482. }
  230483. #if ! SUPPORT_ONLY_10_4_FONTS
  230484. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230485. class CharToGlyphMapper
  230486. {
  230487. public:
  230488. CharToGlyphMapper (CGFontRef fontRef)
  230489. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230490. idRangeOffset (0), glyphIndexes (0)
  230491. {
  230492. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230493. if (cmapTable != 0)
  230494. {
  230495. const int numSubtables = getValue16 (cmapTable, 2);
  230496. for (int i = 0; i < numSubtables; ++i)
  230497. {
  230498. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230499. {
  230500. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230501. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230502. {
  230503. const int length = getValue16 (cmapTable, offset + 2);
  230504. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230505. segCount = segCountX2 / 2;
  230506. const int endCodeOffset = offset + 14;
  230507. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230508. const int idDeltaOffset = startCodeOffset + segCountX2;
  230509. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230510. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230511. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230512. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230513. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230514. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230515. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230516. }
  230517. break;
  230518. }
  230519. }
  230520. CFRelease (cmapTable);
  230521. }
  230522. }
  230523. ~CharToGlyphMapper()
  230524. {
  230525. if (endCode != 0)
  230526. {
  230527. CFRelease (endCode);
  230528. CFRelease (startCode);
  230529. CFRelease (idDelta);
  230530. CFRelease (idRangeOffset);
  230531. CFRelease (glyphIndexes);
  230532. }
  230533. }
  230534. int getGlyphForCharacter (const juce_wchar c) const
  230535. {
  230536. for (int i = 0; i < segCount; ++i)
  230537. {
  230538. if (getValue16 (endCode, i * 2) >= c)
  230539. {
  230540. const int start = getValue16 (startCode, i * 2);
  230541. if (start > c)
  230542. break;
  230543. const int delta = getValue16 (idDelta, i * 2);
  230544. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230545. if (rangeOffset == 0)
  230546. return delta + c;
  230547. else
  230548. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230549. }
  230550. }
  230551. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230552. return jmax (-1, c - 29);
  230553. }
  230554. private:
  230555. int segCount;
  230556. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230557. static uint16 getValue16 (CFDataRef data, const int index)
  230558. {
  230559. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230560. }
  230561. static uint32 getValue32 (CFDataRef data, const int index)
  230562. {
  230563. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230564. }
  230565. };
  230566. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230567. #endif
  230568. MacTypeface (const MacTypeface&);
  230569. MacTypeface& operator= (const MacTypeface&);
  230570. };
  230571. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230572. {
  230573. return new MacTypeface (font);
  230574. }
  230575. const StringArray Font::findAllTypefaceNames()
  230576. {
  230577. StringArray names;
  230578. const ScopedAutoReleasePool pool;
  230579. #if JUCE_IOS
  230580. NSArray* fonts = [UIFont familyNames];
  230581. #else
  230582. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230583. #endif
  230584. for (unsigned int i = 0; i < [fonts count]; ++i)
  230585. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230586. names.sort (true);
  230587. return names;
  230588. }
  230589. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230590. {
  230591. #if JUCE_IOS
  230592. defaultSans = "Helvetica";
  230593. defaultSerif = "Times New Roman";
  230594. defaultFixed = "Courier New";
  230595. #else
  230596. defaultSans = "Lucida Grande";
  230597. defaultSerif = "Times New Roman";
  230598. defaultFixed = "Monaco";
  230599. #endif
  230600. }
  230601. #endif
  230602. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230603. // (must go before juce_mac_CoreGraphicsContext.mm)
  230604. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230605. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230606. // compiled on its own).
  230607. #if JUCE_INCLUDED_FILE
  230608. class CoreGraphicsImage : public Image::SharedImage
  230609. {
  230610. public:
  230611. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230612. : Image::SharedImage (format_, width_, height_)
  230613. {
  230614. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230615. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230616. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230617. imageData = imageDataAllocated;
  230618. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230619. : CGColorSpaceCreateDeviceRGB();
  230620. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230621. colourSpace, getCGImageFlags (format_));
  230622. CGColorSpaceRelease (colourSpace);
  230623. }
  230624. ~CoreGraphicsImage()
  230625. {
  230626. CGContextRelease (context);
  230627. }
  230628. Image::ImageType getType() const { return Image::NativeImage; }
  230629. LowLevelGraphicsContext* createLowLevelContext();
  230630. SharedImage* clone()
  230631. {
  230632. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230633. memcpy (im->imageData, imageData, lineStride * height);
  230634. return im;
  230635. }
  230636. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230637. {
  230638. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230639. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230640. {
  230641. return CGBitmapContextCreateImage (nativeImage->context);
  230642. }
  230643. else
  230644. {
  230645. const Image::BitmapData srcData (juceImage, false);
  230646. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230647. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230648. 8, srcData.pixelStride * 8, srcData.lineStride,
  230649. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230650. 0, true, kCGRenderingIntentDefault);
  230651. CGDataProviderRelease (provider);
  230652. return imageRef;
  230653. }
  230654. }
  230655. #if JUCE_MAC
  230656. static NSImage* createNSImage (const Image& image)
  230657. {
  230658. const ScopedAutoReleasePool pool;
  230659. NSImage* im = [[NSImage alloc] init];
  230660. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230661. [im lockFocus];
  230662. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230663. CGImageRef imageRef = createImage (image, false, colourSpace);
  230664. CGColorSpaceRelease (colourSpace);
  230665. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230666. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230667. CGImageRelease (imageRef);
  230668. [im unlockFocus];
  230669. return im;
  230670. }
  230671. #endif
  230672. CGContextRef context;
  230673. HeapBlock<uint8> imageDataAllocated;
  230674. private:
  230675. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230676. {
  230677. #if JUCE_BIG_ENDIAN
  230678. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230679. #else
  230680. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230681. #endif
  230682. }
  230683. };
  230684. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230685. {
  230686. #if USE_COREGRAPHICS_RENDERING
  230687. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230688. #else
  230689. return createSoftwareImage (format, width, height, clearImage);
  230690. #endif
  230691. }
  230692. class CoreGraphicsContext : public LowLevelGraphicsContext
  230693. {
  230694. public:
  230695. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230696. : context (context_),
  230697. flipHeight (flipHeight_),
  230698. state (new SavedState()),
  230699. numGradientLookupEntries (0),
  230700. lastClipRectIsValid (false)
  230701. {
  230702. CGContextRetain (context);
  230703. CGContextSaveGState(context);
  230704. CGContextSetShouldSmoothFonts (context, true);
  230705. CGContextSetShouldAntialias (context, true);
  230706. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230707. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230708. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230709. gradientCallbacks.version = 0;
  230710. gradientCallbacks.evaluate = gradientCallback;
  230711. gradientCallbacks.releaseInfo = 0;
  230712. setFont (Font());
  230713. }
  230714. ~CoreGraphicsContext()
  230715. {
  230716. CGContextRestoreGState (context);
  230717. CGContextRelease (context);
  230718. CGColorSpaceRelease (rgbColourSpace);
  230719. CGColorSpaceRelease (greyColourSpace);
  230720. }
  230721. bool isVectorDevice() const { return false; }
  230722. void setOrigin (int x, int y)
  230723. {
  230724. CGContextTranslateCTM (context, x, -y);
  230725. if (lastClipRectIsValid)
  230726. lastClipRect.translate (-x, -y);
  230727. }
  230728. bool clipToRectangle (const Rectangle<int>& r)
  230729. {
  230730. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230731. if (lastClipRectIsValid)
  230732. {
  230733. // This is actually incorrect, because the actual clip region may be complex, and
  230734. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230735. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230736. // when calculating the resultant clip bounds, and makes the same mistake!
  230737. lastClipRect = lastClipRect.getIntersection (r);
  230738. return ! lastClipRect.isEmpty();
  230739. }
  230740. return ! isClipEmpty();
  230741. }
  230742. bool clipToRectangleList (const RectangleList& clipRegion)
  230743. {
  230744. if (clipRegion.isEmpty())
  230745. {
  230746. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230747. lastClipRectIsValid = true;
  230748. lastClipRect = Rectangle<int>();
  230749. return false;
  230750. }
  230751. else
  230752. {
  230753. const int numRects = clipRegion.getNumRectangles();
  230754. HeapBlock <CGRect> rects (numRects);
  230755. for (int i = 0; i < numRects; ++i)
  230756. {
  230757. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230758. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230759. }
  230760. CGContextClipToRects (context, rects, numRects);
  230761. lastClipRectIsValid = false;
  230762. return ! isClipEmpty();
  230763. }
  230764. }
  230765. void excludeClipRectangle (const Rectangle<int>& r)
  230766. {
  230767. RectangleList remaining (getClipBounds());
  230768. remaining.subtract (r);
  230769. clipToRectangleList (remaining);
  230770. lastClipRectIsValid = false;
  230771. }
  230772. void clipToPath (const Path& path, const AffineTransform& transform)
  230773. {
  230774. createPath (path, transform);
  230775. CGContextClip (context);
  230776. lastClipRectIsValid = false;
  230777. }
  230778. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230779. {
  230780. if (! transform.isSingularity())
  230781. {
  230782. Image singleChannelImage (sourceImage);
  230783. if (sourceImage.getFormat() != Image::SingleChannel)
  230784. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230785. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230786. flip();
  230787. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230788. applyTransform (t);
  230789. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230790. CGContextClipToMask (context, r, image);
  230791. applyTransform (t.inverted());
  230792. flip();
  230793. CGImageRelease (image);
  230794. lastClipRectIsValid = false;
  230795. }
  230796. }
  230797. bool clipRegionIntersects (const Rectangle<int>& r)
  230798. {
  230799. return getClipBounds().intersects (r);
  230800. }
  230801. const Rectangle<int> getClipBounds() const
  230802. {
  230803. if (! lastClipRectIsValid)
  230804. {
  230805. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230806. lastClipRectIsValid = true;
  230807. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230808. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230809. roundToInt (bounds.size.width),
  230810. roundToInt (bounds.size.height));
  230811. }
  230812. return lastClipRect;
  230813. }
  230814. bool isClipEmpty() const
  230815. {
  230816. return getClipBounds().isEmpty();
  230817. }
  230818. void saveState()
  230819. {
  230820. CGContextSaveGState (context);
  230821. stateStack.add (new SavedState (*state));
  230822. }
  230823. void restoreState()
  230824. {
  230825. CGContextRestoreGState (context);
  230826. SavedState* const top = stateStack.getLast();
  230827. if (top != 0)
  230828. {
  230829. state = top;
  230830. stateStack.removeLast (1, false);
  230831. lastClipRectIsValid = false;
  230832. }
  230833. else
  230834. {
  230835. jassertfalse; // trying to pop with an empty stack!
  230836. }
  230837. }
  230838. void setFill (const FillType& fillType)
  230839. {
  230840. state->fillType = fillType;
  230841. if (fillType.isColour())
  230842. {
  230843. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230844. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230845. CGContextSetAlpha (context, 1.0f);
  230846. }
  230847. }
  230848. void setOpacity (float newOpacity)
  230849. {
  230850. state->fillType.setOpacity (newOpacity);
  230851. setFill (state->fillType);
  230852. }
  230853. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230854. {
  230855. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230856. ? kCGInterpolationLow
  230857. : kCGInterpolationHigh);
  230858. }
  230859. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230860. {
  230861. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230862. }
  230863. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230864. {
  230865. if (replaceExistingContents)
  230866. {
  230867. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230868. CGContextClearRect (context, cgRect);
  230869. #else
  230870. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230871. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230872. CGContextClearRect (context, cgRect);
  230873. else
  230874. #endif
  230875. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230876. #endif
  230877. fillCGRect (cgRect, false);
  230878. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230879. }
  230880. else
  230881. {
  230882. if (state->fillType.isColour())
  230883. {
  230884. CGContextFillRect (context, cgRect);
  230885. }
  230886. else if (state->fillType.isGradient())
  230887. {
  230888. CGContextSaveGState (context);
  230889. CGContextClipToRect (context, cgRect);
  230890. drawGradient();
  230891. CGContextRestoreGState (context);
  230892. }
  230893. else
  230894. {
  230895. CGContextSaveGState (context);
  230896. CGContextClipToRect (context, cgRect);
  230897. drawImage (state->fillType.image, state->fillType.transform, true);
  230898. CGContextRestoreGState (context);
  230899. }
  230900. }
  230901. }
  230902. void fillPath (const Path& path, const AffineTransform& transform)
  230903. {
  230904. CGContextSaveGState (context);
  230905. if (state->fillType.isColour())
  230906. {
  230907. flip();
  230908. applyTransform (transform);
  230909. createPath (path);
  230910. if (path.isUsingNonZeroWinding())
  230911. CGContextFillPath (context);
  230912. else
  230913. CGContextEOFillPath (context);
  230914. }
  230915. else
  230916. {
  230917. createPath (path, transform);
  230918. if (path.isUsingNonZeroWinding())
  230919. CGContextClip (context);
  230920. else
  230921. CGContextEOClip (context);
  230922. if (state->fillType.isGradient())
  230923. drawGradient();
  230924. else
  230925. drawImage (state->fillType.image, state->fillType.transform, true);
  230926. }
  230927. CGContextRestoreGState (context);
  230928. }
  230929. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230930. {
  230931. const int iw = sourceImage.getWidth();
  230932. const int ih = sourceImage.getHeight();
  230933. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230934. CGContextSaveGState (context);
  230935. CGContextSetAlpha (context, state->fillType.getOpacity());
  230936. flip();
  230937. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230938. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230939. if (fillEntireClipAsTiles)
  230940. {
  230941. #if JUCE_IOS
  230942. CGContextDrawTiledImage (context, imageRect, image);
  230943. #else
  230944. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230945. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230946. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230947. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230948. CGContextDrawTiledImage (context, imageRect, image);
  230949. else
  230950. #endif
  230951. {
  230952. // Fallback to manually doing a tiled fill on 10.4
  230953. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230954. int x = 0, y = 0;
  230955. while (x > clip.origin.x) x -= iw;
  230956. while (y > clip.origin.y) y -= ih;
  230957. const int right = (int) (clip.origin.x + clip.size.width);
  230958. const int bottom = (int) (clip.origin.y + clip.size.height);
  230959. while (y < bottom)
  230960. {
  230961. for (int x2 = x; x2 < right; x2 += iw)
  230962. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230963. y += ih;
  230964. }
  230965. }
  230966. #endif
  230967. }
  230968. else
  230969. {
  230970. CGContextDrawImage (context, imageRect, image);
  230971. }
  230972. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230973. CGContextRestoreGState (context);
  230974. }
  230975. void drawLine (const Line<float>& line)
  230976. {
  230977. if (state->fillType.isColour())
  230978. {
  230979. CGContextSetLineCap (context, kCGLineCapSquare);
  230980. CGContextSetLineWidth (context, 1.0f);
  230981. CGContextSetRGBStrokeColor (context,
  230982. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230983. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230984. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230985. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230986. CGContextStrokeLineSegments (context, cgLine, 1);
  230987. }
  230988. else
  230989. {
  230990. Path p;
  230991. p.addLineSegment (line, 1.0f);
  230992. fillPath (p, AffineTransform::identity);
  230993. }
  230994. }
  230995. void drawVerticalLine (const int x, float top, float bottom)
  230996. {
  230997. if (state->fillType.isColour())
  230998. {
  230999. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  231000. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  231001. #else
  231002. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  231003. // the x co-ord slightly to trick it..
  231004. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  231005. #endif
  231006. }
  231007. else
  231008. {
  231009. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  231010. }
  231011. }
  231012. void drawHorizontalLine (const int y, float left, float right)
  231013. {
  231014. if (state->fillType.isColour())
  231015. {
  231016. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  231017. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  231018. #else
  231019. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  231020. // the x co-ord slightly to trick it..
  231021. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  231022. #endif
  231023. }
  231024. else
  231025. {
  231026. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  231027. }
  231028. }
  231029. void setFont (const Font& newFont)
  231030. {
  231031. if (state->font != newFont)
  231032. {
  231033. state->fontRef = 0;
  231034. state->font = newFont;
  231035. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  231036. if (mf != 0)
  231037. {
  231038. state->fontRef = mf->fontRef;
  231039. CGContextSetFont (context, state->fontRef);
  231040. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  231041. state->fontTransform = mf->renderingTransform;
  231042. state->fontTransform.a *= state->font.getHorizontalScale();
  231043. CGContextSetTextMatrix (context, state->fontTransform);
  231044. }
  231045. }
  231046. }
  231047. const Font getFont()
  231048. {
  231049. return state->font;
  231050. }
  231051. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  231052. {
  231053. if (state->fontRef != 0 && state->fillType.isColour())
  231054. {
  231055. if (transform.isOnlyTranslation())
  231056. {
  231057. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  231058. CGGlyph g = glyphNumber;
  231059. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  231060. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  231061. }
  231062. else
  231063. {
  231064. CGContextSaveGState (context);
  231065. flip();
  231066. applyTransform (transform);
  231067. CGAffineTransform t = state->fontTransform;
  231068. t.d = -t.d;
  231069. CGContextSetTextMatrix (context, t);
  231070. CGGlyph g = glyphNumber;
  231071. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  231072. CGContextRestoreGState (context);
  231073. }
  231074. }
  231075. else
  231076. {
  231077. Path p;
  231078. Font& f = state->font;
  231079. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  231080. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  231081. .followedBy (transform));
  231082. }
  231083. }
  231084. private:
  231085. CGContextRef context;
  231086. const CGFloat flipHeight;
  231087. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  231088. CGFunctionCallbacks gradientCallbacks;
  231089. mutable Rectangle<int> lastClipRect;
  231090. mutable bool lastClipRectIsValid;
  231091. struct SavedState
  231092. {
  231093. SavedState()
  231094. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  231095. {
  231096. }
  231097. SavedState (const SavedState& other)
  231098. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  231099. fontTransform (other.fontTransform)
  231100. {
  231101. }
  231102. ~SavedState()
  231103. {
  231104. }
  231105. FillType fillType;
  231106. Font font;
  231107. CGFontRef fontRef;
  231108. CGAffineTransform fontTransform;
  231109. };
  231110. ScopedPointer <SavedState> state;
  231111. OwnedArray <SavedState> stateStack;
  231112. HeapBlock <PixelARGB> gradientLookupTable;
  231113. int numGradientLookupEntries;
  231114. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  231115. {
  231116. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  231117. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  231118. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  231119. colour.unpremultiply();
  231120. outData[0] = colour.getRed() / 255.0f;
  231121. outData[1] = colour.getGreen() / 255.0f;
  231122. outData[2] = colour.getBlue() / 255.0f;
  231123. outData[3] = colour.getAlpha() / 255.0f;
  231124. }
  231125. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  231126. {
  231127. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  231128. --numGradientLookupEntries;
  231129. CGShadingRef result = 0;
  231130. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  231131. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  231132. if (gradient.isRadial)
  231133. {
  231134. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  231135. p1, gradient.point1.getDistanceFrom (gradient.point2),
  231136. function, true, true);
  231137. }
  231138. else
  231139. {
  231140. result = CGShadingCreateAxial (rgbColourSpace, p1,
  231141. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  231142. function, true, true);
  231143. }
  231144. CGFunctionRelease (function);
  231145. return result;
  231146. }
  231147. void drawGradient()
  231148. {
  231149. flip();
  231150. applyTransform (state->fillType.transform);
  231151. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  231152. // you draw a gradient with high quality interp enabled).
  231153. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  231154. CGContextSetAlpha (context, state->fillType.getOpacity());
  231155. CGContextDrawShading (context, shading);
  231156. CGShadingRelease (shading);
  231157. }
  231158. void createPath (const Path& path) const
  231159. {
  231160. CGContextBeginPath (context);
  231161. Path::Iterator i (path);
  231162. while (i.next())
  231163. {
  231164. switch (i.elementType)
  231165. {
  231166. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  231167. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  231168. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  231169. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  231170. case Path::Iterator::closePath: CGContextClosePath (context); break;
  231171. default: jassertfalse; break;
  231172. }
  231173. }
  231174. }
  231175. void createPath (const Path& path, const AffineTransform& transform) const
  231176. {
  231177. CGContextBeginPath (context);
  231178. Path::Iterator i (path);
  231179. while (i.next())
  231180. {
  231181. switch (i.elementType)
  231182. {
  231183. case Path::Iterator::startNewSubPath:
  231184. transform.transformPoint (i.x1, i.y1);
  231185. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  231186. break;
  231187. case Path::Iterator::lineTo:
  231188. transform.transformPoint (i.x1, i.y1);
  231189. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  231190. break;
  231191. case Path::Iterator::quadraticTo:
  231192. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  231193. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  231194. break;
  231195. case Path::Iterator::cubicTo:
  231196. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  231197. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  231198. break;
  231199. case Path::Iterator::closePath:
  231200. CGContextClosePath (context); break;
  231201. default:
  231202. jassertfalse;
  231203. break;
  231204. }
  231205. }
  231206. }
  231207. void flip() const
  231208. {
  231209. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  231210. }
  231211. void applyTransform (const AffineTransform& transform) const
  231212. {
  231213. CGAffineTransform t;
  231214. t.a = transform.mat00;
  231215. t.b = transform.mat10;
  231216. t.c = transform.mat01;
  231217. t.d = transform.mat11;
  231218. t.tx = transform.mat02;
  231219. t.ty = transform.mat12;
  231220. CGContextConcatCTM (context, t);
  231221. }
  231222. CoreGraphicsContext (const CoreGraphicsContext&);
  231223. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  231224. };
  231225. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  231226. {
  231227. return new CoreGraphicsContext (context, height);
  231228. }
  231229. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  231230. const Image juce_loadWithCoreImage (InputStream& input)
  231231. {
  231232. MemoryBlock data;
  231233. input.readIntoMemoryBlock (data, -1);
  231234. #if JUCE_IOS
  231235. JUCE_AUTORELEASEPOOL
  231236. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData() length: data.getSize()]];
  231237. if (image != nil)
  231238. {
  231239. CGImageRef loadedImage = image.CGImage;
  231240. #else
  231241. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  231242. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  231243. CGDataProviderRelease (provider);
  231244. if (imageSource != 0)
  231245. {
  231246. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  231247. CFRelease (imageSource);
  231248. #endif
  231249. if (loadedImage != 0)
  231250. {
  231251. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  231252. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  231253. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  231254. hasAlphaChan, Image::NativeImage);
  231255. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  231256. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  231257. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  231258. CGContextFlush (cgImage->context);
  231259. #if ! JUCE_IOS
  231260. CFRelease (loadedImage);
  231261. #endif
  231262. return image;
  231263. }
  231264. }
  231265. return Image::null;
  231266. }
  231267. #endif
  231268. #endif
  231269. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  231270. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231271. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231272. // compiled on its own).
  231273. #if JUCE_INCLUDED_FILE
  231274. class NSViewComponentPeer;
  231275. END_JUCE_NAMESPACE
  231276. @interface NSEvent (JuceDeviceDelta)
  231277. - (float) deviceDeltaX;
  231278. - (float) deviceDeltaY;
  231279. @end
  231280. #define JuceNSView MakeObjCClassName(JuceNSView)
  231281. @interface JuceNSView : NSView<NSTextInput>
  231282. {
  231283. @public
  231284. NSViewComponentPeer* owner;
  231285. NSNotificationCenter* notificationCenter;
  231286. String* stringBeingComposed;
  231287. bool textWasInserted;
  231288. }
  231289. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  231290. - (void) dealloc;
  231291. - (BOOL) isOpaque;
  231292. - (void) drawRect: (NSRect) r;
  231293. - (void) mouseDown: (NSEvent*) ev;
  231294. - (void) asyncMouseDown: (NSEvent*) ev;
  231295. - (void) mouseUp: (NSEvent*) ev;
  231296. - (void) asyncMouseUp: (NSEvent*) ev;
  231297. - (void) mouseDragged: (NSEvent*) ev;
  231298. - (void) mouseMoved: (NSEvent*) ev;
  231299. - (void) mouseEntered: (NSEvent*) ev;
  231300. - (void) mouseExited: (NSEvent*) ev;
  231301. - (void) rightMouseDown: (NSEvent*) ev;
  231302. - (void) rightMouseDragged: (NSEvent*) ev;
  231303. - (void) rightMouseUp: (NSEvent*) ev;
  231304. - (void) otherMouseDown: (NSEvent*) ev;
  231305. - (void) otherMouseDragged: (NSEvent*) ev;
  231306. - (void) otherMouseUp: (NSEvent*) ev;
  231307. - (void) scrollWheel: (NSEvent*) ev;
  231308. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  231309. - (void) frameChanged: (NSNotification*) n;
  231310. - (void) viewDidMoveToWindow;
  231311. - (void) keyDown: (NSEvent*) ev;
  231312. - (void) keyUp: (NSEvent*) ev;
  231313. // NSTextInput Methods
  231314. - (void) insertText: (id) aString;
  231315. - (void) doCommandBySelector: (SEL) aSelector;
  231316. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231317. - (void) unmarkText;
  231318. - (BOOL) hasMarkedText;
  231319. - (long) conversationIdentifier;
  231320. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231321. - (NSRange) markedRange;
  231322. - (NSRange) selectedRange;
  231323. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231324. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231325. - (NSArray*) validAttributesForMarkedText;
  231326. - (void) flagsChanged: (NSEvent*) ev;
  231327. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231328. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231329. #endif
  231330. - (BOOL) becomeFirstResponder;
  231331. - (BOOL) resignFirstResponder;
  231332. - (BOOL) acceptsFirstResponder;
  231333. - (void) asyncRepaint: (id) rect;
  231334. - (NSArray*) getSupportedDragTypes;
  231335. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231336. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231337. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231338. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231339. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231340. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231341. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231342. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231343. @end
  231344. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231345. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231346. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231347. #else
  231348. @interface JuceNSWindow : NSWindow
  231349. #endif
  231350. {
  231351. @private
  231352. NSViewComponentPeer* owner;
  231353. bool isZooming;
  231354. }
  231355. - (void) setOwner: (NSViewComponentPeer*) owner;
  231356. - (BOOL) canBecomeKeyWindow;
  231357. - (void) becomeKeyWindow;
  231358. - (BOOL) windowShouldClose: (id) window;
  231359. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231360. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231361. - (void) zoom: (id) sender;
  231362. @end
  231363. BEGIN_JUCE_NAMESPACE
  231364. class NSViewComponentPeer : public ComponentPeer
  231365. {
  231366. public:
  231367. NSViewComponentPeer (Component* const component,
  231368. const int windowStyleFlags,
  231369. NSView* viewToAttachTo);
  231370. ~NSViewComponentPeer();
  231371. void* getNativeHandle() const;
  231372. void setVisible (bool shouldBeVisible);
  231373. void setTitle (const String& title);
  231374. void setPosition (int x, int y);
  231375. void setSize (int w, int h);
  231376. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231377. const Rectangle<int> getBounds (const bool global) const;
  231378. const Rectangle<int> getBounds() const;
  231379. const Point<int> getScreenPosition() const;
  231380. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231381. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231382. void setMinimised (bool shouldBeMinimised);
  231383. bool isMinimised() const;
  231384. void setFullScreen (bool shouldBeFullScreen);
  231385. bool isFullScreen() const;
  231386. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231387. const BorderSize getFrameSize() const;
  231388. bool setAlwaysOnTop (bool alwaysOnTop);
  231389. void toFront (bool makeActiveWindow);
  231390. void toBehind (ComponentPeer* other);
  231391. void setIcon (const Image& newIcon);
  231392. const StringArray getAvailableRenderingEngines();
  231393. int getCurrentRenderingEngine() throw();
  231394. void setCurrentRenderingEngine (int index);
  231395. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231396. for example having more than one juce plugin loaded into a host, then when a
  231397. method is called, the actual code that runs might actually be in a different module
  231398. than the one you expect... So any calls to library functions or statics that are
  231399. made inside obj-c methods will probably end up getting executed in a different DLL's
  231400. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231401. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231402. virtual methods of an object that's known to live inside the right module's space.
  231403. */
  231404. virtual void redirectMouseDown (NSEvent* ev);
  231405. virtual void redirectMouseUp (NSEvent* ev);
  231406. virtual void redirectMouseDrag (NSEvent* ev);
  231407. virtual void redirectMouseMove (NSEvent* ev);
  231408. virtual void redirectMouseEnter (NSEvent* ev);
  231409. virtual void redirectMouseExit (NSEvent* ev);
  231410. virtual void redirectMouseWheel (NSEvent* ev);
  231411. void sendMouseEvent (NSEvent* ev);
  231412. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231413. virtual bool redirectKeyDown (NSEvent* ev);
  231414. virtual bool redirectKeyUp (NSEvent* ev);
  231415. virtual void redirectModKeyChange (NSEvent* ev);
  231416. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231417. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231418. #endif
  231419. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231420. virtual bool isOpaque();
  231421. virtual void drawRect (NSRect r);
  231422. virtual bool canBecomeKeyWindow();
  231423. virtual bool windowShouldClose();
  231424. virtual void redirectMovedOrResized();
  231425. virtual void viewMovedToWindow();
  231426. virtual NSRect constrainRect (NSRect r);
  231427. static void showArrowCursorIfNeeded();
  231428. static void updateModifiers (NSEvent* e);
  231429. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231430. static int getKeyCodeFromEvent (NSEvent* ev)
  231431. {
  231432. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231433. int keyCode = unmodified[0];
  231434. if (keyCode == 0x19) // (backwards-tab)
  231435. keyCode = '\t';
  231436. else if (keyCode == 0x03) // (enter)
  231437. keyCode = '\r';
  231438. else
  231439. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231440. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231441. {
  231442. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231443. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231444. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231445. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231446. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231447. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231448. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231449. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231450. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231451. if (keyCode == numPadConversions [i])
  231452. keyCode = numPadConversions [i + 1];
  231453. }
  231454. return keyCode;
  231455. }
  231456. static int64 getMouseTime (NSEvent* e)
  231457. {
  231458. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231459. + (int64) ([e timestamp] * 1000.0);
  231460. }
  231461. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231462. {
  231463. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231464. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231465. }
  231466. static int getModifierForButtonNumber (const NSInteger num)
  231467. {
  231468. return num == 0 ? ModifierKeys::leftButtonModifier
  231469. : (num == 1 ? ModifierKeys::rightButtonModifier
  231470. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231471. }
  231472. virtual void viewFocusGain();
  231473. virtual void viewFocusLoss();
  231474. bool isFocused() const;
  231475. void grabFocus();
  231476. void textInputRequired (const Point<int>& position);
  231477. void repaint (const Rectangle<int>& area);
  231478. void performAnyPendingRepaintsNow();
  231479. juce_UseDebuggingNewOperator
  231480. NSWindow* window;
  231481. JuceNSView* view;
  231482. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231483. static ModifierKeys currentModifiers;
  231484. static ComponentPeer* currentlyFocusedPeer;
  231485. static Array<int> keysCurrentlyDown;
  231486. };
  231487. END_JUCE_NAMESPACE
  231488. @implementation JuceNSView
  231489. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231490. withFrame: (NSRect) frame
  231491. {
  231492. [super initWithFrame: frame];
  231493. owner = owner_;
  231494. stringBeingComposed = 0;
  231495. textWasInserted = false;
  231496. notificationCenter = [NSNotificationCenter defaultCenter];
  231497. [notificationCenter addObserver: self
  231498. selector: @selector (frameChanged:)
  231499. name: NSViewFrameDidChangeNotification
  231500. object: self];
  231501. if (! owner_->isSharedWindow)
  231502. {
  231503. [notificationCenter addObserver: self
  231504. selector: @selector (frameChanged:)
  231505. name: NSWindowDidMoveNotification
  231506. object: owner_->window];
  231507. }
  231508. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231509. return self;
  231510. }
  231511. - (void) dealloc
  231512. {
  231513. [notificationCenter removeObserver: self];
  231514. delete stringBeingComposed;
  231515. [super dealloc];
  231516. }
  231517. - (void) drawRect: (NSRect) r
  231518. {
  231519. if (owner != 0)
  231520. owner->drawRect (r);
  231521. }
  231522. - (BOOL) isOpaque
  231523. {
  231524. return owner == 0 || owner->isOpaque();
  231525. }
  231526. - (void) mouseDown: (NSEvent*) ev
  231527. {
  231528. if (JUCEApplication::isStandaloneApp())
  231529. [self asyncMouseDown: ev];
  231530. else
  231531. // In some host situations, the host will stop modal loops from working
  231532. // correctly if they're called from a mouse event, so we'll trigger
  231533. // the event asynchronously..
  231534. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231535. withObject: ev
  231536. waitUntilDone: NO];
  231537. }
  231538. - (void) asyncMouseDown: (NSEvent*) ev
  231539. {
  231540. if (owner != 0)
  231541. owner->redirectMouseDown (ev);
  231542. }
  231543. - (void) mouseUp: (NSEvent*) ev
  231544. {
  231545. if (! JUCEApplication::isStandaloneApp())
  231546. [self asyncMouseUp: ev];
  231547. else
  231548. // In some host situations, the host will stop modal loops from working
  231549. // correctly if they're called from a mouse event, so we'll trigger
  231550. // the event asynchronously..
  231551. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231552. withObject: ev
  231553. waitUntilDone: NO];
  231554. }
  231555. - (void) asyncMouseUp: (NSEvent*) ev
  231556. {
  231557. if (owner != 0)
  231558. owner->redirectMouseUp (ev);
  231559. }
  231560. - (void) mouseDragged: (NSEvent*) ev
  231561. {
  231562. if (owner != 0)
  231563. owner->redirectMouseDrag (ev);
  231564. }
  231565. - (void) mouseMoved: (NSEvent*) ev
  231566. {
  231567. if (owner != 0)
  231568. owner->redirectMouseMove (ev);
  231569. }
  231570. - (void) mouseEntered: (NSEvent*) ev
  231571. {
  231572. if (owner != 0)
  231573. owner->redirectMouseEnter (ev);
  231574. }
  231575. - (void) mouseExited: (NSEvent*) ev
  231576. {
  231577. if (owner != 0)
  231578. owner->redirectMouseExit (ev);
  231579. }
  231580. - (void) rightMouseDown: (NSEvent*) ev
  231581. {
  231582. [self mouseDown: ev];
  231583. }
  231584. - (void) rightMouseDragged: (NSEvent*) ev
  231585. {
  231586. [self mouseDragged: ev];
  231587. }
  231588. - (void) rightMouseUp: (NSEvent*) ev
  231589. {
  231590. [self mouseUp: ev];
  231591. }
  231592. - (void) otherMouseDown: (NSEvent*) ev
  231593. {
  231594. [self mouseDown: ev];
  231595. }
  231596. - (void) otherMouseDragged: (NSEvent*) ev
  231597. {
  231598. [self mouseDragged: ev];
  231599. }
  231600. - (void) otherMouseUp: (NSEvent*) ev
  231601. {
  231602. [self mouseUp: ev];
  231603. }
  231604. - (void) scrollWheel: (NSEvent*) ev
  231605. {
  231606. if (owner != 0)
  231607. owner->redirectMouseWheel (ev);
  231608. }
  231609. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231610. {
  231611. (void) ev;
  231612. return YES;
  231613. }
  231614. - (void) frameChanged: (NSNotification*) n
  231615. {
  231616. (void) n;
  231617. if (owner != 0)
  231618. owner->redirectMovedOrResized();
  231619. }
  231620. - (void) viewDidMoveToWindow
  231621. {
  231622. if (owner != 0)
  231623. owner->viewMovedToWindow();
  231624. }
  231625. - (void) asyncRepaint: (id) rect
  231626. {
  231627. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231628. [self setNeedsDisplayInRect: *r];
  231629. }
  231630. - (void) keyDown: (NSEvent*) ev
  231631. {
  231632. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231633. textWasInserted = false;
  231634. if (target != 0)
  231635. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231636. else
  231637. deleteAndZero (stringBeingComposed);
  231638. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231639. [super keyDown: ev];
  231640. }
  231641. - (void) keyUp: (NSEvent*) ev
  231642. {
  231643. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231644. [super keyUp: ev];
  231645. }
  231646. - (void) insertText: (id) aString
  231647. {
  231648. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231649. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231650. if ([newText length] > 0)
  231651. {
  231652. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231653. if (target != 0)
  231654. {
  231655. target->insertTextAtCaret (nsStringToJuce (newText));
  231656. textWasInserted = true;
  231657. }
  231658. }
  231659. deleteAndZero (stringBeingComposed);
  231660. }
  231661. - (void) doCommandBySelector: (SEL) aSelector
  231662. {
  231663. (void) aSelector;
  231664. }
  231665. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231666. {
  231667. (void) selectionRange;
  231668. if (stringBeingComposed == 0)
  231669. stringBeingComposed = new String();
  231670. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231671. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231672. if (target != 0)
  231673. {
  231674. const Range<int> currentHighlight (target->getHighlightedRegion());
  231675. target->insertTextAtCaret (*stringBeingComposed);
  231676. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231677. textWasInserted = true;
  231678. }
  231679. }
  231680. - (void) unmarkText
  231681. {
  231682. if (stringBeingComposed != 0)
  231683. {
  231684. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231685. if (target != 0)
  231686. {
  231687. target->insertTextAtCaret (*stringBeingComposed);
  231688. textWasInserted = true;
  231689. }
  231690. }
  231691. deleteAndZero (stringBeingComposed);
  231692. }
  231693. - (BOOL) hasMarkedText
  231694. {
  231695. return stringBeingComposed != 0;
  231696. }
  231697. - (long) conversationIdentifier
  231698. {
  231699. return (long) (pointer_sized_int) self;
  231700. }
  231701. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231702. {
  231703. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231704. if (target != 0)
  231705. {
  231706. const Range<int> r ((int) theRange.location,
  231707. (int) (theRange.location + theRange.length));
  231708. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231709. }
  231710. return nil;
  231711. }
  231712. - (NSRange) markedRange
  231713. {
  231714. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231715. : NSMakeRange (NSNotFound, 0);
  231716. }
  231717. - (NSRange) selectedRange
  231718. {
  231719. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231720. if (target != 0)
  231721. {
  231722. const Range<int> highlight (target->getHighlightedRegion());
  231723. if (! highlight.isEmpty())
  231724. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231725. }
  231726. return NSMakeRange (NSNotFound, 0);
  231727. }
  231728. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231729. {
  231730. (void) theRange;
  231731. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231732. if (comp == 0)
  231733. return NSMakeRect (0, 0, 0, 0);
  231734. const Rectangle<int> bounds (comp->getScreenBounds());
  231735. return NSMakeRect (bounds.getX(),
  231736. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231737. bounds.getWidth(),
  231738. bounds.getHeight());
  231739. }
  231740. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231741. {
  231742. (void) thePoint;
  231743. return NSNotFound;
  231744. }
  231745. - (NSArray*) validAttributesForMarkedText
  231746. {
  231747. return [NSArray array];
  231748. }
  231749. - (void) flagsChanged: (NSEvent*) ev
  231750. {
  231751. if (owner != 0)
  231752. owner->redirectModKeyChange (ev);
  231753. }
  231754. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231755. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231756. {
  231757. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231758. return true;
  231759. return [super performKeyEquivalent: ev];
  231760. }
  231761. #endif
  231762. - (BOOL) becomeFirstResponder
  231763. {
  231764. if (owner != 0)
  231765. owner->viewFocusGain();
  231766. return true;
  231767. }
  231768. - (BOOL) resignFirstResponder
  231769. {
  231770. if (owner != 0)
  231771. owner->viewFocusLoss();
  231772. return true;
  231773. }
  231774. - (BOOL) acceptsFirstResponder
  231775. {
  231776. return owner != 0 && owner->canBecomeKeyWindow();
  231777. }
  231778. - (NSArray*) getSupportedDragTypes
  231779. {
  231780. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231781. }
  231782. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231783. {
  231784. return owner != 0 && owner->sendDragCallback (type, sender);
  231785. }
  231786. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231787. {
  231788. if ([self sendDragCallback: 0 sender: sender])
  231789. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231790. else
  231791. return NSDragOperationNone;
  231792. }
  231793. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231794. {
  231795. if ([self sendDragCallback: 0 sender: sender])
  231796. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231797. else
  231798. return NSDragOperationNone;
  231799. }
  231800. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231801. {
  231802. [self sendDragCallback: 1 sender: sender];
  231803. }
  231804. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231805. {
  231806. [self sendDragCallback: 1 sender: sender];
  231807. }
  231808. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231809. {
  231810. (void) sender;
  231811. return YES;
  231812. }
  231813. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231814. {
  231815. return [self sendDragCallback: 2 sender: sender];
  231816. }
  231817. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231818. {
  231819. (void) sender;
  231820. }
  231821. @end
  231822. @implementation JuceNSWindow
  231823. - (void) setOwner: (NSViewComponentPeer*) owner_
  231824. {
  231825. owner = owner_;
  231826. isZooming = false;
  231827. }
  231828. - (BOOL) canBecomeKeyWindow
  231829. {
  231830. return owner != 0 && owner->canBecomeKeyWindow();
  231831. }
  231832. - (void) becomeKeyWindow
  231833. {
  231834. [super becomeKeyWindow];
  231835. if (owner != 0)
  231836. owner->grabFocus();
  231837. }
  231838. - (BOOL) windowShouldClose: (id) window
  231839. {
  231840. (void) window;
  231841. return owner == 0 || owner->windowShouldClose();
  231842. }
  231843. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231844. {
  231845. (void) screen;
  231846. if (owner != 0)
  231847. frameRect = owner->constrainRect (frameRect);
  231848. return frameRect;
  231849. }
  231850. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231851. {
  231852. (void) window;
  231853. if (isZooming)
  231854. return proposedFrameSize;
  231855. NSRect frameRect = [self frame];
  231856. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231857. frameRect.size = proposedFrameSize;
  231858. if (owner != 0)
  231859. frameRect = owner->constrainRect (frameRect);
  231860. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231861. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231862. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231863. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231864. return frameRect.size;
  231865. }
  231866. - (void) zoom: (id) sender
  231867. {
  231868. isZooming = true;
  231869. [super zoom: sender];
  231870. isZooming = false;
  231871. }
  231872. - (void) windowWillMove: (NSNotification*) notification
  231873. {
  231874. (void) notification;
  231875. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231876. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231877. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231878. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231879. }
  231880. @end
  231881. BEGIN_JUCE_NAMESPACE
  231882. ModifierKeys NSViewComponentPeer::currentModifiers;
  231883. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231884. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231885. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231886. {
  231887. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231888. return true;
  231889. if (keyCode >= 'A' && keyCode <= 'Z'
  231890. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231891. return true;
  231892. if (keyCode >= 'a' && keyCode <= 'z'
  231893. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231894. return true;
  231895. return false;
  231896. }
  231897. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231898. {
  231899. int m = 0;
  231900. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231901. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231902. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231903. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231904. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231905. }
  231906. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231907. {
  231908. updateModifiers (ev);
  231909. int keyCode = getKeyCodeFromEvent (ev);
  231910. if (keyCode != 0)
  231911. {
  231912. if (isKeyDown)
  231913. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231914. else
  231915. keysCurrentlyDown.removeValue (keyCode);
  231916. }
  231917. }
  231918. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231919. {
  231920. return NSViewComponentPeer::currentModifiers;
  231921. }
  231922. void ModifierKeys::updateCurrentModifiers() throw()
  231923. {
  231924. currentModifiers = NSViewComponentPeer::currentModifiers;
  231925. }
  231926. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231927. const int windowStyleFlags,
  231928. NSView* viewToAttachTo)
  231929. : ComponentPeer (component_, windowStyleFlags),
  231930. window (0),
  231931. view (0),
  231932. isSharedWindow (viewToAttachTo != 0),
  231933. fullScreen (false),
  231934. insideDrawRect (false),
  231935. #if USE_COREGRAPHICS_RENDERING
  231936. usingCoreGraphics (true),
  231937. #else
  231938. usingCoreGraphics (false),
  231939. #endif
  231940. recursiveToFrontCall (false)
  231941. {
  231942. NSRect r;
  231943. r.origin.x = 0;
  231944. r.origin.y = 0;
  231945. r.size.width = (float) component->getWidth();
  231946. r.size.height = (float) component->getHeight();
  231947. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231948. [view setPostsFrameChangedNotifications: YES];
  231949. if (isSharedWindow)
  231950. {
  231951. window = [viewToAttachTo window];
  231952. [viewToAttachTo addSubview: view];
  231953. setVisible (component->isVisible());
  231954. }
  231955. else
  231956. {
  231957. r.origin.x = (float) component->getX();
  231958. r.origin.y = (float) component->getY();
  231959. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231960. unsigned int style = 0;
  231961. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231962. style = NSBorderlessWindowMask;
  231963. else
  231964. style = NSTitledWindowMask;
  231965. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231966. style |= NSMiniaturizableWindowMask;
  231967. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231968. style |= NSClosableWindowMask;
  231969. if ((windowStyleFlags & windowIsResizable) != 0)
  231970. style |= NSResizableWindowMask;
  231971. window = [[JuceNSWindow alloc] initWithContentRect: r
  231972. styleMask: style
  231973. backing: NSBackingStoreBuffered
  231974. defer: YES];
  231975. [((JuceNSWindow*) window) setOwner: this];
  231976. [window orderOut: nil];
  231977. [window setDelegate: (JuceNSWindow*) window];
  231978. [window setOpaque: component->isOpaque()];
  231979. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231980. if (component->isAlwaysOnTop())
  231981. [window setLevel: NSFloatingWindowLevel];
  231982. [window setContentView: view];
  231983. [window setAutodisplay: YES];
  231984. [window setAcceptsMouseMovedEvents: YES];
  231985. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231986. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231987. [window setReleasedWhenClosed: YES];
  231988. [window retain];
  231989. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231990. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231991. }
  231992. setTitle (component->getName());
  231993. }
  231994. NSViewComponentPeer::~NSViewComponentPeer()
  231995. {
  231996. view->owner = 0;
  231997. [view removeFromSuperview];
  231998. [view release];
  231999. if (! isSharedWindow)
  232000. {
  232001. [((JuceNSWindow*) window) setOwner: 0];
  232002. [window close];
  232003. [window release];
  232004. }
  232005. }
  232006. void* NSViewComponentPeer::getNativeHandle() const
  232007. {
  232008. return view;
  232009. }
  232010. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  232011. {
  232012. if (isSharedWindow)
  232013. {
  232014. [view setHidden: ! shouldBeVisible];
  232015. }
  232016. else
  232017. {
  232018. if (shouldBeVisible)
  232019. {
  232020. [window orderFront: nil];
  232021. handleBroughtToFront();
  232022. }
  232023. else
  232024. {
  232025. [window orderOut: nil];
  232026. }
  232027. }
  232028. }
  232029. void NSViewComponentPeer::setTitle (const String& title)
  232030. {
  232031. const ScopedAutoReleasePool pool;
  232032. if (! isSharedWindow)
  232033. [window setTitle: juceStringToNS (title)];
  232034. }
  232035. void NSViewComponentPeer::setPosition (int x, int y)
  232036. {
  232037. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  232038. }
  232039. void NSViewComponentPeer::setSize (int w, int h)
  232040. {
  232041. setBounds (component->getX(), component->getY(), w, h, false);
  232042. }
  232043. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  232044. {
  232045. fullScreen = isNowFullScreen;
  232046. w = jmax (0, w);
  232047. h = jmax (0, h);
  232048. NSRect r;
  232049. r.origin.x = (float) x;
  232050. r.origin.y = (float) y;
  232051. r.size.width = (float) w;
  232052. r.size.height = (float) h;
  232053. if (isSharedWindow)
  232054. {
  232055. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232056. if ([view frame].size.width != r.size.width
  232057. || [view frame].size.height != r.size.height)
  232058. [view setNeedsDisplay: true];
  232059. [view setFrame: r];
  232060. }
  232061. else
  232062. {
  232063. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  232064. [window setFrame: [window frameRectForContentRect: r]
  232065. display: true];
  232066. }
  232067. }
  232068. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  232069. {
  232070. NSRect r = [view frame];
  232071. if (global && [view window] != 0)
  232072. {
  232073. r = [view convertRect: r toView: nil];
  232074. NSRect wr = [[view window] frame];
  232075. r.origin.x += wr.origin.x;
  232076. r.origin.y += wr.origin.y;
  232077. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232078. }
  232079. else
  232080. {
  232081. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  232082. }
  232083. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  232084. }
  232085. const Rectangle<int> NSViewComponentPeer::getBounds() const
  232086. {
  232087. return getBounds (! isSharedWindow);
  232088. }
  232089. const Point<int> NSViewComponentPeer::getScreenPosition() const
  232090. {
  232091. return getBounds (true).getPosition();
  232092. }
  232093. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  232094. {
  232095. return relativePosition + getScreenPosition();
  232096. }
  232097. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  232098. {
  232099. return screenPosition - getScreenPosition();
  232100. }
  232101. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  232102. {
  232103. if (constrainer != 0)
  232104. {
  232105. NSRect current = [window frame];
  232106. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  232107. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232108. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  232109. (int) r.size.width, (int) r.size.height);
  232110. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  232111. (int) current.size.width, (int) current.size.height);
  232112. constrainer->checkBounds (pos, original,
  232113. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232114. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  232115. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  232116. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  232117. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  232118. r.origin.x = pos.getX();
  232119. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  232120. r.size.width = pos.getWidth();
  232121. r.size.height = pos.getHeight();
  232122. }
  232123. return r;
  232124. }
  232125. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  232126. {
  232127. if (! isSharedWindow)
  232128. {
  232129. if (shouldBeMinimised)
  232130. [window miniaturize: nil];
  232131. else
  232132. [window deminiaturize: nil];
  232133. }
  232134. }
  232135. bool NSViewComponentPeer::isMinimised() const
  232136. {
  232137. return window != 0 && [window isMiniaturized];
  232138. }
  232139. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  232140. {
  232141. if (! isSharedWindow)
  232142. {
  232143. Rectangle<int> r (lastNonFullscreenBounds);
  232144. setMinimised (false);
  232145. if (fullScreen != shouldBeFullScreen)
  232146. {
  232147. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  232148. {
  232149. fullScreen = true;
  232150. [window performZoom: nil];
  232151. }
  232152. else
  232153. {
  232154. if (shouldBeFullScreen)
  232155. r = Desktop::getInstance().getMainMonitorArea();
  232156. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  232157. if (r != getComponent()->getBounds() && ! r.isEmpty())
  232158. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  232159. }
  232160. }
  232161. }
  232162. }
  232163. bool NSViewComponentPeer::isFullScreen() const
  232164. {
  232165. return fullScreen;
  232166. }
  232167. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  232168. {
  232169. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  232170. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  232171. return false;
  232172. NSPoint p;
  232173. p.x = (float) position.getX();
  232174. p.y = (float) position.getY();
  232175. NSView* v = [view hitTest: p];
  232176. if (trueIfInAChildWindow)
  232177. return v != nil;
  232178. return v == view;
  232179. }
  232180. const BorderSize NSViewComponentPeer::getFrameSize() const
  232181. {
  232182. BorderSize b;
  232183. if (! isSharedWindow)
  232184. {
  232185. NSRect v = [view convertRect: [view frame] toView: nil];
  232186. NSRect w = [window frame];
  232187. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  232188. b.setBottom ((int) v.origin.y);
  232189. b.setLeft ((int) v.origin.x);
  232190. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  232191. }
  232192. return b;
  232193. }
  232194. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  232195. {
  232196. if (! isSharedWindow)
  232197. {
  232198. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  232199. : NSNormalWindowLevel];
  232200. }
  232201. return true;
  232202. }
  232203. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  232204. {
  232205. if (isSharedWindow)
  232206. {
  232207. [[view superview] addSubview: view
  232208. positioned: NSWindowAbove
  232209. relativeTo: nil];
  232210. }
  232211. if (window != 0 && component->isVisible())
  232212. {
  232213. if (makeActiveWindow)
  232214. [window makeKeyAndOrderFront: nil];
  232215. else
  232216. [window orderFront: nil];
  232217. if (! recursiveToFrontCall)
  232218. {
  232219. recursiveToFrontCall = true;
  232220. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232221. handleBroughtToFront();
  232222. recursiveToFrontCall = false;
  232223. }
  232224. }
  232225. }
  232226. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  232227. {
  232228. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  232229. jassert (otherPeer != 0); // wrong type of window?
  232230. if (otherPeer != 0)
  232231. {
  232232. if (isSharedWindow)
  232233. {
  232234. [[view superview] addSubview: view
  232235. positioned: NSWindowBelow
  232236. relativeTo: otherPeer->view];
  232237. }
  232238. else
  232239. {
  232240. [window orderWindow: NSWindowBelow
  232241. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  232242. : nil ];
  232243. }
  232244. }
  232245. }
  232246. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  232247. {
  232248. // to do..
  232249. }
  232250. void NSViewComponentPeer::viewFocusGain()
  232251. {
  232252. if (currentlyFocusedPeer != this)
  232253. {
  232254. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  232255. currentlyFocusedPeer->handleFocusLoss();
  232256. currentlyFocusedPeer = this;
  232257. handleFocusGain();
  232258. }
  232259. }
  232260. void NSViewComponentPeer::viewFocusLoss()
  232261. {
  232262. if (currentlyFocusedPeer == this)
  232263. {
  232264. currentlyFocusedPeer = 0;
  232265. handleFocusLoss();
  232266. }
  232267. }
  232268. void juce_HandleProcessFocusChange()
  232269. {
  232270. NSViewComponentPeer::keysCurrentlyDown.clear();
  232271. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  232272. {
  232273. if (Process::isForegroundProcess())
  232274. {
  232275. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  232276. ComponentPeer::bringModalComponentToFront();
  232277. }
  232278. else
  232279. {
  232280. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  232281. // turn kiosk mode off if we lose focus..
  232282. Desktop::getInstance().setKioskModeComponent (0);
  232283. }
  232284. }
  232285. }
  232286. bool NSViewComponentPeer::isFocused() const
  232287. {
  232288. return isSharedWindow ? this == currentlyFocusedPeer
  232289. : (window != 0 && [window isKeyWindow]);
  232290. }
  232291. void NSViewComponentPeer::grabFocus()
  232292. {
  232293. if (window != 0)
  232294. {
  232295. [window makeKeyWindow];
  232296. [window makeFirstResponder: view];
  232297. viewFocusGain();
  232298. }
  232299. }
  232300. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  232301. {
  232302. }
  232303. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  232304. {
  232305. String unicode (nsStringToJuce ([ev characters]));
  232306. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  232307. int keyCode = getKeyCodeFromEvent (ev);
  232308. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  232309. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  232310. if (unicode.isNotEmpty() || keyCode != 0)
  232311. {
  232312. if (isKeyDown)
  232313. {
  232314. bool used = false;
  232315. while (unicode.length() > 0)
  232316. {
  232317. juce_wchar textCharacter = unicode[0];
  232318. unicode = unicode.substring (1);
  232319. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232320. textCharacter = 0;
  232321. used = handleKeyUpOrDown (true) || used;
  232322. used = handleKeyPress (keyCode, textCharacter) || used;
  232323. }
  232324. return used;
  232325. }
  232326. else
  232327. {
  232328. if (handleKeyUpOrDown (false))
  232329. return true;
  232330. }
  232331. }
  232332. return false;
  232333. }
  232334. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232335. {
  232336. updateKeysDown (ev, true);
  232337. bool used = handleKeyEvent (ev, true);
  232338. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232339. {
  232340. // for command keys, the key-up event is thrown away, so simulate one..
  232341. updateKeysDown (ev, false);
  232342. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232343. }
  232344. // (If we're running modally, don't allow unused keystrokes to be passed
  232345. // along to other blocked views..)
  232346. if (Component::getCurrentlyModalComponent() != 0)
  232347. used = true;
  232348. return used;
  232349. }
  232350. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232351. {
  232352. updateKeysDown (ev, false);
  232353. return handleKeyEvent (ev, false)
  232354. || Component::getCurrentlyModalComponent() != 0;
  232355. }
  232356. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232357. {
  232358. keysCurrentlyDown.clear();
  232359. handleKeyUpOrDown (true);
  232360. updateModifiers (ev);
  232361. handleModifierKeysChange();
  232362. }
  232363. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232364. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232365. {
  232366. if ([ev type] == NSKeyDown)
  232367. return redirectKeyDown (ev);
  232368. else if ([ev type] == NSKeyUp)
  232369. return redirectKeyUp (ev);
  232370. return false;
  232371. }
  232372. #endif
  232373. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232374. {
  232375. updateModifiers (ev);
  232376. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232377. }
  232378. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232379. {
  232380. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232381. sendMouseEvent (ev);
  232382. }
  232383. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232384. {
  232385. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232386. sendMouseEvent (ev);
  232387. showArrowCursorIfNeeded();
  232388. }
  232389. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232390. {
  232391. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232392. sendMouseEvent (ev);
  232393. }
  232394. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232395. {
  232396. currentModifiers = currentModifiers.withoutMouseButtons();
  232397. sendMouseEvent (ev);
  232398. showArrowCursorIfNeeded();
  232399. }
  232400. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232401. {
  232402. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232403. currentModifiers = currentModifiers.withoutMouseButtons();
  232404. sendMouseEvent (ev);
  232405. }
  232406. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232407. {
  232408. currentModifiers = currentModifiers.withoutMouseButtons();
  232409. sendMouseEvent (ev);
  232410. }
  232411. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232412. {
  232413. updateModifiers (ev);
  232414. float x = 0, y = 0;
  232415. @try
  232416. {
  232417. x = [ev deviceDeltaX] * 0.5f;
  232418. y = [ev deviceDeltaY] * 0.5f;
  232419. }
  232420. @catch (...)
  232421. {}
  232422. if (x == 0 && y == 0)
  232423. {
  232424. x = [ev deltaX] * 10.0f;
  232425. y = [ev deltaY] * 10.0f;
  232426. }
  232427. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232428. }
  232429. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232430. {
  232431. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232432. if (mouse.getComponentUnderMouse() == 0
  232433. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232434. {
  232435. [[NSCursor arrowCursor] set];
  232436. }
  232437. }
  232438. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232439. {
  232440. NSString* bestType
  232441. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232442. if (bestType == nil)
  232443. return false;
  232444. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232445. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232446. StringArray files;
  232447. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232448. if (list == nil)
  232449. return false;
  232450. if ([list isKindOfClass: [NSArray class]])
  232451. {
  232452. NSArray* items = (NSArray*) list;
  232453. for (unsigned int i = 0; i < [items count]; ++i)
  232454. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232455. }
  232456. if (files.size() == 0)
  232457. return false;
  232458. if (type == 0)
  232459. handleFileDragMove (files, pos);
  232460. else if (type == 1)
  232461. handleFileDragExit (files);
  232462. else if (type == 2)
  232463. handleFileDragDrop (files, pos);
  232464. return true;
  232465. }
  232466. bool NSViewComponentPeer::isOpaque()
  232467. {
  232468. return component == 0 || component->isOpaque();
  232469. }
  232470. void NSViewComponentPeer::drawRect (NSRect r)
  232471. {
  232472. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232473. return;
  232474. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232475. if (! component->isOpaque())
  232476. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232477. #if USE_COREGRAPHICS_RENDERING
  232478. if (usingCoreGraphics)
  232479. {
  232480. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232481. insideDrawRect = true;
  232482. handlePaint (context);
  232483. insideDrawRect = false;
  232484. }
  232485. else
  232486. #endif
  232487. {
  232488. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232489. (int) (r.size.width + 0.5f),
  232490. (int) (r.size.height + 0.5f),
  232491. ! getComponent()->isOpaque());
  232492. const int xOffset = -roundToInt (r.origin.x);
  232493. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232494. const NSRect* rects = 0;
  232495. NSInteger numRects = 0;
  232496. [view getRectsBeingDrawn: &rects count: &numRects];
  232497. const Rectangle<int> clipBounds (temp.getBounds());
  232498. RectangleList clip;
  232499. for (int i = 0; i < numRects; ++i)
  232500. {
  232501. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232502. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232503. roundToInt (rects[i].size.width),
  232504. roundToInt (rects[i].size.height))));
  232505. }
  232506. if (! clip.isEmpty())
  232507. {
  232508. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232509. insideDrawRect = true;
  232510. handlePaint (context);
  232511. insideDrawRect = false;
  232512. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232513. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232514. CGColorSpaceRelease (colourSpace);
  232515. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232516. CGImageRelease (image);
  232517. }
  232518. }
  232519. }
  232520. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232521. {
  232522. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232523. #if USE_COREGRAPHICS_RENDERING
  232524. s.add ("CoreGraphics Renderer");
  232525. #endif
  232526. return s;
  232527. }
  232528. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232529. {
  232530. return usingCoreGraphics ? 1 : 0;
  232531. }
  232532. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232533. {
  232534. #if USE_COREGRAPHICS_RENDERING
  232535. if (usingCoreGraphics != (index > 0))
  232536. {
  232537. usingCoreGraphics = index > 0;
  232538. [view setNeedsDisplay: true];
  232539. }
  232540. #endif
  232541. }
  232542. bool NSViewComponentPeer::canBecomeKeyWindow()
  232543. {
  232544. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232545. }
  232546. bool NSViewComponentPeer::windowShouldClose()
  232547. {
  232548. if (! isValidPeer (this))
  232549. return YES;
  232550. handleUserClosingWindow();
  232551. return NO;
  232552. }
  232553. void NSViewComponentPeer::redirectMovedOrResized()
  232554. {
  232555. handleMovedOrResized();
  232556. }
  232557. void NSViewComponentPeer::viewMovedToWindow()
  232558. {
  232559. if (isSharedWindow)
  232560. window = [view window];
  232561. }
  232562. void Desktop::createMouseInputSources()
  232563. {
  232564. mouseSources.add (new MouseInputSource (0, true));
  232565. }
  232566. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232567. {
  232568. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232569. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232570. // is apparently still available in 64-bit apps..
  232571. if (enableOrDisable)
  232572. {
  232573. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232574. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232575. }
  232576. else
  232577. {
  232578. SetSystemUIMode (kUIModeNormal, 0);
  232579. }
  232580. }
  232581. class AsyncRepaintMessage : public CallbackMessage
  232582. {
  232583. public:
  232584. NSViewComponentPeer* const peer;
  232585. const Rectangle<int> rect;
  232586. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232587. : peer (peer_), rect (rect_)
  232588. {
  232589. }
  232590. void messageCallback()
  232591. {
  232592. if (ComponentPeer::isValidPeer (peer))
  232593. peer->repaint (rect);
  232594. }
  232595. };
  232596. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232597. {
  232598. if (insideDrawRect)
  232599. {
  232600. (new AsyncRepaintMessage (this, area))->post();
  232601. }
  232602. else
  232603. {
  232604. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232605. (float) area.getWidth(), (float) area.getHeight())];
  232606. }
  232607. }
  232608. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232609. {
  232610. [view displayIfNeeded];
  232611. }
  232612. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232613. {
  232614. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232615. }
  232616. const Image juce_createIconForFile (const File& file)
  232617. {
  232618. const ScopedAutoReleasePool pool;
  232619. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232620. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232621. [NSGraphicsContext saveGraphicsState];
  232622. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232623. [image drawAtPoint: NSMakePoint (0, 0)
  232624. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232625. operation: NSCompositeSourceOver fraction: 1.0f];
  232626. [[NSGraphicsContext currentContext] flushGraphics];
  232627. [NSGraphicsContext restoreGraphicsState];
  232628. return Image (result);
  232629. }
  232630. const int KeyPress::spaceKey = ' ';
  232631. const int KeyPress::returnKey = 0x0d;
  232632. const int KeyPress::escapeKey = 0x1b;
  232633. const int KeyPress::backspaceKey = 0x7f;
  232634. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232635. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232636. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232637. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232638. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232639. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232640. const int KeyPress::endKey = NSEndFunctionKey;
  232641. const int KeyPress::homeKey = NSHomeFunctionKey;
  232642. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232643. const int KeyPress::insertKey = -1;
  232644. const int KeyPress::tabKey = 9;
  232645. const int KeyPress::F1Key = NSF1FunctionKey;
  232646. const int KeyPress::F2Key = NSF2FunctionKey;
  232647. const int KeyPress::F3Key = NSF3FunctionKey;
  232648. const int KeyPress::F4Key = NSF4FunctionKey;
  232649. const int KeyPress::F5Key = NSF5FunctionKey;
  232650. const int KeyPress::F6Key = NSF6FunctionKey;
  232651. const int KeyPress::F7Key = NSF7FunctionKey;
  232652. const int KeyPress::F8Key = NSF8FunctionKey;
  232653. const int KeyPress::F9Key = NSF9FunctionKey;
  232654. const int KeyPress::F10Key = NSF10FunctionKey;
  232655. const int KeyPress::F11Key = NSF1FunctionKey;
  232656. const int KeyPress::F12Key = NSF12FunctionKey;
  232657. const int KeyPress::F13Key = NSF13FunctionKey;
  232658. const int KeyPress::F14Key = NSF14FunctionKey;
  232659. const int KeyPress::F15Key = NSF15FunctionKey;
  232660. const int KeyPress::F16Key = NSF16FunctionKey;
  232661. const int KeyPress::numberPad0 = 0x30020;
  232662. const int KeyPress::numberPad1 = 0x30021;
  232663. const int KeyPress::numberPad2 = 0x30022;
  232664. const int KeyPress::numberPad3 = 0x30023;
  232665. const int KeyPress::numberPad4 = 0x30024;
  232666. const int KeyPress::numberPad5 = 0x30025;
  232667. const int KeyPress::numberPad6 = 0x30026;
  232668. const int KeyPress::numberPad7 = 0x30027;
  232669. const int KeyPress::numberPad8 = 0x30028;
  232670. const int KeyPress::numberPad9 = 0x30029;
  232671. const int KeyPress::numberPadAdd = 0x3002a;
  232672. const int KeyPress::numberPadSubtract = 0x3002b;
  232673. const int KeyPress::numberPadMultiply = 0x3002c;
  232674. const int KeyPress::numberPadDivide = 0x3002d;
  232675. const int KeyPress::numberPadSeparator = 0x3002e;
  232676. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232677. const int KeyPress::numberPadEquals = 0x30030;
  232678. const int KeyPress::numberPadDelete = 0x30031;
  232679. const int KeyPress::playKey = 0x30000;
  232680. const int KeyPress::stopKey = 0x30001;
  232681. const int KeyPress::fastForwardKey = 0x30002;
  232682. const int KeyPress::rewindKey = 0x30003;
  232683. #endif
  232684. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232685. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232686. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232687. // compiled on its own).
  232688. #if JUCE_INCLUDED_FILE
  232689. #if JUCE_MAC
  232690. namespace MouseCursorHelpers
  232691. {
  232692. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232693. {
  232694. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232695. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232696. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232697. [im release];
  232698. return c;
  232699. }
  232700. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232701. {
  232702. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232703. BufferedInputStream buf (&fileStream, 4096, false);
  232704. PNGImageFormat pngFormat;
  232705. Image im (pngFormat.decodeImage (buf));
  232706. if (im.isValid())
  232707. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232708. jassertfalse;
  232709. return 0;
  232710. }
  232711. }
  232712. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232713. {
  232714. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232715. }
  232716. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232717. {
  232718. const ScopedAutoReleasePool pool;
  232719. NSCursor* c = 0;
  232720. switch (type)
  232721. {
  232722. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232723. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232724. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232725. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232726. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232727. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232728. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232729. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232730. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232731. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232732. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232733. case UpDownResizeCursor:
  232734. case TopEdgeResizeCursor:
  232735. case BottomEdgeResizeCursor:
  232736. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232737. case TopLeftCornerResizeCursor:
  232738. case BottomRightCornerResizeCursor:
  232739. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232740. case TopRightCornerResizeCursor:
  232741. case BottomLeftCornerResizeCursor:
  232742. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232743. case UpDownLeftRightResizeCursor:
  232744. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232745. default:
  232746. jassertfalse;
  232747. break;
  232748. }
  232749. [c retain];
  232750. return c;
  232751. }
  232752. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232753. {
  232754. [((NSCursor*) cursorHandle) release];
  232755. }
  232756. void MouseCursor::showInAllWindows() const
  232757. {
  232758. showInWindow (0);
  232759. }
  232760. void MouseCursor::showInWindow (ComponentPeer*) const
  232761. {
  232762. [((NSCursor*) getHandle()) set];
  232763. }
  232764. #else
  232765. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232766. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232767. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232768. void MouseCursor::showInAllWindows() const {}
  232769. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232770. #endif
  232771. #endif
  232772. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232773. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232774. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232775. // compiled on its own).
  232776. #if JUCE_INCLUDED_FILE
  232777. class NSViewComponentInternal : public ComponentMovementWatcher
  232778. {
  232779. Component* const owner;
  232780. NSViewComponentPeer* currentPeer;
  232781. bool wasShowing;
  232782. public:
  232783. NSView* const view;
  232784. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232785. : ComponentMovementWatcher (owner_),
  232786. owner (owner_),
  232787. currentPeer (0),
  232788. wasShowing (false),
  232789. view (view_)
  232790. {
  232791. [view_ retain];
  232792. if (owner_->isShowing())
  232793. componentPeerChanged();
  232794. }
  232795. ~NSViewComponentInternal()
  232796. {
  232797. [view removeFromSuperview];
  232798. [view release];
  232799. }
  232800. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232801. {
  232802. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232803. // The ComponentMovementWatcher version of this method avoids calling
  232804. // us when the top-level comp is resized, but for an NSView we need to know this
  232805. // because with inverted co-ords, we need to update the position even if the
  232806. // top-left pos hasn't changed
  232807. if (comp.isOnDesktop() && wasResized)
  232808. componentMovedOrResized (wasMoved, wasResized);
  232809. }
  232810. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232811. {
  232812. Component* const topComp = owner->getTopLevelComponent();
  232813. if (topComp->getPeer() != 0)
  232814. {
  232815. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232816. NSRect r;
  232817. r.origin.x = (float) pos.getX();
  232818. r.origin.y = (float) pos.getY();
  232819. r.size.width = (float) owner->getWidth();
  232820. r.size.height = (float) owner->getHeight();
  232821. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232822. [view setFrame: r];
  232823. }
  232824. }
  232825. void componentPeerChanged()
  232826. {
  232827. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232828. if (currentPeer != peer)
  232829. {
  232830. [view removeFromSuperview];
  232831. currentPeer = peer;
  232832. if (peer != 0)
  232833. {
  232834. [peer->view addSubview: view];
  232835. componentMovedOrResized (false, false);
  232836. }
  232837. }
  232838. [view setHidden: ! owner->isShowing()];
  232839. }
  232840. void componentVisibilityChanged (Component&)
  232841. {
  232842. componentPeerChanged();
  232843. }
  232844. juce_UseDebuggingNewOperator
  232845. private:
  232846. NSViewComponentInternal (const NSViewComponentInternal&);
  232847. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232848. };
  232849. NSViewComponent::NSViewComponent()
  232850. {
  232851. }
  232852. NSViewComponent::~NSViewComponent()
  232853. {
  232854. }
  232855. void NSViewComponent::setView (void* view)
  232856. {
  232857. if (view != getView())
  232858. {
  232859. if (view != 0)
  232860. info = new NSViewComponentInternal ((NSView*) view, this);
  232861. else
  232862. info = 0;
  232863. }
  232864. }
  232865. void* NSViewComponent::getView() const
  232866. {
  232867. return info == 0 ? 0 : info->view;
  232868. }
  232869. void NSViewComponent::paint (Graphics&)
  232870. {
  232871. }
  232872. #endif
  232873. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232874. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232875. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232876. // compiled on its own).
  232877. #if JUCE_INCLUDED_FILE
  232878. AppleRemoteDevice::AppleRemoteDevice()
  232879. : device (0),
  232880. queue (0),
  232881. remoteId (0)
  232882. {
  232883. }
  232884. AppleRemoteDevice::~AppleRemoteDevice()
  232885. {
  232886. stop();
  232887. }
  232888. static io_object_t getAppleRemoteDevice()
  232889. {
  232890. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232891. io_iterator_t iter = 0;
  232892. io_object_t iod = 0;
  232893. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232894. && iter != 0)
  232895. {
  232896. iod = IOIteratorNext (iter);
  232897. }
  232898. IOObjectRelease (iter);
  232899. return iod;
  232900. }
  232901. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232902. {
  232903. jassert (*device == 0);
  232904. io_name_t classname;
  232905. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232906. {
  232907. IOCFPlugInInterface** cfPlugInInterface = 0;
  232908. SInt32 score = 0;
  232909. if (IOCreatePlugInInterfaceForService (iod,
  232910. kIOHIDDeviceUserClientTypeID,
  232911. kIOCFPlugInInterfaceID,
  232912. &cfPlugInInterface,
  232913. &score) == kIOReturnSuccess)
  232914. {
  232915. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232916. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232917. device);
  232918. (void) hr;
  232919. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232920. }
  232921. }
  232922. return *device != 0;
  232923. }
  232924. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232925. {
  232926. if (queue != 0)
  232927. return true;
  232928. stop();
  232929. bool result = false;
  232930. io_object_t iod = getAppleRemoteDevice();
  232931. if (iod != 0)
  232932. {
  232933. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232934. result = true;
  232935. else
  232936. stop();
  232937. IOObjectRelease (iod);
  232938. }
  232939. return result;
  232940. }
  232941. void AppleRemoteDevice::stop()
  232942. {
  232943. if (queue != 0)
  232944. {
  232945. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232946. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232947. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232948. queue = 0;
  232949. }
  232950. if (device != 0)
  232951. {
  232952. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232953. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232954. device = 0;
  232955. }
  232956. }
  232957. bool AppleRemoteDevice::isActive() const
  232958. {
  232959. return queue != 0;
  232960. }
  232961. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232962. {
  232963. if (result == kIOReturnSuccess)
  232964. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232965. }
  232966. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232967. {
  232968. Array <int> cookies;
  232969. CFArrayRef elements;
  232970. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232971. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232972. return false;
  232973. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232974. {
  232975. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232976. // get the cookie
  232977. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232978. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232979. continue;
  232980. long number;
  232981. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232982. continue;
  232983. cookies.add ((int) number);
  232984. }
  232985. CFRelease (elements);
  232986. if ((*(IOHIDDeviceInterface**) device)
  232987. ->open ((IOHIDDeviceInterface**) device,
  232988. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232989. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232990. {
  232991. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232992. if (queue != 0)
  232993. {
  232994. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232995. for (int i = 0; i < cookies.size(); ++i)
  232996. {
  232997. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232998. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232999. }
  233000. CFRunLoopSourceRef eventSource;
  233001. if ((*(IOHIDQueueInterface**) queue)
  233002. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  233003. {
  233004. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  233005. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  233006. {
  233007. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  233008. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  233009. return true;
  233010. }
  233011. }
  233012. }
  233013. }
  233014. return false;
  233015. }
  233016. void AppleRemoteDevice::handleCallbackInternal()
  233017. {
  233018. int totalValues = 0;
  233019. AbsoluteTime nullTime = { 0, 0 };
  233020. char cookies [12];
  233021. int numCookies = 0;
  233022. while (numCookies < numElementsInArray (cookies))
  233023. {
  233024. IOHIDEventStruct e;
  233025. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  233026. break;
  233027. if ((int) e.elementCookie == 19)
  233028. {
  233029. remoteId = e.value;
  233030. buttonPressed (switched, false);
  233031. }
  233032. else
  233033. {
  233034. totalValues += e.value;
  233035. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  233036. }
  233037. }
  233038. cookies [numCookies++] = 0;
  233039. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  233040. static const char buttonPatterns[] =
  233041. {
  233042. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  233043. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  233044. 0x1f, 0x1d, 0x1c, 0x12, 0,
  233045. 0x1f, 0x1e, 0x1c, 0x12, 0,
  233046. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  233047. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  233048. 0x1f, 0x12, 0x04, 0x02, 0,
  233049. 0x1f, 0x12, 0x03, 0x02, 0,
  233050. 0x1f, 0x12, 0x1f, 0x12, 0,
  233051. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  233052. 19, 0
  233053. };
  233054. int buttonNum = (int) menuButton;
  233055. int i = 0;
  233056. while (i < numElementsInArray (buttonPatterns))
  233057. {
  233058. if (strcmp (cookies, buttonPatterns + i) == 0)
  233059. {
  233060. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  233061. break;
  233062. }
  233063. i += (int) strlen (buttonPatterns + i) + 1;
  233064. ++buttonNum;
  233065. }
  233066. }
  233067. #endif
  233068. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  233069. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  233070. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233071. // compiled on its own).
  233072. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  233073. #if JUCE_MAC
  233074. END_JUCE_NAMESPACE
  233075. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  233076. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  233077. {
  233078. CriticalSection* contextLock;
  233079. bool needsUpdate;
  233080. }
  233081. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  233082. - (bool) makeActive;
  233083. - (void) makeInactive;
  233084. - (void) reshape;
  233085. @end
  233086. @implementation ThreadSafeNSOpenGLView
  233087. - (id) initWithFrame: (NSRect) frameRect
  233088. pixelFormat: (NSOpenGLPixelFormat*) format
  233089. {
  233090. contextLock = new CriticalSection();
  233091. self = [super initWithFrame: frameRect pixelFormat: format];
  233092. if (self != nil)
  233093. [[NSNotificationCenter defaultCenter] addObserver: self
  233094. selector: @selector (_surfaceNeedsUpdate:)
  233095. name: NSViewGlobalFrameDidChangeNotification
  233096. object: self];
  233097. return self;
  233098. }
  233099. - (void) dealloc
  233100. {
  233101. [[NSNotificationCenter defaultCenter] removeObserver: self];
  233102. delete contextLock;
  233103. [super dealloc];
  233104. }
  233105. - (bool) makeActive
  233106. {
  233107. const ScopedLock sl (*contextLock);
  233108. if ([self openGLContext] == 0)
  233109. return false;
  233110. [[self openGLContext] makeCurrentContext];
  233111. if (needsUpdate)
  233112. {
  233113. [super update];
  233114. needsUpdate = false;
  233115. }
  233116. return true;
  233117. }
  233118. - (void) makeInactive
  233119. {
  233120. const ScopedLock sl (*contextLock);
  233121. [NSOpenGLContext clearCurrentContext];
  233122. }
  233123. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  233124. {
  233125. const ScopedLock sl (*contextLock);
  233126. needsUpdate = true;
  233127. }
  233128. - (void) update
  233129. {
  233130. const ScopedLock sl (*contextLock);
  233131. needsUpdate = true;
  233132. }
  233133. - (void) reshape
  233134. {
  233135. const ScopedLock sl (*contextLock);
  233136. needsUpdate = true;
  233137. }
  233138. @end
  233139. BEGIN_JUCE_NAMESPACE
  233140. class WindowedGLContext : public OpenGLContext
  233141. {
  233142. public:
  233143. WindowedGLContext (Component* const component,
  233144. const OpenGLPixelFormat& pixelFormat_,
  233145. NSOpenGLContext* sharedContext)
  233146. : renderContext (0),
  233147. pixelFormat (pixelFormat_)
  233148. {
  233149. jassert (component != 0);
  233150. NSOpenGLPixelFormatAttribute attribs [64];
  233151. int n = 0;
  233152. attribs[n++] = NSOpenGLPFADoubleBuffer;
  233153. attribs[n++] = NSOpenGLPFAAccelerated;
  233154. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  233155. attribs[n++] = NSOpenGLPFAColorSize;
  233156. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  233157. pixelFormat.greenBits,
  233158. pixelFormat.blueBits);
  233159. attribs[n++] = NSOpenGLPFAAlphaSize;
  233160. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  233161. attribs[n++] = NSOpenGLPFADepthSize;
  233162. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  233163. attribs[n++] = NSOpenGLPFAStencilSize;
  233164. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  233165. attribs[n++] = NSOpenGLPFAAccumSize;
  233166. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  233167. pixelFormat.accumulationBufferGreenBits,
  233168. pixelFormat.accumulationBufferBlueBits,
  233169. pixelFormat.accumulationBufferAlphaBits);
  233170. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  233171. attribs[n++] = NSOpenGLPFASampleBuffers;
  233172. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  233173. attribs[n++] = NSOpenGLPFAClosestPolicy;
  233174. attribs[n++] = NSOpenGLPFANoRecovery;
  233175. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  233176. NSOpenGLPixelFormat* format
  233177. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  233178. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233179. pixelFormat: format];
  233180. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  233181. shareContext: sharedContext] autorelease];
  233182. const GLint swapInterval = 1;
  233183. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  233184. [view setOpenGLContext: renderContext];
  233185. [format release];
  233186. viewHolder = new NSViewComponentInternal (view, component);
  233187. }
  233188. ~WindowedGLContext()
  233189. {
  233190. deleteContext();
  233191. viewHolder = 0;
  233192. }
  233193. void deleteContext()
  233194. {
  233195. makeInactive();
  233196. [renderContext clearDrawable];
  233197. [renderContext setView: nil];
  233198. [view setOpenGLContext: nil];
  233199. renderContext = nil;
  233200. }
  233201. bool makeActive() const throw()
  233202. {
  233203. jassert (renderContext != 0);
  233204. if ([renderContext view] != view)
  233205. [renderContext setView: view];
  233206. [view makeActive];
  233207. return isActive();
  233208. }
  233209. bool makeInactive() const throw()
  233210. {
  233211. [view makeInactive];
  233212. return true;
  233213. }
  233214. bool isActive() const throw()
  233215. {
  233216. return [NSOpenGLContext currentContext] == renderContext;
  233217. }
  233218. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233219. void* getRawContext() const throw() { return renderContext; }
  233220. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233221. {
  233222. }
  233223. void swapBuffers()
  233224. {
  233225. [renderContext flushBuffer];
  233226. }
  233227. bool setSwapInterval (const int numFramesPerSwap)
  233228. {
  233229. [renderContext setValues: (const GLint*) &numFramesPerSwap
  233230. forParameter: NSOpenGLCPSwapInterval];
  233231. return true;
  233232. }
  233233. int getSwapInterval() const
  233234. {
  233235. GLint numFrames = 0;
  233236. [renderContext getValues: &numFrames
  233237. forParameter: NSOpenGLCPSwapInterval];
  233238. return numFrames;
  233239. }
  233240. void repaint()
  233241. {
  233242. // we need to invalidate the juce view that holds this gl view, to make it
  233243. // cause a repaint callback
  233244. NSView* v = (NSView*) viewHolder->view;
  233245. NSRect r = [v frame];
  233246. // bit of a bodge here.. if we only invalidate the area of the gl component,
  233247. // it's completely covered by the NSOpenGLView, so the OS throws away the
  233248. // repaint message, thus never causing our paint() callback, and never repainting
  233249. // the comp. So invalidating just a little bit around the edge helps..
  233250. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  233251. }
  233252. void* getNativeWindowHandle() const { return viewHolder->view; }
  233253. juce_UseDebuggingNewOperator
  233254. NSOpenGLContext* renderContext;
  233255. ThreadSafeNSOpenGLView* view;
  233256. private:
  233257. OpenGLPixelFormat pixelFormat;
  233258. ScopedPointer <NSViewComponentInternal> viewHolder;
  233259. WindowedGLContext (const WindowedGLContext&);
  233260. WindowedGLContext& operator= (const WindowedGLContext&);
  233261. };
  233262. OpenGLContext* OpenGLComponent::createContext()
  233263. {
  233264. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  233265. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  233266. return (c->renderContext != 0) ? c.release() : 0;
  233267. }
  233268. void* OpenGLComponent::getNativeWindowHandle() const
  233269. {
  233270. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  233271. : 0;
  233272. }
  233273. void juce_glViewport (const int w, const int h)
  233274. {
  233275. glViewport (0, 0, w, h);
  233276. }
  233277. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233278. OwnedArray <OpenGLPixelFormat>& results)
  233279. {
  233280. /* GLint attribs [64];
  233281. int n = 0;
  233282. attribs[n++] = AGL_RGBA;
  233283. attribs[n++] = AGL_DOUBLEBUFFER;
  233284. attribs[n++] = AGL_ACCELERATED;
  233285. attribs[n++] = AGL_NO_RECOVERY;
  233286. attribs[n++] = AGL_NONE;
  233287. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  233288. while (p != 0)
  233289. {
  233290. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  233291. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  233292. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  233293. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  233294. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  233295. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  233296. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  233297. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  233298. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  233299. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  233300. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  233301. results.add (pf);
  233302. p = aglNextPixelFormat (p);
  233303. }*/
  233304. //jassertfalse // can't see how you do this in cocoa!
  233305. }
  233306. #else
  233307. END_JUCE_NAMESPACE
  233308. @interface JuceGLView : UIView
  233309. {
  233310. }
  233311. + (Class) layerClass;
  233312. @end
  233313. @implementation JuceGLView
  233314. + (Class) layerClass
  233315. {
  233316. return [CAEAGLLayer class];
  233317. }
  233318. @end
  233319. BEGIN_JUCE_NAMESPACE
  233320. class GLESContext : public OpenGLContext
  233321. {
  233322. public:
  233323. GLESContext (UIViewComponentPeer* peer,
  233324. Component* const component_,
  233325. const OpenGLPixelFormat& pixelFormat_,
  233326. const GLESContext* const sharedContext,
  233327. NSUInteger apiType)
  233328. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233329. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233330. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233331. {
  233332. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233333. view.opaque = YES;
  233334. view.hidden = NO;
  233335. view.backgroundColor = [UIColor blackColor];
  233336. view.userInteractionEnabled = NO;
  233337. glLayer = (CAEAGLLayer*) [view layer];
  233338. [peer->view addSubview: view];
  233339. if (sharedContext != 0)
  233340. context = [[EAGLContext alloc] initWithAPI: apiType
  233341. sharegroup: [sharedContext->context sharegroup]];
  233342. else
  233343. context = [[EAGLContext alloc] initWithAPI: apiType];
  233344. createGLBuffers();
  233345. }
  233346. ~GLESContext()
  233347. {
  233348. deleteContext();
  233349. [view removeFromSuperview];
  233350. [view release];
  233351. freeGLBuffers();
  233352. }
  233353. void deleteContext()
  233354. {
  233355. makeInactive();
  233356. [context release];
  233357. context = nil;
  233358. }
  233359. bool makeActive() const throw()
  233360. {
  233361. jassert (context != 0);
  233362. [EAGLContext setCurrentContext: context];
  233363. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233364. return true;
  233365. }
  233366. void swapBuffers()
  233367. {
  233368. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233369. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233370. }
  233371. bool makeInactive() const throw()
  233372. {
  233373. return [EAGLContext setCurrentContext: nil];
  233374. }
  233375. bool isActive() const throw()
  233376. {
  233377. return [EAGLContext currentContext] == context;
  233378. }
  233379. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233380. void* getRawContext() const throw() { return glLayer; }
  233381. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233382. {
  233383. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233384. if (lastWidth != w || lastHeight != h)
  233385. {
  233386. lastWidth = w;
  233387. lastHeight = h;
  233388. freeGLBuffers();
  233389. createGLBuffers();
  233390. }
  233391. }
  233392. bool setSwapInterval (const int numFramesPerSwap)
  233393. {
  233394. numFrames = numFramesPerSwap;
  233395. return true;
  233396. }
  233397. int getSwapInterval() const
  233398. {
  233399. return numFrames;
  233400. }
  233401. void repaint()
  233402. {
  233403. }
  233404. void createGLBuffers()
  233405. {
  233406. makeActive();
  233407. glGenFramebuffersOES (1, &frameBufferHandle);
  233408. glGenRenderbuffersOES (1, &colorBufferHandle);
  233409. glGenRenderbuffersOES (1, &depthBufferHandle);
  233410. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233411. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233412. GLint width, height;
  233413. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233414. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233415. if (useDepthBuffer)
  233416. {
  233417. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233418. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233419. }
  233420. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233421. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233422. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233423. if (useDepthBuffer)
  233424. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233425. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233426. }
  233427. void freeGLBuffers()
  233428. {
  233429. if (frameBufferHandle != 0)
  233430. {
  233431. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233432. frameBufferHandle = 0;
  233433. }
  233434. if (colorBufferHandle != 0)
  233435. {
  233436. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233437. colorBufferHandle = 0;
  233438. }
  233439. if (depthBufferHandle != 0)
  233440. {
  233441. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233442. depthBufferHandle = 0;
  233443. }
  233444. }
  233445. juce_UseDebuggingNewOperator
  233446. private:
  233447. Component::SafePointer<Component> component;
  233448. OpenGLPixelFormat pixelFormat;
  233449. JuceGLView* view;
  233450. CAEAGLLayer* glLayer;
  233451. EAGLContext* context;
  233452. bool useDepthBuffer;
  233453. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233454. int numFrames;
  233455. int lastWidth, lastHeight;
  233456. GLESContext (const GLESContext&);
  233457. GLESContext& operator= (const GLESContext&);
  233458. };
  233459. OpenGLContext* OpenGLComponent::createContext()
  233460. {
  233461. ScopedAutoReleasePool pool;
  233462. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233463. if (peer != 0)
  233464. return new GLESContext (peer, this, preferredPixelFormat,
  233465. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233466. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233467. return 0;
  233468. }
  233469. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233470. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233471. {
  233472. }
  233473. void juce_glViewport (const int w, const int h)
  233474. {
  233475. glViewport (0, 0, w, h);
  233476. }
  233477. #endif
  233478. #endif
  233479. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233480. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233481. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233482. // compiled on its own).
  233483. #if JUCE_INCLUDED_FILE
  233484. class JuceMainMenuHandler;
  233485. END_JUCE_NAMESPACE
  233486. using namespace JUCE_NAMESPACE;
  233487. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233488. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233489. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233490. #else
  233491. @interface JuceMenuCallback : NSObject
  233492. #endif
  233493. {
  233494. JuceMainMenuHandler* owner;
  233495. }
  233496. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233497. - (void) dealloc;
  233498. - (void) menuItemInvoked: (id) menu;
  233499. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233500. @end
  233501. BEGIN_JUCE_NAMESPACE
  233502. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233503. private DeletedAtShutdown
  233504. {
  233505. public:
  233506. static JuceMainMenuHandler* instance;
  233507. JuceMainMenuHandler()
  233508. : currentModel (0),
  233509. lastUpdateTime (0)
  233510. {
  233511. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233512. }
  233513. ~JuceMainMenuHandler()
  233514. {
  233515. setMenu (0);
  233516. jassert (instance == this);
  233517. instance = 0;
  233518. [callback release];
  233519. }
  233520. void setMenu (MenuBarModel* const newMenuBarModel)
  233521. {
  233522. if (currentModel != newMenuBarModel)
  233523. {
  233524. if (currentModel != 0)
  233525. currentModel->removeListener (this);
  233526. currentModel = newMenuBarModel;
  233527. if (currentModel != 0)
  233528. currentModel->addListener (this);
  233529. menuBarItemsChanged (0);
  233530. }
  233531. }
  233532. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233533. const String& name, const int menuId, const int tag)
  233534. {
  233535. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233536. action: nil
  233537. keyEquivalent: @""];
  233538. [item setTag: tag];
  233539. NSMenu* sub = createMenu (child, name, menuId, tag);
  233540. [parent setSubmenu: sub forItem: item];
  233541. [sub setAutoenablesItems: false];
  233542. [sub release];
  233543. }
  233544. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233545. const String& name, const int menuId, const int tag)
  233546. {
  233547. [parentItem setTag: tag];
  233548. NSMenu* menu = [parentItem submenu];
  233549. [menu setTitle: juceStringToNS (name)];
  233550. while ([menu numberOfItems] > 0)
  233551. [menu removeItemAtIndex: 0];
  233552. PopupMenu::MenuItemIterator iter (menuToCopy);
  233553. while (iter.next())
  233554. addMenuItem (iter, menu, menuId, tag);
  233555. [menu setAutoenablesItems: false];
  233556. [menu update];
  233557. }
  233558. void menuBarItemsChanged (MenuBarModel*)
  233559. {
  233560. lastUpdateTime = Time::getMillisecondCounter();
  233561. StringArray menuNames;
  233562. if (currentModel != 0)
  233563. menuNames = currentModel->getMenuBarNames();
  233564. NSMenu* menuBar = [NSApp mainMenu];
  233565. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233566. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233567. int menuId = 1;
  233568. for (int i = 0; i < menuNames.size(); ++i)
  233569. {
  233570. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233571. if (i >= [menuBar numberOfItems] - 1)
  233572. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233573. else
  233574. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233575. }
  233576. }
  233577. static void flashMenuBar (NSMenu* menu)
  233578. {
  233579. if ([[menu title] isEqualToString: @"Apple"])
  233580. return;
  233581. [menu retain];
  233582. const unichar f35Key = NSF35FunctionKey;
  233583. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233584. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233585. action: nil
  233586. keyEquivalent: f35String];
  233587. [item setTarget: nil];
  233588. [menu insertItem: item atIndex: [menu numberOfItems]];
  233589. [item release];
  233590. if ([menu indexOfItem: item] >= 0)
  233591. {
  233592. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233593. location: NSZeroPoint
  233594. modifierFlags: NSCommandKeyMask
  233595. timestamp: 0
  233596. windowNumber: 0
  233597. context: [NSGraphicsContext currentContext]
  233598. characters: f35String
  233599. charactersIgnoringModifiers: f35String
  233600. isARepeat: NO
  233601. keyCode: 0];
  233602. [menu performKeyEquivalent: f35Event];
  233603. if ([menu indexOfItem: item] >= 0)
  233604. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233605. }
  233606. [menu release];
  233607. }
  233608. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233609. {
  233610. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233611. {
  233612. NSMenuItem* m = [menu itemAtIndex: i];
  233613. if ([m tag] == info.commandID)
  233614. return m;
  233615. if ([m submenu] != 0)
  233616. {
  233617. NSMenuItem* found = findMenuItem ([m submenu], info);
  233618. if (found != 0)
  233619. return found;
  233620. }
  233621. }
  233622. return 0;
  233623. }
  233624. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233625. {
  233626. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233627. if (item != 0)
  233628. flashMenuBar ([item menu]);
  233629. }
  233630. void updateMenus()
  233631. {
  233632. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233633. menuBarItemsChanged (0);
  233634. }
  233635. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233636. {
  233637. if (currentModel != 0)
  233638. {
  233639. if (commandManager != 0)
  233640. {
  233641. ApplicationCommandTarget::InvocationInfo info (commandId);
  233642. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233643. commandManager->invoke (info, true);
  233644. }
  233645. currentModel->menuItemSelected (commandId, topLevelIndex);
  233646. }
  233647. }
  233648. MenuBarModel* currentModel;
  233649. uint32 lastUpdateTime;
  233650. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233651. const int topLevelMenuId, const int topLevelIndex)
  233652. {
  233653. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233654. if (text == 0)
  233655. text = @"";
  233656. if (iter.isSeparator)
  233657. {
  233658. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233659. }
  233660. else if (iter.isSectionHeader)
  233661. {
  233662. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233663. action: nil
  233664. keyEquivalent: @""];
  233665. [item setEnabled: false];
  233666. }
  233667. else if (iter.subMenu != 0)
  233668. {
  233669. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233670. action: nil
  233671. keyEquivalent: @""];
  233672. [item setTag: iter.itemId];
  233673. [item setEnabled: iter.isEnabled];
  233674. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233675. [sub setDelegate: nil];
  233676. [menuToAddTo setSubmenu: sub forItem: item];
  233677. [sub release];
  233678. }
  233679. else
  233680. {
  233681. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233682. action: @selector (menuItemInvoked:)
  233683. keyEquivalent: @""];
  233684. [item setTag: iter.itemId];
  233685. [item setEnabled: iter.isEnabled];
  233686. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233687. [item setTarget: (id) callback];
  233688. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233689. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233690. [item setRepresentedObject: info];
  233691. if (iter.commandManager != 0)
  233692. {
  233693. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233694. ->getKeyPressesAssignedToCommand (iter.itemId));
  233695. if (keyPresses.size() > 0)
  233696. {
  233697. const KeyPress& kp = keyPresses.getReference(0);
  233698. if (kp.getKeyCode() != KeyPress::backspaceKey
  233699. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233700. // every time you press the key while editing text)
  233701. {
  233702. juce_wchar key = kp.getTextCharacter();
  233703. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233704. key = NSBackspaceCharacter;
  233705. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233706. key = NSDeleteCharacter;
  233707. else if (key == 0)
  233708. key = (juce_wchar) kp.getKeyCode();
  233709. unsigned int mods = 0;
  233710. if (kp.getModifiers().isShiftDown())
  233711. mods |= NSShiftKeyMask;
  233712. if (kp.getModifiers().isCtrlDown())
  233713. mods |= NSControlKeyMask;
  233714. if (kp.getModifiers().isAltDown())
  233715. mods |= NSAlternateKeyMask;
  233716. if (kp.getModifiers().isCommandDown())
  233717. mods |= NSCommandKeyMask;
  233718. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233719. [item setKeyEquivalentModifierMask: mods];
  233720. }
  233721. }
  233722. }
  233723. }
  233724. }
  233725. JuceMenuCallback* callback;
  233726. private:
  233727. NSMenu* createMenu (const PopupMenu menu,
  233728. const String& menuName,
  233729. const int topLevelMenuId,
  233730. const int topLevelIndex)
  233731. {
  233732. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233733. [m setAutoenablesItems: false];
  233734. [m setDelegate: callback];
  233735. PopupMenu::MenuItemIterator iter (menu);
  233736. while (iter.next())
  233737. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233738. [m update];
  233739. return m;
  233740. }
  233741. };
  233742. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233743. END_JUCE_NAMESPACE
  233744. @implementation JuceMenuCallback
  233745. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233746. {
  233747. [super init];
  233748. owner = owner_;
  233749. return self;
  233750. }
  233751. - (void) dealloc
  233752. {
  233753. [super dealloc];
  233754. }
  233755. - (void) menuItemInvoked: (id) menu
  233756. {
  233757. NSMenuItem* item = (NSMenuItem*) menu;
  233758. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233759. {
  233760. // 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
  233761. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233762. // into the focused component and let it trigger the menu item indirectly.
  233763. NSEvent* e = [NSApp currentEvent];
  233764. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233765. {
  233766. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233767. {
  233768. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233769. if (peer != 0)
  233770. {
  233771. if ([e type] == NSKeyDown)
  233772. peer->redirectKeyDown (e);
  233773. else
  233774. peer->redirectKeyUp (e);
  233775. return;
  233776. }
  233777. }
  233778. }
  233779. NSArray* info = (NSArray*) [item representedObject];
  233780. owner->invoke ((int) [item tag],
  233781. (ApplicationCommandManager*) (pointer_sized_int)
  233782. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233783. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233784. }
  233785. }
  233786. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233787. {
  233788. (void) menu;
  233789. if (JuceMainMenuHandler::instance != 0)
  233790. JuceMainMenuHandler::instance->updateMenus();
  233791. }
  233792. @end
  233793. BEGIN_JUCE_NAMESPACE
  233794. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233795. const PopupMenu* extraItems)
  233796. {
  233797. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233798. {
  233799. PopupMenu::MenuItemIterator iter (*extraItems);
  233800. while (iter.next())
  233801. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233802. [menu addItem: [NSMenuItem separatorItem]];
  233803. }
  233804. NSMenuItem* item;
  233805. // Services...
  233806. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233807. action: nil keyEquivalent: @""];
  233808. [menu addItem: item];
  233809. [item release];
  233810. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233811. [menu setSubmenu: servicesMenu forItem: item];
  233812. [NSApp setServicesMenu: servicesMenu];
  233813. [servicesMenu release];
  233814. [menu addItem: [NSMenuItem separatorItem]];
  233815. // Hide + Show stuff...
  233816. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233817. action: @selector (hide:) keyEquivalent: @"h"];
  233818. [item setTarget: NSApp];
  233819. [menu addItem: item];
  233820. [item release];
  233821. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233822. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233823. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233824. [item setTarget: NSApp];
  233825. [menu addItem: item];
  233826. [item release];
  233827. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233828. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233829. [item setTarget: NSApp];
  233830. [menu addItem: item];
  233831. [item release];
  233832. [menu addItem: [NSMenuItem separatorItem]];
  233833. // Quit item....
  233834. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233835. action: @selector (terminate:) keyEquivalent: @"q"];
  233836. [item setTarget: NSApp];
  233837. [menu addItem: item];
  233838. [item release];
  233839. return menu;
  233840. }
  233841. // Since our app has no NIB, this initialises a standard app menu...
  233842. static void rebuildMainMenu (const PopupMenu* extraItems)
  233843. {
  233844. // this can't be used in a plugin!
  233845. jassert (JUCEApplication::isStandaloneApp());
  233846. if (JUCEApplication::getInstance() != 0)
  233847. {
  233848. const ScopedAutoReleasePool pool;
  233849. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233850. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233851. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233852. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233853. [mainMenu setSubmenu: appMenu forItem: item];
  233854. [NSApp setMainMenu: mainMenu];
  233855. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233856. [appMenu release];
  233857. [mainMenu release];
  233858. }
  233859. }
  233860. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233861. const PopupMenu* extraAppleMenuItems)
  233862. {
  233863. if (getMacMainMenu() != newMenuBarModel)
  233864. {
  233865. const ScopedAutoReleasePool pool;
  233866. if (newMenuBarModel == 0)
  233867. {
  233868. delete JuceMainMenuHandler::instance;
  233869. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233870. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233871. extraAppleMenuItems = 0;
  233872. }
  233873. else
  233874. {
  233875. if (JuceMainMenuHandler::instance == 0)
  233876. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233877. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233878. }
  233879. }
  233880. rebuildMainMenu (extraAppleMenuItems);
  233881. if (newMenuBarModel != 0)
  233882. newMenuBarModel->menuItemsChanged();
  233883. }
  233884. MenuBarModel* MenuBarModel::getMacMainMenu()
  233885. {
  233886. return JuceMainMenuHandler::instance != 0
  233887. ? JuceMainMenuHandler::instance->currentModel : 0;
  233888. }
  233889. void juce_initialiseMacMainMenu()
  233890. {
  233891. if (JuceMainMenuHandler::instance == 0)
  233892. rebuildMainMenu (0);
  233893. }
  233894. #endif
  233895. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233896. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233897. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233898. // compiled on its own).
  233899. #if JUCE_INCLUDED_FILE
  233900. #if JUCE_MAC
  233901. END_JUCE_NAMESPACE
  233902. using namespace JUCE_NAMESPACE;
  233903. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233904. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233905. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233906. #else
  233907. @interface JuceFileChooserDelegate : NSObject
  233908. #endif
  233909. {
  233910. StringArray* filters;
  233911. }
  233912. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233913. - (void) dealloc;
  233914. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233915. @end
  233916. @implementation JuceFileChooserDelegate
  233917. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233918. {
  233919. [super init];
  233920. filters = filters_;
  233921. return self;
  233922. }
  233923. - (void) dealloc
  233924. {
  233925. delete filters;
  233926. [super dealloc];
  233927. }
  233928. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233929. {
  233930. (void) sender;
  233931. const File f (nsStringToJuce (filename));
  233932. for (int i = filters->size(); --i >= 0;)
  233933. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233934. return true;
  233935. return f.isDirectory();
  233936. }
  233937. @end
  233938. BEGIN_JUCE_NAMESPACE
  233939. void FileChooser::showPlatformDialog (Array<File>& results,
  233940. const String& title,
  233941. const File& currentFileOrDirectory,
  233942. const String& filter,
  233943. bool selectsDirectory,
  233944. bool selectsFiles,
  233945. bool isSaveDialogue,
  233946. bool warnAboutOverwritingExistingFiles,
  233947. bool selectMultipleFiles,
  233948. FilePreviewComponent* extraInfoComponent)
  233949. {
  233950. const ScopedAutoReleasePool pool;
  233951. StringArray* filters = new StringArray();
  233952. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233953. filters->trim();
  233954. filters->removeEmptyStrings();
  233955. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233956. [delegate autorelease];
  233957. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233958. : [NSOpenPanel openPanel];
  233959. [panel setTitle: juceStringToNS (title)];
  233960. if (! isSaveDialogue)
  233961. {
  233962. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233963. [openPanel setCanChooseDirectories: selectsDirectory];
  233964. [openPanel setCanChooseFiles: selectsFiles];
  233965. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233966. }
  233967. [panel setDelegate: delegate];
  233968. if (isSaveDialogue || selectsDirectory)
  233969. [panel setCanCreateDirectories: YES];
  233970. String directory, filename;
  233971. if (currentFileOrDirectory.isDirectory())
  233972. {
  233973. directory = currentFileOrDirectory.getFullPathName();
  233974. }
  233975. else
  233976. {
  233977. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233978. filename = currentFileOrDirectory.getFileName();
  233979. }
  233980. if ([panel runModalForDirectory: juceStringToNS (directory)
  233981. file: juceStringToNS (filename)]
  233982. == NSOKButton)
  233983. {
  233984. if (isSaveDialogue)
  233985. {
  233986. results.add (File (nsStringToJuce ([panel filename])));
  233987. }
  233988. else
  233989. {
  233990. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233991. NSArray* urls = [openPanel filenames];
  233992. for (unsigned int i = 0; i < [urls count]; ++i)
  233993. {
  233994. NSString* f = [urls objectAtIndex: i];
  233995. results.add (File (nsStringToJuce (f)));
  233996. }
  233997. }
  233998. }
  233999. [panel setDelegate: nil];
  234000. }
  234001. #else
  234002. void FileChooser::showPlatformDialog (Array<File>& results,
  234003. const String& title,
  234004. const File& currentFileOrDirectory,
  234005. const String& filter,
  234006. bool selectsDirectory,
  234007. bool selectsFiles,
  234008. bool isSaveDialogue,
  234009. bool warnAboutOverwritingExistingFiles,
  234010. bool selectMultipleFiles,
  234011. FilePreviewComponent* extraInfoComponent)
  234012. {
  234013. const ScopedAutoReleasePool pool;
  234014. jassertfalse; //xxx to do
  234015. }
  234016. #endif
  234017. #endif
  234018. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  234019. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234020. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234021. // compiled on its own).
  234022. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  234023. END_JUCE_NAMESPACE
  234024. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  234025. @interface NonInterceptingQTMovieView : QTMovieView
  234026. {
  234027. }
  234028. - (id) initWithFrame: (NSRect) frame;
  234029. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  234030. - (NSView*) hitTest: (NSPoint) p;
  234031. @end
  234032. @implementation NonInterceptingQTMovieView
  234033. - (id) initWithFrame: (NSRect) frame
  234034. {
  234035. self = [super initWithFrame: frame];
  234036. [self setNextResponder: [self superview]];
  234037. return self;
  234038. }
  234039. - (void) dealloc
  234040. {
  234041. [super dealloc];
  234042. }
  234043. - (NSView*) hitTest: (NSPoint) point
  234044. {
  234045. return [self isControllerVisible] ? [super hitTest: point] : nil;
  234046. }
  234047. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  234048. {
  234049. return YES;
  234050. }
  234051. @end
  234052. BEGIN_JUCE_NAMESPACE
  234053. #define theMovie (static_cast <QTMovie*> (movie))
  234054. QuickTimeMovieComponent::QuickTimeMovieComponent()
  234055. : movie (0)
  234056. {
  234057. setOpaque (true);
  234058. setVisible (true);
  234059. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  234060. setView (view);
  234061. [view release];
  234062. }
  234063. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  234064. {
  234065. closeMovie();
  234066. setView (0);
  234067. }
  234068. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  234069. {
  234070. return true;
  234071. }
  234072. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  234073. {
  234074. // unfortunately, QTMovie objects can only be created on the main thread..
  234075. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234076. QTMovie* movie = 0;
  234077. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  234078. if (fin != 0)
  234079. {
  234080. movieFile = fin->getFile();
  234081. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  234082. error: nil];
  234083. }
  234084. else
  234085. {
  234086. MemoryBlock temp;
  234087. movieStream->readIntoMemoryBlock (temp);
  234088. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  234089. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  234090. {
  234091. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  234092. length: temp.getSize()]
  234093. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  234094. MIMEType: @""]
  234095. error: nil];
  234096. if (movie != 0)
  234097. break;
  234098. }
  234099. }
  234100. return movie;
  234101. }
  234102. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  234103. const bool isControllerVisible_)
  234104. {
  234105. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  234106. }
  234107. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  234108. const bool controllerVisible_)
  234109. {
  234110. closeMovie();
  234111. if (getPeer() == 0)
  234112. {
  234113. // To open a movie, this component must be visible inside a functioning window, so that
  234114. // the QT control can be assigned to the window.
  234115. jassertfalse;
  234116. return false;
  234117. }
  234118. movie = openMovieFromStream (movieStream, movieFile);
  234119. [theMovie retain];
  234120. QTMovieView* view = (QTMovieView*) getView();
  234121. [view setMovie: theMovie];
  234122. [view setControllerVisible: controllerVisible_];
  234123. setLooping (looping);
  234124. return movie != nil;
  234125. }
  234126. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  234127. const bool isControllerVisible_)
  234128. {
  234129. // unfortunately, QTMovie objects can only be created on the main thread..
  234130. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234131. closeMovie();
  234132. if (getPeer() == 0)
  234133. {
  234134. // To open a movie, this component must be visible inside a functioning window, so that
  234135. // the QT control can be assigned to the window.
  234136. jassertfalse;
  234137. return false;
  234138. }
  234139. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  234140. NSError* err;
  234141. if ([QTMovie canInitWithURL: url])
  234142. movie = [QTMovie movieWithURL: url error: &err];
  234143. [theMovie retain];
  234144. QTMovieView* view = (QTMovieView*) getView();
  234145. [view setMovie: theMovie];
  234146. [view setControllerVisible: controllerVisible];
  234147. setLooping (looping);
  234148. return movie != nil;
  234149. }
  234150. void QuickTimeMovieComponent::closeMovie()
  234151. {
  234152. stop();
  234153. QTMovieView* view = (QTMovieView*) getView();
  234154. [view setMovie: nil];
  234155. [theMovie release];
  234156. movie = 0;
  234157. movieFile = File::nonexistent;
  234158. }
  234159. bool QuickTimeMovieComponent::isMovieOpen() const
  234160. {
  234161. return movie != nil;
  234162. }
  234163. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  234164. {
  234165. return movieFile;
  234166. }
  234167. void QuickTimeMovieComponent::play()
  234168. {
  234169. [theMovie play];
  234170. }
  234171. void QuickTimeMovieComponent::stop()
  234172. {
  234173. [theMovie stop];
  234174. }
  234175. bool QuickTimeMovieComponent::isPlaying() const
  234176. {
  234177. return movie != 0 && [theMovie rate] != 0;
  234178. }
  234179. void QuickTimeMovieComponent::setPosition (const double seconds)
  234180. {
  234181. if (movie != 0)
  234182. {
  234183. QTTime t;
  234184. t.timeValue = (uint64) (100000.0 * seconds);
  234185. t.timeScale = 100000;
  234186. t.flags = 0;
  234187. [theMovie setCurrentTime: t];
  234188. }
  234189. }
  234190. double QuickTimeMovieComponent::getPosition() const
  234191. {
  234192. if (movie == 0)
  234193. return 0.0;
  234194. QTTime t = [theMovie currentTime];
  234195. return t.timeValue / (double) t.timeScale;
  234196. }
  234197. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  234198. {
  234199. [theMovie setRate: newSpeed];
  234200. }
  234201. double QuickTimeMovieComponent::getMovieDuration() const
  234202. {
  234203. if (movie == 0)
  234204. return 0.0;
  234205. QTTime t = [theMovie duration];
  234206. return t.timeValue / (double) t.timeScale;
  234207. }
  234208. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  234209. {
  234210. looping = shouldLoop;
  234211. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  234212. forKey: QTMovieLoopsAttribute];
  234213. }
  234214. bool QuickTimeMovieComponent::isLooping() const
  234215. {
  234216. return looping;
  234217. }
  234218. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  234219. {
  234220. [theMovie setVolume: newVolume];
  234221. }
  234222. float QuickTimeMovieComponent::getMovieVolume() const
  234223. {
  234224. return movie != 0 ? [theMovie volume] : 0.0f;
  234225. }
  234226. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  234227. {
  234228. width = 0;
  234229. height = 0;
  234230. if (movie != 0)
  234231. {
  234232. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  234233. width = (int) s.width;
  234234. height = (int) s.height;
  234235. }
  234236. }
  234237. void QuickTimeMovieComponent::paint (Graphics& g)
  234238. {
  234239. if (movie == 0)
  234240. g.fillAll (Colours::black);
  234241. }
  234242. bool QuickTimeMovieComponent::isControllerVisible() const
  234243. {
  234244. return controllerVisible;
  234245. }
  234246. void QuickTimeMovieComponent::goToStart()
  234247. {
  234248. setPosition (0.0);
  234249. }
  234250. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  234251. const RectanglePlacement& placement)
  234252. {
  234253. int normalWidth, normalHeight;
  234254. getMovieNormalSize (normalWidth, normalHeight);
  234255. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  234256. {
  234257. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  234258. placement.applyTo (x, y, w, h,
  234259. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  234260. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  234261. if (w > 0 && h > 0)
  234262. {
  234263. setBounds (roundToInt (x), roundToInt (y),
  234264. roundToInt (w), roundToInt (h));
  234265. }
  234266. }
  234267. else
  234268. {
  234269. setBounds (spaceToFitWithin);
  234270. }
  234271. }
  234272. #if ! (JUCE_MAC && JUCE_64BIT)
  234273. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  234274. {
  234275. if (movieStream == 0)
  234276. return false;
  234277. File file;
  234278. QTMovie* movie = openMovieFromStream (movieStream, file);
  234279. if (movie != nil)
  234280. result = [movie quickTimeMovie];
  234281. return movie != nil;
  234282. }
  234283. #endif
  234284. #endif
  234285. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234286. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  234287. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234288. // compiled on its own).
  234289. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  234290. const int kilobytesPerSecond1x = 176;
  234291. END_JUCE_NAMESPACE
  234292. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  234293. @interface OpenDiskDevice : NSObject
  234294. {
  234295. @public
  234296. DRDevice* device;
  234297. NSMutableArray* tracks;
  234298. bool underrunProtection;
  234299. }
  234300. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  234301. - (void) dealloc;
  234302. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  234303. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234304. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  234305. @end
  234306. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  234307. @interface AudioTrackProducer : NSObject
  234308. {
  234309. JUCE_NAMESPACE::AudioSource* source;
  234310. int readPosition, lengthInFrames;
  234311. }
  234312. - (AudioTrackProducer*) init: (int) lengthInFrames;
  234313. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  234314. - (void) dealloc;
  234315. - (void) setupTrackProperties: (DRTrack*) track;
  234316. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  234317. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  234318. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  234319. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  234320. toMedia:(NSDictionary*)mediaInfo;
  234321. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  234322. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  234323. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234324. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234325. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234326. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234327. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234328. ioFlags:(uint32_t*)flags;
  234329. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234330. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234331. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234332. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234333. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234334. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234335. ioFlags:(uint32_t*)flags;
  234336. @end
  234337. @implementation OpenDiskDevice
  234338. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234339. {
  234340. [super init];
  234341. device = device_;
  234342. tracks = [[NSMutableArray alloc] init];
  234343. underrunProtection = true;
  234344. return self;
  234345. }
  234346. - (void) dealloc
  234347. {
  234348. [tracks release];
  234349. [super dealloc];
  234350. }
  234351. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234352. {
  234353. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234354. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234355. [p setupTrackProperties: t];
  234356. [tracks addObject: t];
  234357. [t release];
  234358. [p release];
  234359. }
  234360. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234361. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234362. {
  234363. DRBurn* burn = [DRBurn burnForDevice: device];
  234364. if (! [device acquireExclusiveAccess])
  234365. {
  234366. *error = "Couldn't open or write to the CD device";
  234367. return;
  234368. }
  234369. [device acquireMediaReservation];
  234370. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234371. [d autorelease];
  234372. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234373. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234374. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234375. if (burnSpeed > 0)
  234376. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234377. if (! underrunProtection)
  234378. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234379. [burn setProperties: d];
  234380. [burn writeLayout: tracks];
  234381. for (;;)
  234382. {
  234383. JUCE_NAMESPACE::Thread::sleep (300);
  234384. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234385. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234386. {
  234387. [burn abort];
  234388. *error = "User cancelled the write operation";
  234389. break;
  234390. }
  234391. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234392. {
  234393. *error = "Write operation failed";
  234394. break;
  234395. }
  234396. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234397. {
  234398. break;
  234399. }
  234400. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234401. objectForKey: DRErrorStatusErrorStringKey];
  234402. if ([err length] > 0)
  234403. {
  234404. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234405. break;
  234406. }
  234407. }
  234408. [device releaseMediaReservation];
  234409. [device releaseExclusiveAccess];
  234410. }
  234411. @end
  234412. @implementation AudioTrackProducer
  234413. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234414. {
  234415. lengthInFrames = lengthInFrames_;
  234416. readPosition = 0;
  234417. return self;
  234418. }
  234419. - (void) setupTrackProperties: (DRTrack*) track
  234420. {
  234421. NSMutableDictionary* p = [[track properties] mutableCopy];
  234422. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234423. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234424. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234425. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234426. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234427. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234428. [track setProperties: p];
  234429. [p release];
  234430. }
  234431. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234432. {
  234433. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234434. if (s != nil)
  234435. s->source = source_;
  234436. return s;
  234437. }
  234438. - (void) dealloc
  234439. {
  234440. if (source != 0)
  234441. {
  234442. source->releaseResources();
  234443. delete source;
  234444. }
  234445. [super dealloc];
  234446. }
  234447. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234448. {
  234449. }
  234450. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234451. {
  234452. return true;
  234453. }
  234454. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234455. {
  234456. return lengthInFrames;
  234457. }
  234458. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234459. toMedia: (NSDictionary*) mediaInfo
  234460. {
  234461. if (source != 0)
  234462. source->prepareToPlay (44100 / 75, 44100);
  234463. readPosition = 0;
  234464. return true;
  234465. }
  234466. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234467. {
  234468. if (source != 0)
  234469. source->prepareToPlay (44100 / 75, 44100);
  234470. return true;
  234471. }
  234472. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234473. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234474. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234475. {
  234476. if (source != 0)
  234477. {
  234478. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234479. if (numSamples > 0)
  234480. {
  234481. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234482. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234483. info.buffer = &tempBuffer;
  234484. info.startSample = 0;
  234485. info.numSamples = numSamples;
  234486. source->getNextAudioBlock (info);
  234487. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  234488. buffer, numSamples, 4);
  234489. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  234490. buffer + 2, numSamples, 4);
  234491. readPosition += numSamples;
  234492. }
  234493. return numSamples * 4;
  234494. }
  234495. return 0;
  234496. }
  234497. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234498. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234499. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234500. ioFlags: (uint32_t*) flags
  234501. {
  234502. zeromem (buffer, bufferLength);
  234503. return bufferLength;
  234504. }
  234505. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234506. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234507. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234508. {
  234509. return true;
  234510. }
  234511. @end
  234512. BEGIN_JUCE_NAMESPACE
  234513. class AudioCDBurner::Pimpl : public Timer
  234514. {
  234515. public:
  234516. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234517. : device (0), owner (owner_)
  234518. {
  234519. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234520. if (dev != 0)
  234521. {
  234522. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234523. lastState = getDiskState();
  234524. startTimer (1000);
  234525. }
  234526. }
  234527. ~Pimpl()
  234528. {
  234529. stopTimer();
  234530. [device release];
  234531. }
  234532. void timerCallback()
  234533. {
  234534. const DiskState state = getDiskState();
  234535. if (state != lastState)
  234536. {
  234537. lastState = state;
  234538. owner.sendChangeMessage (&owner);
  234539. }
  234540. }
  234541. DiskState getDiskState() const
  234542. {
  234543. if ([device->device isValid])
  234544. {
  234545. NSDictionary* status = [device->device status];
  234546. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234547. if ([state isEqualTo: DRDeviceMediaStateNone])
  234548. {
  234549. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234550. return trayOpen;
  234551. return noDisc;
  234552. }
  234553. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234554. {
  234555. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234556. return writableDiskPresent;
  234557. else
  234558. return readOnlyDiskPresent;
  234559. }
  234560. }
  234561. return unknown;
  234562. }
  234563. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234564. const Array<int> getAvailableWriteSpeeds() const
  234565. {
  234566. Array<int> results;
  234567. if ([device->device isValid])
  234568. {
  234569. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234570. for (unsigned int i = 0; i < [speeds count]; ++i)
  234571. {
  234572. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234573. results.add (kbPerSec / kilobytesPerSecond1x);
  234574. }
  234575. }
  234576. return results;
  234577. }
  234578. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234579. {
  234580. if ([device->device isValid])
  234581. {
  234582. device->underrunProtection = shouldBeEnabled;
  234583. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234584. }
  234585. return false;
  234586. }
  234587. int getNumAvailableAudioBlocks() const
  234588. {
  234589. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234590. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234591. }
  234592. OpenDiskDevice* device;
  234593. private:
  234594. DiskState lastState;
  234595. AudioCDBurner& owner;
  234596. };
  234597. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234598. {
  234599. pimpl = new Pimpl (*this, deviceIndex);
  234600. }
  234601. AudioCDBurner::~AudioCDBurner()
  234602. {
  234603. }
  234604. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234605. {
  234606. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234607. if (b->pimpl->device == 0)
  234608. b = 0;
  234609. return b.release();
  234610. }
  234611. static NSArray* findDiskBurnerDevices()
  234612. {
  234613. NSMutableArray* results = [NSMutableArray array];
  234614. NSArray* devs = [DRDevice devices];
  234615. if (devs != 0)
  234616. {
  234617. int num = [devs count];
  234618. int i;
  234619. for (i = 0; i < num; ++i)
  234620. {
  234621. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234622. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234623. if (name != nil)
  234624. [results addObject: name];
  234625. }
  234626. }
  234627. return results;
  234628. }
  234629. const StringArray AudioCDBurner::findAvailableDevices()
  234630. {
  234631. NSArray* names = findDiskBurnerDevices();
  234632. StringArray s;
  234633. for (unsigned int i = 0; i < [names count]; ++i)
  234634. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234635. return s;
  234636. }
  234637. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234638. {
  234639. return pimpl->getDiskState();
  234640. }
  234641. bool AudioCDBurner::isDiskPresent() const
  234642. {
  234643. return getDiskState() == writableDiskPresent;
  234644. }
  234645. bool AudioCDBurner::openTray()
  234646. {
  234647. return pimpl->openTray();
  234648. }
  234649. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234650. {
  234651. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234652. DiskState oldState = getDiskState();
  234653. DiskState newState = oldState;
  234654. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234655. {
  234656. newState = getDiskState();
  234657. Thread::sleep (100);
  234658. }
  234659. return newState;
  234660. }
  234661. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234662. {
  234663. return pimpl->getAvailableWriteSpeeds();
  234664. }
  234665. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234666. {
  234667. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234668. }
  234669. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234670. {
  234671. return pimpl->getNumAvailableAudioBlocks();
  234672. }
  234673. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234674. {
  234675. if ([pimpl->device->device isValid])
  234676. {
  234677. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234678. return true;
  234679. }
  234680. return false;
  234681. }
  234682. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234683. bool ejectDiscAfterwards,
  234684. bool performFakeBurnForTesting,
  234685. int writeSpeed)
  234686. {
  234687. String error ("Couldn't open or write to the CD device");
  234688. if ([pimpl->device->device isValid])
  234689. {
  234690. error = String::empty;
  234691. [pimpl->device burn: listener
  234692. errorString: &error
  234693. ejectAfterwards: ejectDiscAfterwards
  234694. isFake: performFakeBurnForTesting
  234695. speed: writeSpeed];
  234696. }
  234697. return error;
  234698. }
  234699. #endif
  234700. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234701. void AudioCDReader::ejectDisk()
  234702. {
  234703. const ScopedAutoReleasePool p;
  234704. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234705. }
  234706. #endif
  234707. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234708. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234709. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234710. // compiled on its own).
  234711. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234712. namespace CDReaderHelpers
  234713. {
  234714. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234715. {
  234716. forEachXmlChildElementWithTagName (xml, child, "key")
  234717. if (child->getAllSubText() == key)
  234718. return child->getNextElement();
  234719. return 0;
  234720. }
  234721. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234722. {
  234723. const XmlElement* const block = getElementForKey (xml, key);
  234724. return block != 0 ? block->getAllSubText().getIntValue() : defaultValue;
  234725. }
  234726. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234727. // Returns NULL on success, otherwise a const char* representing an error.
  234728. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234729. {
  234730. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234731. if (xml == 0)
  234732. return "Couldn't parse XML in file";
  234733. const XmlElement* const dict = xml->getChildByName ("dict");
  234734. if (dict == 0)
  234735. return "Couldn't get top level dictionary";
  234736. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234737. if (sessions == 0)
  234738. return "Couldn't find sessions key";
  234739. const XmlElement* const session = sessions->getFirstChildElement();
  234740. if (session == 0)
  234741. return "Couldn't find first session";
  234742. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234743. if (leadOut < 0)
  234744. return "Couldn't find Leadout Block";
  234745. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234746. if (trackArray == 0)
  234747. return "Couldn't find Track Array";
  234748. forEachXmlChildElement (*trackArray, track)
  234749. {
  234750. const int trackValue = getIntValueForKey (*track, "Start Block");
  234751. if (trackValue < 0)
  234752. return "Couldn't find Start Block in the track";
  234753. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234754. }
  234755. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234756. return 0;
  234757. }
  234758. static void findDevices (Array<File>& cds)
  234759. {
  234760. File volumes ("/Volumes");
  234761. volumes.findChildFiles (cds, File::findDirectories, false);
  234762. for (int i = cds.size(); --i >= 0;)
  234763. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234764. cds.remove (i);
  234765. }
  234766. struct TrackSorter
  234767. {
  234768. static int getCDTrackNumber (const File& file)
  234769. {
  234770. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234771. }
  234772. static int compareElements (const File& first, const File& second)
  234773. {
  234774. const int firstTrack = getCDTrackNumber (first);
  234775. const int secondTrack = getCDTrackNumber (second);
  234776. jassert (firstTrack > 0 && secondTrack > 0);
  234777. return firstTrack - secondTrack;
  234778. }
  234779. };
  234780. }
  234781. const StringArray AudioCDReader::getAvailableCDNames()
  234782. {
  234783. Array<File> cds;
  234784. CDReaderHelpers::findDevices (cds);
  234785. StringArray names;
  234786. for (int i = 0; i < cds.size(); ++i)
  234787. names.add (cds.getReference(i).getFileName());
  234788. return names;
  234789. }
  234790. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234791. {
  234792. Array<File> cds;
  234793. CDReaderHelpers::findDevices (cds);
  234794. if (cds[index].exists())
  234795. return new AudioCDReader (cds[index]);
  234796. return 0;
  234797. }
  234798. AudioCDReader::AudioCDReader (const File& volume)
  234799. : AudioFormatReader (0, "CD Audio"),
  234800. volumeDir (volume),
  234801. currentReaderTrack (-1),
  234802. reader (0)
  234803. {
  234804. sampleRate = 44100.0;
  234805. bitsPerSample = 16;
  234806. numChannels = 2;
  234807. usesFloatingPointData = false;
  234808. refreshTrackLengths();
  234809. }
  234810. AudioCDReader::~AudioCDReader()
  234811. {
  234812. }
  234813. void AudioCDReader::refreshTrackLengths()
  234814. {
  234815. tracks.clear();
  234816. trackStartSamples.clear();
  234817. lengthInSamples = 0;
  234818. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234819. CDReaderHelpers::TrackSorter sorter;
  234820. tracks.sort (sorter);
  234821. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234822. if (toc.exists())
  234823. {
  234824. XmlDocument doc (toc);
  234825. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234826. (void) error; // could be logged..
  234827. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234828. }
  234829. }
  234830. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234831. int64 startSampleInFile, int numSamples)
  234832. {
  234833. while (numSamples > 0)
  234834. {
  234835. int track = -1;
  234836. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234837. {
  234838. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234839. {
  234840. track = i;
  234841. break;
  234842. }
  234843. }
  234844. if (track < 0)
  234845. return false;
  234846. if (track != currentReaderTrack)
  234847. {
  234848. reader = 0;
  234849. FileInputStream* const in = tracks [track].createInputStream();
  234850. if (in != 0)
  234851. {
  234852. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234853. AiffAudioFormat format;
  234854. reader = format.createReaderFor (bin, true);
  234855. if (reader == 0)
  234856. currentReaderTrack = -1;
  234857. else
  234858. currentReaderTrack = track;
  234859. }
  234860. }
  234861. if (reader == 0)
  234862. return false;
  234863. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234864. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234865. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234866. numSamples -= numAvailable;
  234867. startSampleInFile += numAvailable;
  234868. }
  234869. return true;
  234870. }
  234871. bool AudioCDReader::isCDStillPresent() const
  234872. {
  234873. return volumeDir.exists();
  234874. }
  234875. bool AudioCDReader::isTrackAudio (int trackNum) const
  234876. {
  234877. return tracks [trackNum].hasFileExtension (".aiff");
  234878. }
  234879. void AudioCDReader::enableIndexScanning (bool b)
  234880. {
  234881. // any way to do this on a Mac??
  234882. }
  234883. int AudioCDReader::getLastIndex() const
  234884. {
  234885. return 0;
  234886. }
  234887. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234888. {
  234889. return Array <int>();
  234890. }
  234891. #endif
  234892. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234893. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234894. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234895. // compiled on its own).
  234896. #if JUCE_INCLUDED_FILE
  234897. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234898. for example having more than one juce plugin loaded into a host, then when a
  234899. method is called, the actual code that runs might actually be in a different module
  234900. than the one you expect... So any calls to library functions or statics that are
  234901. made inside obj-c methods will probably end up getting executed in a different DLL's
  234902. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234903. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234904. virtual methods of an object that's known to live inside the right module's space.
  234905. */
  234906. class AppDelegateRedirector
  234907. {
  234908. public:
  234909. AppDelegateRedirector()
  234910. {
  234911. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234912. runLoop = CFRunLoopGetMain();
  234913. #else
  234914. runLoop = CFRunLoopGetCurrent();
  234915. #endif
  234916. CFRunLoopSourceContext sourceContext;
  234917. zerostruct (sourceContext);
  234918. sourceContext.info = this;
  234919. sourceContext.perform = runLoopSourceCallback;
  234920. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234921. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234922. }
  234923. virtual ~AppDelegateRedirector()
  234924. {
  234925. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234926. CFRunLoopSourceInvalidate (runLoopSource);
  234927. CFRelease (runLoopSource);
  234928. }
  234929. virtual NSApplicationTerminateReply shouldTerminate()
  234930. {
  234931. if (JUCEApplication::getInstance() != 0)
  234932. {
  234933. JUCEApplication::getInstance()->systemRequestedQuit();
  234934. if (MessageManager::getInstance()->hasStopMessageBeenSent())
  234935. {
  234936. [NSApp performSelectorOnMainThread: @selector (replyToApplicationShouldTerminate:)
  234937. withObject: [NSNumber numberWithBool: YES]
  234938. waitUntilDone: NO];
  234939. return NSTerminateLater;
  234940. }
  234941. return NSTerminateCancel;
  234942. }
  234943. return NSTerminateNow;
  234944. }
  234945. virtual BOOL openFile (const NSString* filename)
  234946. {
  234947. if (JUCEApplication::getInstance() != 0)
  234948. {
  234949. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234950. return YES;
  234951. }
  234952. return NO;
  234953. }
  234954. virtual void openFiles (NSArray* filenames)
  234955. {
  234956. StringArray files;
  234957. for (unsigned int i = 0; i < [filenames count]; ++i)
  234958. {
  234959. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234960. if (filename.containsChar (' '))
  234961. filename = filename.quoted('"');
  234962. files.add (filename);
  234963. }
  234964. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234965. {
  234966. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234967. }
  234968. }
  234969. virtual void focusChanged()
  234970. {
  234971. juce_HandleProcessFocusChange();
  234972. }
  234973. struct CallbackMessagePayload
  234974. {
  234975. MessageCallbackFunction* function;
  234976. void* parameter;
  234977. void* volatile result;
  234978. bool volatile hasBeenExecuted;
  234979. };
  234980. virtual void performCallback (CallbackMessagePayload* pl)
  234981. {
  234982. pl->result = (*pl->function) (pl->parameter);
  234983. pl->hasBeenExecuted = true;
  234984. }
  234985. virtual void deleteSelf()
  234986. {
  234987. delete this;
  234988. }
  234989. void postMessage (Message* const m)
  234990. {
  234991. messages.add (m);
  234992. CFRunLoopSourceSignal (runLoopSource);
  234993. CFRunLoopWakeUp (runLoop);
  234994. }
  234995. private:
  234996. CFRunLoopRef runLoop;
  234997. CFRunLoopSourceRef runLoopSource;
  234998. OwnedArray <Message, CriticalSection> messages;
  234999. void runLoopCallback()
  235000. {
  235001. int numDispatched = 0;
  235002. do
  235003. {
  235004. Message* const nextMessage = messages.removeAndReturn (0);
  235005. if (nextMessage == 0)
  235006. return;
  235007. const ScopedAutoReleasePool pool;
  235008. MessageManager::getInstance()->deliverMessage (nextMessage);
  235009. } while (++numDispatched <= 4);
  235010. CFRunLoopSourceSignal (runLoopSource);
  235011. CFRunLoopWakeUp (runLoop);
  235012. }
  235013. static void runLoopSourceCallback (void* info)
  235014. {
  235015. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  235016. }
  235017. };
  235018. END_JUCE_NAMESPACE
  235019. using namespace JUCE_NAMESPACE;
  235020. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  235021. @interface JuceAppDelegate : NSObject
  235022. {
  235023. @private
  235024. id oldDelegate;
  235025. @public
  235026. AppDelegateRedirector* redirector;
  235027. }
  235028. - (JuceAppDelegate*) init;
  235029. - (void) dealloc;
  235030. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  235031. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  235032. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  235033. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  235034. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  235035. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  235036. - (void) performCallback: (id) info;
  235037. - (void) dummyMethod;
  235038. @end
  235039. @implementation JuceAppDelegate
  235040. - (JuceAppDelegate*) init
  235041. {
  235042. [super init];
  235043. redirector = new AppDelegateRedirector();
  235044. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  235045. if (JUCEApplication::isStandaloneApp())
  235046. {
  235047. oldDelegate = [NSApp delegate];
  235048. [NSApp setDelegate: self];
  235049. }
  235050. else
  235051. {
  235052. oldDelegate = 0;
  235053. [center addObserver: self selector: @selector (applicationDidResignActive:)
  235054. name: NSApplicationDidResignActiveNotification object: NSApp];
  235055. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  235056. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  235057. [center addObserver: self selector: @selector (applicationWillUnhide:)
  235058. name: NSApplicationWillUnhideNotification object: NSApp];
  235059. }
  235060. return self;
  235061. }
  235062. - (void) dealloc
  235063. {
  235064. if (oldDelegate != 0)
  235065. [NSApp setDelegate: oldDelegate];
  235066. redirector->deleteSelf();
  235067. [super dealloc];
  235068. }
  235069. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  235070. {
  235071. (void) app;
  235072. return redirector->shouldTerminate();
  235073. }
  235074. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  235075. {
  235076. (void) app;
  235077. return redirector->openFile (filename);
  235078. }
  235079. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  235080. {
  235081. (void) sender;
  235082. return redirector->openFiles (filenames);
  235083. }
  235084. - (void) applicationDidBecomeActive: (NSNotification*) notification
  235085. {
  235086. (void) notification;
  235087. redirector->focusChanged();
  235088. }
  235089. - (void) applicationDidResignActive: (NSNotification*) notification
  235090. {
  235091. (void) notification;
  235092. redirector->focusChanged();
  235093. }
  235094. - (void) applicationWillUnhide: (NSNotification*) notification
  235095. {
  235096. (void) notification;
  235097. redirector->focusChanged();
  235098. }
  235099. - (void) performCallback: (id) info
  235100. {
  235101. if ([info isKindOfClass: [NSData class]])
  235102. {
  235103. AppDelegateRedirector::CallbackMessagePayload* pl
  235104. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  235105. if (pl != 0)
  235106. redirector->performCallback (pl);
  235107. }
  235108. else
  235109. {
  235110. jassertfalse; // should never get here!
  235111. }
  235112. }
  235113. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  235114. @end
  235115. BEGIN_JUCE_NAMESPACE
  235116. static JuceAppDelegate* juceAppDelegate = 0;
  235117. void MessageManager::runDispatchLoop()
  235118. {
  235119. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  235120. {
  235121. const ScopedAutoReleasePool pool;
  235122. // must only be called by the message thread!
  235123. jassert (isThisTheMessageThread());
  235124. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  235125. @try
  235126. {
  235127. [NSApp run];
  235128. }
  235129. @catch (NSException* e)
  235130. {
  235131. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  235132. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  235133. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  235134. }
  235135. @finally
  235136. {
  235137. }
  235138. #else
  235139. [NSApp run];
  235140. #endif
  235141. }
  235142. }
  235143. void MessageManager::stopDispatchLoop()
  235144. {
  235145. quitMessagePosted = true;
  235146. [NSApp stop: nil];
  235147. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  235148. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  235149. }
  235150. static bool isEventBlockedByModalComps (NSEvent* e)
  235151. {
  235152. if (Component::getNumCurrentlyModalComponents() == 0)
  235153. return false;
  235154. NSWindow* const w = [e window];
  235155. if (w == 0 || [w worksWhenModal])
  235156. return false;
  235157. bool isKey = false, isInputAttempt = false;
  235158. switch ([e type])
  235159. {
  235160. case NSKeyDown:
  235161. case NSKeyUp:
  235162. isKey = isInputAttempt = true;
  235163. break;
  235164. case NSLeftMouseDown:
  235165. case NSRightMouseDown:
  235166. case NSOtherMouseDown:
  235167. isInputAttempt = true;
  235168. break;
  235169. case NSLeftMouseDragged:
  235170. case NSRightMouseDragged:
  235171. case NSLeftMouseUp:
  235172. case NSRightMouseUp:
  235173. case NSOtherMouseUp:
  235174. case NSOtherMouseDragged:
  235175. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  235176. return false;
  235177. break;
  235178. case NSMouseMoved:
  235179. case NSMouseEntered:
  235180. case NSMouseExited:
  235181. case NSCursorUpdate:
  235182. case NSScrollWheel:
  235183. case NSTabletPoint:
  235184. case NSTabletProximity:
  235185. break;
  235186. default:
  235187. return false;
  235188. }
  235189. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  235190. {
  235191. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  235192. NSView* const compView = (NSView*) peer->getNativeHandle();
  235193. if ([compView window] == w)
  235194. {
  235195. if (isKey)
  235196. {
  235197. if (compView == [w firstResponder])
  235198. return false;
  235199. }
  235200. else
  235201. {
  235202. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  235203. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  235204. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  235205. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  235206. return false;
  235207. }
  235208. }
  235209. }
  235210. if (isInputAttempt)
  235211. {
  235212. if (! [NSApp isActive])
  235213. [NSApp activateIgnoringOtherApps: YES];
  235214. Component* const modal = Component::getCurrentlyModalComponent (0);
  235215. if (modal != 0)
  235216. modal->inputAttemptWhenModal();
  235217. }
  235218. return true;
  235219. }
  235220. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  235221. {
  235222. jassert (isThisTheMessageThread()); // must only be called by the message thread
  235223. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  235224. while (! quitMessagePosted)
  235225. {
  235226. const ScopedAutoReleasePool pool;
  235227. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  235228. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  235229. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  235230. inMode: NSDefaultRunLoopMode
  235231. dequeue: YES];
  235232. if (e != 0 && ! isEventBlockedByModalComps (e))
  235233. [NSApp sendEvent: e];
  235234. if (Time::getMillisecondCounter() >= endTime)
  235235. break;
  235236. }
  235237. return ! quitMessagePosted;
  235238. }
  235239. void MessageManager::doPlatformSpecificInitialisation()
  235240. {
  235241. if (juceAppDelegate == 0)
  235242. juceAppDelegate = [[JuceAppDelegate alloc] init];
  235243. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  235244. // correctly (needed prior to 10.5)
  235245. if (! [NSThread isMultiThreaded])
  235246. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  235247. toTarget: juceAppDelegate
  235248. withObject: nil];
  235249. }
  235250. void MessageManager::doPlatformSpecificShutdown()
  235251. {
  235252. if (juceAppDelegate != 0)
  235253. {
  235254. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  235255. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  235256. [juceAppDelegate release];
  235257. juceAppDelegate = 0;
  235258. }
  235259. }
  235260. bool juce_postMessageToSystemQueue (Message* message)
  235261. {
  235262. juceAppDelegate->redirector->postMessage (message);
  235263. return true;
  235264. }
  235265. void MessageManager::broadcastMessage (const String& value)
  235266. {
  235267. }
  235268. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  235269. {
  235270. if (isThisTheMessageThread())
  235271. {
  235272. return (*callback) (data);
  235273. }
  235274. else
  235275. {
  235276. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  235277. // deadlock because the message manager is blocked from running, so can never
  235278. // call your function..
  235279. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  235280. const ScopedAutoReleasePool pool;
  235281. AppDelegateRedirector::CallbackMessagePayload cmp;
  235282. cmp.function = callback;
  235283. cmp.parameter = data;
  235284. cmp.result = 0;
  235285. cmp.hasBeenExecuted = false;
  235286. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  235287. withObject: [NSData dataWithBytesNoCopy: &cmp
  235288. length: sizeof (cmp)
  235289. freeWhenDone: NO]
  235290. waitUntilDone: YES];
  235291. return cmp.result;
  235292. }
  235293. }
  235294. #endif
  235295. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  235296. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235297. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235298. // compiled on its own).
  235299. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  235300. #if JUCE_MAC
  235301. END_JUCE_NAMESPACE
  235302. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  235303. @interface DownloadClickDetector : NSObject
  235304. {
  235305. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  235306. }
  235307. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  235308. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235309. request: (NSURLRequest*) request
  235310. frame: (WebFrame*) frame
  235311. decisionListener: (id<WebPolicyDecisionListener>) listener;
  235312. @end
  235313. @implementation DownloadClickDetector
  235314. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235315. {
  235316. [super init];
  235317. ownerComponent = ownerComponent_;
  235318. return self;
  235319. }
  235320. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235321. request: (NSURLRequest*) request
  235322. frame: (WebFrame*) frame
  235323. decisionListener: (id <WebPolicyDecisionListener>) listener
  235324. {
  235325. (void) sender;
  235326. (void) request;
  235327. (void) frame;
  235328. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235329. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235330. [listener use];
  235331. else
  235332. [listener ignore];
  235333. }
  235334. @end
  235335. BEGIN_JUCE_NAMESPACE
  235336. class WebBrowserComponentInternal : public NSViewComponent
  235337. {
  235338. public:
  235339. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235340. {
  235341. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235342. frameName: @""
  235343. groupName: @""];
  235344. setView (webView);
  235345. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235346. [webView setPolicyDelegate: clickListener];
  235347. }
  235348. ~WebBrowserComponentInternal()
  235349. {
  235350. [webView setPolicyDelegate: nil];
  235351. [clickListener release];
  235352. setView (0);
  235353. }
  235354. void goToURL (const String& url,
  235355. const StringArray* headers,
  235356. const MemoryBlock* postData)
  235357. {
  235358. NSMutableURLRequest* r
  235359. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235360. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235361. timeoutInterval: 30.0];
  235362. if (postData != 0 && postData->getSize() > 0)
  235363. {
  235364. [r setHTTPMethod: @"POST"];
  235365. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235366. length: postData->getSize()]];
  235367. }
  235368. if (headers != 0)
  235369. {
  235370. for (int i = 0; i < headers->size(); ++i)
  235371. {
  235372. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235373. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235374. [r setValue: juceStringToNS (headerValue)
  235375. forHTTPHeaderField: juceStringToNS (headerName)];
  235376. }
  235377. }
  235378. stop();
  235379. [[webView mainFrame] loadRequest: r];
  235380. }
  235381. void goBack()
  235382. {
  235383. [webView goBack];
  235384. }
  235385. void goForward()
  235386. {
  235387. [webView goForward];
  235388. }
  235389. void stop()
  235390. {
  235391. [webView stopLoading: nil];
  235392. }
  235393. void refresh()
  235394. {
  235395. [webView reload: nil];
  235396. }
  235397. private:
  235398. WebView* webView;
  235399. DownloadClickDetector* clickListener;
  235400. };
  235401. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235402. : browser (0),
  235403. blankPageShown (false),
  235404. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235405. {
  235406. setOpaque (true);
  235407. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235408. }
  235409. WebBrowserComponent::~WebBrowserComponent()
  235410. {
  235411. deleteAndZero (browser);
  235412. }
  235413. void WebBrowserComponent::goToURL (const String& url,
  235414. const StringArray* headers,
  235415. const MemoryBlock* postData)
  235416. {
  235417. lastURL = url;
  235418. lastHeaders.clear();
  235419. if (headers != 0)
  235420. lastHeaders = *headers;
  235421. lastPostData.setSize (0);
  235422. if (postData != 0)
  235423. lastPostData = *postData;
  235424. blankPageShown = false;
  235425. browser->goToURL (url, headers, postData);
  235426. }
  235427. void WebBrowserComponent::stop()
  235428. {
  235429. browser->stop();
  235430. }
  235431. void WebBrowserComponent::goBack()
  235432. {
  235433. lastURL = String::empty;
  235434. blankPageShown = false;
  235435. browser->goBack();
  235436. }
  235437. void WebBrowserComponent::goForward()
  235438. {
  235439. lastURL = String::empty;
  235440. browser->goForward();
  235441. }
  235442. void WebBrowserComponent::refresh()
  235443. {
  235444. browser->refresh();
  235445. }
  235446. void WebBrowserComponent::paint (Graphics&)
  235447. {
  235448. }
  235449. void WebBrowserComponent::checkWindowAssociation()
  235450. {
  235451. if (isShowing())
  235452. {
  235453. if (blankPageShown)
  235454. goBack();
  235455. }
  235456. else
  235457. {
  235458. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235459. {
  235460. // when the component becomes invisible, some stuff like flash
  235461. // carries on playing audio, so we need to force it onto a blank
  235462. // page to avoid this, (and send it back when it's made visible again).
  235463. blankPageShown = true;
  235464. browser->goToURL ("about:blank", 0, 0);
  235465. }
  235466. }
  235467. }
  235468. void WebBrowserComponent::reloadLastURL()
  235469. {
  235470. if (lastURL.isNotEmpty())
  235471. {
  235472. goToURL (lastURL, &lastHeaders, &lastPostData);
  235473. lastURL = String::empty;
  235474. }
  235475. }
  235476. void WebBrowserComponent::parentHierarchyChanged()
  235477. {
  235478. checkWindowAssociation();
  235479. }
  235480. void WebBrowserComponent::resized()
  235481. {
  235482. browser->setSize (getWidth(), getHeight());
  235483. }
  235484. void WebBrowserComponent::visibilityChanged()
  235485. {
  235486. checkWindowAssociation();
  235487. }
  235488. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235489. {
  235490. return true;
  235491. }
  235492. #else
  235493. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235494. {
  235495. }
  235496. WebBrowserComponent::~WebBrowserComponent()
  235497. {
  235498. }
  235499. void WebBrowserComponent::goToURL (const String& url,
  235500. const StringArray* headers,
  235501. const MemoryBlock* postData)
  235502. {
  235503. }
  235504. void WebBrowserComponent::stop()
  235505. {
  235506. }
  235507. void WebBrowserComponent::goBack()
  235508. {
  235509. }
  235510. void WebBrowserComponent::goForward()
  235511. {
  235512. }
  235513. void WebBrowserComponent::refresh()
  235514. {
  235515. }
  235516. void WebBrowserComponent::paint (Graphics& g)
  235517. {
  235518. }
  235519. void WebBrowserComponent::checkWindowAssociation()
  235520. {
  235521. }
  235522. void WebBrowserComponent::reloadLastURL()
  235523. {
  235524. }
  235525. void WebBrowserComponent::parentHierarchyChanged()
  235526. {
  235527. }
  235528. void WebBrowserComponent::resized()
  235529. {
  235530. }
  235531. void WebBrowserComponent::visibilityChanged()
  235532. {
  235533. }
  235534. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235535. {
  235536. return true;
  235537. }
  235538. #endif
  235539. #endif
  235540. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235541. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235542. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235543. // compiled on its own).
  235544. #if JUCE_INCLUDED_FILE
  235545. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235546. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235547. #endif
  235548. #undef log
  235549. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235550. #define log(a) Logger::writeToLog (a)
  235551. #else
  235552. #define log(a)
  235553. #endif
  235554. #undef OK
  235555. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235556. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235557. {
  235558. if (err == noErr)
  235559. return true;
  235560. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235561. jassertfalse;
  235562. return false;
  235563. }
  235564. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235565. #else
  235566. #define OK(a) (a == noErr)
  235567. #endif
  235568. class CoreAudioInternal : public Timer
  235569. {
  235570. public:
  235571. CoreAudioInternal (AudioDeviceID id)
  235572. : inputLatency (0),
  235573. outputLatency (0),
  235574. callback (0),
  235575. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235576. audioProcID (0),
  235577. #endif
  235578. isSlaveDevice (false),
  235579. deviceID (id),
  235580. started (false),
  235581. sampleRate (0),
  235582. bufferSize (512),
  235583. numInputChans (0),
  235584. numOutputChans (0),
  235585. callbacksAllowed (true),
  235586. numInputChannelInfos (0),
  235587. numOutputChannelInfos (0)
  235588. {
  235589. jassert (deviceID != 0);
  235590. updateDetailsFromDevice();
  235591. AudioObjectPropertyAddress pa;
  235592. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235593. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235594. pa.mElement = kAudioObjectPropertyElementWildcard;
  235595. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235596. }
  235597. ~CoreAudioInternal()
  235598. {
  235599. AudioObjectPropertyAddress pa;
  235600. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235601. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235602. pa.mElement = kAudioObjectPropertyElementWildcard;
  235603. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235604. stop (false);
  235605. }
  235606. void allocateTempBuffers()
  235607. {
  235608. const int tempBufSize = bufferSize + 4;
  235609. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235610. tempInputBuffers.calloc (numInputChans + 2);
  235611. tempOutputBuffers.calloc (numOutputChans + 2);
  235612. int i, count = 0;
  235613. for (i = 0; i < numInputChans; ++i)
  235614. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235615. for (i = 0; i < numOutputChans; ++i)
  235616. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235617. }
  235618. // returns the number of actual available channels
  235619. void fillInChannelInfo (const bool input)
  235620. {
  235621. int chanNum = 0;
  235622. UInt32 size;
  235623. AudioObjectPropertyAddress pa;
  235624. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235625. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235626. pa.mElement = kAudioObjectPropertyElementMaster;
  235627. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235628. {
  235629. HeapBlock <AudioBufferList> bufList;
  235630. bufList.calloc (size, 1);
  235631. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235632. {
  235633. const int numStreams = bufList->mNumberBuffers;
  235634. for (int i = 0; i < numStreams; ++i)
  235635. {
  235636. const AudioBuffer& b = bufList->mBuffers[i];
  235637. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235638. {
  235639. String name;
  235640. {
  235641. char channelName [256];
  235642. zerostruct (channelName);
  235643. UInt32 nameSize = sizeof (channelName);
  235644. UInt32 channelNum = chanNum + 1;
  235645. pa.mSelector = kAudioDevicePropertyChannelName;
  235646. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235647. name = String::fromUTF8 (channelName, nameSize);
  235648. }
  235649. if (input)
  235650. {
  235651. if (activeInputChans[chanNum])
  235652. {
  235653. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235654. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235655. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235656. ++numInputChannelInfos;
  235657. }
  235658. if (name.isEmpty())
  235659. name << "Input " << (chanNum + 1);
  235660. inChanNames.add (name);
  235661. }
  235662. else
  235663. {
  235664. if (activeOutputChans[chanNum])
  235665. {
  235666. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235667. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235668. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235669. ++numOutputChannelInfos;
  235670. }
  235671. if (name.isEmpty())
  235672. name << "Output " << (chanNum + 1);
  235673. outChanNames.add (name);
  235674. }
  235675. ++chanNum;
  235676. }
  235677. }
  235678. }
  235679. }
  235680. }
  235681. void updateDetailsFromDevice()
  235682. {
  235683. stopTimer();
  235684. if (deviceID == 0)
  235685. return;
  235686. const ScopedLock sl (callbackLock);
  235687. Float64 sr;
  235688. UInt32 size = sizeof (Float64);
  235689. AudioObjectPropertyAddress pa;
  235690. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235691. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235692. pa.mElement = kAudioObjectPropertyElementMaster;
  235693. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235694. sampleRate = sr;
  235695. UInt32 framesPerBuf;
  235696. size = sizeof (framesPerBuf);
  235697. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235698. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235699. {
  235700. bufferSize = framesPerBuf;
  235701. allocateTempBuffers();
  235702. }
  235703. bufferSizes.clear();
  235704. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235705. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235706. {
  235707. HeapBlock <AudioValueRange> ranges;
  235708. ranges.calloc (size, 1);
  235709. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235710. {
  235711. bufferSizes.add ((int) ranges[0].mMinimum);
  235712. for (int i = 32; i < 2048; i += 32)
  235713. {
  235714. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235715. {
  235716. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235717. {
  235718. bufferSizes.addIfNotAlreadyThere (i);
  235719. break;
  235720. }
  235721. }
  235722. }
  235723. if (bufferSize > 0)
  235724. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235725. }
  235726. }
  235727. if (bufferSizes.size() == 0 && bufferSize > 0)
  235728. bufferSizes.add (bufferSize);
  235729. sampleRates.clear();
  235730. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235731. String rates;
  235732. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235733. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235734. {
  235735. HeapBlock <AudioValueRange> ranges;
  235736. ranges.calloc (size, 1);
  235737. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235738. {
  235739. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235740. {
  235741. bool ok = false;
  235742. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235743. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235744. ok = true;
  235745. if (ok)
  235746. {
  235747. sampleRates.add (possibleRates[i]);
  235748. rates << possibleRates[i] << ' ';
  235749. }
  235750. }
  235751. }
  235752. }
  235753. if (sampleRates.size() == 0 && sampleRate > 0)
  235754. {
  235755. sampleRates.add (sampleRate);
  235756. rates << sampleRate;
  235757. }
  235758. log ("sr: " + rates);
  235759. inputLatency = 0;
  235760. outputLatency = 0;
  235761. UInt32 lat;
  235762. size = sizeof (lat);
  235763. pa.mSelector = kAudioDevicePropertyLatency;
  235764. pa.mScope = kAudioDevicePropertyScopeInput;
  235765. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  235766. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235767. inputLatency = (int) lat;
  235768. pa.mScope = kAudioDevicePropertyScopeOutput;
  235769. size = sizeof (lat);
  235770. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235771. outputLatency = (int) lat;
  235772. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235773. inChanNames.clear();
  235774. outChanNames.clear();
  235775. inputChannelInfo.calloc (numInputChans + 2);
  235776. numInputChannelInfos = 0;
  235777. outputChannelInfo.calloc (numOutputChans + 2);
  235778. numOutputChannelInfos = 0;
  235779. fillInChannelInfo (true);
  235780. fillInChannelInfo (false);
  235781. }
  235782. const StringArray getSources (bool input)
  235783. {
  235784. StringArray s;
  235785. HeapBlock <OSType> types;
  235786. const int num = getAllDataSourcesForDevice (deviceID, types);
  235787. for (int i = 0; i < num; ++i)
  235788. {
  235789. AudioValueTranslation avt;
  235790. char buffer[256];
  235791. avt.mInputData = &(types[i]);
  235792. avt.mInputDataSize = sizeof (UInt32);
  235793. avt.mOutputData = buffer;
  235794. avt.mOutputDataSize = 256;
  235795. UInt32 transSize = sizeof (avt);
  235796. AudioObjectPropertyAddress pa;
  235797. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235798. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235799. pa.mElement = kAudioObjectPropertyElementMaster;
  235800. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235801. {
  235802. DBG (buffer);
  235803. s.add (buffer);
  235804. }
  235805. }
  235806. return s;
  235807. }
  235808. int getCurrentSourceIndex (bool input) const
  235809. {
  235810. OSType currentSourceID = 0;
  235811. UInt32 size = sizeof (currentSourceID);
  235812. int result = -1;
  235813. AudioObjectPropertyAddress pa;
  235814. pa.mSelector = kAudioDevicePropertyDataSource;
  235815. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235816. pa.mElement = kAudioObjectPropertyElementMaster;
  235817. if (deviceID != 0)
  235818. {
  235819. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235820. {
  235821. HeapBlock <OSType> types;
  235822. const int num = getAllDataSourcesForDevice (deviceID, types);
  235823. for (int i = 0; i < num; ++i)
  235824. {
  235825. if (types[num] == currentSourceID)
  235826. {
  235827. result = i;
  235828. break;
  235829. }
  235830. }
  235831. }
  235832. }
  235833. return result;
  235834. }
  235835. void setCurrentSourceIndex (int index, bool input)
  235836. {
  235837. if (deviceID != 0)
  235838. {
  235839. HeapBlock <OSType> types;
  235840. const int num = getAllDataSourcesForDevice (deviceID, types);
  235841. if (((unsigned int) index) < (unsigned int) num)
  235842. {
  235843. AudioObjectPropertyAddress pa;
  235844. pa.mSelector = kAudioDevicePropertyDataSource;
  235845. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235846. pa.mElement = kAudioObjectPropertyElementMaster;
  235847. OSType typeId = types[index];
  235848. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235849. }
  235850. }
  235851. }
  235852. const String reopen (const BigInteger& inputChannels,
  235853. const BigInteger& outputChannels,
  235854. double newSampleRate,
  235855. int bufferSizeSamples)
  235856. {
  235857. String error;
  235858. log ("CoreAudio reopen");
  235859. callbacksAllowed = false;
  235860. stopTimer();
  235861. stop (false);
  235862. activeInputChans = inputChannels;
  235863. activeInputChans.setRange (inChanNames.size(),
  235864. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235865. false);
  235866. activeOutputChans = outputChannels;
  235867. activeOutputChans.setRange (outChanNames.size(),
  235868. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235869. false);
  235870. numInputChans = activeInputChans.countNumberOfSetBits();
  235871. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235872. // set sample rate
  235873. AudioObjectPropertyAddress pa;
  235874. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235875. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235876. pa.mElement = kAudioObjectPropertyElementMaster;
  235877. Float64 sr = newSampleRate;
  235878. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235879. {
  235880. error = "Couldn't change sample rate";
  235881. }
  235882. else
  235883. {
  235884. // change buffer size
  235885. UInt32 framesPerBuf = bufferSizeSamples;
  235886. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235887. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235888. {
  235889. error = "Couldn't change buffer size";
  235890. }
  235891. else
  235892. {
  235893. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235894. // correctly report their new settings until some random time in the future, so
  235895. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235896. // to make sure we're using the correct numbers..
  235897. updateDetailsFromDevice();
  235898. sampleRate = newSampleRate;
  235899. bufferSize = bufferSizeSamples;
  235900. if (sampleRates.size() == 0)
  235901. error = "Device has no available sample-rates";
  235902. else if (bufferSizes.size() == 0)
  235903. error = "Device has no available buffer-sizes";
  235904. else if (inputDevice != 0)
  235905. error = inputDevice->reopen (inputChannels,
  235906. outputChannels,
  235907. newSampleRate,
  235908. bufferSizeSamples);
  235909. }
  235910. }
  235911. callbacksAllowed = true;
  235912. return error;
  235913. }
  235914. bool start (AudioIODeviceCallback* cb)
  235915. {
  235916. if (! started)
  235917. {
  235918. callback = 0;
  235919. if (deviceID != 0)
  235920. {
  235921. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235922. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235923. #else
  235924. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235925. #endif
  235926. {
  235927. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235928. {
  235929. started = true;
  235930. }
  235931. else
  235932. {
  235933. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235934. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235935. #else
  235936. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235937. audioProcID = 0;
  235938. #endif
  235939. }
  235940. }
  235941. }
  235942. }
  235943. if (started)
  235944. {
  235945. const ScopedLock sl (callbackLock);
  235946. callback = cb;
  235947. }
  235948. if (inputDevice != 0)
  235949. return started && inputDevice->start (cb);
  235950. else
  235951. return started;
  235952. }
  235953. void stop (bool leaveInterruptRunning)
  235954. {
  235955. {
  235956. const ScopedLock sl (callbackLock);
  235957. callback = 0;
  235958. }
  235959. if (started
  235960. && (deviceID != 0)
  235961. && ! leaveInterruptRunning)
  235962. {
  235963. OK (AudioDeviceStop (deviceID, audioIOProc));
  235964. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235965. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235966. #else
  235967. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235968. audioProcID = 0;
  235969. #endif
  235970. started = false;
  235971. { const ScopedLock sl (callbackLock); }
  235972. // wait until it's definately stopped calling back..
  235973. for (int i = 40; --i >= 0;)
  235974. {
  235975. Thread::sleep (50);
  235976. UInt32 running = 0;
  235977. UInt32 size = sizeof (running);
  235978. AudioObjectPropertyAddress pa;
  235979. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235980. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235981. pa.mElement = kAudioObjectPropertyElementMaster;
  235982. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235983. if (running == 0)
  235984. break;
  235985. }
  235986. const ScopedLock sl (callbackLock);
  235987. }
  235988. if (inputDevice != 0)
  235989. inputDevice->stop (leaveInterruptRunning);
  235990. }
  235991. double getSampleRate() const
  235992. {
  235993. return sampleRate;
  235994. }
  235995. int getBufferSize() const
  235996. {
  235997. return bufferSize;
  235998. }
  235999. void audioCallback (const AudioBufferList* inInputData,
  236000. AudioBufferList* outOutputData)
  236001. {
  236002. int i;
  236003. const ScopedLock sl (callbackLock);
  236004. if (callback != 0)
  236005. {
  236006. if (inputDevice == 0)
  236007. {
  236008. for (i = numInputChans; --i >= 0;)
  236009. {
  236010. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  236011. float* dest = tempInputBuffers [i];
  236012. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  236013. + info.dataOffsetSamples;
  236014. const int stride = info.dataStrideSamples;
  236015. if (stride != 0) // if this is zero, info is invalid
  236016. {
  236017. for (int j = bufferSize; --j >= 0;)
  236018. {
  236019. *dest++ = *src;
  236020. src += stride;
  236021. }
  236022. }
  236023. }
  236024. }
  236025. if (! isSlaveDevice)
  236026. {
  236027. if (inputDevice == 0)
  236028. {
  236029. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  236030. numInputChans,
  236031. tempOutputBuffers,
  236032. numOutputChans,
  236033. bufferSize);
  236034. }
  236035. else
  236036. {
  236037. jassert (inputDevice->bufferSize == bufferSize);
  236038. // Sometimes the two linked devices seem to get their callbacks in
  236039. // parallel, so we need to lock both devices to stop the input data being
  236040. // changed while inside our callback..
  236041. const ScopedLock sl2 (inputDevice->callbackLock);
  236042. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  236043. inputDevice->numInputChans,
  236044. tempOutputBuffers,
  236045. numOutputChans,
  236046. bufferSize);
  236047. }
  236048. for (i = numOutputChans; --i >= 0;)
  236049. {
  236050. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236051. const float* src = tempOutputBuffers [i];
  236052. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236053. + info.dataOffsetSamples;
  236054. const int stride = info.dataStrideSamples;
  236055. if (stride != 0) // if this is zero, info is invalid
  236056. {
  236057. for (int j = bufferSize; --j >= 0;)
  236058. {
  236059. *dest = *src++;
  236060. dest += stride;
  236061. }
  236062. }
  236063. }
  236064. }
  236065. }
  236066. else
  236067. {
  236068. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  236069. {
  236070. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236071. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236072. + info.dataOffsetSamples;
  236073. const int stride = info.dataStrideSamples;
  236074. if (stride != 0) // if this is zero, info is invalid
  236075. {
  236076. for (int j = bufferSize; --j >= 0;)
  236077. {
  236078. *dest = 0.0f;
  236079. dest += stride;
  236080. }
  236081. }
  236082. }
  236083. }
  236084. }
  236085. // called by callbacks
  236086. void deviceDetailsChanged()
  236087. {
  236088. if (callbacksAllowed)
  236089. startTimer (100);
  236090. }
  236091. void timerCallback()
  236092. {
  236093. stopTimer();
  236094. log ("CoreAudio device changed callback");
  236095. const double oldSampleRate = sampleRate;
  236096. const int oldBufferSize = bufferSize;
  236097. updateDetailsFromDevice();
  236098. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  236099. {
  236100. callbacksAllowed = false;
  236101. stop (false);
  236102. updateDetailsFromDevice();
  236103. callbacksAllowed = true;
  236104. }
  236105. }
  236106. CoreAudioInternal* getRelatedDevice() const
  236107. {
  236108. UInt32 size = 0;
  236109. ScopedPointer <CoreAudioInternal> result;
  236110. AudioObjectPropertyAddress pa;
  236111. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  236112. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236113. pa.mElement = kAudioObjectPropertyElementMaster;
  236114. if (deviceID != 0
  236115. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  236116. && size > 0)
  236117. {
  236118. HeapBlock <AudioDeviceID> devs;
  236119. devs.calloc (size, 1);
  236120. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  236121. {
  236122. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  236123. {
  236124. if (devs[i] != deviceID && devs[i] != 0)
  236125. {
  236126. result = new CoreAudioInternal (devs[i]);
  236127. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  236128. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  236129. if (thisIsInput != otherIsInput
  236130. || (inChanNames.size() + outChanNames.size() == 0)
  236131. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  236132. break;
  236133. result = 0;
  236134. }
  236135. }
  236136. }
  236137. }
  236138. return result.release();
  236139. }
  236140. juce_UseDebuggingNewOperator
  236141. int inputLatency, outputLatency;
  236142. BigInteger activeInputChans, activeOutputChans;
  236143. StringArray inChanNames, outChanNames;
  236144. Array <double> sampleRates;
  236145. Array <int> bufferSizes;
  236146. AudioIODeviceCallback* callback;
  236147. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  236148. AudioDeviceIOProcID audioProcID;
  236149. #endif
  236150. ScopedPointer<CoreAudioInternal> inputDevice;
  236151. bool isSlaveDevice;
  236152. private:
  236153. CriticalSection callbackLock;
  236154. AudioDeviceID deviceID;
  236155. bool started;
  236156. double sampleRate;
  236157. int bufferSize;
  236158. HeapBlock <float> audioBuffer;
  236159. int numInputChans, numOutputChans;
  236160. bool callbacksAllowed;
  236161. struct CallbackDetailsForChannel
  236162. {
  236163. int streamNum;
  236164. int dataOffsetSamples;
  236165. int dataStrideSamples;
  236166. };
  236167. int numInputChannelInfos, numOutputChannelInfos;
  236168. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  236169. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  236170. CoreAudioInternal (const CoreAudioInternal&);
  236171. CoreAudioInternal& operator= (const CoreAudioInternal&);
  236172. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  236173. const AudioTimeStamp* /*inNow*/,
  236174. const AudioBufferList* inInputData,
  236175. const AudioTimeStamp* /*inInputTime*/,
  236176. AudioBufferList* outOutputData,
  236177. const AudioTimeStamp* /*inOutputTime*/,
  236178. void* device)
  236179. {
  236180. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  236181. return noErr;
  236182. }
  236183. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236184. {
  236185. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236186. switch (pa->mSelector)
  236187. {
  236188. case kAudioDevicePropertyBufferSize:
  236189. case kAudioDevicePropertyBufferFrameSize:
  236190. case kAudioDevicePropertyNominalSampleRate:
  236191. case kAudioDevicePropertyStreamFormat:
  236192. case kAudioDevicePropertyDeviceIsAlive:
  236193. intern->deviceDetailsChanged();
  236194. break;
  236195. case kAudioDevicePropertyBufferSizeRange:
  236196. case kAudioDevicePropertyVolumeScalar:
  236197. case kAudioDevicePropertyMute:
  236198. case kAudioDevicePropertyPlayThru:
  236199. case kAudioDevicePropertyDataSource:
  236200. case kAudioDevicePropertyDeviceIsRunning:
  236201. break;
  236202. }
  236203. return noErr;
  236204. }
  236205. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  236206. {
  236207. AudioObjectPropertyAddress pa;
  236208. pa.mSelector = kAudioDevicePropertyDataSources;
  236209. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236210. pa.mElement = kAudioObjectPropertyElementMaster;
  236211. UInt32 size = 0;
  236212. if (deviceID != 0
  236213. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236214. {
  236215. types.calloc (size, 1);
  236216. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  236217. return size / (int) sizeof (OSType);
  236218. }
  236219. return 0;
  236220. }
  236221. };
  236222. class CoreAudioIODevice : public AudioIODevice
  236223. {
  236224. public:
  236225. CoreAudioIODevice (const String& deviceName,
  236226. AudioDeviceID inputDeviceId,
  236227. const int inputIndex_,
  236228. AudioDeviceID outputDeviceId,
  236229. const int outputIndex_)
  236230. : AudioIODevice (deviceName, "CoreAudio"),
  236231. inputIndex (inputIndex_),
  236232. outputIndex (outputIndex_),
  236233. isOpen_ (false),
  236234. isStarted (false)
  236235. {
  236236. CoreAudioInternal* device = 0;
  236237. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  236238. {
  236239. jassert (inputDeviceId != 0);
  236240. device = new CoreAudioInternal (inputDeviceId);
  236241. }
  236242. else
  236243. {
  236244. device = new CoreAudioInternal (outputDeviceId);
  236245. if (inputDeviceId != 0)
  236246. {
  236247. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  236248. device->inputDevice = secondDevice;
  236249. secondDevice->isSlaveDevice = true;
  236250. }
  236251. }
  236252. internal = device;
  236253. AudioObjectPropertyAddress pa;
  236254. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236255. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236256. pa.mElement = kAudioObjectPropertyElementWildcard;
  236257. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236258. }
  236259. ~CoreAudioIODevice()
  236260. {
  236261. AudioObjectPropertyAddress pa;
  236262. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236263. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236264. pa.mElement = kAudioObjectPropertyElementWildcard;
  236265. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236266. }
  236267. const StringArray getOutputChannelNames()
  236268. {
  236269. return internal->outChanNames;
  236270. }
  236271. const StringArray getInputChannelNames()
  236272. {
  236273. if (internal->inputDevice != 0)
  236274. return internal->inputDevice->inChanNames;
  236275. else
  236276. return internal->inChanNames;
  236277. }
  236278. int getNumSampleRates()
  236279. {
  236280. return internal->sampleRates.size();
  236281. }
  236282. double getSampleRate (int index)
  236283. {
  236284. return internal->sampleRates [index];
  236285. }
  236286. int getNumBufferSizesAvailable()
  236287. {
  236288. return internal->bufferSizes.size();
  236289. }
  236290. int getBufferSizeSamples (int index)
  236291. {
  236292. return internal->bufferSizes [index];
  236293. }
  236294. int getDefaultBufferSize()
  236295. {
  236296. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  236297. if (getBufferSizeSamples(i) >= 512)
  236298. return getBufferSizeSamples(i);
  236299. return 512;
  236300. }
  236301. const String open (const BigInteger& inputChannels,
  236302. const BigInteger& outputChannels,
  236303. double sampleRate,
  236304. int bufferSizeSamples)
  236305. {
  236306. isOpen_ = true;
  236307. if (bufferSizeSamples <= 0)
  236308. bufferSizeSamples = getDefaultBufferSize();
  236309. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  236310. isOpen_ = lastError.isEmpty();
  236311. return lastError;
  236312. }
  236313. void close()
  236314. {
  236315. isOpen_ = false;
  236316. internal->stop (false);
  236317. }
  236318. bool isOpen()
  236319. {
  236320. return isOpen_;
  236321. }
  236322. int getCurrentBufferSizeSamples()
  236323. {
  236324. return internal != 0 ? internal->getBufferSize() : 512;
  236325. }
  236326. double getCurrentSampleRate()
  236327. {
  236328. return internal != 0 ? internal->getSampleRate() : 0;
  236329. }
  236330. int getCurrentBitDepth()
  236331. {
  236332. return 32; // no way to find out, so just assume it's high..
  236333. }
  236334. const BigInteger getActiveOutputChannels() const
  236335. {
  236336. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236337. }
  236338. const BigInteger getActiveInputChannels() const
  236339. {
  236340. BigInteger chans;
  236341. if (internal != 0)
  236342. {
  236343. chans = internal->activeInputChans;
  236344. if (internal->inputDevice != 0)
  236345. chans |= internal->inputDevice->activeInputChans;
  236346. }
  236347. return chans;
  236348. }
  236349. int getOutputLatencyInSamples()
  236350. {
  236351. if (internal == 0)
  236352. return 0;
  236353. // this seems like a good guess at getting the latency right - comparing
  236354. // this with a round-trip measurement, it gets it to within a few millisecs
  236355. // for the built-in mac soundcard
  236356. return internal->outputLatency + internal->getBufferSize() * 2;
  236357. }
  236358. int getInputLatencyInSamples()
  236359. {
  236360. if (internal == 0)
  236361. return 0;
  236362. return internal->inputLatency + internal->getBufferSize() * 2;
  236363. }
  236364. void start (AudioIODeviceCallback* callback)
  236365. {
  236366. if (internal != 0 && ! isStarted)
  236367. {
  236368. if (callback != 0)
  236369. callback->audioDeviceAboutToStart (this);
  236370. isStarted = true;
  236371. internal->start (callback);
  236372. }
  236373. }
  236374. void stop()
  236375. {
  236376. if (isStarted && internal != 0)
  236377. {
  236378. AudioIODeviceCallback* const lastCallback = internal->callback;
  236379. isStarted = false;
  236380. internal->stop (true);
  236381. if (lastCallback != 0)
  236382. lastCallback->audioDeviceStopped();
  236383. }
  236384. }
  236385. bool isPlaying()
  236386. {
  236387. if (internal->callback == 0)
  236388. isStarted = false;
  236389. return isStarted;
  236390. }
  236391. const String getLastError()
  236392. {
  236393. return lastError;
  236394. }
  236395. int inputIndex, outputIndex;
  236396. juce_UseDebuggingNewOperator
  236397. private:
  236398. ScopedPointer<CoreAudioInternal> internal;
  236399. bool isOpen_, isStarted;
  236400. String lastError;
  236401. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236402. {
  236403. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236404. switch (pa->mSelector)
  236405. {
  236406. case kAudioHardwarePropertyDevices:
  236407. intern->deviceDetailsChanged();
  236408. break;
  236409. case kAudioHardwarePropertyDefaultOutputDevice:
  236410. case kAudioHardwarePropertyDefaultInputDevice:
  236411. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236412. break;
  236413. }
  236414. return noErr;
  236415. }
  236416. CoreAudioIODevice (const CoreAudioIODevice&);
  236417. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236418. };
  236419. class CoreAudioIODeviceType : public AudioIODeviceType
  236420. {
  236421. public:
  236422. CoreAudioIODeviceType()
  236423. : AudioIODeviceType ("CoreAudio"),
  236424. hasScanned (false)
  236425. {
  236426. }
  236427. ~CoreAudioIODeviceType()
  236428. {
  236429. }
  236430. void scanForDevices()
  236431. {
  236432. hasScanned = true;
  236433. inputDeviceNames.clear();
  236434. outputDeviceNames.clear();
  236435. inputIds.clear();
  236436. outputIds.clear();
  236437. UInt32 size;
  236438. AudioObjectPropertyAddress pa;
  236439. pa.mSelector = kAudioHardwarePropertyDevices;
  236440. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236441. pa.mElement = kAudioObjectPropertyElementMaster;
  236442. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236443. {
  236444. HeapBlock <AudioDeviceID> devs;
  236445. devs.calloc (size, 1);
  236446. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236447. {
  236448. const int num = size / (int) sizeof (AudioDeviceID);
  236449. for (int i = 0; i < num; ++i)
  236450. {
  236451. char name [1024];
  236452. size = sizeof (name);
  236453. pa.mSelector = kAudioDevicePropertyDeviceName;
  236454. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236455. {
  236456. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236457. const int numIns = getNumChannels (devs[i], true);
  236458. const int numOuts = getNumChannels (devs[i], false);
  236459. if (numIns > 0)
  236460. {
  236461. inputDeviceNames.add (nameString);
  236462. inputIds.add (devs[i]);
  236463. }
  236464. if (numOuts > 0)
  236465. {
  236466. outputDeviceNames.add (nameString);
  236467. outputIds.add (devs[i]);
  236468. }
  236469. }
  236470. }
  236471. }
  236472. }
  236473. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236474. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236475. }
  236476. const StringArray getDeviceNames (bool wantInputNames) const
  236477. {
  236478. jassert (hasScanned); // need to call scanForDevices() before doing this
  236479. if (wantInputNames)
  236480. return inputDeviceNames;
  236481. else
  236482. return outputDeviceNames;
  236483. }
  236484. int getDefaultDeviceIndex (bool forInput) const
  236485. {
  236486. jassert (hasScanned); // need to call scanForDevices() before doing this
  236487. AudioDeviceID deviceID;
  236488. UInt32 size = sizeof (deviceID);
  236489. // if they're asking for any input channels at all, use the default input, so we
  236490. // get the built-in mic rather than the built-in output with no inputs..
  236491. AudioObjectPropertyAddress pa;
  236492. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236493. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236494. pa.mElement = kAudioObjectPropertyElementMaster;
  236495. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236496. {
  236497. if (forInput)
  236498. {
  236499. for (int i = inputIds.size(); --i >= 0;)
  236500. if (inputIds[i] == deviceID)
  236501. return i;
  236502. }
  236503. else
  236504. {
  236505. for (int i = outputIds.size(); --i >= 0;)
  236506. if (outputIds[i] == deviceID)
  236507. return i;
  236508. }
  236509. }
  236510. return 0;
  236511. }
  236512. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236513. {
  236514. jassert (hasScanned); // need to call scanForDevices() before doing this
  236515. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236516. if (d == 0)
  236517. return -1;
  236518. return asInput ? d->inputIndex
  236519. : d->outputIndex;
  236520. }
  236521. bool hasSeparateInputsAndOutputs() const { return true; }
  236522. AudioIODevice* createDevice (const String& outputDeviceName,
  236523. const String& inputDeviceName)
  236524. {
  236525. jassert (hasScanned); // need to call scanForDevices() before doing this
  236526. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236527. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236528. String deviceName (outputDeviceName);
  236529. if (deviceName.isEmpty())
  236530. deviceName = inputDeviceName;
  236531. if (index >= 0)
  236532. return new CoreAudioIODevice (deviceName,
  236533. inputIds [inputIndex],
  236534. inputIndex,
  236535. outputIds [outputIndex],
  236536. outputIndex);
  236537. return 0;
  236538. }
  236539. juce_UseDebuggingNewOperator
  236540. private:
  236541. StringArray inputDeviceNames, outputDeviceNames;
  236542. Array <AudioDeviceID> inputIds, outputIds;
  236543. bool hasScanned;
  236544. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236545. {
  236546. int total = 0;
  236547. UInt32 size;
  236548. AudioObjectPropertyAddress pa;
  236549. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236550. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236551. pa.mElement = kAudioObjectPropertyElementMaster;
  236552. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236553. {
  236554. HeapBlock <AudioBufferList> bufList;
  236555. bufList.calloc (size, 1);
  236556. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236557. {
  236558. const int numStreams = bufList->mNumberBuffers;
  236559. for (int i = 0; i < numStreams; ++i)
  236560. {
  236561. const AudioBuffer& b = bufList->mBuffers[i];
  236562. total += b.mNumberChannels;
  236563. }
  236564. }
  236565. }
  236566. return total;
  236567. }
  236568. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236569. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236570. };
  236571. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236572. {
  236573. return new CoreAudioIODeviceType();
  236574. }
  236575. #undef log
  236576. #endif
  236577. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236578. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236579. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236580. // compiled on its own).
  236581. #if JUCE_INCLUDED_FILE
  236582. #if JUCE_MAC
  236583. #undef log
  236584. #define log(a) Logger::writeToLog(a)
  236585. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  236586. {
  236587. if (err == noErr)
  236588. return true;
  236589. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236590. jassertfalse;
  236591. return false;
  236592. }
  236593. #undef OK
  236594. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  236595. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236596. {
  236597. String result;
  236598. CFStringRef str = 0;
  236599. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236600. if (str != 0)
  236601. {
  236602. result = PlatformUtilities::cfStringToJuceString (str);
  236603. CFRelease (str);
  236604. str = 0;
  236605. }
  236606. MIDIEntityRef entity = 0;
  236607. MIDIEndpointGetEntity (endpoint, &entity);
  236608. if (entity == 0)
  236609. return result; // probably virtual
  236610. if (result.isEmpty())
  236611. {
  236612. // endpoint name has zero length - try the entity
  236613. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236614. if (str != 0)
  236615. {
  236616. result += PlatformUtilities::cfStringToJuceString (str);
  236617. CFRelease (str);
  236618. str = 0;
  236619. }
  236620. }
  236621. // now consider the device's name
  236622. MIDIDeviceRef device = 0;
  236623. MIDIEntityGetDevice (entity, &device);
  236624. if (device == 0)
  236625. return result;
  236626. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236627. if (str != 0)
  236628. {
  236629. const String s (PlatformUtilities::cfStringToJuceString (str));
  236630. CFRelease (str);
  236631. // if an external device has only one entity, throw away
  236632. // the endpoint name and just use the device name
  236633. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236634. {
  236635. result = s;
  236636. }
  236637. else if (! result.startsWithIgnoreCase (s))
  236638. {
  236639. // prepend the device name to the entity name
  236640. result = (s + " " + result).trimEnd();
  236641. }
  236642. }
  236643. return result;
  236644. }
  236645. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236646. {
  236647. String result;
  236648. // Does the endpoint have connections?
  236649. CFDataRef connections = 0;
  236650. int numConnections = 0;
  236651. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236652. if (connections != 0)
  236653. {
  236654. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236655. if (numConnections > 0)
  236656. {
  236657. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236658. for (int i = 0; i < numConnections; ++i, ++pid)
  236659. {
  236660. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236661. MIDIObjectRef connObject;
  236662. MIDIObjectType connObjectType;
  236663. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236664. if (err == noErr)
  236665. {
  236666. String s;
  236667. if (connObjectType == kMIDIObjectType_ExternalSource
  236668. || connObjectType == kMIDIObjectType_ExternalDestination)
  236669. {
  236670. // Connected to an external device's endpoint (10.3 and later).
  236671. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236672. }
  236673. else
  236674. {
  236675. // Connected to an external device (10.2) (or something else, catch-all)
  236676. CFStringRef str = 0;
  236677. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236678. if (str != 0)
  236679. {
  236680. s = PlatformUtilities::cfStringToJuceString (str);
  236681. CFRelease (str);
  236682. }
  236683. }
  236684. if (s.isNotEmpty())
  236685. {
  236686. if (result.isNotEmpty())
  236687. result += ", ";
  236688. result += s;
  236689. }
  236690. }
  236691. }
  236692. }
  236693. CFRelease (connections);
  236694. }
  236695. if (result.isNotEmpty())
  236696. return result;
  236697. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236698. return getEndpointName (endpoint, false);
  236699. }
  236700. const StringArray MidiOutput::getDevices()
  236701. {
  236702. StringArray s;
  236703. const ItemCount num = MIDIGetNumberOfDestinations();
  236704. for (ItemCount i = 0; i < num; ++i)
  236705. {
  236706. MIDIEndpointRef dest = MIDIGetDestination (i);
  236707. if (dest != 0)
  236708. {
  236709. String name (getConnectedEndpointName (dest));
  236710. if (name.isEmpty())
  236711. name = "<error>";
  236712. s.add (name);
  236713. }
  236714. else
  236715. {
  236716. s.add ("<error>");
  236717. }
  236718. }
  236719. return s;
  236720. }
  236721. int MidiOutput::getDefaultDeviceIndex()
  236722. {
  236723. return 0;
  236724. }
  236725. static MIDIClientRef globalMidiClient;
  236726. static bool hasGlobalClientBeenCreated = false;
  236727. static bool makeSureClientExists()
  236728. {
  236729. if (! hasGlobalClientBeenCreated)
  236730. {
  236731. String name ("JUCE");
  236732. if (JUCEApplication::getInstance() != 0)
  236733. name = JUCEApplication::getInstance()->getApplicationName();
  236734. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236735. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236736. CFRelease (appName);
  236737. }
  236738. return hasGlobalClientBeenCreated;
  236739. }
  236740. class MidiPortAndEndpoint
  236741. {
  236742. public:
  236743. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236744. : port (port_), endPoint (endPoint_)
  236745. {
  236746. }
  236747. ~MidiPortAndEndpoint()
  236748. {
  236749. if (port != 0)
  236750. MIDIPortDispose (port);
  236751. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236752. MIDIEndpointDispose (endPoint);
  236753. }
  236754. MIDIPortRef port;
  236755. MIDIEndpointRef endPoint;
  236756. };
  236757. MidiOutput* MidiOutput::openDevice (int index)
  236758. {
  236759. MidiOutput* mo = 0;
  236760. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236761. {
  236762. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236763. CFStringRef pname;
  236764. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236765. {
  236766. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  236767. if (makeSureClientExists())
  236768. {
  236769. MIDIPortRef port;
  236770. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  236771. {
  236772. mo = new MidiOutput();
  236773. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  236774. }
  236775. }
  236776. CFRelease (pname);
  236777. }
  236778. }
  236779. return mo;
  236780. }
  236781. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236782. {
  236783. MidiOutput* mo = 0;
  236784. if (makeSureClientExists())
  236785. {
  236786. MIDIEndpointRef endPoint;
  236787. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236788. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  236789. {
  236790. mo = new MidiOutput();
  236791. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  236792. }
  236793. CFRelease (name);
  236794. }
  236795. return mo;
  236796. }
  236797. MidiOutput::~MidiOutput()
  236798. {
  236799. delete static_cast<MidiPortAndEndpoint*> (internal);
  236800. }
  236801. void MidiOutput::reset()
  236802. {
  236803. }
  236804. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236805. {
  236806. return false;
  236807. }
  236808. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236809. {
  236810. }
  236811. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236812. {
  236813. MidiPortAndEndpoint* const mpe = static_cast<MidiPortAndEndpoint*> (internal);
  236814. if (message.isSysEx())
  236815. {
  236816. const int maxPacketSize = 256;
  236817. int pos = 0, bytesLeft = message.getRawDataSize();
  236818. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236819. HeapBlock <MIDIPacketList> packets;
  236820. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236821. packets->numPackets = numPackets;
  236822. MIDIPacket* p = packets->packet;
  236823. for (int i = 0; i < numPackets; ++i)
  236824. {
  236825. p->timeStamp = 0;
  236826. p->length = jmin (maxPacketSize, bytesLeft);
  236827. memcpy (p->data, message.getRawData() + pos, p->length);
  236828. pos += p->length;
  236829. bytesLeft -= p->length;
  236830. p = MIDIPacketNext (p);
  236831. }
  236832. if (mpe->port != 0)
  236833. MIDISend (mpe->port, mpe->endPoint, packets);
  236834. else
  236835. MIDIReceived (mpe->endPoint, packets);
  236836. }
  236837. else
  236838. {
  236839. MIDIPacketList packets;
  236840. packets.numPackets = 1;
  236841. packets.packet[0].timeStamp = 0;
  236842. packets.packet[0].length = message.getRawDataSize();
  236843. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236844. if (mpe->port != 0)
  236845. MIDISend (mpe->port, mpe->endPoint, &packets);
  236846. else
  236847. MIDIReceived (mpe->endPoint, &packets);
  236848. }
  236849. }
  236850. const StringArray MidiInput::getDevices()
  236851. {
  236852. StringArray s;
  236853. const ItemCount num = MIDIGetNumberOfSources();
  236854. for (ItemCount i = 0; i < num; ++i)
  236855. {
  236856. MIDIEndpointRef source = MIDIGetSource (i);
  236857. if (source != 0)
  236858. {
  236859. String name (getConnectedEndpointName (source));
  236860. if (name.isEmpty())
  236861. name = "<error>";
  236862. s.add (name);
  236863. }
  236864. else
  236865. {
  236866. s.add ("<error>");
  236867. }
  236868. }
  236869. return s;
  236870. }
  236871. int MidiInput::getDefaultDeviceIndex()
  236872. {
  236873. return 0;
  236874. }
  236875. struct MidiPortAndCallback
  236876. {
  236877. MidiInput* input;
  236878. MidiPortAndEndpoint* portAndEndpoint;
  236879. MidiInputCallback* callback;
  236880. MemoryBlock pendingData;
  236881. int pendingBytes;
  236882. double pendingDataTime;
  236883. bool active;
  236884. void processSysex (const uint8*& d, int& size, const double time)
  236885. {
  236886. if (*d == 0xf0)
  236887. {
  236888. pendingBytes = 0;
  236889. pendingDataTime = time;
  236890. }
  236891. pendingData.ensureSize (pendingBytes + size, false);
  236892. uint8* totalMessage = (uint8*) pendingData.getData();
  236893. uint8* dest = totalMessage + pendingBytes;
  236894. while (size > 0)
  236895. {
  236896. if (pendingBytes > 0 && *d >= 0x80)
  236897. {
  236898. if (*d >= 0xfa || *d == 0xf8)
  236899. {
  236900. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  236901. ++d;
  236902. --size;
  236903. }
  236904. else
  236905. {
  236906. if (*d == 0xf7)
  236907. {
  236908. *dest++ = *d++;
  236909. pendingBytes++;
  236910. --size;
  236911. }
  236912. break;
  236913. }
  236914. }
  236915. else
  236916. {
  236917. *dest++ = *d++;
  236918. pendingBytes++;
  236919. --size;
  236920. }
  236921. }
  236922. if (totalMessage [pendingBytes - 1] == 0xf7)
  236923. {
  236924. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  236925. pendingBytes = 0;
  236926. }
  236927. else
  236928. {
  236929. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  236930. }
  236931. }
  236932. };
  236933. namespace CoreMidiCallbacks
  236934. {
  236935. static CriticalSection callbackLock;
  236936. static Array<void*> activeCallbacks;
  236937. }
  236938. static void midiInputProc (const MIDIPacketList* pktlist,
  236939. void* readProcRefCon,
  236940. void* /*srcConnRefCon*/)
  236941. {
  236942. double time = Time::getMillisecondCounterHiRes() * 0.001;
  236943. const double originalTime = time;
  236944. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  236945. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  236946. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  236947. {
  236948. const MIDIPacket* packet = &pktlist->packet[0];
  236949. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236950. {
  236951. const uint8* d = (const uint8*) (packet->data);
  236952. int size = packet->length;
  236953. while (size > 0)
  236954. {
  236955. time = originalTime;
  236956. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  236957. {
  236958. mpc->processSysex (d, size, time);
  236959. }
  236960. else
  236961. {
  236962. int used = 0;
  236963. const MidiMessage m (d, size, used, 0, time);
  236964. if (used <= 0)
  236965. {
  236966. jassertfalse; // malformed midi message
  236967. break;
  236968. }
  236969. else
  236970. {
  236971. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  236972. }
  236973. size -= used;
  236974. d += used;
  236975. }
  236976. }
  236977. packet = MIDIPacketNext (packet);
  236978. }
  236979. }
  236980. }
  236981. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236982. {
  236983. MidiInput* mi = 0;
  236984. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236985. {
  236986. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236987. if (endPoint != 0)
  236988. {
  236989. CFStringRef pname;
  236990. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236991. {
  236992. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  236993. if (makeSureClientExists())
  236994. {
  236995. MIDIPortRef port;
  236996. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  236997. mpc->active = false;
  236998. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  236999. {
  237000. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  237001. {
  237002. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  237003. mpc->callback = callback;
  237004. mpc->pendingBytes = 0;
  237005. mpc->pendingData.ensureSize (128);
  237006. mi = new MidiInput (getDevices() [index]);
  237007. mpc->input = mi;
  237008. mi->internal = mpc;
  237009. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  237010. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  237011. }
  237012. else
  237013. {
  237014. OK (MIDIPortDispose (port));
  237015. }
  237016. }
  237017. }
  237018. }
  237019. CFRelease (pname);
  237020. }
  237021. }
  237022. return mi;
  237023. }
  237024. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  237025. {
  237026. MidiInput* mi = 0;
  237027. if (makeSureClientExists())
  237028. {
  237029. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  237030. mpc->active = false;
  237031. MIDIEndpointRef endPoint;
  237032. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  237033. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  237034. {
  237035. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  237036. mpc->callback = callback;
  237037. mpc->pendingBytes = 0;
  237038. mpc->pendingData.ensureSize (128);
  237039. mi = new MidiInput (deviceName);
  237040. mpc->input = mi;
  237041. mi->internal = mpc;
  237042. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  237043. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  237044. }
  237045. CFRelease (name);
  237046. }
  237047. return mi;
  237048. }
  237049. MidiInput::MidiInput (const String& name_)
  237050. : name (name_)
  237051. {
  237052. }
  237053. MidiInput::~MidiInput()
  237054. {
  237055. MidiPortAndCallback* const mpc = static_cast<MidiPortAndCallback*> (internal);
  237056. mpc->active = false;
  237057. {
  237058. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  237059. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  237060. }
  237061. if (mpc->portAndEndpoint->port != 0)
  237062. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  237063. delete mpc->portAndEndpoint;
  237064. delete mpc;
  237065. }
  237066. void MidiInput::start()
  237067. {
  237068. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  237069. static_cast<MidiPortAndCallback*> (internal)->active = true;
  237070. }
  237071. void MidiInput::stop()
  237072. {
  237073. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  237074. static_cast<MidiPortAndCallback*> (internal)->active = false;
  237075. }
  237076. #undef log
  237077. #else
  237078. MidiOutput::~MidiOutput()
  237079. {
  237080. }
  237081. void MidiOutput::reset()
  237082. {
  237083. }
  237084. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  237085. {
  237086. return false;
  237087. }
  237088. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  237089. {
  237090. }
  237091. void MidiOutput::sendMessageNow (const MidiMessage& message)
  237092. {
  237093. }
  237094. const StringArray MidiOutput::getDevices()
  237095. {
  237096. return StringArray();
  237097. }
  237098. MidiOutput* MidiOutput::openDevice (int index)
  237099. {
  237100. return 0;
  237101. }
  237102. const StringArray MidiInput::getDevices()
  237103. {
  237104. return StringArray();
  237105. }
  237106. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  237107. {
  237108. return 0;
  237109. }
  237110. #endif
  237111. #endif
  237112. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  237113. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  237114. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237115. // compiled on its own).
  237116. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  237117. #if ! JUCE_QUICKTIME
  237118. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  237119. #endif
  237120. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  237121. class QTCameraDeviceInteral;
  237122. END_JUCE_NAMESPACE
  237123. @interface QTCaptureCallbackDelegate : NSObject
  237124. {
  237125. @public
  237126. CameraDevice* owner;
  237127. QTCameraDeviceInteral* internal;
  237128. int64 firstPresentationTime;
  237129. int64 averageTimeOffset;
  237130. }
  237131. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  237132. - (void) dealloc;
  237133. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237134. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237135. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237136. fromConnection: (QTCaptureConnection*) connection;
  237137. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237138. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237139. fromConnection: (QTCaptureConnection*) connection;
  237140. @end
  237141. BEGIN_JUCE_NAMESPACE
  237142. class QTCameraDeviceInteral
  237143. {
  237144. public:
  237145. QTCameraDeviceInteral (CameraDevice* owner, int index)
  237146. {
  237147. const ScopedAutoReleasePool pool;
  237148. session = [[QTCaptureSession alloc] init];
  237149. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237150. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  237151. input = 0;
  237152. audioInput = 0;
  237153. audioDevice = 0;
  237154. fileOutput = 0;
  237155. imageOutput = 0;
  237156. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  237157. internalDev: this];
  237158. NSError* err = 0;
  237159. [device retain];
  237160. [device open: &err];
  237161. if (err == 0)
  237162. {
  237163. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237164. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237165. [session addInput: input error: &err];
  237166. if (err == 0)
  237167. {
  237168. resetFile();
  237169. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  237170. [imageOutput setDelegate: callbackDelegate];
  237171. if (err == 0)
  237172. {
  237173. [session startRunning];
  237174. return;
  237175. }
  237176. }
  237177. }
  237178. openingError = nsStringToJuce ([err description]);
  237179. DBG (openingError);
  237180. }
  237181. ~QTCameraDeviceInteral()
  237182. {
  237183. [session stopRunning];
  237184. [session removeOutput: imageOutput];
  237185. [session release];
  237186. [input release];
  237187. [device release];
  237188. [audioDevice release];
  237189. [audioInput release];
  237190. [fileOutput release];
  237191. [imageOutput release];
  237192. [callbackDelegate release];
  237193. }
  237194. void resetFile()
  237195. {
  237196. [fileOutput recordToOutputFileURL: nil];
  237197. [session removeOutput: fileOutput];
  237198. [fileOutput release];
  237199. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  237200. [session removeInput: audioInput];
  237201. [audioInput release];
  237202. audioInput = 0;
  237203. [audioDevice release];
  237204. audioDevice = 0;
  237205. [fileOutput setDelegate: callbackDelegate];
  237206. }
  237207. void addDefaultAudioInput()
  237208. {
  237209. NSError* err = nil;
  237210. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  237211. if ([audioDevice open: &err])
  237212. [audioDevice retain];
  237213. else
  237214. audioDevice = nil;
  237215. if (audioDevice != 0)
  237216. {
  237217. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  237218. [session addInput: audioInput error: &err];
  237219. }
  237220. }
  237221. void addListener (CameraDevice::Listener* listenerToAdd)
  237222. {
  237223. const ScopedLock sl (listenerLock);
  237224. if (listeners.size() == 0)
  237225. [session addOutput: imageOutput error: nil];
  237226. listeners.addIfNotAlreadyThere (listenerToAdd);
  237227. }
  237228. void removeListener (CameraDevice::Listener* listenerToRemove)
  237229. {
  237230. const ScopedLock sl (listenerLock);
  237231. listeners.removeValue (listenerToRemove);
  237232. if (listeners.size() == 0)
  237233. [session removeOutput: imageOutput];
  237234. }
  237235. void callListeners (CIImage* frame, int w, int h)
  237236. {
  237237. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  237238. Image image (cgImage);
  237239. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  237240. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  237241. CGContextFlush (cgImage->context);
  237242. const ScopedLock sl (listenerLock);
  237243. for (int i = listeners.size(); --i >= 0;)
  237244. {
  237245. CameraDevice::Listener* const l = listeners[i];
  237246. if (l != 0)
  237247. l->imageReceived (image);
  237248. }
  237249. }
  237250. QTCaptureDevice* device;
  237251. QTCaptureDeviceInput* input;
  237252. QTCaptureDevice* audioDevice;
  237253. QTCaptureDeviceInput* audioInput;
  237254. QTCaptureSession* session;
  237255. QTCaptureMovieFileOutput* fileOutput;
  237256. QTCaptureDecompressedVideoOutput* imageOutput;
  237257. QTCaptureCallbackDelegate* callbackDelegate;
  237258. String openingError;
  237259. Array<CameraDevice::Listener*> listeners;
  237260. CriticalSection listenerLock;
  237261. };
  237262. END_JUCE_NAMESPACE
  237263. @implementation QTCaptureCallbackDelegate
  237264. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  237265. internalDev: (QTCameraDeviceInteral*) d
  237266. {
  237267. [super init];
  237268. owner = owner_;
  237269. internal = d;
  237270. firstPresentationTime = 0;
  237271. averageTimeOffset = 0;
  237272. return self;
  237273. }
  237274. - (void) dealloc
  237275. {
  237276. [super dealloc];
  237277. }
  237278. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237279. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237280. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237281. fromConnection: (QTCaptureConnection*) connection
  237282. {
  237283. if (internal->listeners.size() > 0)
  237284. {
  237285. const ScopedAutoReleasePool pool;
  237286. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  237287. CVPixelBufferGetWidth (videoFrame),
  237288. CVPixelBufferGetHeight (videoFrame));
  237289. }
  237290. }
  237291. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237292. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237293. fromConnection: (QTCaptureConnection*) connection
  237294. {
  237295. const Time now (Time::getCurrentTime());
  237296. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  237297. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  237298. #else
  237299. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  237300. #endif
  237301. int64 presentationTime = (hosttime != nil)
  237302. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  237303. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  237304. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  237305. if (firstPresentationTime == 0)
  237306. {
  237307. firstPresentationTime = presentationTime;
  237308. averageTimeOffset = timeDiff;
  237309. }
  237310. else
  237311. {
  237312. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  237313. }
  237314. }
  237315. @end
  237316. BEGIN_JUCE_NAMESPACE
  237317. class QTCaptureViewerComp : public NSViewComponent
  237318. {
  237319. public:
  237320. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  237321. {
  237322. const ScopedAutoReleasePool pool;
  237323. captureView = [[QTCaptureView alloc] init];
  237324. [captureView setCaptureSession: internal->session];
  237325. setSize (640, 480); // xxx need to somehow get the movie size - how?
  237326. setView (captureView);
  237327. }
  237328. ~QTCaptureViewerComp()
  237329. {
  237330. setView (0);
  237331. [captureView setCaptureSession: nil];
  237332. [captureView release];
  237333. }
  237334. QTCaptureView* captureView;
  237335. };
  237336. CameraDevice::CameraDevice (const String& name_, int index)
  237337. : name (name_)
  237338. {
  237339. isRecording = false;
  237340. internal = new QTCameraDeviceInteral (this, index);
  237341. }
  237342. CameraDevice::~CameraDevice()
  237343. {
  237344. stopRecording();
  237345. delete static_cast <QTCameraDeviceInteral*> (internal);
  237346. internal = 0;
  237347. }
  237348. Component* CameraDevice::createViewerComponent()
  237349. {
  237350. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  237351. }
  237352. const String CameraDevice::getFileExtension()
  237353. {
  237354. return ".mov";
  237355. }
  237356. void CameraDevice::startRecordingToFile (const File& file, int quality)
  237357. {
  237358. stopRecording();
  237359. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237360. d->callbackDelegate->firstPresentationTime = 0;
  237361. file.deleteFile();
  237362. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  237363. // out wrong, so we'll put some audio in there too..,
  237364. d->addDefaultAudioInput();
  237365. [d->session addOutput: d->fileOutput error: nil];
  237366. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  237367. for (;;)
  237368. {
  237369. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  237370. if (connection == 0)
  237371. break;
  237372. QTCompressionOptions* options = 0;
  237373. NSString* mediaType = [connection mediaType];
  237374. if ([mediaType isEqualToString: QTMediaTypeVideo])
  237375. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  237376. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  237377. : @"QTCompressionOptions240SizeH264Video"];
  237378. else if ([mediaType isEqualToString: QTMediaTypeSound])
  237379. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  237380. [d->fileOutput setCompressionOptions: options forConnection: connection];
  237381. }
  237382. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  237383. isRecording = true;
  237384. }
  237385. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237386. {
  237387. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237388. if (d->callbackDelegate->firstPresentationTime != 0)
  237389. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237390. return Time();
  237391. }
  237392. void CameraDevice::stopRecording()
  237393. {
  237394. if (isRecording)
  237395. {
  237396. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237397. isRecording = false;
  237398. }
  237399. }
  237400. void CameraDevice::addListener (Listener* listenerToAdd)
  237401. {
  237402. if (listenerToAdd != 0)
  237403. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237404. }
  237405. void CameraDevice::removeListener (Listener* listenerToRemove)
  237406. {
  237407. if (listenerToRemove != 0)
  237408. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237409. }
  237410. const StringArray CameraDevice::getAvailableDevices()
  237411. {
  237412. const ScopedAutoReleasePool pool;
  237413. StringArray results;
  237414. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237415. for (int i = 0; i < (int) [devs count]; ++i)
  237416. {
  237417. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237418. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237419. }
  237420. return results;
  237421. }
  237422. CameraDevice* CameraDevice::openDevice (int index,
  237423. int minWidth, int minHeight,
  237424. int maxWidth, int maxHeight)
  237425. {
  237426. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237427. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237428. return d.release();
  237429. return 0;
  237430. }
  237431. #endif
  237432. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237433. #endif
  237434. #endif
  237435. END_JUCE_NAMESPACE
  237436. #endif
  237437. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237438. #endif
  237439. #endif